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