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