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