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