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