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