Automatic date update in version.in
[binutils-gdb.git] / gdb / ser-mingw.c
blob5c2e06c292626c1ca714f315051805b4ee6bda3a
1 /* Serial interface for local (hardwired) serial ports on Windows systems
3 Copyright (C) 2006-2024 Free Software Foundation, Inc.
5 This file is part of GDB.
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.
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.
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/>. */
20 #include "defs.h"
21 #include "serial.h"
22 #include "ser-base.h"
23 #include "ser-tcp.h"
25 #include <windows.h>
26 #include <conio.h>
28 #include <fcntl.h>
29 #include <unistd.h>
30 #include <sys/types.h>
32 #include "command.h"
33 #include "gdbsupport/buildargv.h"
35 struct ser_windows_state
37 int in_progress;
38 OVERLAPPED ov;
39 DWORD lastCommMask;
40 HANDLE except_event;
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;
49 /* Open up a real live device for serial I/O. */
51 static void
52 ser_windows_open (struct serial *scb, const char *name)
54 HANDLE h;
55 struct ser_windows_state *state;
56 COMMTIMEOUTS timeouts;
58 h = CreateFile (name, GENERIC_READ | GENERIC_WRITE, 0, NULL,
59 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
60 if (h == INVALID_HANDLE_VALUE)
62 std::string msg = string_printf(_("could not open file: %s"),
63 name);
64 throw_winerror_with_name (msg.c_str (), GetLastError ());
67 scb->fd = _open_osfhandle ((intptr_t) h, O_RDWR);
68 if (scb->fd < 0)
69 error (_("could not get underlying file descriptor"));
71 if (!SetCommMask (h, EV_RXCHAR))
72 throw_winerror_with_name (_("error calling SetCommMask"),
73 GetLastError ());
75 timeouts.ReadIntervalTimeout = MAXDWORD;
76 timeouts.ReadTotalTimeoutConstant = 0;
77 timeouts.ReadTotalTimeoutMultiplier = 0;
78 timeouts.WriteTotalTimeoutConstant = 0;
79 timeouts.WriteTotalTimeoutMultiplier = 0;
80 if (!SetCommTimeouts (h, &timeouts))
81 throw_winerror_with_name (_("error calling SetCommTimeouts"),
82 GetLastError ());
84 state = XCNEW (struct ser_windows_state);
85 scb->state = state;
87 /* Create a manual reset event to watch the input buffer. */
88 state->ov.hEvent = CreateEvent (0, TRUE, FALSE, 0);
90 /* Create a (currently unused) handle to record exceptions. */
91 state->except_event = CreateEvent (0, TRUE, FALSE, 0);
94 /* Wait for the output to drain away, as opposed to flushing (discarding)
95 it. */
97 static int
98 ser_windows_drain_output (struct serial *scb)
100 HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
102 return (FlushFileBuffers (h) != 0) ? 0 : -1;
105 static int
106 ser_windows_flush_output (struct serial *scb)
108 HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
110 return (PurgeComm (h, PURGE_TXCLEAR) != 0) ? 0 : -1;
113 static int
114 ser_windows_flush_input (struct serial *scb)
116 HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
118 return (PurgeComm (h, PURGE_RXCLEAR) != 0) ? 0 : -1;
121 static void
122 ser_windows_send_break (struct serial *scb)
124 HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
126 if (SetCommBreak (h) == 0)
127 throw_winerror_with_name ("error calling SetCommBreak",
128 GetLastError ());
130 /* Delay for 250 milliseconds. */
131 Sleep (250);
133 if (ClearCommBreak (h) == 0)
134 throw_winerror_with_name ("error calling ClearCommBreak",
135 GetLastError ());
138 static void
139 ser_windows_raw (struct serial *scb)
141 HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
142 DCB state;
144 if (GetCommState (h, &state) == 0)
145 return;
147 state.fOutxCtsFlow = FALSE;
148 state.fOutxDsrFlow = FALSE;
149 state.fDtrControl = DTR_CONTROL_ENABLE;
150 state.fDsrSensitivity = FALSE;
151 state.fOutX = FALSE;
152 state.fInX = FALSE;
153 state.fNull = FALSE;
154 state.fAbortOnError = FALSE;
155 state.ByteSize = 8;
157 if (SetCommState (h, &state) == 0)
158 warning (_("SetCommState failed"));
161 static int
162 ser_windows_setstopbits (struct serial *scb, int num)
164 HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
165 DCB state;
167 if (GetCommState (h, &state) == 0)
168 return -1;
170 switch (num)
172 case SERIAL_1_STOPBITS:
173 state.StopBits = ONESTOPBIT;
174 break;
175 case SERIAL_1_AND_A_HALF_STOPBITS:
176 state.StopBits = ONE5STOPBITS;
177 break;
178 case SERIAL_2_STOPBITS:
179 state.StopBits = TWOSTOPBITS;
180 break;
181 default:
182 return 1;
185 return (SetCommState (h, &state) != 0) ? 0 : -1;
188 /* Implement the "setparity" serial_ops callback. */
190 static int
191 ser_windows_setparity (struct serial *scb, int parity)
193 HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
194 DCB state;
196 if (GetCommState (h, &state) == 0)
197 return -1;
199 switch (parity)
201 case GDBPARITY_NONE:
202 state.Parity = NOPARITY;
203 state.fParity = FALSE;
204 break;
205 case GDBPARITY_ODD:
206 state.Parity = ODDPARITY;
207 state.fParity = TRUE;
208 break;
209 case GDBPARITY_EVEN:
210 state.Parity = EVENPARITY;
211 state.fParity = TRUE;
212 break;
213 default:
214 internal_warning ("Incorrect parity value: %d", parity);
215 return -1;
218 return (SetCommState (h, &state) != 0) ? 0 : -1;
221 static void
222 ser_windows_setbaudrate (struct serial *scb, int rate)
224 HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
225 DCB state;
227 if (GetCommState (h, &state) == 0)
228 throw_winerror_with_name ("call to GetCommState failed", GetLastError ());
230 state.BaudRate = rate;
232 if (SetCommState (h, &state) == 0)
233 throw_winerror_with_name ("call to SetCommState failed", GetLastError ());
236 static void
237 ser_windows_close (struct serial *scb)
239 struct ser_windows_state *state;
241 /* Stop any pending selects. On Windows 95 OS, CancelIo function does
242 not exist. In that case, it can be replaced by a call to CloseHandle,
243 but this is not necessary here as we do close the Windows handle
244 by calling close (scb->fd) below. */
245 if (CancelIo)
246 CancelIo ((HANDLE) _get_osfhandle (scb->fd));
247 state = (struct ser_windows_state *) scb->state;
248 CloseHandle (state->ov.hEvent);
249 CloseHandle (state->except_event);
251 if (scb->fd < 0)
252 return;
254 close (scb->fd);
255 scb->fd = -1;
257 xfree (scb->state);
260 static void
261 ser_windows_wait_handle (struct serial *scb, HANDLE *read, HANDLE *except)
263 struct ser_windows_state *state;
264 COMSTAT status;
265 DWORD errors;
266 HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
268 state = (struct ser_windows_state *) scb->state;
270 *except = state->except_event;
271 *read = state->ov.hEvent;
273 if (state->in_progress)
274 return;
276 /* Reset the mask - we are only interested in any characters which
277 arrive after this point, not characters which might have arrived
278 and already been read. */
280 /* This really, really shouldn't be necessary - just the second one.
281 But otherwise an internal flag for EV_RXCHAR does not get
282 cleared, and we get a duplicated event, if the last batch
283 of characters included at least two arriving close together. */
284 if (!SetCommMask (h, 0))
285 warning (_("ser_windows_wait_handle: reseting mask failed"));
287 if (!SetCommMask (h, EV_RXCHAR))
288 warning (_("ser_windows_wait_handle: reseting mask failed (2)"));
290 /* There's a potential race condition here; we must check cbInQue
291 and not wait if that's nonzero. */
293 ClearCommError (h, &errors, &status);
294 if (status.cbInQue > 0)
296 SetEvent (state->ov.hEvent);
297 return;
300 state->in_progress = 1;
301 ResetEvent (state->ov.hEvent);
302 state->lastCommMask = -2;
303 if (WaitCommEvent (h, &state->lastCommMask, &state->ov))
305 gdb_assert (state->lastCommMask & EV_RXCHAR);
306 SetEvent (state->ov.hEvent);
308 else
309 gdb_assert (GetLastError () == ERROR_IO_PENDING);
312 static int
313 ser_windows_read_prim (struct serial *scb, size_t count)
315 struct ser_windows_state *state;
316 OVERLAPPED ov;
317 DWORD bytes_read;
318 HANDLE h;
320 state = (struct ser_windows_state *) scb->state;
321 if (state->in_progress)
323 WaitForSingleObject (state->ov.hEvent, INFINITE);
324 state->in_progress = 0;
325 ResetEvent (state->ov.hEvent);
328 memset (&ov, 0, sizeof (OVERLAPPED));
329 ov.hEvent = CreateEvent (0, FALSE, FALSE, 0);
330 h = (HANDLE) _get_osfhandle (scb->fd);
332 if (!ReadFile (h, scb->buf, /* count */ 1, &bytes_read, &ov))
334 if (GetLastError () != ERROR_IO_PENDING
335 || !GetOverlappedResult (h, &ov, &bytes_read, TRUE))
337 ULONGEST err = GetLastError ();
338 CloseHandle (ov.hEvent);
339 throw_winerror_with_name (_("error while reading"), err);
343 CloseHandle (ov.hEvent);
344 return bytes_read;
347 static int
348 ser_windows_write_prim (struct serial *scb, const void *buf, size_t len)
350 OVERLAPPED ov;
351 DWORD bytes_written;
352 HANDLE h;
354 memset (&ov, 0, sizeof (OVERLAPPED));
355 ov.hEvent = CreateEvent (0, FALSE, FALSE, 0);
356 h = (HANDLE) _get_osfhandle (scb->fd);
357 if (!WriteFile (h, buf, len, &bytes_written, &ov))
359 if (GetLastError () != ERROR_IO_PENDING
360 || !GetOverlappedResult (h, &ov, &bytes_written, TRUE))
361 throw_winerror_with_name ("error while writing", GetLastError ());
364 CloseHandle (ov.hEvent);
365 return bytes_written;
368 /* On Windows, gdb_select is implemented using WaitForMulpleObjects.
369 A "select thread" is created for each file descriptor. These
370 threads looks for activity on the corresponding descriptor, using
371 whatever techniques are appropriate for the descriptor type. When
372 that activity occurs, the thread signals an appropriate event,
373 which wakes up WaitForMultipleObjects.
375 Each select thread is in one of two states: stopped or started.
376 Select threads begin in the stopped state. When gdb_select is
377 called, threads corresponding to the descriptors of interest are
378 started by calling a wait_handle function. Each thread that
379 notices activity signals the appropriate event and then reenters
380 the stopped state. Before gdb_select returns it calls the
381 wait_handle_done functions, which return the threads to the stopped
382 state. */
384 enum select_thread_state {
385 STS_STARTED,
386 STS_STOPPED
389 struct ser_console_state
391 /* Signaled by the select thread to indicate that data is available
392 on the file descriptor. */
393 HANDLE read_event;
394 /* Signaled by the select thread to indicate that an exception has
395 occurred on the file descriptor. */
396 HANDLE except_event;
397 /* Signaled by the select thread to indicate that it has entered the
398 started state. HAVE_STARTED and HAVE_STOPPED are never signaled
399 simultaneously. */
400 HANDLE have_started;
401 /* Signaled by the select thread to indicate that it has stopped,
402 either because data is available (and READ_EVENT is signaled),
403 because an exception has occurred (and EXCEPT_EVENT is signaled),
404 or because STOP_SELECT was signaled. */
405 HANDLE have_stopped;
407 /* Signaled by the main program to tell the select thread to enter
408 the started state. */
409 HANDLE start_select;
410 /* Signaled by the main program to tell the select thread to enter
411 the stopped state. */
412 HANDLE stop_select;
413 /* Signaled by the main program to tell the select thread to
414 exit. */
415 HANDLE exit_select;
417 /* The handle for the select thread. */
418 HANDLE thread;
419 /* The state of the select thread. This field is only accessed in
420 the main program, never by the select thread itself. */
421 enum select_thread_state thread_state;
424 /* Called by a select thread to enter the stopped state. This
425 function does not return until the thread has re-entered the
426 started state. */
427 static void
428 select_thread_wait (struct ser_console_state *state)
430 HANDLE wait_events[2];
432 /* There are two things that can wake us up: a request that we enter
433 the started state, or that we exit this thread. */
434 wait_events[0] = state->start_select;
435 wait_events[1] = state->exit_select;
436 if (WaitForMultipleObjects (2, wait_events, FALSE, INFINITE)
437 != WAIT_OBJECT_0)
438 /* Either the EXIT_SELECT event was signaled (requesting that the
439 thread exit) or an error has occurred. In either case, we exit
440 the thread. */
441 ExitThread (0);
443 /* We are now in the started state. */
444 SetEvent (state->have_started);
447 typedef DWORD WINAPI (*thread_fn_type)(void *);
449 /* Create a new select thread for SCB executing THREAD_FN. The STATE
450 will be filled in by this function before return. */
451 static void
452 create_select_thread (thread_fn_type thread_fn,
453 struct serial *scb,
454 struct ser_console_state *state)
456 DWORD threadId;
458 /* Create all of the events. These are all auto-reset events. */
459 state->read_event = CreateEvent (NULL, FALSE, FALSE, NULL);
460 state->except_event = CreateEvent (NULL, FALSE, FALSE, NULL);
461 state->have_started = CreateEvent (NULL, FALSE, FALSE, NULL);
462 state->have_stopped = CreateEvent (NULL, FALSE, FALSE, NULL);
463 state->start_select = CreateEvent (NULL, FALSE, FALSE, NULL);
464 state->stop_select = CreateEvent (NULL, FALSE, FALSE, NULL);
465 state->exit_select = CreateEvent (NULL, FALSE, FALSE, NULL);
467 state->thread = CreateThread (NULL, 0, thread_fn, scb, 0, &threadId);
468 /* The thread begins in the stopped state. */
469 state->thread_state = STS_STOPPED;
472 /* Destroy the select thread indicated by STATE. */
473 static void
474 destroy_select_thread (struct ser_console_state *state)
476 /* Ask the thread to exit. */
477 SetEvent (state->exit_select);
478 /* Wait until it does. */
479 WaitForSingleObject (state->thread, INFINITE);
481 /* Destroy the events. */
482 CloseHandle (state->read_event);
483 CloseHandle (state->except_event);
484 CloseHandle (state->have_started);
485 CloseHandle (state->have_stopped);
486 CloseHandle (state->start_select);
487 CloseHandle (state->stop_select);
488 CloseHandle (state->exit_select);
491 /* Called by gdb_select to start the select thread indicated by STATE.
492 This function does not return until the thread has started. */
493 static void
494 start_select_thread (struct ser_console_state *state)
496 /* Ask the thread to start. */
497 SetEvent (state->start_select);
498 /* Wait until it does. */
499 WaitForSingleObject (state->have_started, INFINITE);
500 /* The thread is now started. */
501 state->thread_state = STS_STARTED;
504 /* Called by gdb_select to stop the select thread indicated by STATE.
505 This function does not return until the thread has stopped. */
506 static void
507 stop_select_thread (struct ser_console_state *state)
509 /* If the thread is already in the stopped state, we have nothing to
510 do. Some of the wait_handle functions avoid calling
511 start_select_thread if they notice activity on the relevant file
512 descriptors. The wait_handle_done functions still call
513 stop_select_thread -- but it is already stopped. */
514 if (state->thread_state != STS_STARTED)
515 return;
516 /* Ask the thread to stop. */
517 SetEvent (state->stop_select);
518 /* Wait until it does. */
519 WaitForSingleObject (state->have_stopped, INFINITE);
520 /* The thread is now stopped. */
521 state->thread_state = STS_STOPPED;
524 static DWORD WINAPI
525 console_select_thread (void *arg)
527 struct serial *scb = (struct serial *) arg;
528 struct ser_console_state *state;
529 int event_index;
530 HANDLE h;
532 state = (struct ser_console_state *) scb->state;
533 h = (HANDLE) _get_osfhandle (scb->fd);
535 while (1)
537 HANDLE wait_events[2];
538 INPUT_RECORD record;
539 DWORD n_records;
541 select_thread_wait (state);
543 while (1)
545 wait_events[0] = state->stop_select;
546 wait_events[1] = h;
548 event_index = WaitForMultipleObjects (2, wait_events,
549 FALSE, INFINITE);
551 if (event_index == WAIT_OBJECT_0
552 || WaitForSingleObject (state->stop_select, 0) == WAIT_OBJECT_0)
553 break;
555 if (event_index != WAIT_OBJECT_0 + 1)
557 /* Wait must have failed; assume an error has occurred, e.g.
558 the handle has been closed. */
559 SetEvent (state->except_event);
560 break;
563 /* We've got a pending event on the console. See if it's
564 of interest. */
565 if (!PeekConsoleInput (h, &record, 1, &n_records) || n_records != 1)
567 /* Something went wrong. Maybe the console is gone. */
568 SetEvent (state->except_event);
569 break;
572 if (record.EventType == KEY_EVENT && record.Event.KeyEvent.bKeyDown)
574 WORD keycode = record.Event.KeyEvent.wVirtualKeyCode;
576 /* Ignore events containing only control keys. We must
577 recognize "enhanced" keys which we are interested in
578 reading via getch, if they do not map to ASCII. But we
579 do not want to report input available for e.g. the
580 control key alone. */
582 if (record.Event.KeyEvent.uChar.AsciiChar != 0
583 || keycode == VK_PRIOR
584 || keycode == VK_NEXT
585 || keycode == VK_END
586 || keycode == VK_HOME
587 || keycode == VK_LEFT
588 || keycode == VK_UP
589 || keycode == VK_RIGHT
590 || keycode == VK_DOWN
591 || keycode == VK_INSERT
592 || keycode == VK_DELETE)
594 /* This is really a keypress. */
595 SetEvent (state->read_event);
596 break;
599 else if (record.EventType == MOUSE_EVENT)
601 SetEvent (state->read_event);
602 break;
605 /* Otherwise discard it and wait again. */
606 ReadConsoleInput (h, &record, 1, &n_records);
609 SetEvent(state->have_stopped);
611 return 0;
614 static int
615 fd_is_pipe (int fd)
617 if (PeekNamedPipe ((HANDLE) _get_osfhandle (fd), NULL, 0, NULL, NULL, NULL))
618 return 1;
619 else
620 return 0;
623 static int
624 fd_is_file (int fd)
626 if (GetFileType ((HANDLE) _get_osfhandle (fd)) == FILE_TYPE_DISK)
627 return 1;
628 else
629 return 0;
632 static DWORD WINAPI
633 pipe_select_thread (void *arg)
635 struct serial *scb = (struct serial *) arg;
636 struct ser_console_state *state;
637 HANDLE h;
639 state = (struct ser_console_state *) scb->state;
640 h = (HANDLE) _get_osfhandle (scb->fd);
642 while (1)
644 DWORD n_avail;
646 select_thread_wait (state);
648 /* Wait for something to happen on the pipe. */
649 while (1)
651 if (!PeekNamedPipe (h, NULL, 0, NULL, &n_avail, NULL))
653 SetEvent (state->except_event);
654 break;
657 if (n_avail > 0)
659 SetEvent (state->read_event);
660 break;
663 /* Delay 10ms before checking again, but allow the stop
664 event to wake us. */
665 if (WaitForSingleObject (state->stop_select, 10) == WAIT_OBJECT_0)
666 break;
669 SetEvent (state->have_stopped);
671 return 0;
674 static DWORD WINAPI
675 file_select_thread (void *arg)
677 struct serial *scb = (struct serial *) arg;
678 struct ser_console_state *state;
679 HANDLE h;
681 state = (struct ser_console_state *) scb->state;
682 h = (HANDLE) _get_osfhandle (scb->fd);
684 while (1)
686 select_thread_wait (state);
688 if (SetFilePointer (h, 0, NULL, FILE_CURRENT)
689 == INVALID_SET_FILE_POINTER)
690 SetEvent (state->except_event);
691 else
692 SetEvent (state->read_event);
694 SetEvent (state->have_stopped);
696 return 0;
699 static void
700 ser_console_wait_handle (struct serial *scb, HANDLE *read, HANDLE *except)
702 struct ser_console_state *state = (struct ser_console_state *) scb->state;
704 if (state == NULL)
706 thread_fn_type thread_fn;
707 int is_tty;
709 is_tty = isatty (scb->fd);
710 if (!is_tty && !fd_is_file (scb->fd) && !fd_is_pipe (scb->fd))
712 *read = NULL;
713 *except = NULL;
714 return;
717 state = XCNEW (struct ser_console_state);
718 scb->state = state;
720 if (is_tty)
721 thread_fn = console_select_thread;
722 else if (fd_is_pipe (scb->fd))
723 thread_fn = pipe_select_thread;
724 else
725 thread_fn = file_select_thread;
727 create_select_thread (thread_fn, scb, state);
730 *read = state->read_event;
731 *except = state->except_event;
733 /* Start from a blank state. */
734 ResetEvent (state->read_event);
735 ResetEvent (state->except_event);
736 ResetEvent (state->stop_select);
738 /* First check for a key already in the buffer. If there is one,
739 we don't need a thread. This also catches the second key of
740 multi-character returns from getch, for instance for arrow
741 keys. The second half is in a C library internal buffer,
742 and PeekConsoleInput will not find it. */
743 if (_kbhit ())
745 SetEvent (state->read_event);
746 return;
749 /* Otherwise, start the select thread. */
750 start_select_thread (state);
753 static void
754 ser_console_done_wait_handle (struct serial *scb)
756 struct ser_console_state *state = (struct ser_console_state *) scb->state;
758 if (state == NULL)
759 return;
761 stop_select_thread (state);
764 static void
765 ser_console_close (struct serial *scb)
767 struct ser_console_state *state = (struct ser_console_state *) scb->state;
769 if (scb->state)
771 destroy_select_thread (state);
772 xfree (scb->state);
776 struct ser_console_ttystate
778 int is_a_tty;
781 static serial_ttystate
782 ser_console_get_tty_state (struct serial *scb)
784 if (isatty (scb->fd))
786 struct ser_console_ttystate *state;
788 state = XNEW (struct ser_console_ttystate);
789 state->is_a_tty = 1;
790 return state;
792 else
793 return NULL;
796 struct pipe_state
798 /* Since we use the pipe_select_thread for our select emulation,
799 we need to place the state structure it requires at the front
800 of our state. */
801 struct ser_console_state wait;
803 /* The pex obj for our (one-stage) pipeline. */
804 struct pex_obj *pex;
806 /* Streams for the pipeline's input and output. */
807 FILE *input, *output;
810 static struct pipe_state *
811 make_pipe_state (void)
813 struct pipe_state *ps = XCNEW (struct pipe_state);
815 ps->wait.read_event = INVALID_HANDLE_VALUE;
816 ps->wait.except_event = INVALID_HANDLE_VALUE;
817 ps->wait.start_select = INVALID_HANDLE_VALUE;
818 ps->wait.stop_select = INVALID_HANDLE_VALUE;
820 return ps;
823 static void
824 free_pipe_state (struct pipe_state *ps)
826 int saved_errno = errno;
828 if (ps->wait.read_event != INVALID_HANDLE_VALUE)
829 destroy_select_thread (&ps->wait);
831 /* Close the pipe to the child. We must close the pipe before
832 calling pex_free because pex_free will wait for the child to exit
833 and the child will not exit until the pipe is closed. */
834 if (ps->input)
835 fclose (ps->input);
836 if (ps->pex)
838 pex_free (ps->pex);
839 /* pex_free closes ps->output. */
841 else if (ps->output)
842 fclose (ps->output);
844 xfree (ps);
846 errno = saved_errno;
849 struct pipe_state_destroyer
851 void operator() (pipe_state *ps) const
853 free_pipe_state (ps);
857 typedef std::unique_ptr<pipe_state, pipe_state_destroyer> pipe_state_up;
859 static void
860 pipe_windows_open (struct serial *scb, const char *name)
862 FILE *pex_stderr;
864 if (name == NULL)
865 error_no_arg (_("child command"));
867 if (*name == '|')
869 name++;
870 name = skip_spaces (name);
873 gdb_argv argv (name);
875 if (! argv[0] || argv[0][0] == '\0')
876 error (_("missing child command"));
878 pipe_state_up ps (make_pipe_state ());
880 ps->pex = pex_init (PEX_USE_PIPES, "target remote pipe", NULL);
881 if (! ps->pex)
882 error (_("could not start pipeline"));
883 ps->input = pex_input_pipe (ps->pex, 1);
884 if (! ps->input)
885 error (_("could not find input pipe"));
888 int err;
889 const char *err_msg
890 = pex_run (ps->pex, PEX_SEARCH | PEX_BINARY_INPUT | PEX_BINARY_OUTPUT
891 | PEX_STDERR_TO_PIPE,
892 argv[0], argv.get (), NULL, NULL,
893 &err);
895 if (err_msg)
897 /* Our caller expects us to return -1, but all they'll do with
898 it generally is print the message based on errno. We have
899 all the same information here, plus err_msg provided by
900 pex_run, so we just raise the error here. */
901 if (err)
902 error (_("error starting child process '%s': %s: %s"),
903 name, err_msg, safe_strerror (err));
904 else
905 error (_("error starting child process '%s': %s"),
906 name, err_msg);
910 ps->output = pex_read_output (ps->pex, 1);
911 if (! ps->output)
912 error (_("could not find output pipe"));
913 scb->fd = fileno (ps->output);
915 pex_stderr = pex_read_err (ps->pex, 1);
916 if (! pex_stderr)
917 error (_("could not find error pipe"));
918 scb->error_fd = fileno (pex_stderr);
920 scb->state = ps.release ();
923 static int
924 pipe_windows_fdopen (struct serial *scb, int fd)
926 struct pipe_state *ps;
928 ps = make_pipe_state ();
930 ps->input = fdopen (fd, "r+");
931 if (! ps->input)
932 goto fail;
934 ps->output = fdopen (fd, "r+");
935 if (! ps->output)
936 goto fail;
938 scb->fd = fd;
939 scb->state = (void *) ps;
941 return 0;
943 fail:
944 free_pipe_state (ps);
945 return -1;
948 static void
949 pipe_windows_close (struct serial *scb)
951 struct pipe_state *ps = (struct pipe_state *) scb->state;
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. */
957 free_pipe_state (ps);
961 static int
962 pipe_windows_read (struct serial *scb, size_t count)
964 HANDLE pipeline_out = (HANDLE) _get_osfhandle (scb->fd);
965 DWORD available;
966 DWORD bytes_read;
968 if (pipeline_out == INVALID_HANDLE_VALUE)
969 error (_("could not find file number for pipe"));
971 if (! PeekNamedPipe (pipeline_out, NULL, 0, NULL, &available, NULL))
972 throw_winerror_with_name (_("could not peek into pipe"), GetLastError ());
974 if (count > available)
975 count = available;
977 if (! ReadFile (pipeline_out, scb->buf, count, &bytes_read, NULL))
978 throw_winerror_with_name (_("could not read from pipe"), GetLastError ());
980 return bytes_read;
984 static int
985 pipe_windows_write (struct serial *scb, const void *buf, size_t count)
987 struct pipe_state *ps = (struct pipe_state *) scb->state;
988 HANDLE pipeline_in;
989 DWORD written;
991 int pipeline_in_fd = fileno (ps->input);
992 if (pipeline_in_fd < 0)
993 error (_("could not find file number for pipe"));
995 pipeline_in = (HANDLE) _get_osfhandle (pipeline_in_fd);
996 if (pipeline_in == INVALID_HANDLE_VALUE)
997 error (_("could not find handle for pipe"));
999 if (! WriteFile (pipeline_in, buf, count, &written, NULL))
1000 throw_winerror_with_name (_("could not write to pipe"), GetLastError ());
1002 return written;
1006 static void
1007 pipe_wait_handle (struct serial *scb, HANDLE *read, HANDLE *except)
1009 struct pipe_state *ps = (struct pipe_state *) scb->state;
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);
1016 *read = ps->wait.read_event;
1017 *except = ps->wait.except_event;
1019 /* Start from a blank state. */
1020 ResetEvent (ps->wait.read_event);
1021 ResetEvent (ps->wait.except_event);
1022 ResetEvent (ps->wait.stop_select);
1024 start_select_thread (&ps->wait);
1027 static void
1028 pipe_done_wait_handle (struct serial *scb)
1030 struct pipe_state *ps = (struct pipe_state *) scb->state;
1032 /* Have we allocated our events yet? */
1033 if (ps->wait.read_event == INVALID_HANDLE_VALUE)
1034 return;
1036 stop_select_thread (&ps->wait);
1039 static int
1040 pipe_avail (struct serial *scb, int fd)
1042 HANDLE h = (HANDLE) _get_osfhandle (fd);
1043 DWORD numBytes;
1044 BOOL r = PeekNamedPipe (h, NULL, 0, NULL, &numBytes, NULL);
1046 if (r == FALSE)
1047 numBytes = 0;
1048 return numBytes;
1052 gdb_pipe (int pdes[2])
1054 if (_pipe (pdes, 512, _O_BINARY | _O_NOINHERIT) == -1)
1055 return -1;
1056 return 0;
1059 struct net_windows_state
1061 struct ser_console_state base;
1063 HANDLE sock_event;
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. */
1071 static int
1072 net_windows_socket_check_pending (struct serial *scb)
1074 struct net_windows_state *state = (struct net_windows_state *) scb->state;
1075 unsigned long available;
1077 if (ioctlsocket (scb->fd, FIONREAD, &available) != 0)
1079 /* The socket closed, or some other error. */
1080 SetEvent (state->base.except_event);
1081 return 1;
1083 else if (available > 0)
1085 SetEvent (state->base.read_event);
1086 return 1;
1089 return 0;
1092 static DWORD WINAPI
1093 net_windows_select_thread (void *arg)
1095 struct serial *scb = (struct serial *) arg;
1096 struct net_windows_state *state;
1097 int event_index;
1099 state = (struct net_windows_state *) scb->state;
1101 while (1)
1103 HANDLE wait_events[2];
1104 WSANETWORKEVENTS events;
1106 select_thread_wait (&state->base);
1108 wait_events[0] = state->base.stop_select;
1109 wait_events[1] = state->sock_event;
1111 /* Wait for something to happen on the socket. */
1112 while (1)
1114 event_index = WaitForMultipleObjects (2, wait_events, FALSE, INFINITE);
1116 if (event_index == WAIT_OBJECT_0
1117 || WaitForSingleObject (state->base.stop_select, 0) == WAIT_OBJECT_0)
1119 /* We have been requested to stop. */
1120 break;
1123 if (event_index != WAIT_OBJECT_0 + 1)
1125 /* Some error has occurred. Assume that this is an error
1126 condition. */
1127 SetEvent (state->base.except_event);
1128 break;
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)
1135 /* Something went wrong. Maybe the socket is gone. */
1136 SetEvent (state->base.except_event);
1137 break;
1140 if (events.lNetworkEvents & FD_READ)
1142 if (net_windows_socket_check_pending (scb))
1143 break;
1145 /* Spurious wakeup. That is, the socket's event was
1146 signalled before we last called recv. */
1149 if (events.lNetworkEvents & FD_CLOSE)
1151 SetEvent (state->base.except_event);
1152 break;
1156 SetEvent (state->base.have_stopped);
1158 return 0;
1161 static void
1162 net_windows_wait_handle (struct serial *scb, HANDLE *read, HANDLE *except)
1164 struct net_windows_state *state = (struct net_windows_state *) scb->state;
1166 /* Start from a clean slate. */
1167 ResetEvent (state->base.read_event);
1168 ResetEvent (state->base.except_event);
1169 ResetEvent (state->base.stop_select);
1171 *read = state->base.read_event;
1172 *except = state->base.except_event;
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);
1180 static void
1181 net_windows_done_wait_handle (struct serial *scb)
1183 struct net_windows_state *state = (struct net_windows_state *) scb->state;
1185 stop_select_thread (&state->base);
1188 static void
1189 net_windows_open (struct serial *scb, const char *name)
1191 struct net_windows_state *state;
1193 net_open (scb, name);
1195 state = XCNEW (struct net_windows_state);
1196 scb->state = state;
1198 /* Associate an event with the socket. */
1199 state->sock_event = CreateEvent (0, TRUE, FALSE, 0);
1200 WSAEventSelect (scb->fd, state->sock_event, FD_READ | FD_CLOSE);
1202 /* Start the thread. */
1203 create_select_thread (net_windows_select_thread, scb, &state->base);
1207 static void
1208 net_windows_close (struct serial *scb)
1210 struct net_windows_state *state = (struct net_windows_state *) scb->state;
1212 destroy_select_thread (&state->base);
1213 CloseHandle (state->sock_event);
1215 xfree (scb->state);
1217 net_close (scb);
1220 /* The serial port driver. */
1222 static const struct serial_ops hardwire_ops =
1224 "hardwire",
1225 ser_windows_open,
1226 ser_windows_close,
1227 NULL,
1228 ser_base_readchar,
1229 ser_base_write,
1230 ser_windows_flush_output,
1231 ser_windows_flush_input,
1232 ser_windows_send_break,
1233 ser_windows_raw,
1234 /* These are only used for stdin; we do not need them for serial
1235 ports, so supply the standard dummies. */
1236 ser_base_get_tty_state,
1237 ser_base_copy_tty_state,
1238 ser_base_set_tty_state,
1239 ser_base_print_tty_state,
1240 ser_windows_setbaudrate,
1241 ser_windows_setstopbits,
1242 ser_windows_setparity,
1243 ser_windows_drain_output,
1244 ser_base_async,
1245 ser_windows_read_prim,
1246 ser_windows_write_prim,
1247 NULL,
1248 ser_windows_wait_handle
1251 /* The dummy serial driver used for terminals. We only provide the
1252 TTY-related methods. */
1254 static const struct serial_ops tty_ops =
1256 "terminal",
1257 NULL,
1258 ser_console_close,
1259 NULL,
1260 NULL,
1261 NULL,
1262 NULL,
1263 NULL,
1264 NULL,
1265 NULL,
1266 ser_console_get_tty_state,
1267 ser_base_copy_tty_state,
1268 ser_base_set_tty_state,
1269 ser_base_print_tty_state,
1270 NULL,
1271 NULL,
1272 NULL,
1273 ser_base_drain_output,
1274 NULL,
1275 NULL,
1276 NULL,
1277 NULL,
1278 ser_console_wait_handle,
1279 ser_console_done_wait_handle
1282 /* The pipe interface. */
1284 static const struct serial_ops pipe_ops =
1286 "pipe",
1287 pipe_windows_open,
1288 pipe_windows_close,
1289 pipe_windows_fdopen,
1290 ser_base_readchar,
1291 ser_base_write,
1292 ser_base_flush_output,
1293 ser_base_flush_input,
1294 ser_base_send_break,
1295 ser_base_raw,
1296 ser_base_get_tty_state,
1297 ser_base_copy_tty_state,
1298 ser_base_set_tty_state,
1299 ser_base_print_tty_state,
1300 ser_base_setbaudrate,
1301 ser_base_setstopbits,
1302 ser_base_setparity,
1303 ser_base_drain_output,
1304 ser_base_async,
1305 pipe_windows_read,
1306 pipe_windows_write,
1307 pipe_avail,
1308 pipe_wait_handle,
1309 pipe_done_wait_handle
1312 /* The TCP/UDP socket driver. */
1314 static const struct serial_ops tcp_ops =
1316 "tcp",
1317 net_windows_open,
1318 net_windows_close,
1319 NULL,
1320 ser_base_readchar,
1321 ser_base_write,
1322 ser_base_flush_output,
1323 ser_base_flush_input,
1324 ser_tcp_send_break,
1325 ser_base_raw,
1326 ser_base_get_tty_state,
1327 ser_base_copy_tty_state,
1328 ser_base_set_tty_state,
1329 ser_base_print_tty_state,
1330 ser_base_setbaudrate,
1331 ser_base_setstopbits,
1332 ser_base_setparity,
1333 ser_base_drain_output,
1334 ser_base_async,
1335 net_read_prim,
1336 net_write_prim,
1337 NULL,
1338 net_windows_wait_handle,
1339 net_windows_done_wait_handle
1342 void _initialize_ser_windows ();
1343 void
1344 _initialize_ser_windows ()
1346 WSADATA wsa_data;
1348 HMODULE hm = NULL;
1350 /* First find out if kernel32 exports CancelIo function. */
1351 hm = LoadLibrary ("kernel32.dll");
1352 if (hm)
1354 CancelIo = (CancelIo_ftype *) GetProcAddress (hm, "CancelIo");
1355 FreeLibrary (hm);
1357 else
1358 CancelIo = NULL;
1360 serial_add_interface (&hardwire_ops);
1361 serial_add_interface (&tty_ops);
1362 serial_add_interface (&pipe_ops);
1364 /* If WinSock works, register the TCP/UDP socket driver. */
1366 if (WSAStartup (MAKEWORD (1, 0), &wsa_data) != 0)
1367 /* WinSock is unavailable. */
1368 return;
1370 serial_add_interface (&tcp_ops);