gdb/ser-mingw.c - gdb

Global variables defined

Data types defined

Functions defined

Macros defined

Source code

  1. /* Serial interface for local (hardwired) serial ports on Windows systems

  2.    Copyright (C) 2006-2015 Free Software Foundation, Inc.

  3.    This file is part of GDB.

  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 3 of the License, or
  7.    (at your option) any later version.

  8.    This program is distributed in the hope that it will be useful,
  9.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  10.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  11.    GNU General Public License for more details.

  12.    You should have received a copy of the GNU General Public License
  13.    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */

  14. #include "defs.h"
  15. #include "serial.h"
  16. #include "ser-base.h"
  17. #include "ser-tcp.h"

  18. #include <windows.h>
  19. #include <conio.h>

  20. #include <fcntl.h>
  21. #include <unistd.h>
  22. #include <sys/types.h>

  23. #include "command.h"

  24. void _initialize_ser_windows (void);

  25. struct ser_windows_state
  26. {
  27.   int in_progress;
  28.   OVERLAPPED ov;
  29.   DWORD lastCommMask;
  30.   HANDLE except_event;
  31. };

  32. /* CancelIo is not available for Windows 95 OS, so we need to use
  33.    LoadLibrary/GetProcAddress to avoid a startup failure.  */
  34. #define CancelIo dyn_CancelIo
  35. static BOOL WINAPI (*CancelIo) (HANDLE);

  36. /* Open up a real live device for serial I/O.  */

  37. static int
  38. ser_windows_open (struct serial *scb, const char *name)
  39. {
  40.   HANDLE h;
  41.   struct ser_windows_state *state;
  42.   COMMTIMEOUTS timeouts;

  43.   h = CreateFile (name, GENERIC_READ | GENERIC_WRITE, 0, NULL,
  44.                   OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
  45.   if (h == INVALID_HANDLE_VALUE)
  46.     {
  47.       errno = ENOENT;
  48.       return -1;
  49.     }

  50.   scb->fd = _open_osfhandle ((intptr_t) h, O_RDWR);
  51.   if (scb->fd < 0)
  52.     {
  53.       errno = ENOENT;
  54.       return -1;
  55.     }

  56.   if (!SetCommMask (h, EV_RXCHAR))
  57.     {
  58.       errno = EINVAL;
  59.       return -1;
  60.     }

  61.   timeouts.ReadIntervalTimeout = MAXDWORD;
  62.   timeouts.ReadTotalTimeoutConstant = 0;
  63.   timeouts.ReadTotalTimeoutMultiplier = 0;
  64.   timeouts.WriteTotalTimeoutConstant = 0;
  65.   timeouts.WriteTotalTimeoutMultiplier = 0;
  66.   if (!SetCommTimeouts (h, &timeouts))
  67.     {
  68.       errno = EINVAL;
  69.       return -1;
  70.     }

  71.   state = xmalloc (sizeof (struct ser_windows_state));
  72.   memset (state, 0, sizeof (struct ser_windows_state));
  73.   scb->state = state;

  74.   /* Create a manual reset event to watch the input buffer.  */
  75.   state->ov.hEvent = CreateEvent (0, TRUE, FALSE, 0);

  76.   /* Create a (currently unused) handle to record exceptions.  */
  77.   state->except_event = CreateEvent (0, TRUE, FALSE, 0);

  78.   return 0;
  79. }

  80. /* Wait for the output to drain away, as opposed to flushing (discarding)
  81.    it.  */

  82. static int
  83. ser_windows_drain_output (struct serial *scb)
  84. {
  85.   HANDLE h = (HANDLE) _get_osfhandle (scb->fd);

  86.   return (FlushFileBuffers (h) != 0) ? 0 : -1;
  87. }

  88. static int
  89. ser_windows_flush_output (struct serial *scb)
  90. {
  91.   HANDLE h = (HANDLE) _get_osfhandle (scb->fd);

  92.   return (PurgeComm (h, PURGE_TXCLEAR) != 0) ? 0 : -1;
  93. }

  94. static int
  95. ser_windows_flush_input (struct serial *scb)
  96. {
  97.   HANDLE h = (HANDLE) _get_osfhandle (scb->fd);

  98.   return (PurgeComm (h, PURGE_RXCLEAR) != 0) ? 0 : -1;
  99. }

  100. static int
  101. ser_windows_send_break (struct serial *scb)
  102. {
  103.   HANDLE h = (HANDLE) _get_osfhandle (scb->fd);

  104.   if (SetCommBreak (h) == 0)
  105.     return -1;

  106.   /* Delay for 250 milliseconds.  */
  107.   Sleep (250);

  108.   if (ClearCommBreak (h))
  109.     return -1;

  110.   return 0;
  111. }

  112. static void
  113. ser_windows_raw (struct serial *scb)
  114. {
  115.   HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
  116.   DCB state;

  117.   if (GetCommState (h, &state) == 0)
  118.     return;

  119.   state.fParity = FALSE;
  120.   state.fOutxCtsFlow = FALSE;
  121.   state.fOutxDsrFlow = FALSE;
  122.   state.fDtrControl = DTR_CONTROL_ENABLE;
  123.   state.fDsrSensitivity = FALSE;
  124.   state.fOutX = FALSE;
  125.   state.fInX = FALSE;
  126.   state.fNull = FALSE;
  127.   state.fAbortOnError = FALSE;
  128.   state.ByteSize = 8;
  129.   state.Parity = NOPARITY;

  130.   scb->current_timeout = 0;

  131.   if (SetCommState (h, &state) == 0)
  132.     warning (_("SetCommState failed"));
  133. }

  134. static int
  135. ser_windows_setstopbits (struct serial *scb, int num)
  136. {
  137.   HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
  138.   DCB state;

  139.   if (GetCommState (h, &state) == 0)
  140.     return -1;

  141.   switch (num)
  142.     {
  143.     case SERIAL_1_STOPBITS:
  144.       state.StopBits = ONESTOPBIT;
  145.       break;
  146.     case SERIAL_1_AND_A_HALF_STOPBITS:
  147.       state.StopBits = ONE5STOPBITS;
  148.       break;
  149.     case SERIAL_2_STOPBITS:
  150.       state.StopBits = TWOSTOPBITS;
  151.       break;
  152.     default:
  153.       return 1;
  154.     }

  155.   return (SetCommState (h, &state) != 0) ? 0 : -1;
  156. }

  157. static int
  158. ser_windows_setbaudrate (struct serial *scb, int rate)
  159. {
  160.   HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
  161.   DCB state;

  162.   if (GetCommState (h, &state) == 0)
  163.     return -1;

  164.   state.BaudRate = rate;

  165.   return (SetCommState (h, &state) != 0) ? 0 : -1;
  166. }

  167. static void
  168. ser_windows_close (struct serial *scb)
  169. {
  170.   struct ser_windows_state *state;

  171.   /* Stop any pending selects.  On Windows 95 OS, CancelIo function does
  172.      not exist.  In that case, it can be replaced by a call to CloseHandle,
  173.      but this is not necessary here as we do close the Windows handle
  174.      by calling close (scb->fd) below.  */
  175.   if (CancelIo)
  176.     CancelIo ((HANDLE) _get_osfhandle (scb->fd));
  177.   state = scb->state;
  178.   CloseHandle (state->ov.hEvent);
  179.   CloseHandle (state->except_event);

  180.   if (scb->fd < 0)
  181.     return;

  182.   close (scb->fd);
  183.   scb->fd = -1;

  184.   xfree (scb->state);
  185. }

  186. static void
  187. ser_windows_wait_handle (struct serial *scb, HANDLE *read, HANDLE *except)
  188. {
  189.   struct ser_windows_state *state;
  190.   COMSTAT status;
  191.   DWORD errors;
  192.   HANDLE h = (HANDLE) _get_osfhandle (scb->fd);

  193.   state = scb->state;

  194.   *except = state->except_event;
  195.   *read = state->ov.hEvent;

  196.   if (state->in_progress)
  197.     return;

  198.   /* Reset the mask - we are only interested in any characters which
  199.      arrive after this point, not characters which might have arrived
  200.      and already been read.  */

  201.   /* This really, really shouldn't be necessary - just the second one.
  202.      But otherwise an internal flag for EV_RXCHAR does not get
  203.      cleared, and we get a duplicated event, if the last batch
  204.      of characters included at least two arriving close together.  */
  205.   if (!SetCommMask (h, 0))
  206.     warning (_("ser_windows_wait_handle: reseting mask failed"));

  207.   if (!SetCommMask (h, EV_RXCHAR))
  208.     warning (_("ser_windows_wait_handle: reseting mask failed (2)"));

  209.   /* There's a potential race condition here; we must check cbInQue
  210.      and not wait if that's nonzero.  */

  211.   ClearCommError (h, &errors, &status);
  212.   if (status.cbInQue > 0)
  213.     {
  214.       SetEvent (state->ov.hEvent);
  215.       return;
  216.     }

  217.   state->in_progress = 1;
  218.   ResetEvent (state->ov.hEvent);
  219.   state->lastCommMask = -2;
  220.   if (WaitCommEvent (h, &state->lastCommMask, &state->ov))
  221.     {
  222.       gdb_assert (state->lastCommMask & EV_RXCHAR);
  223.       SetEvent (state->ov.hEvent);
  224.     }
  225.   else
  226.     gdb_assert (GetLastError () == ERROR_IO_PENDING);
  227. }

  228. static int
  229. ser_windows_read_prim (struct serial *scb, size_t count)
  230. {
  231.   struct ser_windows_state *state;
  232.   OVERLAPPED ov;
  233.   DWORD bytes_read, bytes_read_tmp;
  234.   HANDLE h;
  235.   gdb_byte *p;

  236.   state = scb->state;
  237.   if (state->in_progress)
  238.     {
  239.       WaitForSingleObject (state->ov.hEvent, INFINITE);
  240.       state->in_progress = 0;
  241.       ResetEvent (state->ov.hEvent);
  242.     }

  243.   memset (&ov, 0, sizeof (OVERLAPPED));
  244.   ov.hEvent = CreateEvent (0, FALSE, FALSE, 0);
  245.   h = (HANDLE) _get_osfhandle (scb->fd);

  246.   if (!ReadFile (h, scb->buf, /* count */ 1, &bytes_read, &ov))
  247.     {
  248.       if (GetLastError () != ERROR_IO_PENDING
  249.           || !GetOverlappedResult (h, &ov, &bytes_read, TRUE))
  250.         bytes_read = -1;
  251.     }

  252.   CloseHandle (ov.hEvent);
  253.   return bytes_read;
  254. }

  255. static int
  256. ser_windows_write_prim (struct serial *scb, const void *buf, size_t len)
  257. {
  258.   struct ser_windows_state *state;
  259.   OVERLAPPED ov;
  260.   DWORD bytes_written;
  261.   HANDLE h;

  262.   memset (&ov, 0, sizeof (OVERLAPPED));
  263.   ov.hEvent = CreateEvent (0, FALSE, FALSE, 0);
  264.   h = (HANDLE) _get_osfhandle (scb->fd);
  265.   if (!WriteFile (h, buf, len, &bytes_written, &ov))
  266.     {
  267.       if (GetLastError () != ERROR_IO_PENDING
  268.           || !GetOverlappedResult (h, &ov, &bytes_written, TRUE))
  269.         bytes_written = -1;
  270.     }

  271.   CloseHandle (ov.hEvent);
  272.   return bytes_written;
  273. }

  274. /* On Windows, gdb_select is implemented using WaitForMulpleObjects.
  275.    A "select thread" is created for each file descriptor.  These
  276.    threads looks for activity on the corresponding descriptor, using
  277.    whatever techniques are appropriate for the descriptor type.  When
  278.    that activity occurs, the thread signals an appropriate event,
  279.    which wakes up WaitForMultipleObjects.

  280.    Each select thread is in one of two states: stopped or started.
  281.    Select threads begin in the stopped state.  When gdb_select is
  282.    called, threads corresponding to the descriptors of interest are
  283.    started by calling a wait_handle function.  Each thread that
  284.    notices activity signals the appropriate event and then reenters
  285.    the stopped state.  Before gdb_select returns it calls the
  286.    wait_handle_done functions, which return the threads to the stopped
  287.    state.  */

  288. enum select_thread_state {
  289.   STS_STARTED,
  290.   STS_STOPPED
  291. };

  292. struct ser_console_state
  293. {
  294.   /* Signaled by the select thread to indicate that data is available
  295.      on the file descriptor.  */
  296.   HANDLE read_event;
  297.   /* Signaled by the select thread to indicate that an exception has
  298.      occurred on the file descriptor.  */
  299.   HANDLE except_event;
  300.   /* Signaled by the select thread to indicate that it has entered the
  301.      started state.  HAVE_STARTED and HAVE_STOPPED are never signaled
  302.      simultaneously.  */
  303.   HANDLE have_started;
  304.   /* Signaled by the select thread to indicate that it has stopped,
  305.      either because data is available (and READ_EVENT is signaled),
  306.      because an exception has occurred (and EXCEPT_EVENT is signaled),
  307.      or because STOP_SELECT was signaled.  */
  308.   HANDLE have_stopped;

  309.   /* Signaled by the main program to tell the select thread to enter
  310.      the started state.  */
  311.   HANDLE start_select;
  312.   /* Signaled by the main program to tell the select thread to enter
  313.      the stopped state.  */
  314.   HANDLE stop_select;
  315.   /* Signaled by the main program to tell the select thread to
  316.      exit.  */
  317.   HANDLE exit_select;

  318.   /* The handle for the select thread.  */
  319.   HANDLE thread;
  320.   /* The state of the select thread.  This field is only accessed in
  321.      the main program, never by the select thread itself.  */
  322.   enum select_thread_state thread_state;
  323. };

  324. /* Called by a select thread to enter the stopped state.  This
  325.    function does not return until the thread has re-entered the
  326.    started state.  */
  327. static void
  328. select_thread_wait (struct ser_console_state *state)
  329. {
  330.   HANDLE wait_events[2];

  331.   /* There are two things that can wake us up: a request that we enter
  332.      the started state, or that we exit this thread.  */
  333.   wait_events[0] = state->start_select;
  334.   wait_events[1] = state->exit_select;
  335.   if (WaitForMultipleObjects (2, wait_events, FALSE, INFINITE)
  336.       != WAIT_OBJECT_0)
  337.     /* Either the EXIT_SELECT event was signaled (requesting that the
  338.        thread exit) or an error has occurred.  In either case, we exit
  339.        the thread.  */
  340.     ExitThread (0);

  341.   /* We are now in the started state.  */
  342.   SetEvent (state->have_started);
  343. }

  344. typedef DWORD WINAPI (*thread_fn_type)(void *);

  345. /* Create a new select thread for SCB executing THREAD_FN.  The STATE
  346.    will be filled in by this function before return.  */
  347. static void
  348. create_select_thread (thread_fn_type thread_fn,
  349.                       struct serial *scb,
  350.                       struct ser_console_state *state)
  351. {
  352.   DWORD threadId;

  353.   /* Create all of the events.  These are all auto-reset events.  */
  354.   state->read_event = CreateEvent (NULL, FALSE, FALSE, NULL);
  355.   state->except_event = CreateEvent (NULL, FALSE, FALSE, NULL);
  356.   state->have_started = CreateEvent (NULL, FALSE, FALSE, NULL);
  357.   state->have_stopped = CreateEvent (NULL, FALSE, FALSE, NULL);
  358.   state->start_select = CreateEvent (NULL, FALSE, FALSE, NULL);
  359.   state->stop_select = CreateEvent (NULL, FALSE, FALSE, NULL);
  360.   state->exit_select = CreateEvent (NULL, FALSE, FALSE, NULL);

  361.   state->thread = CreateThread (NULL, 0, thread_fn, scb, 0, &threadId);
  362.   /* The thread begins in the stopped state.  */
  363.   state->thread_state = STS_STOPPED;
  364. }

  365. /* Destroy the select thread indicated by STATE.  */
  366. static void
  367. destroy_select_thread (struct ser_console_state *state)
  368. {
  369.   /* Ask the thread to exit.  */
  370.   SetEvent (state->exit_select);
  371.   /* Wait until it does.  */
  372.   WaitForSingleObject (state->thread, INFINITE);

  373.   /* Destroy the events.  */
  374.   CloseHandle (state->read_event);
  375.   CloseHandle (state->except_event);
  376.   CloseHandle (state->have_started);
  377.   CloseHandle (state->have_stopped);
  378.   CloseHandle (state->start_select);
  379.   CloseHandle (state->stop_select);
  380.   CloseHandle (state->exit_select);
  381. }

  382. /* Called by gdb_select to start the select thread indicated by STATE.
  383.    This function does not return until the thread has started.  */
  384. static void
  385. start_select_thread (struct ser_console_state *state)
  386. {
  387.   /* Ask the thread to start.  */
  388.   SetEvent (state->start_select);
  389.   /* Wait until it does.  */
  390.   WaitForSingleObject (state->have_started, INFINITE);
  391.   /* The thread is now started.  */
  392.   state->thread_state = STS_STARTED;
  393. }

  394. /* Called by gdb_select to stop the select thread indicated by STATE.
  395.    This function does not return until the thread has stopped.  */
  396. static void
  397. stop_select_thread (struct ser_console_state *state)
  398. {
  399.   /* If the thread is already in the stopped state, we have nothing to
  400.      do.  Some of the wait_handle functions avoid calling
  401.      start_select_thread if they notice activity on the relevant file
  402.      descriptors.  The wait_handle_done functions still call
  403.      stop_select_thread -- but it is already stopped.  */
  404.   if (state->thread_state != STS_STARTED)
  405.     return;
  406.   /* Ask the thread to stop.  */
  407.   SetEvent (state->stop_select);
  408.   /* Wait until it does.  */
  409.   WaitForSingleObject (state->have_stopped, INFINITE);
  410.   /* The thread is now stopped.  */
  411.   state->thread_state = STS_STOPPED;
  412. }

  413. static DWORD WINAPI
  414. console_select_thread (void *arg)
  415. {
  416.   struct serial *scb = arg;
  417.   struct ser_console_state *state;
  418.   int event_index;
  419.   HANDLE h;

  420.   state = scb->state;
  421.   h = (HANDLE) _get_osfhandle (scb->fd);

  422.   while (1)
  423.     {
  424.       HANDLE wait_events[2];
  425.       INPUT_RECORD record;
  426.       DWORD n_records;

  427.       select_thread_wait (state);

  428.       while (1)
  429.         {
  430.           wait_events[0] = state->stop_select;
  431.           wait_events[1] = h;

  432.           event_index = WaitForMultipleObjects (2, wait_events,
  433.                                                 FALSE, INFINITE);

  434.           if (event_index == WAIT_OBJECT_0
  435.               || WaitForSingleObject (state->stop_select, 0) == WAIT_OBJECT_0)
  436.             break;

  437.           if (event_index != WAIT_OBJECT_0 + 1)
  438.             {
  439.               /* Wait must have failed; assume an error has occured, e.g.
  440.                  the handle has been closed.  */
  441.               SetEvent (state->except_event);
  442.               break;
  443.             }

  444.           /* We've got a pending event on the console.  See if it's
  445.              of interest.  */
  446.           if (!PeekConsoleInput (h, &record, 1, &n_records) || n_records != 1)
  447.             {
  448.               /* Something went wrong.  Maybe the console is gone.  */
  449.               SetEvent (state->except_event);
  450.               break;
  451.             }

  452.           if (record.EventType == KEY_EVENT && record.Event.KeyEvent.bKeyDown)
  453.             {
  454.               WORD keycode = record.Event.KeyEvent.wVirtualKeyCode;

  455.               /* Ignore events containing only control keys.  We must
  456.                  recognize "enhanced" keys which we are interested in
  457.                  reading via getch, if they do not map to ASCII.  But we
  458.                  do not want to report input available for e.g. the
  459.                  control key alone.  */

  460.               if (record.Event.KeyEvent.uChar.AsciiChar != 0
  461.                   || keycode == VK_PRIOR
  462.                   || keycode == VK_NEXT
  463.                   || keycode == VK_END
  464.                   || keycode == VK_HOME
  465.                   || keycode == VK_LEFT
  466.                   || keycode == VK_UP
  467.                   || keycode == VK_RIGHT
  468.                   || keycode == VK_DOWN
  469.                   || keycode == VK_INSERT
  470.                   || keycode == VK_DELETE)
  471.                 {
  472.                   /* This is really a keypress.  */
  473.                   SetEvent (state->read_event);
  474.                   break;
  475.                 }
  476.             }

  477.           /* Otherwise discard it and wait again.  */
  478.           ReadConsoleInput (h, &record, 1, &n_records);
  479.         }

  480.       SetEvent(state->have_stopped);
  481.     }
  482.   return 0;
  483. }

  484. static int
  485. fd_is_pipe (int fd)
  486. {
  487.   if (PeekNamedPipe ((HANDLE) _get_osfhandle (fd), NULL, 0, NULL, NULL, NULL))
  488.     return 1;
  489.   else
  490.     return 0;
  491. }

  492. static int
  493. fd_is_file (int fd)
  494. {
  495.   if (GetFileType ((HANDLE) _get_osfhandle (fd)) == FILE_TYPE_DISK)
  496.     return 1;
  497.   else
  498.     return 0;
  499. }

  500. static DWORD WINAPI
  501. pipe_select_thread (void *arg)
  502. {
  503.   struct serial *scb = arg;
  504.   struct ser_console_state *state;
  505.   int event_index;
  506.   HANDLE h;

  507.   state = scb->state;
  508.   h = (HANDLE) _get_osfhandle (scb->fd);

  509.   while (1)
  510.     {
  511.       DWORD n_avail;

  512.       select_thread_wait (state);

  513.       /* Wait for something to happen on the pipe.  */
  514.       while (1)
  515.         {
  516.           if (!PeekNamedPipe (h, NULL, 0, NULL, &n_avail, NULL))
  517.             {
  518.               SetEvent (state->except_event);
  519.               break;
  520.             }

  521.           if (n_avail > 0)
  522.             {
  523.               SetEvent (state->read_event);
  524.               break;
  525.             }

  526.           /* Delay 10ms before checking again, but allow the stop
  527.              event to wake us.  */
  528.           if (WaitForSingleObject (state->stop_select, 10) == WAIT_OBJECT_0)
  529.             break;
  530.         }

  531.       SetEvent (state->have_stopped);
  532.     }
  533.   return 0;
  534. }

  535. static DWORD WINAPI
  536. file_select_thread (void *arg)
  537. {
  538.   struct serial *scb = arg;
  539.   struct ser_console_state *state;
  540.   int event_index;
  541.   HANDLE h;

  542.   state = scb->state;
  543.   h = (HANDLE) _get_osfhandle (scb->fd);

  544.   while (1)
  545.     {
  546.       select_thread_wait (state);

  547.       if (SetFilePointer (h, 0, NULL, FILE_CURRENT)
  548.           == INVALID_SET_FILE_POINTER)
  549.         SetEvent (state->except_event);
  550.       else
  551.         SetEvent (state->read_event);

  552.       SetEvent (state->have_stopped);
  553.     }
  554.   return 0;
  555. }

  556. static void
  557. ser_console_wait_handle (struct serial *scb, HANDLE *read, HANDLE *except)
  558. {
  559.   struct ser_console_state *state = scb->state;

  560.   if (state == NULL)
  561.     {
  562.       thread_fn_type thread_fn;
  563.       int is_tty;

  564.       is_tty = isatty (scb->fd);
  565.       if (!is_tty && !fd_is_file (scb->fd) && !fd_is_pipe (scb->fd))
  566.         {
  567.           *read = NULL;
  568.           *except = NULL;
  569.           return;
  570.         }

  571.       state = xmalloc (sizeof (struct ser_console_state));
  572.       memset (state, 0, sizeof (struct ser_console_state));
  573.       scb->state = state;

  574.       if (is_tty)
  575.         thread_fn = console_select_thread;
  576.       else if (fd_is_pipe (scb->fd))
  577.         thread_fn = pipe_select_thread;
  578.       else
  579.         thread_fn = file_select_thread;

  580.       create_select_thread (thread_fn, scb, state);
  581.     }

  582.   *read = state->read_event;
  583.   *except = state->except_event;

  584.   /* Start from a blank state.  */
  585.   ResetEvent (state->read_event);
  586.   ResetEvent (state->except_event);
  587.   ResetEvent (state->stop_select);

  588.   /* First check for a key already in the buffer.  If there is one,
  589.      we don't need a thread.  This also catches the second key of
  590.      multi-character returns from getch, for instance for arrow
  591.      keys.  The second half is in a C library internal buffer,
  592.      and PeekConsoleInput will not find it.  */
  593.   if (_kbhit ())
  594.     {
  595.       SetEvent (state->read_event);
  596.       return;
  597.     }

  598.   /* Otherwise, start the select thread.  */
  599.   start_select_thread (state);
  600. }

  601. static void
  602. ser_console_done_wait_handle (struct serial *scb)
  603. {
  604.   struct ser_console_state *state = scb->state;

  605.   if (state == NULL)
  606.     return;

  607.   stop_select_thread (state);
  608. }

  609. static void
  610. ser_console_close (struct serial *scb)
  611. {
  612.   struct ser_console_state *state = scb->state;

  613.   if (scb->state)
  614.     {
  615.       destroy_select_thread (state);
  616.       xfree (scb->state);
  617.     }
  618. }

  619. struct ser_console_ttystate
  620. {
  621.   int is_a_tty;
  622. };

  623. static serial_ttystate
  624. ser_console_get_tty_state (struct serial *scb)
  625. {
  626.   if (isatty (scb->fd))
  627.     {
  628.       struct ser_console_ttystate *state;

  629.       state = (struct ser_console_ttystate *) xmalloc (sizeof *state);
  630.       state->is_a_tty = 1;
  631.       return state;
  632.     }
  633.   else
  634.     return NULL;
  635. }

  636. struct pipe_state
  637. {
  638.   /* Since we use the pipe_select_thread for our select emulation,
  639.      we need to place the state structure it requires at the front
  640.      of our state.  */
  641.   struct ser_console_state wait;

  642.   /* The pex obj for our (one-stage) pipeline.  */
  643.   struct pex_obj *pex;

  644.   /* Streams for the pipeline's input and output.  */
  645.   FILE *input, *output;
  646. };

  647. static struct pipe_state *
  648. make_pipe_state (void)
  649. {
  650.   struct pipe_state *ps = XNEW (struct pipe_state);

  651.   memset (ps, 0, sizeof (*ps));
  652.   ps->wait.read_event = INVALID_HANDLE_VALUE;
  653.   ps->wait.except_event = INVALID_HANDLE_VALUE;
  654.   ps->wait.start_select = INVALID_HANDLE_VALUE;
  655.   ps->wait.stop_select = INVALID_HANDLE_VALUE;

  656.   return ps;
  657. }

  658. static void
  659. free_pipe_state (struct pipe_state *ps)
  660. {
  661.   int saved_errno = errno;

  662.   if (ps->wait.read_event != INVALID_HANDLE_VALUE)
  663.     destroy_select_thread (&ps->wait);

  664.   /* Close the pipe to the child.  We must close the pipe before
  665.      calling pex_free because pex_free will wait for the child to exit
  666.      and the child will not exit until the pipe is closed.  */
  667.   if (ps->input)
  668.     fclose (ps->input);
  669.   if (ps->pex)
  670.     {
  671.       pex_free (ps->pex);
  672.       /* pex_free closes ps->output.  */
  673.     }
  674.   else if (ps->output)
  675.     fclose (ps->output);

  676.   xfree (ps);

  677.   errno = saved_errno;
  678. }

  679. static void
  680. cleanup_pipe_state (void *untyped)
  681. {
  682.   struct pipe_state *ps = untyped;

  683.   free_pipe_state (ps);
  684. }

  685. static int
  686. pipe_windows_open (struct serial *scb, const char *name)
  687. {
  688.   struct pipe_state *ps;
  689.   FILE *pex_stderr;
  690.   char **argv;
  691.   struct cleanup *back_to;

  692.   if (name == NULL)
  693.     error_no_arg (_("child command"));

  694.   argv = gdb_buildargv (name);
  695.   back_to = make_cleanup_freeargv (argv);

  696.   if (! argv[0] || argv[0][0] == '\0')
  697.     error (_("missing child command"));

  698.   ps = make_pipe_state ();
  699.   make_cleanup (cleanup_pipe_state, ps);

  700.   ps->pex = pex_init (PEX_USE_PIPES, "target remote pipe", NULL);
  701.   if (! ps->pex)
  702.     goto fail;
  703.   ps->input = pex_input_pipe (ps->pex, 1);
  704.   if (! ps->input)
  705.     goto fail;

  706.   {
  707.     int err;
  708.     const char *err_msg
  709.       = pex_run (ps->pex, PEX_SEARCH | PEX_BINARY_INPUT | PEX_BINARY_OUTPUT
  710.                  | PEX_STDERR_TO_PIPE,
  711.                  argv[0], argv, NULL, NULL,
  712.                  &err);

  713.     if (err_msg)
  714.       {
  715.         /* Our caller expects us to return -1, but all they'll do with
  716.            it generally is print the message based on errno.  We have
  717.            all the same information here, plus err_msg provided by
  718.            pex_run, so we just raise the error here.  */
  719.         if (err)
  720.           error (_("error starting child process '%s': %s: %s"),
  721.                  name, err_msg, safe_strerror (err));
  722.         else
  723.           error (_("error starting child process '%s': %s"),
  724.                  name, err_msg);
  725.       }
  726.   }

  727.   ps->output = pex_read_output (ps->pex, 1);
  728.   if (! ps->output)
  729.     goto fail;
  730.   scb->fd = fileno (ps->output);

  731.   pex_stderr = pex_read_err (ps->pex, 1);
  732.   if (! pex_stderr)
  733.     goto fail;
  734.   scb->error_fd = fileno (pex_stderr);

  735.   scb->state = (void *) ps;

  736.   discard_cleanups (back_to);
  737.   return 0;

  738. fail:
  739.   do_cleanups (back_to);
  740.   return -1;
  741. }

  742. static int
  743. pipe_windows_fdopen (struct serial *scb, int fd)
  744. {
  745.   struct pipe_state *ps;

  746.   ps = make_pipe_state ();

  747.   ps->input = fdopen (fd, "r+");
  748.   if (! ps->input)
  749.     goto fail;

  750.   ps->output = fdopen (fd, "r+");
  751.   if (! ps->output)
  752.     goto fail;

  753.   scb->fd = fd;
  754.   scb->state = (void *) ps;

  755.   return 0;

  756. fail:
  757.   free_pipe_state (ps);
  758.   return -1;
  759. }

  760. static void
  761. pipe_windows_close (struct serial *scb)
  762. {
  763.   struct pipe_state *ps = scb->state;

  764.   /* In theory, we should try to kill the subprocess here, but the pex
  765.      interface doesn't give us enough information to do that.  Usually
  766.      closing the input pipe will get the message across.  */

  767.   free_pipe_state (ps);
  768. }


  769. static int
  770. pipe_windows_read (struct serial *scb, size_t count)
  771. {
  772.   HANDLE pipeline_out = (HANDLE) _get_osfhandle (scb->fd);
  773.   DWORD available;
  774.   DWORD bytes_read;

  775.   if (pipeline_out == INVALID_HANDLE_VALUE)
  776.     return -1;

  777.   if (! PeekNamedPipe (pipeline_out, NULL, 0, NULL, &available, NULL))
  778.     return -1;

  779.   if (count > available)
  780.     count = available;

  781.   if (! ReadFile (pipeline_out, scb->buf, count, &bytes_read, NULL))
  782.     return -1;

  783.   return bytes_read;
  784. }


  785. static int
  786. pipe_windows_write (struct serial *scb, const void *buf, size_t count)
  787. {
  788.   struct pipe_state *ps = scb->state;
  789.   HANDLE pipeline_in;
  790.   DWORD written;

  791.   int pipeline_in_fd = fileno (ps->input);
  792.   if (pipeline_in_fd < 0)
  793.     return -1;

  794.   pipeline_in = (HANDLE) _get_osfhandle (pipeline_in_fd);
  795.   if (pipeline_in == INVALID_HANDLE_VALUE)
  796.     return -1;

  797.   if (! WriteFile (pipeline_in, buf, count, &written, NULL))
  798.     return -1;

  799.   return written;
  800. }


  801. static void
  802. pipe_wait_handle (struct serial *scb, HANDLE *read, HANDLE *except)
  803. {
  804.   struct pipe_state *ps = scb->state;

  805.   /* Have we allocated our events yet?  */
  806.   if (ps->wait.read_event == INVALID_HANDLE_VALUE)
  807.     /* Start the thread.  */
  808.     create_select_thread (pipe_select_thread, scb, &ps->wait);

  809.   *read = ps->wait.read_event;
  810.   *except = ps->wait.except_event;

  811.   /* Start from a blank state.  */
  812.   ResetEvent (ps->wait.read_event);
  813.   ResetEvent (ps->wait.except_event);
  814.   ResetEvent (ps->wait.stop_select);

  815.   start_select_thread (&ps->wait);
  816. }

  817. static void
  818. pipe_done_wait_handle (struct serial *scb)
  819. {
  820.   struct pipe_state *ps = scb->state;

  821.   /* Have we allocated our events yet?  */
  822.   if (ps->wait.read_event == INVALID_HANDLE_VALUE)
  823.     return;

  824.   stop_select_thread (&ps->wait);
  825. }

  826. static int
  827. pipe_avail (struct serial *scb, int fd)
  828. {
  829.   HANDLE h = (HANDLE) _get_osfhandle (fd);
  830.   DWORD numBytes;
  831.   BOOL r = PeekNamedPipe (h, NULL, 0, NULL, &numBytes, NULL);

  832.   if (r == FALSE)
  833.     numBytes = 0;
  834.   return numBytes;
  835. }

  836. int
  837. gdb_pipe (int pdes[2])
  838. {
  839.   if (_pipe (pdes, 512, _O_BINARY | _O_NOINHERIT) == -1)
  840.     return -1;
  841.   return 0;
  842. }

  843. struct net_windows_state
  844. {
  845.   struct ser_console_state base;

  846.   HANDLE sock_event;
  847. };

  848. /* Check whether the socket has any pending data to be read.  If so,
  849.    set the select thread's read event.  On error, set the select
  850.    thread's except event.  If any event was set, return true,
  851.    otherwise return false.  */

  852. static int
  853. net_windows_socket_check_pending (struct serial *scb)
  854. {
  855.   struct net_windows_state *state = scb->state;
  856.   unsigned long available;

  857.   if (ioctlsocket (scb->fd, FIONREAD, &available) != 0)
  858.     {
  859.       /* The socket closed, or some other error.  */
  860.       SetEvent (state->base.except_event);
  861.       return 1;
  862.     }
  863.   else if (available > 0)
  864.     {
  865.       SetEvent (state->base.read_event);
  866.       return 1;
  867.     }

  868.   return 0;
  869. }

  870. static DWORD WINAPI
  871. net_windows_select_thread (void *arg)
  872. {
  873.   struct serial *scb = arg;
  874.   struct net_windows_state *state;
  875.   int event_index;

  876.   state = scb->state;

  877.   while (1)
  878.     {
  879.       HANDLE wait_events[2];
  880.       WSANETWORKEVENTS events;

  881.       select_thread_wait (&state->base);

  882.       wait_events[0] = state->base.stop_select;
  883.       wait_events[1] = state->sock_event;

  884.       /* Wait for something to happen on the socket.  */
  885.       while (1)
  886.         {
  887.           event_index = WaitForMultipleObjects (2, wait_events, FALSE, INFINITE);

  888.           if (event_index == WAIT_OBJECT_0
  889.               || WaitForSingleObject (state->base.stop_select, 0) == WAIT_OBJECT_0)
  890.             {
  891.               /* We have been requested to stop.  */
  892.               break;
  893.             }

  894.           if (event_index != WAIT_OBJECT_0 + 1)
  895.             {
  896.               /* Some error has occured.  Assume that this is an error
  897.                  condition.  */
  898.               SetEvent (state->base.except_event);
  899.               break;
  900.             }

  901.           /* Enumerate the internal network events, and reset the
  902.              object that signalled us to catch the next event.  */
  903.           if (WSAEnumNetworkEvents (scb->fd, state->sock_event, &events) != 0)
  904.             {
  905.               /* Something went wrong.  Maybe the socket is gone.  */
  906.               SetEvent (state->base.except_event);
  907.               break;
  908.             }

  909.           if (events.lNetworkEvents & FD_READ)
  910.             {
  911.               if (net_windows_socket_check_pending (scb))
  912.                 break;

  913.               /* Spurious wakeup.  That is, the socket's event was
  914.                  signalled before we last called recv.  */
  915.             }

  916.           if (events.lNetworkEvents & FD_CLOSE)
  917.             {
  918.               SetEvent (state->base.except_event);
  919.               break;
  920.             }
  921.         }

  922.       SetEvent (state->base.have_stopped);
  923.     }
  924.   return 0;
  925. }

  926. static void
  927. net_windows_wait_handle (struct serial *scb, HANDLE *read, HANDLE *except)
  928. {
  929.   struct net_windows_state *state = scb->state;

  930.   /* Start from a clean slate.  */
  931.   ResetEvent (state->base.read_event);
  932.   ResetEvent (state->base.except_event);
  933.   ResetEvent (state->base.stop_select);

  934.   *read = state->base.read_event;
  935.   *except = state->base.except_event;

  936.   /* Check any pending events.  Otherwise, start the select
  937.      thread.  */
  938.   if (!net_windows_socket_check_pending (scb))
  939.     start_select_thread (&state->base);
  940. }

  941. static void
  942. net_windows_done_wait_handle (struct serial *scb)
  943. {
  944.   struct net_windows_state *state = scb->state;

  945.   stop_select_thread (&state->base);
  946. }

  947. static int
  948. net_windows_open (struct serial *scb, const char *name)
  949. {
  950.   struct net_windows_state *state;
  951.   int ret;
  952.   DWORD threadId;

  953.   ret = net_open (scb, name);
  954.   if (ret != 0)
  955.     return ret;

  956.   state = xmalloc (sizeof (struct net_windows_state));
  957.   memset (state, 0, sizeof (struct net_windows_state));
  958.   scb->state = state;

  959.   /* Associate an event with the socket.  */
  960.   state->sock_event = CreateEvent (0, TRUE, FALSE, 0);
  961.   WSAEventSelect (scb->fd, state->sock_event, FD_READ | FD_CLOSE);

  962.   /* Start the thread.  */
  963.   create_select_thread (net_windows_select_thread, scb, &state->base);

  964.   return 0;
  965. }


  966. static void
  967. net_windows_close (struct serial *scb)
  968. {
  969.   struct net_windows_state *state = scb->state;

  970.   destroy_select_thread (&state->base);
  971.   CloseHandle (state->sock_event);

  972.   xfree (scb->state);

  973.   net_close (scb);
  974. }

  975. /* The serial port driver.  */

  976. static const struct serial_ops hardwire_ops =
  977. {
  978.   "hardwire",
  979.   ser_windows_open,
  980.   ser_windows_close,
  981.   NULL,
  982.   ser_base_readchar,
  983.   ser_base_write,
  984.   ser_windows_flush_output,
  985.   ser_windows_flush_input,
  986.   ser_windows_send_break,
  987.   ser_windows_raw,
  988.   /* These are only used for stdin; we do not need them for serial
  989.      ports, so supply the standard dummies.  */
  990.   ser_base_get_tty_state,
  991.   ser_base_copy_tty_state,
  992.   ser_base_set_tty_state,
  993.   ser_base_print_tty_state,
  994.   ser_base_noflush_set_tty_state,
  995.   ser_windows_setbaudrate,
  996.   ser_windows_setstopbits,
  997.   ser_windows_drain_output,
  998.   ser_base_async,
  999.   ser_windows_read_prim,
  1000.   ser_windows_write_prim,
  1001.   NULL,
  1002.   ser_windows_wait_handle
  1003. };

  1004. /* The dummy serial driver used for terminals.  We only provide the
  1005.    TTY-related methods.  */

  1006. static const struct serial_ops tty_ops =
  1007. {
  1008.   "terminal",
  1009.   NULL,
  1010.   ser_console_close,
  1011.   NULL,
  1012.   NULL,
  1013.   NULL,
  1014.   NULL,
  1015.   NULL,
  1016.   NULL,
  1017.   NULL,
  1018.   ser_console_get_tty_state,
  1019.   ser_base_copy_tty_state,
  1020.   ser_base_set_tty_state,
  1021.   ser_base_print_tty_state,
  1022.   ser_base_noflush_set_tty_state,
  1023.   NULL,
  1024.   NULL,
  1025.   ser_base_drain_output,
  1026.   NULL,
  1027.   NULL,
  1028.   NULL,
  1029.   NULL,
  1030.   ser_console_wait_handle,
  1031.   ser_console_done_wait_handle
  1032. };

  1033. /* The pipe interface.  */

  1034. static const struct serial_ops pipe_ops =
  1035. {
  1036.   "pipe",
  1037.   pipe_windows_open,
  1038.   pipe_windows_close,
  1039.   pipe_windows_fdopen,
  1040.   ser_base_readchar,
  1041.   ser_base_write,
  1042.   ser_base_flush_output,
  1043.   ser_base_flush_input,
  1044.   ser_base_send_break,
  1045.   ser_base_raw,
  1046.   ser_base_get_tty_state,
  1047.   ser_base_copy_tty_state,
  1048.   ser_base_set_tty_state,
  1049.   ser_base_print_tty_state,
  1050.   ser_base_noflush_set_tty_state,
  1051.   ser_base_setbaudrate,
  1052.   ser_base_setstopbits,
  1053.   ser_base_drain_output,
  1054.   ser_base_async,
  1055.   pipe_windows_read,
  1056.   pipe_windows_write,
  1057.   pipe_avail,
  1058.   pipe_wait_handle,
  1059.   pipe_done_wait_handle
  1060. };

  1061. /* The TCP/UDP socket driver.  */

  1062. static const struct serial_ops tcp_ops =
  1063. {
  1064.   "tcp",
  1065.   net_windows_open,
  1066.   net_windows_close,
  1067.   NULL,
  1068.   ser_base_readchar,
  1069.   ser_base_write,
  1070.   ser_base_flush_output,
  1071.   ser_base_flush_input,
  1072.   ser_tcp_send_break,
  1073.   ser_base_raw,
  1074.   ser_base_get_tty_state,
  1075.   ser_base_copy_tty_state,
  1076.   ser_base_set_tty_state,
  1077.   ser_base_print_tty_state,
  1078.   ser_base_noflush_set_tty_state,
  1079.   ser_base_setbaudrate,
  1080.   ser_base_setstopbits,
  1081.   ser_base_drain_output,
  1082.   ser_base_async,
  1083.   net_read_prim,
  1084.   net_write_prim,
  1085.   NULL,
  1086.   net_windows_wait_handle,
  1087.   net_windows_done_wait_handle
  1088. };

  1089. void
  1090. _initialize_ser_windows (void)
  1091. {
  1092.   WSADATA wsa_data;
  1093.   struct serial_ops *ops;

  1094.   HMODULE hm = NULL;

  1095.   /* First find out if kernel32 exports CancelIo function.  */
  1096.   hm = LoadLibrary ("kernel32.dll");
  1097.   if (hm)
  1098.     {
  1099.       CancelIo = (void *) GetProcAddress (hm, "CancelIo");
  1100.       FreeLibrary (hm);
  1101.     }
  1102.   else
  1103.     CancelIo = NULL;

  1104.   serial_add_interface (&hardwire_ops);
  1105.   serial_add_interface (&tty_ops);
  1106.   serial_add_interface (&pipe_ops);

  1107.   /* If WinSock works, register the TCP/UDP socket driver.  */

  1108.   if (WSAStartup (MAKEWORD (1, 0), &wsa_data) != 0)
  1109.     /* WinSock is unavailable.  */
  1110.     return;

  1111.   serial_add_interface (&tcp_ops);
  1112. }