GDB (API)
/home/stan/gdb/src/gdb/ser-mingw.c
Go to the documentation of this file.
00001 /* Serial interface for local (hardwired) serial ports on Windows systems
00002 
00003    Copyright (C) 2006-2013 Free Software Foundation, Inc.
00004 
00005    This file is part of GDB.
00006 
00007    This program is free software; you can redistribute it and/or modify
00008    it under the terms of the GNU General Public License as published by
00009    the Free Software Foundation; either version 3 of the License, or
00010    (at your option) any later version.
00011 
00012    This program is distributed in the hope that it will be useful,
00013    but WITHOUT ANY WARRANTY; without even the implied warranty of
00014    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00015    GNU General Public License for more details.
00016 
00017    You should have received a copy of the GNU General Public License
00018    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
00019 
00020 #include "defs.h"
00021 #include "serial.h"
00022 #include "ser-base.h"
00023 #include "ser-tcp.h"
00024 
00025 #include <windows.h>
00026 #include <conio.h>
00027 
00028 #include <fcntl.h>
00029 #include <unistd.h>
00030 #include <sys/types.h>
00031 
00032 #include "gdb_assert.h"
00033 #include "gdb_string.h"
00034 
00035 #include "command.h"
00036 
00037 void _initialize_ser_windows (void);
00038 
00039 struct ser_windows_state
00040 {
00041   int in_progress;
00042   OVERLAPPED ov;
00043   DWORD lastCommMask;
00044   HANDLE except_event;
00045 };
00046 
00047 /* CancelIo is not available for Windows 95 OS, so we need to use
00048    LoadLibrary/GetProcAddress to avoid a startup failure.  */
00049 #define CancelIo dyn_CancelIo
00050 static BOOL WINAPI (*CancelIo) (HANDLE);
00051 
00052 /* Open up a real live device for serial I/O.  */
00053 
00054 static int
00055 ser_windows_open (struct serial *scb, const char *name)
00056 {
00057   HANDLE h;
00058   struct ser_windows_state *state;
00059   COMMTIMEOUTS timeouts;
00060 
00061   h = CreateFile (name, GENERIC_READ | GENERIC_WRITE, 0, NULL,
00062                   OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
00063   if (h == INVALID_HANDLE_VALUE)
00064     {
00065       errno = ENOENT;
00066       return -1;
00067     }
00068 
00069   scb->fd = _open_osfhandle ((intptr_t) h, O_RDWR);
00070   if (scb->fd < 0)
00071     {
00072       errno = ENOENT;
00073       return -1;
00074     }
00075 
00076   if (!SetCommMask (h, EV_RXCHAR))
00077     {
00078       errno = EINVAL;
00079       return -1;
00080     }
00081 
00082   timeouts.ReadIntervalTimeout = MAXDWORD;
00083   timeouts.ReadTotalTimeoutConstant = 0;
00084   timeouts.ReadTotalTimeoutMultiplier = 0;
00085   timeouts.WriteTotalTimeoutConstant = 0;
00086   timeouts.WriteTotalTimeoutMultiplier = 0;
00087   if (!SetCommTimeouts (h, &timeouts))
00088     {
00089       errno = EINVAL;
00090       return -1;
00091     }
00092 
00093   state = xmalloc (sizeof (struct ser_windows_state));
00094   memset (state, 0, sizeof (struct ser_windows_state));
00095   scb->state = state;
00096 
00097   /* Create a manual reset event to watch the input buffer.  */
00098   state->ov.hEvent = CreateEvent (0, TRUE, FALSE, 0);
00099 
00100   /* Create a (currently unused) handle to record exceptions.  */
00101   state->except_event = CreateEvent (0, TRUE, FALSE, 0);
00102 
00103   return 0;
00104 }
00105 
00106 /* Wait for the output to drain away, as opposed to flushing (discarding)
00107    it.  */
00108 
00109 static int
00110 ser_windows_drain_output (struct serial *scb)
00111 {
00112   HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
00113 
00114   return (FlushFileBuffers (h) != 0) ? 0 : -1;
00115 }
00116 
00117 static int
00118 ser_windows_flush_output (struct serial *scb)
00119 {
00120   HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
00121 
00122   return (PurgeComm (h, PURGE_TXCLEAR) != 0) ? 0 : -1;
00123 }
00124 
00125 static int
00126 ser_windows_flush_input (struct serial *scb)
00127 {
00128   HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
00129 
00130   return (PurgeComm (h, PURGE_RXCLEAR) != 0) ? 0 : -1;
00131 }
00132 
00133 static int
00134 ser_windows_send_break (struct serial *scb)
00135 {
00136   HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
00137 
00138   if (SetCommBreak (h) == 0)
00139     return -1;
00140 
00141   /* Delay for 250 milliseconds.  */
00142   Sleep (250);
00143 
00144   if (ClearCommBreak (h))
00145     return -1;
00146 
00147   return 0;
00148 }
00149 
00150 static void
00151 ser_windows_raw (struct serial *scb)
00152 {
00153   HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
00154   DCB state;
00155 
00156   if (GetCommState (h, &state) == 0)
00157     return;
00158 
00159   state.fParity = FALSE;
00160   state.fOutxCtsFlow = FALSE;
00161   state.fOutxDsrFlow = FALSE;
00162   state.fDtrControl = DTR_CONTROL_ENABLE;
00163   state.fDsrSensitivity = FALSE;
00164   state.fOutX = FALSE;
00165   state.fInX = FALSE;
00166   state.fNull = FALSE;
00167   state.fAbortOnError = FALSE;
00168   state.ByteSize = 8;
00169   state.Parity = NOPARITY;
00170 
00171   scb->current_timeout = 0;
00172 
00173   if (SetCommState (h, &state) == 0)
00174     warning (_("SetCommState failed"));
00175 }
00176 
00177 static int
00178 ser_windows_setstopbits (struct serial *scb, int num)
00179 {
00180   HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
00181   DCB state;
00182 
00183   if (GetCommState (h, &state) == 0)
00184     return -1;
00185 
00186   switch (num)
00187     {
00188     case SERIAL_1_STOPBITS:
00189       state.StopBits = ONESTOPBIT;
00190       break;
00191     case SERIAL_1_AND_A_HALF_STOPBITS:
00192       state.StopBits = ONE5STOPBITS;
00193       break;
00194     case SERIAL_2_STOPBITS:
00195       state.StopBits = TWOSTOPBITS;
00196       break;
00197     default:
00198       return 1;
00199     }
00200 
00201   return (SetCommState (h, &state) != 0) ? 0 : -1;
00202 }
00203 
00204 static int
00205 ser_windows_setbaudrate (struct serial *scb, int rate)
00206 {
00207   HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
00208   DCB state;
00209 
00210   if (GetCommState (h, &state) == 0)
00211     return -1;
00212 
00213   state.BaudRate = rate;
00214 
00215   return (SetCommState (h, &state) != 0) ? 0 : -1;
00216 }
00217 
00218 static void
00219 ser_windows_close (struct serial *scb)
00220 {
00221   struct ser_windows_state *state;
00222 
00223   /* Stop any pending selects.  On Windows 95 OS, CancelIo function does
00224      not exist.  In that case, it can be replaced by a call to CloseHandle,
00225      but this is not necessary here as we do close the Windows handle
00226      by calling close (scb->fd) below.  */
00227   if (CancelIo)
00228     CancelIo ((HANDLE) _get_osfhandle (scb->fd));
00229   state = scb->state;
00230   CloseHandle (state->ov.hEvent);
00231   CloseHandle (state->except_event);
00232 
00233   if (scb->fd < 0)
00234     return;
00235 
00236   close (scb->fd);
00237   scb->fd = -1;
00238 
00239   xfree (scb->state);
00240 }
00241 
00242 static void
00243 ser_windows_wait_handle (struct serial *scb, HANDLE *read, HANDLE *except)
00244 {
00245   struct ser_windows_state *state;
00246   COMSTAT status;
00247   DWORD errors;
00248   HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
00249 
00250   state = scb->state;
00251 
00252   *except = state->except_event;
00253   *read = state->ov.hEvent;
00254 
00255   if (state->in_progress)
00256     return;
00257 
00258   /* Reset the mask - we are only interested in any characters which
00259      arrive after this point, not characters which might have arrived
00260      and already been read.  */
00261 
00262   /* This really, really shouldn't be necessary - just the second one.
00263      But otherwise an internal flag for EV_RXCHAR does not get
00264      cleared, and we get a duplicated event, if the last batch
00265      of characters included at least two arriving close together.  */
00266   if (!SetCommMask (h, 0))
00267     warning (_("ser_windows_wait_handle: reseting mask failed"));
00268 
00269   if (!SetCommMask (h, EV_RXCHAR))
00270     warning (_("ser_windows_wait_handle: reseting mask failed (2)"));
00271 
00272   /* There's a potential race condition here; we must check cbInQue
00273      and not wait if that's nonzero.  */
00274 
00275   ClearCommError (h, &errors, &status);
00276   if (status.cbInQue > 0)
00277     {
00278       SetEvent (state->ov.hEvent);
00279       return;
00280     }
00281 
00282   state->in_progress = 1;
00283   ResetEvent (state->ov.hEvent);
00284   state->lastCommMask = -2;
00285   if (WaitCommEvent (h, &state->lastCommMask, &state->ov))
00286     {
00287       gdb_assert (state->lastCommMask & EV_RXCHAR);
00288       SetEvent (state->ov.hEvent);
00289     }
00290   else
00291     gdb_assert (GetLastError () == ERROR_IO_PENDING);
00292 }
00293 
00294 static int
00295 ser_windows_read_prim (struct serial *scb, size_t count)
00296 {
00297   struct ser_windows_state *state;
00298   OVERLAPPED ov;
00299   DWORD bytes_read, bytes_read_tmp;
00300   HANDLE h;
00301   gdb_byte *p;
00302 
00303   state = scb->state;
00304   if (state->in_progress)
00305     {
00306       WaitForSingleObject (state->ov.hEvent, INFINITE);
00307       state->in_progress = 0;
00308       ResetEvent (state->ov.hEvent);
00309     }
00310 
00311   memset (&ov, 0, sizeof (OVERLAPPED));
00312   ov.hEvent = CreateEvent (0, FALSE, FALSE, 0);
00313   h = (HANDLE) _get_osfhandle (scb->fd);
00314 
00315   if (!ReadFile (h, scb->buf, /* count */ 1, &bytes_read, &ov))
00316     {
00317       if (GetLastError () != ERROR_IO_PENDING
00318           || !GetOverlappedResult (h, &ov, &bytes_read, TRUE))
00319         bytes_read = -1;
00320     }
00321 
00322   CloseHandle (ov.hEvent);
00323   return bytes_read;
00324 }
00325 
00326 static int
00327 ser_windows_write_prim (struct serial *scb, const void *buf, size_t len)
00328 {
00329   struct ser_windows_state *state;
00330   OVERLAPPED ov;
00331   DWORD bytes_written;
00332   HANDLE h;
00333 
00334   memset (&ov, 0, sizeof (OVERLAPPED));
00335   ov.hEvent = CreateEvent (0, FALSE, FALSE, 0);
00336   h = (HANDLE) _get_osfhandle (scb->fd);
00337   if (!WriteFile (h, buf, len, &bytes_written, &ov))
00338     {
00339       if (GetLastError () != ERROR_IO_PENDING
00340           || !GetOverlappedResult (h, &ov, &bytes_written, TRUE))
00341         bytes_written = -1;
00342     }
00343 
00344   CloseHandle (ov.hEvent);
00345   return bytes_written;
00346 }
00347 
00348 /* On Windows, gdb_select is implemented using WaitForMulpleObjects.
00349    A "select thread" is created for each file descriptor.  These
00350    threads looks for activity on the corresponding descriptor, using
00351    whatever techniques are appropriate for the descriptor type.  When
00352    that activity occurs, the thread signals an appropriate event,
00353    which wakes up WaitForMultipleObjects.
00354 
00355    Each select thread is in one of two states: stopped or started.
00356    Select threads begin in the stopped state.  When gdb_select is
00357    called, threads corresponding to the descriptors of interest are
00358    started by calling a wait_handle function.  Each thread that
00359    notices activity signals the appropriate event and then reenters
00360    the stopped state.  Before gdb_select returns it calls the
00361    wait_handle_done functions, which return the threads to the stopped
00362    state.  */
00363 
00364 enum select_thread_state {
00365   STS_STARTED,
00366   STS_STOPPED
00367 };
00368 
00369 struct ser_console_state
00370 {
00371   /* Signaled by the select thread to indicate that data is available
00372      on the file descriptor.  */
00373   HANDLE read_event;
00374   /* Signaled by the select thread to indicate that an exception has
00375      occurred on the file descriptor.  */
00376   HANDLE except_event;
00377   /* Signaled by the select thread to indicate that it has entered the
00378      started state.  HAVE_STARTED and HAVE_STOPPED are never signaled
00379      simultaneously.  */
00380   HANDLE have_started;
00381   /* Signaled by the select thread to indicate that it has stopped,
00382      either because data is available (and READ_EVENT is signaled),
00383      because an exception has occurred (and EXCEPT_EVENT is signaled),
00384      or because STOP_SELECT was signaled.  */
00385   HANDLE have_stopped;
00386 
00387   /* Signaled by the main program to tell the select thread to enter
00388      the started state.  */
00389   HANDLE start_select;
00390   /* Signaled by the main program to tell the select thread to enter
00391      the stopped state.  */
00392   HANDLE stop_select;
00393   /* Signaled by the main program to tell the select thread to
00394      exit.  */
00395   HANDLE exit_select;
00396 
00397   /* The handle for the select thread.  */
00398   HANDLE thread;
00399   /* The state of the select thread.  This field is only accessed in
00400      the main program, never by the select thread itself.  */
00401   enum select_thread_state thread_state;
00402 };
00403 
00404 /* Called by a select thread to enter the stopped state.  This
00405    function does not return until the thread has re-entered the
00406    started state.  */
00407 static void
00408 select_thread_wait (struct ser_console_state *state)
00409 {
00410   HANDLE wait_events[2];
00411 
00412   /* There are two things that can wake us up: a request that we enter
00413      the started state, or that we exit this thread.  */
00414   wait_events[0] = state->start_select;
00415   wait_events[1] = state->exit_select;
00416   if (WaitForMultipleObjects (2, wait_events, FALSE, INFINITE) 
00417       != WAIT_OBJECT_0)
00418     /* Either the EXIT_SELECT event was signaled (requesting that the
00419        thread exit) or an error has occurred.  In either case, we exit
00420        the thread.  */
00421     ExitThread (0);
00422   
00423   /* We are now in the started state.  */
00424   SetEvent (state->have_started);
00425 }
00426 
00427 typedef DWORD WINAPI (*thread_fn_type)(void *);
00428 
00429 /* Create a new select thread for SCB executing THREAD_FN.  The STATE
00430    will be filled in by this function before return.  */
00431 static void
00432 create_select_thread (thread_fn_type thread_fn,
00433                       struct serial *scb,
00434                       struct ser_console_state *state)
00435 {
00436   DWORD threadId;
00437 
00438   /* Create all of the events.  These are all auto-reset events.  */
00439   state->read_event = CreateEvent (NULL, FALSE, FALSE, NULL);
00440   state->except_event = CreateEvent (NULL, FALSE, FALSE, NULL);
00441   state->have_started = CreateEvent (NULL, FALSE, FALSE, NULL);
00442   state->have_stopped = CreateEvent (NULL, FALSE, FALSE, NULL);
00443   state->start_select = CreateEvent (NULL, FALSE, FALSE, NULL);
00444   state->stop_select = CreateEvent (NULL, FALSE, FALSE, NULL);
00445   state->exit_select = CreateEvent (NULL, FALSE, FALSE, NULL);
00446 
00447   state->thread = CreateThread (NULL, 0, thread_fn, scb, 0, &threadId);
00448   /* The thread begins in the stopped state.  */
00449   state->thread_state = STS_STOPPED;
00450 }
00451 
00452 /* Destroy the select thread indicated by STATE.  */
00453 static void
00454 destroy_select_thread (struct ser_console_state *state)
00455 {
00456   /* Ask the thread to exit.  */
00457   SetEvent (state->exit_select);
00458   /* Wait until it does.  */
00459   WaitForSingleObject (state->thread, INFINITE);
00460 
00461   /* Destroy the events.  */
00462   CloseHandle (state->read_event);
00463   CloseHandle (state->except_event);
00464   CloseHandle (state->have_started);
00465   CloseHandle (state->have_stopped);
00466   CloseHandle (state->start_select);
00467   CloseHandle (state->stop_select);
00468   CloseHandle (state->exit_select);
00469 }
00470 
00471 /* Called by gdb_select to start the select thread indicated by STATE.
00472    This function does not return until the thread has started.  */
00473 static void
00474 start_select_thread (struct ser_console_state *state)
00475 {
00476   /* Ask the thread to start.  */
00477   SetEvent (state->start_select);
00478   /* Wait until it does.  */
00479   WaitForSingleObject (state->have_started, INFINITE);
00480   /* The thread is now started.  */
00481   state->thread_state = STS_STARTED;
00482 }
00483 
00484 /* Called by gdb_select to stop the select thread indicated by STATE.
00485    This function does not return until the thread has stopped.  */
00486 static void
00487 stop_select_thread (struct ser_console_state *state)
00488 {
00489   /* If the thread is already in the stopped state, we have nothing to
00490      do.  Some of the wait_handle functions avoid calling
00491      start_select_thread if they notice activity on the relevant file
00492      descriptors.  The wait_handle_done functions still call
00493      stop_select_thread -- but it is already stopped.  */
00494   if (state->thread_state != STS_STARTED)
00495     return;
00496   /* Ask the thread to stop.  */
00497   SetEvent (state->stop_select);
00498   /* Wait until it does.  */
00499   WaitForSingleObject (state->have_stopped, INFINITE);
00500   /* The thread is now stopped.  */
00501   state->thread_state = STS_STOPPED;
00502 }
00503 
00504 static DWORD WINAPI
00505 console_select_thread (void *arg)
00506 {
00507   struct serial *scb = arg;
00508   struct ser_console_state *state;
00509   int event_index;
00510   HANDLE h;
00511 
00512   state = scb->state;
00513   h = (HANDLE) _get_osfhandle (scb->fd);
00514 
00515   while (1)
00516     {
00517       HANDLE wait_events[2];
00518       INPUT_RECORD record;
00519       DWORD n_records;
00520 
00521       select_thread_wait (state);
00522 
00523       while (1)
00524         {
00525           wait_events[0] = state->stop_select;
00526           wait_events[1] = h;
00527 
00528           event_index = WaitForMultipleObjects (2, wait_events,
00529                                                 FALSE, INFINITE);
00530 
00531           if (event_index == WAIT_OBJECT_0
00532               || WaitForSingleObject (state->stop_select, 0) == WAIT_OBJECT_0)
00533             break;
00534 
00535           if (event_index != WAIT_OBJECT_0 + 1)
00536             {
00537               /* Wait must have failed; assume an error has occured, e.g.
00538                  the handle has been closed.  */
00539               SetEvent (state->except_event);
00540               break;
00541             }
00542 
00543           /* We've got a pending event on the console.  See if it's
00544              of interest.  */
00545           if (!PeekConsoleInput (h, &record, 1, &n_records) || n_records != 1)
00546             {
00547               /* Something went wrong.  Maybe the console is gone.  */
00548               SetEvent (state->except_event);
00549               break;
00550             }
00551 
00552           if (record.EventType == KEY_EVENT && record.Event.KeyEvent.bKeyDown)
00553             {
00554               WORD keycode = record.Event.KeyEvent.wVirtualKeyCode;
00555 
00556               /* Ignore events containing only control keys.  We must
00557                  recognize "enhanced" keys which we are interested in
00558                  reading via getch, if they do not map to ASCII.  But we
00559                  do not want to report input available for e.g. the
00560                  control key alone.  */
00561 
00562               if (record.Event.KeyEvent.uChar.AsciiChar != 0
00563                   || keycode == VK_PRIOR
00564                   || keycode == VK_NEXT
00565                   || keycode == VK_END
00566                   || keycode == VK_HOME
00567                   || keycode == VK_LEFT
00568                   || keycode == VK_UP
00569                   || keycode == VK_RIGHT
00570                   || keycode == VK_DOWN
00571                   || keycode == VK_INSERT
00572                   || keycode == VK_DELETE)
00573                 {
00574                   /* This is really a keypress.  */
00575                   SetEvent (state->read_event);
00576                   break;
00577                 }
00578             }
00579 
00580           /* Otherwise discard it and wait again.  */
00581           ReadConsoleInput (h, &record, 1, &n_records);
00582         }
00583 
00584       SetEvent(state->have_stopped);
00585     }
00586   return 0;
00587 }
00588 
00589 static int
00590 fd_is_pipe (int fd)
00591 {
00592   if (PeekNamedPipe ((HANDLE) _get_osfhandle (fd), NULL, 0, NULL, NULL, NULL))
00593     return 1;
00594   else
00595     return 0;
00596 }
00597 
00598 static int
00599 fd_is_file (int fd)
00600 {
00601   if (GetFileType ((HANDLE) _get_osfhandle (fd)) == FILE_TYPE_DISK)
00602     return 1;
00603   else
00604     return 0;
00605 }
00606 
00607 static DWORD WINAPI
00608 pipe_select_thread (void *arg)
00609 {
00610   struct serial *scb = arg;
00611   struct ser_console_state *state;
00612   int event_index;
00613   HANDLE h;
00614 
00615   state = scb->state;
00616   h = (HANDLE) _get_osfhandle (scb->fd);
00617 
00618   while (1)
00619     {
00620       DWORD n_avail;
00621 
00622       select_thread_wait (state);
00623 
00624       /* Wait for something to happen on the pipe.  */
00625       while (1)
00626         {
00627           if (!PeekNamedPipe (h, NULL, 0, NULL, &n_avail, NULL))
00628             {
00629               SetEvent (state->except_event);
00630               break;
00631             }
00632 
00633           if (n_avail > 0)
00634             {
00635               SetEvent (state->read_event);
00636               break;
00637             }
00638 
00639           /* Delay 10ms before checking again, but allow the stop
00640              event to wake us.  */
00641           if (WaitForSingleObject (state->stop_select, 10) == WAIT_OBJECT_0)
00642             break;
00643         }
00644 
00645       SetEvent (state->have_stopped);
00646     }
00647   return 0;
00648 }
00649 
00650 static DWORD WINAPI
00651 file_select_thread (void *arg)
00652 {
00653   struct serial *scb = arg;
00654   struct ser_console_state *state;
00655   int event_index;
00656   HANDLE h;
00657 
00658   state = scb->state;
00659   h = (HANDLE) _get_osfhandle (scb->fd);
00660 
00661   while (1)
00662     {
00663       select_thread_wait (state);
00664 
00665       if (SetFilePointer (h, 0, NULL, FILE_CURRENT)
00666           == INVALID_SET_FILE_POINTER)
00667         SetEvent (state->except_event);
00668       else
00669         SetEvent (state->read_event);
00670 
00671       SetEvent (state->have_stopped);
00672     }
00673   return 0;
00674 }
00675 
00676 static void
00677 ser_console_wait_handle (struct serial *scb, HANDLE *read, HANDLE *except)
00678 {
00679   struct ser_console_state *state = scb->state;
00680 
00681   if (state == NULL)
00682     {
00683       thread_fn_type thread_fn;
00684       int is_tty;
00685 
00686       is_tty = isatty (scb->fd);
00687       if (!is_tty && !fd_is_file (scb->fd) && !fd_is_pipe (scb->fd))
00688         {
00689           *read = NULL;
00690           *except = NULL;
00691           return;
00692         }
00693 
00694       state = xmalloc (sizeof (struct ser_console_state));
00695       memset (state, 0, sizeof (struct ser_console_state));
00696       scb->state = state;
00697 
00698       if (is_tty)
00699         thread_fn = console_select_thread;
00700       else if (fd_is_pipe (scb->fd))
00701         thread_fn = pipe_select_thread;
00702       else
00703         thread_fn = file_select_thread;
00704 
00705       create_select_thread (thread_fn, scb, state);
00706     }
00707 
00708   *read = state->read_event;
00709   *except = state->except_event;
00710 
00711   /* Start from a blank state.  */
00712   ResetEvent (state->read_event);
00713   ResetEvent (state->except_event);
00714   ResetEvent (state->stop_select);
00715 
00716   /* First check for a key already in the buffer.  If there is one,
00717      we don't need a thread.  This also catches the second key of
00718      multi-character returns from getch, for instance for arrow
00719      keys.  The second half is in a C library internal buffer,
00720      and PeekConsoleInput will not find it.  */
00721   if (_kbhit ())
00722     {
00723       SetEvent (state->read_event);
00724       return;
00725     }
00726 
00727   /* Otherwise, start the select thread.  */
00728   start_select_thread (state);
00729 }
00730 
00731 static void
00732 ser_console_done_wait_handle (struct serial *scb)
00733 {
00734   struct ser_console_state *state = scb->state;
00735 
00736   if (state == NULL)
00737     return;
00738 
00739   stop_select_thread (state);
00740 }
00741 
00742 static void
00743 ser_console_close (struct serial *scb)
00744 {
00745   struct ser_console_state *state = scb->state;
00746 
00747   if (scb->state)
00748     {
00749       destroy_select_thread (state);
00750       xfree (scb->state);
00751     }
00752 }
00753 
00754 struct ser_console_ttystate
00755 {
00756   int is_a_tty;
00757 };
00758 
00759 static serial_ttystate
00760 ser_console_get_tty_state (struct serial *scb)
00761 {
00762   if (isatty (scb->fd))
00763     {
00764       struct ser_console_ttystate *state;
00765 
00766       state = (struct ser_console_ttystate *) xmalloc (sizeof *state);
00767       state->is_a_tty = 1;
00768       return state;
00769     }
00770   else
00771     return NULL;
00772 }
00773 
00774 struct pipe_state
00775 {
00776   /* Since we use the pipe_select_thread for our select emulation,
00777      we need to place the state structure it requires at the front
00778      of our state.  */
00779   struct ser_console_state wait;
00780 
00781   /* The pex obj for our (one-stage) pipeline.  */
00782   struct pex_obj *pex;
00783 
00784   /* Streams for the pipeline's input and output.  */
00785   FILE *input, *output;
00786 };
00787 
00788 static struct pipe_state *
00789 make_pipe_state (void)
00790 {
00791   struct pipe_state *ps = XMALLOC (struct pipe_state);
00792 
00793   memset (ps, 0, sizeof (*ps));
00794   ps->wait.read_event = INVALID_HANDLE_VALUE;
00795   ps->wait.except_event = INVALID_HANDLE_VALUE;
00796   ps->wait.start_select = INVALID_HANDLE_VALUE;
00797   ps->wait.stop_select = INVALID_HANDLE_VALUE;
00798 
00799   return ps;
00800 }
00801 
00802 static void
00803 free_pipe_state (struct pipe_state *ps)
00804 {
00805   int saved_errno = errno;
00806 
00807   if (ps->wait.read_event != INVALID_HANDLE_VALUE)
00808     destroy_select_thread (&ps->wait);
00809 
00810   /* Close the pipe to the child.  We must close the pipe before
00811      calling pex_free because pex_free will wait for the child to exit
00812      and the child will not exit until the pipe is closed.  */
00813   if (ps->input)
00814     fclose (ps->input);
00815   if (ps->pex)
00816     {
00817       pex_free (ps->pex);
00818       /* pex_free closes ps->output.  */
00819     }
00820   else if (ps->output)
00821     fclose (ps->output);
00822 
00823   xfree (ps);
00824 
00825   errno = saved_errno;
00826 }
00827 
00828 static void
00829 cleanup_pipe_state (void *untyped)
00830 {
00831   struct pipe_state *ps = untyped;
00832 
00833   free_pipe_state (ps);
00834 }
00835 
00836 static int
00837 pipe_windows_open (struct serial *scb, const char *name)
00838 {
00839   struct pipe_state *ps;
00840   FILE *pex_stderr;
00841   char **argv;
00842   struct cleanup *back_to;
00843 
00844   if (name == NULL)
00845     error_no_arg (_("child command"));
00846 
00847   argv = gdb_buildargv (name);
00848   back_to = make_cleanup_freeargv (argv);
00849 
00850   if (! argv[0] || argv[0][0] == '\0')
00851     error (_("missing child command"));
00852 
00853   ps = make_pipe_state ();
00854   make_cleanup (cleanup_pipe_state, ps);
00855 
00856   ps->pex = pex_init (PEX_USE_PIPES, "target remote pipe", NULL);
00857   if (! ps->pex)
00858     goto fail;
00859   ps->input = pex_input_pipe (ps->pex, 1);
00860   if (! ps->input)
00861     goto fail;
00862 
00863   {
00864     int err;
00865     const char *err_msg
00866       = pex_run (ps->pex, PEX_SEARCH | PEX_BINARY_INPUT | PEX_BINARY_OUTPUT
00867                  | PEX_STDERR_TO_PIPE,
00868                  argv[0], argv, NULL, NULL,
00869                  &err);
00870 
00871     if (err_msg)
00872       {
00873         /* Our caller expects us to return -1, but all they'll do with
00874            it generally is print the message based on errno.  We have
00875            all the same information here, plus err_msg provided by
00876            pex_run, so we just raise the error here.  */
00877         if (err)
00878           error (_("error starting child process '%s': %s: %s"),
00879                  name, err_msg, safe_strerror (err));
00880         else
00881           error (_("error starting child process '%s': %s"),
00882                  name, err_msg);
00883       }
00884   }
00885 
00886   ps->output = pex_read_output (ps->pex, 1);
00887   if (! ps->output)
00888     goto fail;
00889   scb->fd = fileno (ps->output);
00890 
00891   pex_stderr = pex_read_err (ps->pex, 1);
00892   if (! pex_stderr)
00893     goto fail;
00894   scb->error_fd = fileno (pex_stderr);
00895 
00896   scb->state = (void *) ps;
00897 
00898   discard_cleanups (back_to);
00899   return 0;
00900 
00901  fail:
00902   do_cleanups (back_to);
00903   return -1;
00904 }
00905 
00906 static int
00907 pipe_windows_fdopen (struct serial *scb, int fd)
00908 {
00909   struct pipe_state *ps;
00910 
00911   ps = make_pipe_state ();
00912 
00913   ps->input = fdopen (fd, "r+");
00914   if (! ps->input)
00915     goto fail;
00916 
00917   ps->output = fdopen (fd, "r+");
00918   if (! ps->output)
00919     goto fail;
00920 
00921   scb->fd = fd;
00922   scb->state = (void *) ps;
00923 
00924   return 0;
00925 
00926  fail:
00927   free_pipe_state (ps);
00928   return -1;
00929 }
00930 
00931 static void
00932 pipe_windows_close (struct serial *scb)
00933 {
00934   struct pipe_state *ps = scb->state;
00935 
00936   /* In theory, we should try to kill the subprocess here, but the pex
00937      interface doesn't give us enough information to do that.  Usually
00938      closing the input pipe will get the message across.  */
00939 
00940   free_pipe_state (ps);
00941 }
00942 
00943 
00944 static int
00945 pipe_windows_read (struct serial *scb, size_t count)
00946 {
00947   HANDLE pipeline_out = (HANDLE) _get_osfhandle (scb->fd);
00948   DWORD available;
00949   DWORD bytes_read;
00950 
00951   if (pipeline_out == INVALID_HANDLE_VALUE)
00952     return -1;
00953 
00954   if (! PeekNamedPipe (pipeline_out, NULL, 0, NULL, &available, NULL))
00955     return -1;
00956 
00957   if (count > available)
00958     count = available;
00959 
00960   if (! ReadFile (pipeline_out, scb->buf, count, &bytes_read, NULL))
00961     return -1;
00962 
00963   return bytes_read;
00964 }
00965 
00966 
00967 static int
00968 pipe_windows_write (struct serial *scb, const void *buf, size_t count)
00969 {
00970   struct pipe_state *ps = scb->state;
00971   HANDLE pipeline_in;
00972   DWORD written;
00973 
00974   int pipeline_in_fd = fileno (ps->input);
00975   if (pipeline_in_fd < 0)
00976     return -1;
00977 
00978   pipeline_in = (HANDLE) _get_osfhandle (pipeline_in_fd);
00979   if (pipeline_in == INVALID_HANDLE_VALUE)
00980     return -1;
00981 
00982   if (! WriteFile (pipeline_in, buf, count, &written, NULL))
00983     return -1;
00984 
00985   return written;
00986 }
00987 
00988 
00989 static void
00990 pipe_wait_handle (struct serial *scb, HANDLE *read, HANDLE *except)
00991 {
00992   struct pipe_state *ps = scb->state;
00993 
00994   /* Have we allocated our events yet?  */
00995   if (ps->wait.read_event == INVALID_HANDLE_VALUE)
00996     /* Start the thread.  */
00997     create_select_thread (pipe_select_thread, scb, &ps->wait);
00998 
00999   *read = ps->wait.read_event;
01000   *except = ps->wait.except_event;
01001 
01002   /* Start from a blank state.  */
01003   ResetEvent (ps->wait.read_event);
01004   ResetEvent (ps->wait.except_event);
01005   ResetEvent (ps->wait.stop_select);
01006 
01007   start_select_thread (&ps->wait);
01008 }
01009 
01010 static void
01011 pipe_done_wait_handle (struct serial *scb)
01012 {
01013   struct pipe_state *ps = scb->state;
01014 
01015   /* Have we allocated our events yet?  */
01016   if (ps->wait.read_event == INVALID_HANDLE_VALUE)
01017     return;
01018 
01019   stop_select_thread (&ps->wait);
01020 }
01021 
01022 static int
01023 pipe_avail (struct serial *scb, int fd)
01024 {
01025   HANDLE h = (HANDLE) _get_osfhandle (fd);
01026   DWORD numBytes;
01027   BOOL r = PeekNamedPipe (h, NULL, 0, NULL, &numBytes, NULL);
01028 
01029   if (r == FALSE)
01030     numBytes = 0;
01031   return numBytes;
01032 }
01033 
01034 int
01035 gdb_pipe (int pdes[2])
01036 {
01037   if (_pipe (pdes, 512, _O_BINARY | _O_NOINHERIT) == -1)
01038     return -1;
01039   return 0;
01040 }
01041 
01042 struct net_windows_state
01043 {
01044   struct ser_console_state base;
01045   
01046   HANDLE sock_event;
01047 };
01048 
01049 static DWORD WINAPI
01050 net_windows_select_thread (void *arg)
01051 {
01052   struct serial *scb = arg;
01053   struct net_windows_state *state;
01054   int event_index;
01055 
01056   state = scb->state;
01057 
01058   while (1)
01059     {
01060       HANDLE wait_events[2];
01061       WSANETWORKEVENTS events;
01062 
01063       select_thread_wait (&state->base);
01064 
01065       wait_events[0] = state->base.stop_select;
01066       wait_events[1] = state->sock_event;
01067 
01068       event_index = WaitForMultipleObjects (2, wait_events, FALSE, INFINITE);
01069 
01070       if (event_index == WAIT_OBJECT_0
01071           || WaitForSingleObject (state->base.stop_select, 0) == WAIT_OBJECT_0)
01072         /* We have been requested to stop.  */
01073         ;
01074       else if (event_index != WAIT_OBJECT_0 + 1)
01075         /* Some error has occured.  Assume that this is an error
01076            condition.  */
01077         SetEvent (state->base.except_event);
01078       else
01079         {
01080           /* Enumerate the internal network events, and reset the
01081              object that signalled us to catch the next event.  */
01082           WSAEnumNetworkEvents (scb->fd, state->sock_event, &events);
01083           
01084           gdb_assert (events.lNetworkEvents & (FD_READ | FD_CLOSE));
01085           
01086           if (events.lNetworkEvents & FD_READ)
01087             SetEvent (state->base.read_event);
01088           
01089           if (events.lNetworkEvents & FD_CLOSE)
01090             SetEvent (state->base.except_event);
01091         }
01092 
01093       SetEvent (state->base.have_stopped);
01094     }
01095 }
01096 
01097 static void
01098 net_windows_wait_handle (struct serial *scb, HANDLE *read, HANDLE *except)
01099 {
01100   struct net_windows_state *state = scb->state;
01101 
01102   /* Start from a clean slate.  */
01103   ResetEvent (state->base.read_event);
01104   ResetEvent (state->base.except_event);
01105   ResetEvent (state->base.stop_select);
01106 
01107   *read = state->base.read_event;
01108   *except = state->base.except_event;
01109 
01110   /* Check any pending events.  This both avoids starting the thread
01111      unnecessarily, and handles stray FD_READ events (see below).  */
01112   if (WaitForSingleObject (state->sock_event, 0) == WAIT_OBJECT_0)
01113     {
01114       WSANETWORKEVENTS events;
01115       int any = 0;
01116 
01117       /* Enumerate the internal network events, and reset the object that
01118          signalled us to catch the next event.  */
01119       WSAEnumNetworkEvents (scb->fd, state->sock_event, &events);
01120 
01121       /* You'd think that FD_READ or FD_CLOSE would be set here.  But,
01122          sometimes, neither is.  I suspect that the FD_READ is set and
01123          the corresponding event signalled while recv is running, and
01124          the FD_READ is then lowered when recv consumes all the data,
01125          but there's no way to un-signal the event.  This isn't a
01126          problem for the call in net_select_thread, since any new
01127          events after this point will not have been drained by recv.
01128          It just means that we can't have the obvious assert here.  */
01129 
01130       /* If there is a read event, it might be still valid, or it might
01131          not be - it may have been signalled before we last called
01132          recv.  Double-check that there is data.  */
01133       if (events.lNetworkEvents & FD_READ)
01134         {
01135           unsigned long available;
01136 
01137           if (ioctlsocket (scb->fd, FIONREAD, &available) == 0
01138               && available > 0)
01139             {
01140               SetEvent (state->base.read_event);
01141               any = 1;
01142             }
01143           else
01144             /* Oops, no data.  This call to recv will cause future
01145                data to retrigger the event, e.g. while we are
01146                in net_select_thread.  */
01147             recv (scb->fd, NULL, 0, 0);
01148         }
01149 
01150       /* If there's a close event, then record it - it is obviously
01151          still valid, and it will not be resignalled.  */
01152       if (events.lNetworkEvents & FD_CLOSE)
01153         {
01154           SetEvent (state->base.except_event);
01155           any = 1;
01156         }
01157 
01158       /* If we set either handle, there's no need to wake the thread.  */
01159       if (any)
01160         return;
01161     }
01162 
01163   start_select_thread (&state->base);
01164 }
01165 
01166 static void
01167 net_windows_done_wait_handle (struct serial *scb)
01168 {
01169   struct net_windows_state *state = scb->state;
01170 
01171   stop_select_thread (&state->base);
01172 }
01173 
01174 static int
01175 net_windows_open (struct serial *scb, const char *name)
01176 {
01177   struct net_windows_state *state;
01178   int ret;
01179   DWORD threadId;
01180 
01181   ret = net_open (scb, name);
01182   if (ret != 0)
01183     return ret;
01184 
01185   state = xmalloc (sizeof (struct net_windows_state));
01186   memset (state, 0, sizeof (struct net_windows_state));
01187   scb->state = state;
01188 
01189   /* Associate an event with the socket.  */
01190   state->sock_event = CreateEvent (0, TRUE, FALSE, 0);
01191   WSAEventSelect (scb->fd, state->sock_event, FD_READ | FD_CLOSE);
01192 
01193   /* Start the thread.  */
01194   create_select_thread (net_windows_select_thread, scb, &state->base);
01195 
01196   return 0;
01197 }
01198 
01199 
01200 static void
01201 net_windows_close (struct serial *scb)
01202 {
01203   struct net_windows_state *state = scb->state;
01204 
01205   destroy_select_thread (&state->base);
01206   CloseHandle (state->sock_event);
01207 
01208   xfree (scb->state);
01209 
01210   net_close (scb);
01211 }
01212 
01213 void
01214 _initialize_ser_windows (void)
01215 {
01216   WSADATA wsa_data;
01217   struct serial_ops *ops;
01218 
01219   HMODULE hm = NULL;
01220 
01221   /* First find out if kernel32 exports CancelIo function.  */
01222   hm = LoadLibrary ("kernel32.dll");
01223   if (hm)
01224     {
01225       CancelIo = (void *) GetProcAddress (hm, "CancelIo");
01226       FreeLibrary (hm);
01227     }
01228   else
01229     CancelIo = NULL;
01230 
01231   /* Now register the serial port driver.  */
01232   ops = XMALLOC (struct serial_ops);
01233   memset (ops, 0, sizeof (struct serial_ops));
01234   ops->name = "hardwire";
01235   ops->next = 0;
01236   ops->open = ser_windows_open;
01237   ops->close = ser_windows_close;
01238 
01239   ops->flush_output = ser_windows_flush_output;
01240   ops->flush_input = ser_windows_flush_input;
01241   ops->send_break = ser_windows_send_break;
01242 
01243   /* These are only used for stdin; we do not need them for serial
01244      ports, so supply the standard dummies.  */
01245   ops->get_tty_state = ser_base_get_tty_state;
01246   ops->copy_tty_state = ser_base_copy_tty_state;
01247   ops->set_tty_state = ser_base_set_tty_state;
01248   ops->print_tty_state = ser_base_print_tty_state;
01249   ops->noflush_set_tty_state = ser_base_noflush_set_tty_state;
01250 
01251   ops->go_raw = ser_windows_raw;
01252   ops->setbaudrate = ser_windows_setbaudrate;
01253   ops->setstopbits = ser_windows_setstopbits;
01254   ops->drain_output = ser_windows_drain_output;
01255   ops->readchar = ser_base_readchar;
01256   ops->write = ser_base_write;
01257   ops->async = ser_base_async;
01258   ops->read_prim = ser_windows_read_prim;
01259   ops->write_prim = ser_windows_write_prim;
01260   ops->wait_handle = ser_windows_wait_handle;
01261 
01262   serial_add_interface (ops);
01263 
01264   /* Next create the dummy serial driver used for terminals.  We only
01265      provide the TTY-related methods.  */
01266 
01267   ops = XMALLOC (struct serial_ops);
01268   memset (ops, 0, sizeof (struct serial_ops));
01269 
01270   ops->name = "terminal";
01271   ops->next = 0;
01272 
01273   ops->close = ser_console_close;
01274   ops->get_tty_state = ser_console_get_tty_state;
01275   ops->copy_tty_state = ser_base_copy_tty_state;
01276   ops->set_tty_state = ser_base_set_tty_state;
01277   ops->print_tty_state = ser_base_print_tty_state;
01278   ops->noflush_set_tty_state = ser_base_noflush_set_tty_state;
01279   ops->drain_output = ser_base_drain_output;
01280   ops->wait_handle = ser_console_wait_handle;
01281   ops->done_wait_handle = ser_console_done_wait_handle;
01282 
01283   serial_add_interface (ops);
01284 
01285   /* The pipe interface.  */
01286 
01287   ops = XMALLOC (struct serial_ops);
01288   memset (ops, 0, sizeof (struct serial_ops));
01289   ops->name = "pipe";
01290   ops->next = 0;
01291   ops->open = pipe_windows_open;
01292   ops->close = pipe_windows_close;
01293   ops->fdopen = pipe_windows_fdopen;
01294   ops->readchar = ser_base_readchar;
01295   ops->write = ser_base_write;
01296   ops->flush_output = ser_base_flush_output;
01297   ops->flush_input = ser_base_flush_input;
01298   ops->send_break = ser_base_send_break;
01299   ops->go_raw = ser_base_raw;
01300   ops->get_tty_state = ser_base_get_tty_state;
01301   ops->copy_tty_state = ser_base_copy_tty_state;
01302   ops->set_tty_state = ser_base_set_tty_state;
01303   ops->print_tty_state = ser_base_print_tty_state;
01304   ops->noflush_set_tty_state = ser_base_noflush_set_tty_state;
01305   ops->setbaudrate = ser_base_setbaudrate;
01306   ops->setstopbits = ser_base_setstopbits;
01307   ops->drain_output = ser_base_drain_output;
01308   ops->async = ser_base_async;
01309   ops->read_prim = pipe_windows_read;
01310   ops->write_prim = pipe_windows_write;
01311   ops->wait_handle = pipe_wait_handle;
01312   ops->done_wait_handle = pipe_done_wait_handle;
01313   ops->avail = pipe_avail;
01314 
01315   serial_add_interface (ops);
01316 
01317   /* If WinSock works, register the TCP/UDP socket driver.  */
01318 
01319   if (WSAStartup (MAKEWORD (1, 0), &wsa_data) != 0)
01320     /* WinSock is unavailable.  */
01321     return;
01322 
01323   ops = XMALLOC (struct serial_ops);
01324   memset (ops, 0, sizeof (struct serial_ops));
01325   ops->name = "tcp";
01326   ops->next = 0;
01327   ops->open = net_windows_open;
01328   ops->close = net_windows_close;
01329   ops->readchar = ser_base_readchar;
01330   ops->write = ser_base_write;
01331   ops->flush_output = ser_base_flush_output;
01332   ops->flush_input = ser_base_flush_input;
01333   ops->send_break = ser_tcp_send_break;
01334   ops->go_raw = ser_base_raw;
01335   ops->get_tty_state = ser_base_get_tty_state;
01336   ops->copy_tty_state = ser_base_copy_tty_state;
01337   ops->set_tty_state = ser_base_set_tty_state;
01338   ops->print_tty_state = ser_base_print_tty_state;
01339   ops->noflush_set_tty_state = ser_base_noflush_set_tty_state;
01340   ops->setbaudrate = ser_base_setbaudrate;
01341   ops->setstopbits = ser_base_setstopbits;
01342   ops->drain_output = ser_base_drain_output;
01343   ops->async = ser_base_async;
01344   ops->read_prim = net_read_prim;
01345   ops->write_prim = net_write_prim;
01346   ops->wait_handle = net_windows_wait_handle;
01347   ops->done_wait_handle = net_windows_done_wait_handle;
01348   serial_add_interface (ops);
01349 }
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Defines