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