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