run copyright.sh for 2011.
[external/binutils.git] / gdb / ser-mingw.c
1 /* Serial interface for local (hardwired) serial ports on Windows systems
2
3    Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011
4    Free Software Foundation, Inc.
5
6    This file is part of GDB.
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
20
21 #include "defs.h"
22 #include "serial.h"
23 #include "ser-base.h"
24 #include "ser-tcp.h"
25
26 #include <windows.h>
27 #include <conio.h>
28
29 #include <fcntl.h>
30 #include <unistd.h>
31 #include <sys/types.h>
32
33 #include "gdb_assert.h"
34 #include "gdb_string.h"
35
36 #include "command.h"
37
38 void _initialize_ser_windows (void);
39
40 struct ser_windows_state
41 {
42   int in_progress;
43   OVERLAPPED ov;
44   DWORD lastCommMask;
45   HANDLE except_event;
46 };
47
48 /* Open up a real live device for serial I/O.  */
49
50 static int
51 ser_windows_open (struct serial *scb, const char *name)
52 {
53   HANDLE h;
54   struct ser_windows_state *state;
55   COMMTIMEOUTS timeouts;
56
57   h = CreateFile (name, GENERIC_READ | GENERIC_WRITE, 0, NULL,
58                   OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
59   if (h == INVALID_HANDLE_VALUE)
60     {
61       errno = ENOENT;
62       return -1;
63     }
64
65   scb->fd = _open_osfhandle ((intptr_t) h, O_RDWR);
66   if (scb->fd < 0)
67     {
68       errno = ENOENT;
69       return -1;
70     }
71
72   if (!SetCommMask (h, EV_RXCHAR))
73     {
74       errno = EINVAL;
75       return -1;
76     }
77
78   timeouts.ReadIntervalTimeout = MAXDWORD;
79   timeouts.ReadTotalTimeoutConstant = 0;
80   timeouts.ReadTotalTimeoutMultiplier = 0;
81   timeouts.WriteTotalTimeoutConstant = 0;
82   timeouts.WriteTotalTimeoutMultiplier = 0;
83   if (!SetCommTimeouts (h, &timeouts))
84     {
85       errno = EINVAL;
86       return -1;
87     }
88
89   state = xmalloc (sizeof (struct ser_windows_state));
90   memset (state, 0, sizeof (struct ser_windows_state));
91   scb->state = state;
92
93   /* Create a manual reset event to watch the input buffer.  */
94   state->ov.hEvent = CreateEvent (0, TRUE, FALSE, 0);
95
96   /* Create a (currently unused) handle to record exceptions.  */
97   state->except_event = CreateEvent (0, TRUE, FALSE, 0);
98
99   return 0;
100 }
101
102 /* Wait for the output to drain away, as opposed to flushing (discarding)
103    it.  */
104
105 static int
106 ser_windows_drain_output (struct serial *scb)
107 {
108   HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
109
110   return (FlushFileBuffers (h) != 0) ? 0 : -1;
111 }
112
113 static int
114 ser_windows_flush_output (struct serial *scb)
115 {
116   HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
117
118   return (PurgeComm (h, PURGE_TXCLEAR) != 0) ? 0 : -1;
119 }
120
121 static int
122 ser_windows_flush_input (struct serial *scb)
123 {
124   HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
125
126   return (PurgeComm (h, PURGE_RXCLEAR) != 0) ? 0 : -1;
127 }
128
129 static int
130 ser_windows_send_break (struct serial *scb)
131 {
132   HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
133
134   if (SetCommBreak (h) == 0)
135     return -1;
136
137   /* Delay for 250 milliseconds.  */
138   Sleep (250);
139
140   if (ClearCommBreak (h))
141     return -1;
142
143   return 0;
144 }
145
146 static void
147 ser_windows_raw (struct serial *scb)
148 {
149   HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
150   DCB state;
151
152   if (GetCommState (h, &state) == 0)
153     return;
154
155   state.fParity = FALSE;
156   state.fOutxCtsFlow = FALSE;
157   state.fOutxDsrFlow = FALSE;
158   state.fDtrControl = DTR_CONTROL_ENABLE;
159   state.fDsrSensitivity = FALSE;
160   state.fOutX = FALSE;
161   state.fInX = FALSE;
162   state.fNull = FALSE;
163   state.fAbortOnError = FALSE;
164   state.ByteSize = 8;
165   state.Parity = NOPARITY;
166
167   scb->current_timeout = 0;
168
169   if (SetCommState (h, &state) == 0)
170     warning (_("SetCommState failed\n"));
171 }
172
173 static int
174 ser_windows_setstopbits (struct serial *scb, int num)
175 {
176   HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
177   DCB state;
178
179   if (GetCommState (h, &state) == 0)
180     return -1;
181
182   switch (num)
183     {
184     case SERIAL_1_STOPBITS:
185       state.StopBits = ONESTOPBIT;
186       break;
187     case SERIAL_1_AND_A_HALF_STOPBITS:
188       state.StopBits = ONE5STOPBITS;
189       break;
190     case SERIAL_2_STOPBITS:
191       state.StopBits = TWOSTOPBITS;
192       break;
193     default:
194       return 1;
195     }
196
197   return (SetCommState (h, &state) != 0) ? 0 : -1;
198 }
199
200 static int
201 ser_windows_setbaudrate (struct serial *scb, int rate)
202 {
203   HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
204   DCB state;
205
206   if (GetCommState (h, &state) == 0)
207     return -1;
208
209   state.BaudRate = rate;
210
211   return (SetCommState (h, &state) != 0) ? 0 : -1;
212 }
213
214 static void
215 ser_windows_close (struct serial *scb)
216 {
217   struct ser_windows_state *state;
218
219   /* Stop any pending selects.  */
220   CancelIo ((HANDLE) _get_osfhandle (scb->fd));
221   state = scb->state;
222   CloseHandle (state->ov.hEvent);
223   CloseHandle (state->except_event);
224
225   if (scb->fd < 0)
226     return;
227
228   close (scb->fd);
229   scb->fd = -1;
230
231   xfree (scb->state);
232 }
233
234 static void
235 ser_windows_wait_handle (struct serial *scb, HANDLE *read, HANDLE *except)
236 {
237   struct ser_windows_state *state;
238   COMSTAT status;
239   DWORD errors;
240   HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
241
242   state = scb->state;
243
244   *except = state->except_event;
245   *read = state->ov.hEvent;
246
247   if (state->in_progress)
248     return;
249
250   /* Reset the mask - we are only interested in any characters which
251      arrive after this point, not characters which might have arrived
252      and already been read.  */
253
254   /* This really, really shouldn't be necessary - just the second one.
255      But otherwise an internal flag for EV_RXCHAR does not get
256      cleared, and we get a duplicated event, if the last batch
257      of characters included at least two arriving close together.  */
258   if (!SetCommMask (h, 0))
259     warning (_("ser_windows_wait_handle: reseting mask failed"));
260
261   if (!SetCommMask (h, EV_RXCHAR))
262     warning (_("ser_windows_wait_handle: reseting mask failed (2)"));
263
264   /* There's a potential race condition here; we must check cbInQue
265      and not wait if that's nonzero.  */
266
267   ClearCommError (h, &errors, &status);
268   if (status.cbInQue > 0)
269     {
270       SetEvent (state->ov.hEvent);
271       return;
272     }
273
274   state->in_progress = 1;
275   ResetEvent (state->ov.hEvent);
276   state->lastCommMask = -2;
277   if (WaitCommEvent (h, &state->lastCommMask, &state->ov))
278     {
279       gdb_assert (state->lastCommMask & EV_RXCHAR);
280       SetEvent (state->ov.hEvent);
281     }
282   else
283     gdb_assert (GetLastError () == ERROR_IO_PENDING);
284 }
285
286 static int
287 ser_windows_read_prim (struct serial *scb, size_t count)
288 {
289   struct ser_windows_state *state;
290   OVERLAPPED ov;
291   DWORD bytes_read, bytes_read_tmp;
292   HANDLE h;
293   gdb_byte *p;
294
295   state = scb->state;
296   if (state->in_progress)
297     {
298       WaitForSingleObject (state->ov.hEvent, INFINITE);
299       state->in_progress = 0;
300       ResetEvent (state->ov.hEvent);
301     }
302
303   memset (&ov, 0, sizeof (OVERLAPPED));
304   ov.hEvent = CreateEvent (0, FALSE, FALSE, 0);
305   h = (HANDLE) _get_osfhandle (scb->fd);
306
307   if (!ReadFile (h, scb->buf, /* count */ 1, &bytes_read, &ov))
308     {
309       if (GetLastError () != ERROR_IO_PENDING
310           || !GetOverlappedResult (h, &ov, &bytes_read, TRUE))
311         bytes_read = -1;
312     }
313
314   CloseHandle (ov.hEvent);
315   return bytes_read;
316 }
317
318 static int
319 ser_windows_write_prim (struct serial *scb, const void *buf, size_t len)
320 {
321   struct ser_windows_state *state;
322   OVERLAPPED ov;
323   DWORD bytes_written;
324   HANDLE h;
325
326   memset (&ov, 0, sizeof (OVERLAPPED));
327   ov.hEvent = CreateEvent (0, FALSE, FALSE, 0);
328   h = (HANDLE) _get_osfhandle (scb->fd);
329   if (!WriteFile (h, buf, len, &bytes_written, &ov))
330     {
331       if (GetLastError () != ERROR_IO_PENDING
332           || !GetOverlappedResult (h, &ov, &bytes_written, TRUE))
333         bytes_written = -1;
334     }
335
336   CloseHandle (ov.hEvent);
337   return bytes_written;
338 }
339
340 /* On Windows, gdb_select is implemented using WaitForMulpleObjects.
341    A "select thread" is created for each file descriptor.  These
342    threads looks for activity on the corresponding descriptor, using
343    whatever techniques are appropriate for the descriptor type.  When
344    that activity occurs, the thread signals an appropriate event,
345    which wakes up WaitForMultipleObjects.
346
347    Each select thread is in one of two states: stopped or started.
348    Select threads begin in the stopped state.  When gdb_select is
349    called, threads corresponding to the descriptors of interest are
350    started by calling a wait_handle function.  Each thread that
351    notices activity signals the appropriate event and then reenters
352    the stopped state.  Before gdb_select returns it calls the
353    wait_handle_done functions, which return the threads to the stopped
354    state.  */
355
356 enum select_thread_state {
357   STS_STARTED,
358   STS_STOPPED
359 };
360
361 struct ser_console_state
362 {
363   /* Signaled by the select thread to indicate that data is available
364      on the file descriptor.  */
365   HANDLE read_event;
366   /* Signaled by the select thread to indicate that an exception has
367      occurred on the file descriptor.  */
368   HANDLE except_event;
369   /* Signaled by the select thread to indicate that it has entered the
370      started state.  HAVE_STARTED and HAVE_STOPPED are never signaled
371      simultaneously.  */
372   HANDLE have_started;
373   /* Signaled by the select thread to indicate that it has stopped,
374      either because data is available (and READ_EVENT is signaled),
375      because an exception has occurred (and EXCEPT_EVENT is signaled),
376      or because STOP_SELECT was signaled.  */
377   HANDLE have_stopped;
378
379   /* Signaled by the main program to tell the select thread to enter
380      the started state.  */
381   HANDLE start_select;
382   /* Signaled by the main program to tell the select thread to enter
383      the stopped state. */
384   HANDLE stop_select;
385   /* Signaled by the main program to tell the select thread to
386      exit.  */
387   HANDLE exit_select;
388
389   /* The handle for the select thread.  */
390   HANDLE thread;
391   /* The state of the select thread.  This field is only accessed in
392      the main program, never by the select thread itself.  */
393   enum select_thread_state thread_state;
394 };
395
396 /* Called by a select thread to enter the stopped state.  This
397    function does not return until the thread has re-entered the
398    started state.  */
399 static void
400 select_thread_wait (struct ser_console_state *state)
401 {
402   HANDLE wait_events[2];
403
404   /* There are two things that can wake us up: a request that we enter
405      the started state, or that we exit this thread.  */
406   wait_events[0] = state->start_select;
407   wait_events[1] = state->exit_select;
408   if (WaitForMultipleObjects (2, wait_events, FALSE, INFINITE) 
409       != WAIT_OBJECT_0)
410     /* Either the EXIT_SELECT event was signaled (requesting that the
411        thread exit) or an error has occurred.  In either case, we exit
412        the thread.  */
413     ExitThread (0);
414   
415   /* We are now in the started state.  */
416   SetEvent (state->have_started);
417 }
418
419 typedef DWORD WINAPI (*thread_fn_type)(void *);
420
421 /* Create a new select thread for SCB executing THREAD_FN.  The STATE
422    will be filled in by this function before return.  */
423 void
424 create_select_thread (thread_fn_type thread_fn,
425                       struct serial *scb,
426                       struct ser_console_state *state)
427 {
428   DWORD threadId;
429
430   /* Create all of the events.  These are all auto-reset events.  */
431   state->read_event = CreateEvent (NULL, FALSE, FALSE, NULL);
432   state->except_event = CreateEvent (NULL, FALSE, FALSE, NULL);
433   state->have_started = CreateEvent (NULL, FALSE, FALSE, NULL);
434   state->have_stopped = CreateEvent (NULL, FALSE, FALSE, NULL);
435   state->start_select = CreateEvent (NULL, FALSE, FALSE, NULL);
436   state->stop_select = CreateEvent (NULL, FALSE, FALSE, NULL);
437   state->exit_select = CreateEvent (NULL, FALSE, FALSE, NULL);
438
439   state->thread = CreateThread (NULL, 0, thread_fn, scb, 0, &threadId);
440   /* The thread begins in the stopped state.  */
441   state->thread_state = STS_STOPPED;
442 }
443
444 /* Destroy the select thread indicated by STATE.  */
445 static void
446 destroy_select_thread (struct ser_console_state *state)
447 {
448   /* Ask the thread to exit.  */
449   SetEvent (state->exit_select);
450   /* Wait until it does.  */
451   WaitForSingleObject (state->thread, INFINITE);
452
453   /* Destroy the events.  */
454   CloseHandle (state->read_event);
455   CloseHandle (state->except_event);
456   CloseHandle (state->have_started);
457   CloseHandle (state->have_stopped);
458   CloseHandle (state->start_select);
459   CloseHandle (state->stop_select);
460   CloseHandle (state->exit_select);
461 }
462
463 /* Called by gdb_select to start the select thread indicated by STATE.
464    This function does not return until the thread has started.  */
465 static void
466 start_select_thread (struct ser_console_state *state)
467 {
468   /* Ask the thread to start.  */
469   SetEvent (state->start_select);
470   /* Wait until it does.  */
471   WaitForSingleObject (state->have_started, INFINITE);
472   /* The thread is now started.  */
473   state->thread_state = STS_STARTED;
474 }
475
476 /* Called by gdb_select to stop the select thread indicated by STATE.
477    This function does not return until the thread has stopped.  */
478 static void
479 stop_select_thread (struct ser_console_state *state)
480 {
481   /* If the thread is already in the stopped state, we have nothing to
482      do.  Some of the wait_handle functions avoid calling
483      start_select_thread if they notice activity on the relevant file
484      descriptors.  The wait_handle_done functions still call
485      stop_select_thread -- but it is already stopped.  */
486   if (state->thread_state != STS_STARTED)
487     return;
488   /* Ask the thread to stop.  */
489   SetEvent (state->stop_select);
490   /* Wait until it does.  */
491   WaitForSingleObject (state->have_stopped, INFINITE);
492   /* The thread is now stopped.  */
493   state->thread_state = STS_STOPPED;
494 }
495
496 static DWORD WINAPI
497 console_select_thread (void *arg)
498 {
499   struct serial *scb = arg;
500   struct ser_console_state *state;
501   int event_index;
502   HANDLE h;
503
504   state = scb->state;
505   h = (HANDLE) _get_osfhandle (scb->fd);
506
507   while (1)
508     {
509       HANDLE wait_events[2];
510       INPUT_RECORD record;
511       DWORD n_records;
512
513       select_thread_wait (state);
514
515       while (1)
516         {
517           wait_events[0] = state->stop_select;
518           wait_events[1] = h;
519
520           event_index = WaitForMultipleObjects (2, wait_events, FALSE, INFINITE);
521
522           if (event_index == WAIT_OBJECT_0
523               || WaitForSingleObject (state->stop_select, 0) == WAIT_OBJECT_0)
524             break;
525
526           if (event_index != WAIT_OBJECT_0 + 1)
527             {
528               /* Wait must have failed; assume an error has occured, e.g.
529                  the handle has been closed.  */
530               SetEvent (state->except_event);
531               break;
532             }
533
534           /* We've got a pending event on the console.  See if it's
535              of interest.  */
536           if (!PeekConsoleInput (h, &record, 1, &n_records) || n_records != 1)
537             {
538               /* Something went wrong.  Maybe the console is gone.  */
539               SetEvent (state->except_event);
540               break;
541             }
542
543           if (record.EventType == KEY_EVENT && record.Event.KeyEvent.bKeyDown)
544             {
545               WORD keycode = record.Event.KeyEvent.wVirtualKeyCode;
546
547               /* Ignore events containing only control keys.  We must
548                  recognize "enhanced" keys which we are interested in
549                  reading via getch, if they do not map to ASCII.  But we
550                  do not want to report input available for e.g. the
551                  control key alone.  */
552
553               if (record.Event.KeyEvent.uChar.AsciiChar != 0
554                   || keycode == VK_PRIOR
555                   || keycode == VK_NEXT
556                   || keycode == VK_END
557                   || keycode == VK_HOME
558                   || keycode == VK_LEFT
559                   || keycode == VK_UP
560                   || keycode == VK_RIGHT
561                   || keycode == VK_DOWN
562                   || keycode == VK_INSERT
563                   || keycode == VK_DELETE)
564                 {
565                   /* This is really a keypress.  */
566                   SetEvent (state->read_event);
567                   break;
568                 }
569             }
570
571           /* Otherwise discard it and wait again.  */
572           ReadConsoleInput (h, &record, 1, &n_records);
573         }
574
575       SetEvent(state->have_stopped);
576     }
577   return 0;
578 }
579
580 static int
581 fd_is_pipe (int fd)
582 {
583   if (PeekNamedPipe ((HANDLE) _get_osfhandle (fd), NULL, 0, NULL, NULL, NULL))
584     return 1;
585   else
586     return 0;
587 }
588
589 static int
590 fd_is_file (int fd)
591 {
592   if (GetFileType ((HANDLE) _get_osfhandle (fd)) == FILE_TYPE_DISK)
593     return 1;
594   else
595     return 0;
596 }
597
598 static DWORD WINAPI
599 pipe_select_thread (void *arg)
600 {
601   struct serial *scb = arg;
602   struct ser_console_state *state;
603   int event_index;
604   HANDLE h;
605
606   state = scb->state;
607   h = (HANDLE) _get_osfhandle (scb->fd);
608
609   while (1)
610     {
611       DWORD n_avail;
612
613       select_thread_wait (state);
614
615       /* Wait for something to happen on the pipe.  */
616       while (1)
617         {
618           if (!PeekNamedPipe (h, NULL, 0, NULL, &n_avail, NULL))
619             {
620               SetEvent (state->except_event);
621               break;
622             }
623
624           if (n_avail > 0)
625             {
626               SetEvent (state->read_event);
627               break;
628             }
629
630           /* Delay 10ms before checking again, but allow the stop
631              event to wake us.  */
632           if (WaitForSingleObject (state->stop_select, 10) == WAIT_OBJECT_0)
633             break;
634         }
635
636       SetEvent (state->have_stopped);
637     }
638   return 0;
639 }
640
641 static DWORD WINAPI
642 file_select_thread (void *arg)
643 {
644   struct serial *scb = arg;
645   struct ser_console_state *state;
646   int event_index;
647   HANDLE h;
648
649   state = scb->state;
650   h = (HANDLE) _get_osfhandle (scb->fd);
651
652   while (1)
653     {
654       select_thread_wait (state);
655
656       if (SetFilePointer (h, 0, NULL, FILE_CURRENT) == INVALID_SET_FILE_POINTER)
657         SetEvent (state->except_event);
658       else
659         SetEvent (state->read_event);
660
661       SetEvent (state->have_stopped);
662     }
663   return 0;
664 }
665
666 static void
667 ser_console_wait_handle (struct serial *scb, HANDLE *read, HANDLE *except)
668 {
669   struct ser_console_state *state = scb->state;
670
671   if (state == NULL)
672     {
673       thread_fn_type thread_fn;
674       int is_tty;
675
676       is_tty = isatty (scb->fd);
677       if (!is_tty && !fd_is_file (scb->fd) && !fd_is_pipe (scb->fd))
678         {
679           *read = NULL;
680           *except = NULL;
681           return;
682         }
683
684       state = xmalloc (sizeof (struct ser_console_state));
685       memset (state, 0, sizeof (struct ser_console_state));
686       scb->state = state;
687
688       if (is_tty)
689         thread_fn = console_select_thread;
690       else if (fd_is_pipe (scb->fd))
691         thread_fn = pipe_select_thread;
692       else
693         thread_fn = file_select_thread;
694
695       create_select_thread (thread_fn, scb, state);
696     }
697
698   *read = state->read_event;
699   *except = state->except_event;
700
701   /* Start from a blank state.  */
702   ResetEvent (state->read_event);
703   ResetEvent (state->except_event);
704   ResetEvent (state->stop_select);
705
706   /* First check for a key already in the buffer.  If there is one,
707      we don't need a thread.  This also catches the second key of
708      multi-character returns from getch, for instance for arrow
709      keys.  The second half is in a C library internal buffer,
710      and PeekConsoleInput will not find it.  */
711   if (_kbhit ())
712     {
713       SetEvent (state->read_event);
714       return;
715     }
716
717   /* Otherwise, start the select thread.  */
718   start_select_thread (state);
719 }
720
721 static void
722 ser_console_done_wait_handle (struct serial *scb)
723 {
724   struct ser_console_state *state = scb->state;
725
726   if (state == NULL)
727     return;
728
729   stop_select_thread (state);
730 }
731
732 static void
733 ser_console_close (struct serial *scb)
734 {
735   struct ser_console_state *state = scb->state;
736
737   if (scb->state)
738     {
739       destroy_select_thread (state);
740       xfree (scb->state);
741     }
742 }
743
744 struct ser_console_ttystate
745 {
746   int is_a_tty;
747 };
748
749 static serial_ttystate
750 ser_console_get_tty_state (struct serial *scb)
751 {
752   if (isatty (scb->fd))
753     {
754       struct ser_console_ttystate *state;
755
756       state = (struct ser_console_ttystate *) xmalloc (sizeof *state);
757       state->is_a_tty = 1;
758       return state;
759     }
760   else
761     return NULL;
762 }
763
764 struct pipe_state
765 {
766   /* Since we use the pipe_select_thread for our select emulation,
767      we need to place the state structure it requires at the front
768      of our state.  */
769   struct ser_console_state wait;
770
771   /* The pex obj for our (one-stage) pipeline.  */
772   struct pex_obj *pex;
773
774   /* Streams for the pipeline's input and output.  */
775   FILE *input, *output;
776 };
777
778 static struct pipe_state *
779 make_pipe_state (void)
780 {
781   struct pipe_state *ps = XMALLOC (struct pipe_state);
782
783   memset (ps, 0, sizeof (*ps));
784   ps->wait.read_event = INVALID_HANDLE_VALUE;
785   ps->wait.except_event = INVALID_HANDLE_VALUE;
786   ps->wait.start_select = INVALID_HANDLE_VALUE;
787   ps->wait.stop_select = INVALID_HANDLE_VALUE;
788
789   return ps;
790 }
791
792 static void
793 free_pipe_state (struct pipe_state *ps)
794 {
795   int saved_errno = errno;
796
797   if (ps->wait.read_event != INVALID_HANDLE_VALUE)
798     destroy_select_thread (&ps->wait);
799
800   /* Close the pipe to the child.  We must close the pipe before
801      calling pex_free because pex_free will wait for the child to exit
802      and the child will not exit until the pipe is closed.  */
803   if (ps->input)
804     fclose (ps->input);
805   if (ps->pex)
806     {
807       pex_free (ps->pex);
808       /* pex_free closes ps->output.  */
809     }
810   else if (ps->output)
811     fclose (ps->output);
812
813   xfree (ps);
814
815   errno = saved_errno;
816 }
817
818 static void
819 cleanup_pipe_state (void *untyped)
820 {
821   struct pipe_state *ps = untyped;
822
823   free_pipe_state (ps);
824 }
825
826 static int
827 pipe_windows_open (struct serial *scb, const char *name)
828 {
829   struct pipe_state *ps;
830   FILE *pex_stderr;
831   char **argv;
832   struct cleanup *back_to;
833
834   if (name == NULL)
835     error_no_arg (_("child command"));
836
837   argv = gdb_buildargv (name);
838   back_to = make_cleanup_freeargv (argv);
839
840   if (! argv[0] || argv[0][0] == '\0')
841     error ("missing child command");
842
843   ps = make_pipe_state ();
844   make_cleanup (cleanup_pipe_state, ps);
845
846   ps->pex = pex_init (PEX_USE_PIPES, "target remote pipe", NULL);
847   if (! ps->pex)
848     goto fail;
849   ps->input = pex_input_pipe (ps->pex, 1);
850   if (! ps->input)
851     goto fail;
852
853   {
854     int err;
855     const char *err_msg
856       = pex_run (ps->pex, PEX_SEARCH | PEX_BINARY_INPUT | PEX_BINARY_OUTPUT
857                  | PEX_STDERR_TO_PIPE,
858                  argv[0], argv, NULL, NULL,
859                  &err);
860
861     if (err_msg)
862       {
863         /* Our caller expects us to return -1, but all they'll do with
864            it generally is print the message based on errno.  We have
865            all the same information here, plus err_msg provided by
866            pex_run, so we just raise the error here.  */
867         if (err)
868           error ("error starting child process '%s': %s: %s",
869                  name, err_msg, safe_strerror (err));
870         else
871           error ("error starting child process '%s': %s",
872                  name, err_msg);
873       }
874   }
875
876   ps->output = pex_read_output (ps->pex, 1);
877   if (! ps->output)
878     goto fail;
879   scb->fd = fileno (ps->output);
880
881   pex_stderr = pex_read_err (ps->pex, 1);
882   if (! pex_stderr)
883     goto fail;
884   scb->error_fd = fileno (pex_stderr);
885
886   scb->state = (void *) ps;
887
888   discard_cleanups (back_to);
889   return 0;
890
891  fail:
892   do_cleanups (back_to);
893   return -1;
894 }
895
896 static int
897 pipe_windows_fdopen (struct serial *scb, int fd)
898 {
899   struct pipe_state *ps;
900
901   ps = make_pipe_state ();
902
903   ps->input = fdopen (fd, "r+");
904   if (! ps->input)
905     goto fail;
906
907   ps->output = fdopen (fd, "r+");
908   if (! ps->output)
909     goto fail;
910
911   scb->fd = fd;
912   scb->state = (void *) ps;
913
914   return 0;
915
916  fail:
917   free_pipe_state (ps);
918   return -1;
919 }
920
921 static void
922 pipe_windows_close (struct serial *scb)
923 {
924   struct pipe_state *ps = scb->state;
925
926   /* In theory, we should try to kill the subprocess here, but the pex
927      interface doesn't give us enough information to do that.  Usually
928      closing the input pipe will get the message across.  */
929
930   free_pipe_state (ps);
931 }
932
933
934 static int
935 pipe_windows_read (struct serial *scb, size_t count)
936 {
937   HANDLE pipeline_out = (HANDLE) _get_osfhandle (scb->fd);
938   DWORD available;
939   DWORD bytes_read;
940
941   if (pipeline_out == INVALID_HANDLE_VALUE)
942     return -1;
943
944   if (! PeekNamedPipe (pipeline_out, NULL, 0, NULL, &available, NULL))
945     return -1;
946
947   if (count > available)
948     count = available;
949
950   if (! ReadFile (pipeline_out, scb->buf, count, &bytes_read, NULL))
951     return -1;
952
953   return bytes_read;
954 }
955
956
957 static int
958 pipe_windows_write (struct serial *scb, const void *buf, size_t count)
959 {
960   struct pipe_state *ps = scb->state;
961   HANDLE pipeline_in;
962   DWORD written;
963
964   int pipeline_in_fd = fileno (ps->input);
965   if (pipeline_in_fd < 0)
966     return -1;
967
968   pipeline_in = (HANDLE) _get_osfhandle (pipeline_in_fd);
969   if (pipeline_in == INVALID_HANDLE_VALUE)
970     return -1;
971
972   if (! WriteFile (pipeline_in, buf, count, &written, NULL))
973     return -1;
974
975   return written;
976 }
977
978
979 static void
980 pipe_wait_handle (struct serial *scb, HANDLE *read, HANDLE *except)
981 {
982   struct pipe_state *ps = scb->state;
983
984   /* Have we allocated our events yet?  */
985   if (ps->wait.read_event == INVALID_HANDLE_VALUE)
986     /* Start the thread.  */
987     create_select_thread (pipe_select_thread, scb, &ps->wait);
988
989   *read = ps->wait.read_event;
990   *except = ps->wait.except_event;
991
992   /* Start from a blank state.  */
993   ResetEvent (ps->wait.read_event);
994   ResetEvent (ps->wait.except_event);
995   ResetEvent (ps->wait.stop_select);
996
997   start_select_thread (&ps->wait);
998 }
999
1000 static void
1001 pipe_done_wait_handle (struct serial *scb)
1002 {
1003   struct pipe_state *ps = scb->state;
1004
1005   /* Have we allocated our events yet?  */
1006   if (ps->wait.read_event == INVALID_HANDLE_VALUE)
1007     return;
1008
1009   stop_select_thread (&ps->wait);
1010 }
1011
1012 static int
1013 pipe_avail (struct serial *scb, int fd)
1014 {
1015   HANDLE h = (HANDLE) _get_osfhandle (fd);
1016   DWORD numBytes;
1017   BOOL r = PeekNamedPipe (h, NULL, 0, NULL, &numBytes, NULL);
1018
1019   if (r == FALSE)
1020     numBytes = 0;
1021   return numBytes;
1022 }
1023
1024 int
1025 gdb_pipe (int pdes[2])
1026 {
1027   if (_pipe (pdes, 512, _O_BINARY | _O_NOINHERIT) == -1)
1028     return -1;
1029   return 0;
1030 }
1031
1032 struct net_windows_state
1033 {
1034   struct ser_console_state base;
1035   
1036   HANDLE sock_event;
1037 };
1038
1039 static DWORD WINAPI
1040 net_windows_select_thread (void *arg)
1041 {
1042   struct serial *scb = arg;
1043   struct net_windows_state *state;
1044   int event_index;
1045
1046   state = scb->state;
1047
1048   while (1)
1049     {
1050       HANDLE wait_events[2];
1051       WSANETWORKEVENTS events;
1052
1053       select_thread_wait (&state->base);
1054
1055       wait_events[0] = state->base.stop_select;
1056       wait_events[1] = state->sock_event;
1057
1058       event_index = WaitForMultipleObjects (2, wait_events, FALSE, INFINITE);
1059
1060       if (event_index == WAIT_OBJECT_0
1061           || WaitForSingleObject (state->base.stop_select, 0) == WAIT_OBJECT_0)
1062         /* We have been requested to stop.  */
1063         ;
1064       else if (event_index != WAIT_OBJECT_0 + 1)
1065         /* Some error has occured.  Assume that this is an error
1066            condition.  */
1067         SetEvent (state->base.except_event);
1068       else
1069         {
1070           /* Enumerate the internal network events, and reset the
1071              object that signalled us to catch the next event.  */
1072           WSAEnumNetworkEvents (scb->fd, state->sock_event, &events);
1073           
1074           gdb_assert (events.lNetworkEvents & (FD_READ | FD_CLOSE));
1075           
1076           if (events.lNetworkEvents & FD_READ)
1077             SetEvent (state->base.read_event);
1078           
1079           if (events.lNetworkEvents & FD_CLOSE)
1080             SetEvent (state->base.except_event);
1081         }
1082
1083       SetEvent (state->base.have_stopped);
1084     }
1085 }
1086
1087 static void
1088 net_windows_wait_handle (struct serial *scb, HANDLE *read, HANDLE *except)
1089 {
1090   struct net_windows_state *state = scb->state;
1091
1092   /* Start from a clean slate.  */
1093   ResetEvent (state->base.read_event);
1094   ResetEvent (state->base.except_event);
1095   ResetEvent (state->base.stop_select);
1096
1097   *read = state->base.read_event;
1098   *except = state->base.except_event;
1099
1100   /* Check any pending events.  This both avoids starting the thread
1101      unnecessarily, and handles stray FD_READ events (see below).  */
1102   if (WaitForSingleObject (state->sock_event, 0) == WAIT_OBJECT_0)
1103     {
1104       WSANETWORKEVENTS events;
1105       int any = 0;
1106
1107       /* Enumerate the internal network events, and reset the object that
1108          signalled us to catch the next event.  */
1109       WSAEnumNetworkEvents (scb->fd, state->sock_event, &events);
1110
1111       /* You'd think that FD_READ or FD_CLOSE would be set here.  But,
1112          sometimes, neither is.  I suspect that the FD_READ is set and
1113          the corresponding event signalled while recv is running, and
1114          the FD_READ is then lowered when recv consumes all the data,
1115          but there's no way to un-signal the event.  This isn't a
1116          problem for the call in net_select_thread, since any new
1117          events after this point will not have been drained by recv.
1118          It just means that we can't have the obvious assert here.  */
1119
1120       /* If there is a read event, it might be still valid, or it might
1121          not be - it may have been signalled before we last called
1122          recv.  Double-check that there is data.  */
1123       if (events.lNetworkEvents & FD_READ)
1124         {
1125           unsigned long available;
1126
1127           if (ioctlsocket (scb->fd, FIONREAD, &available) == 0
1128               && available > 0)
1129             {
1130               SetEvent (state->base.read_event);
1131               any = 1;
1132             }
1133           else
1134             /* Oops, no data.  This call to recv will cause future
1135                data to retrigger the event, e.g. while we are
1136                in net_select_thread.  */
1137             recv (scb->fd, NULL, 0, 0);
1138         }
1139
1140       /* If there's a close event, then record it - it is obviously
1141          still valid, and it will not be resignalled.  */
1142       if (events.lNetworkEvents & FD_CLOSE)
1143         {
1144           SetEvent (state->base.except_event);
1145           any = 1;
1146         }
1147
1148       /* If we set either handle, there's no need to wake the thread.  */
1149       if (any)
1150         return;
1151     }
1152
1153   start_select_thread (&state->base);
1154 }
1155
1156 static void
1157 net_windows_done_wait_handle (struct serial *scb)
1158 {
1159   struct net_windows_state *state = scb->state;
1160
1161   stop_select_thread (&state->base);
1162 }
1163
1164 static int
1165 net_windows_open (struct serial *scb, const char *name)
1166 {
1167   struct net_windows_state *state;
1168   int ret;
1169   DWORD threadId;
1170
1171   ret = net_open (scb, name);
1172   if (ret != 0)
1173     return ret;
1174
1175   state = xmalloc (sizeof (struct net_windows_state));
1176   memset (state, 0, sizeof (struct net_windows_state));
1177   scb->state = state;
1178
1179   /* Associate an event with the socket.  */
1180   state->sock_event = CreateEvent (0, TRUE, FALSE, 0);
1181   WSAEventSelect (scb->fd, state->sock_event, FD_READ | FD_CLOSE);
1182
1183   /* Start the thread.  */
1184   create_select_thread (net_windows_select_thread, scb, &state->base);
1185
1186   return 0;
1187 }
1188
1189
1190 static void
1191 net_windows_close (struct serial *scb)
1192 {
1193   struct net_windows_state *state = scb->state;
1194
1195   destroy_select_thread (&state->base);
1196   CloseHandle (state->sock_event);
1197
1198   xfree (scb->state);
1199
1200   net_close (scb);
1201 }
1202
1203 void
1204 _initialize_ser_windows (void)
1205 {
1206   WSADATA wsa_data;
1207   struct serial_ops *ops;
1208
1209   /* First register the serial port driver.  */
1210
1211   ops = XMALLOC (struct serial_ops);
1212   memset (ops, 0, sizeof (struct serial_ops));
1213   ops->name = "hardwire";
1214   ops->next = 0;
1215   ops->open = ser_windows_open;
1216   ops->close = ser_windows_close;
1217
1218   ops->flush_output = ser_windows_flush_output;
1219   ops->flush_input = ser_windows_flush_input;
1220   ops->send_break = ser_windows_send_break;
1221
1222   /* These are only used for stdin; we do not need them for serial
1223      ports, so supply the standard dummies.  */
1224   ops->get_tty_state = ser_base_get_tty_state;
1225   ops->set_tty_state = ser_base_set_tty_state;
1226   ops->print_tty_state = ser_base_print_tty_state;
1227   ops->noflush_set_tty_state = ser_base_noflush_set_tty_state;
1228
1229   ops->go_raw = ser_windows_raw;
1230   ops->setbaudrate = ser_windows_setbaudrate;
1231   ops->setstopbits = ser_windows_setstopbits;
1232   ops->drain_output = ser_windows_drain_output;
1233   ops->readchar = ser_base_readchar;
1234   ops->write = ser_base_write;
1235   ops->async = ser_base_async;
1236   ops->read_prim = ser_windows_read_prim;
1237   ops->write_prim = ser_windows_write_prim;
1238   ops->wait_handle = ser_windows_wait_handle;
1239
1240   serial_add_interface (ops);
1241
1242   /* Next create the dummy serial driver used for terminals.  We only
1243      provide the TTY-related methods.  */
1244
1245   ops = XMALLOC (struct serial_ops);
1246   memset (ops, 0, sizeof (struct serial_ops));
1247
1248   ops->name = "terminal";
1249   ops->next = 0;
1250
1251   ops->close = ser_console_close;
1252   ops->get_tty_state = ser_console_get_tty_state;
1253   ops->set_tty_state = ser_base_set_tty_state;
1254   ops->print_tty_state = ser_base_print_tty_state;
1255   ops->noflush_set_tty_state = ser_base_noflush_set_tty_state;
1256   ops->drain_output = ser_base_drain_output;
1257   ops->wait_handle = ser_console_wait_handle;
1258   ops->done_wait_handle = ser_console_done_wait_handle;
1259
1260   serial_add_interface (ops);
1261
1262   /* The pipe interface.  */
1263
1264   ops = XMALLOC (struct serial_ops);
1265   memset (ops, 0, sizeof (struct serial_ops));
1266   ops->name = "pipe";
1267   ops->next = 0;
1268   ops->open = pipe_windows_open;
1269   ops->close = pipe_windows_close;
1270   ops->fdopen = pipe_windows_fdopen;
1271   ops->readchar = ser_base_readchar;
1272   ops->write = ser_base_write;
1273   ops->flush_output = ser_base_flush_output;
1274   ops->flush_input = ser_base_flush_input;
1275   ops->send_break = ser_base_send_break;
1276   ops->go_raw = ser_base_raw;
1277   ops->get_tty_state = ser_base_get_tty_state;
1278   ops->set_tty_state = ser_base_set_tty_state;
1279   ops->print_tty_state = ser_base_print_tty_state;
1280   ops->noflush_set_tty_state = ser_base_noflush_set_tty_state;
1281   ops->setbaudrate = ser_base_setbaudrate;
1282   ops->setstopbits = ser_base_setstopbits;
1283   ops->drain_output = ser_base_drain_output;
1284   ops->async = ser_base_async;
1285   ops->read_prim = pipe_windows_read;
1286   ops->write_prim = pipe_windows_write;
1287   ops->wait_handle = pipe_wait_handle;
1288   ops->done_wait_handle = pipe_done_wait_handle;
1289   ops->avail = pipe_avail;
1290
1291   serial_add_interface (ops);
1292
1293   /* If WinSock works, register the TCP/UDP socket driver.  */
1294
1295   if (WSAStartup (MAKEWORD (1, 0), &wsa_data) != 0)
1296     /* WinSock is unavailable.  */
1297     return;
1298
1299   ops = XMALLOC (struct serial_ops);
1300   memset (ops, 0, sizeof (struct serial_ops));
1301   ops->name = "tcp";
1302   ops->next = 0;
1303   ops->open = net_windows_open;
1304   ops->close = net_windows_close;
1305   ops->readchar = ser_base_readchar;
1306   ops->write = ser_base_write;
1307   ops->flush_output = ser_base_flush_output;
1308   ops->flush_input = ser_base_flush_input;
1309   ops->send_break = ser_tcp_send_break;
1310   ops->go_raw = ser_base_raw;
1311   ops->get_tty_state = ser_base_get_tty_state;
1312   ops->set_tty_state = ser_base_set_tty_state;
1313   ops->print_tty_state = ser_base_print_tty_state;
1314   ops->noflush_set_tty_state = ser_base_noflush_set_tty_state;
1315   ops->setbaudrate = ser_base_setbaudrate;
1316   ops->setstopbits = ser_base_setstopbits;
1317   ops->drain_output = ser_base_drain_output;
1318   ops->async = ser_base_async;
1319   ops->read_prim = net_read_prim;
1320   ops->write_prim = net_write_prim;
1321   ops->wait_handle = net_windows_wait_handle;
1322   ops->done_wait_handle = net_windows_done_wait_handle;
1323   serial_add_interface (ops);
1324 }