Update copyright year range in header of all files managed by GDB
[binutils-gdb.git] / gdb / ser-mingw.c
blob232da59bdbf90d58111d482c3f606124e580190e
1 /* Serial interface for local (hardwired) serial ports on Windows systems
3 Copyright (C) 2006-2023 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 int
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 errno = ENOENT;
63 return -1;
66 scb->fd = _open_osfhandle ((intptr_t) h, O_RDWR);
67 if (scb->fd < 0)
69 errno = ENOENT;
70 return -1;
73 if (!SetCommMask (h, EV_RXCHAR))
75 errno = EINVAL;
76 return -1;
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))
86 errno = EINVAL;
87 return -1;
90 state = XCNEW (struct ser_windows_state);
91 scb->state = state;
93 /* Create a manual reset event to watch the input buffer. */
94 state->ov.hEvent = CreateEvent (0, TRUE, FALSE, 0);
96 /* Create a (currently unused) handle to record exceptions. */
97 state->except_event = CreateEvent (0, TRUE, FALSE, 0);
99 return 0;
102 /* Wait for the output to drain away, as opposed to flushing (discarding)
103 it. */
105 static int
106 ser_windows_drain_output (struct serial *scb)
108 HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
110 return (FlushFileBuffers (h) != 0) ? 0 : -1;
113 static int
114 ser_windows_flush_output (struct serial *scb)
116 HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
118 return (PurgeComm (h, PURGE_TXCLEAR) != 0) ? 0 : -1;
121 static int
122 ser_windows_flush_input (struct serial *scb)
124 HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
126 return (PurgeComm (h, PURGE_RXCLEAR) != 0) ? 0 : -1;
129 static int
130 ser_windows_send_break (struct serial *scb)
132 HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
134 if (SetCommBreak (h) == 0)
135 return -1;
137 /* Delay for 250 milliseconds. */
138 Sleep (250);
140 if (ClearCommBreak (h))
141 return -1;
143 return 0;
146 static void
147 ser_windows_raw (struct serial *scb)
149 HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
150 DCB state;
152 if (GetCommState (h, &state) == 0)
153 return;
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;
165 if (SetCommState (h, &state) == 0)
166 warning (_("SetCommState failed"));
169 static int
170 ser_windows_setstopbits (struct serial *scb, int num)
172 HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
173 DCB state;
175 if (GetCommState (h, &state) == 0)
176 return -1;
178 switch (num)
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;
193 return (SetCommState (h, &state) != 0) ? 0 : -1;
196 /* Implement the "setparity" serial_ops callback. */
198 static int
199 ser_windows_setparity (struct serial *scb, int parity)
201 HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
202 DCB state;
204 if (GetCommState (h, &state) == 0)
205 return -1;
207 switch (parity)
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 ("Incorrect parity value: %d", parity);
223 return -1;
226 return (SetCommState (h, &state) != 0) ? 0 : -1;
229 static int
230 ser_windows_setbaudrate (struct serial *scb, int rate)
232 HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
233 DCB state;
235 if (GetCommState (h, &state) == 0)
236 return -1;
238 state.BaudRate = rate;
240 return (SetCommState (h, &state) != 0) ? 0 : -1;
243 static void
244 ser_windows_close (struct serial *scb)
246 struct ser_windows_state *state;
248 /* Stop any pending selects. On Windows 95 OS, CancelIo function does
249 not exist. In that case, it can be replaced by a call to CloseHandle,
250 but this is not necessary here as we do close the Windows handle
251 by calling close (scb->fd) below. */
252 if (CancelIo)
253 CancelIo ((HANDLE) _get_osfhandle (scb->fd));
254 state = (struct ser_windows_state *) scb->state;
255 CloseHandle (state->ov.hEvent);
256 CloseHandle (state->except_event);
258 if (scb->fd < 0)
259 return;
261 close (scb->fd);
262 scb->fd = -1;
264 xfree (scb->state);
267 static void
268 ser_windows_wait_handle (struct serial *scb, HANDLE *read, HANDLE *except)
270 struct ser_windows_state *state;
271 COMSTAT status;
272 DWORD errors;
273 HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
275 state = (struct ser_windows_state *) scb->state;
277 *except = state->except_event;
278 *read = state->ov.hEvent;
280 if (state->in_progress)
281 return;
283 /* Reset the mask - we are only interested in any characters which
284 arrive after this point, not characters which might have arrived
285 and already been read. */
287 /* This really, really shouldn't be necessary - just the second one.
288 But otherwise an internal flag for EV_RXCHAR does not get
289 cleared, and we get a duplicated event, if the last batch
290 of characters included at least two arriving close together. */
291 if (!SetCommMask (h, 0))
292 warning (_("ser_windows_wait_handle: reseting mask failed"));
294 if (!SetCommMask (h, EV_RXCHAR))
295 warning (_("ser_windows_wait_handle: reseting mask failed (2)"));
297 /* There's a potential race condition here; we must check cbInQue
298 and not wait if that's nonzero. */
300 ClearCommError (h, &errors, &status);
301 if (status.cbInQue > 0)
303 SetEvent (state->ov.hEvent);
304 return;
307 state->in_progress = 1;
308 ResetEvent (state->ov.hEvent);
309 state->lastCommMask = -2;
310 if (WaitCommEvent (h, &state->lastCommMask, &state->ov))
312 gdb_assert (state->lastCommMask & EV_RXCHAR);
313 SetEvent (state->ov.hEvent);
315 else
316 gdb_assert (GetLastError () == ERROR_IO_PENDING);
319 static int
320 ser_windows_read_prim (struct serial *scb, size_t count)
322 struct ser_windows_state *state;
323 OVERLAPPED ov;
324 DWORD bytes_read;
325 HANDLE h;
327 state = (struct ser_windows_state *) scb->state;
328 if (state->in_progress)
330 WaitForSingleObject (state->ov.hEvent, INFINITE);
331 state->in_progress = 0;
332 ResetEvent (state->ov.hEvent);
335 memset (&ov, 0, sizeof (OVERLAPPED));
336 ov.hEvent = CreateEvent (0, FALSE, FALSE, 0);
337 h = (HANDLE) _get_osfhandle (scb->fd);
339 if (!ReadFile (h, scb->buf, /* count */ 1, &bytes_read, &ov))
341 if (GetLastError () != ERROR_IO_PENDING
342 || !GetOverlappedResult (h, &ov, &bytes_read, TRUE))
343 bytes_read = -1;
346 CloseHandle (ov.hEvent);
347 return bytes_read;
350 static int
351 ser_windows_write_prim (struct serial *scb, const void *buf, size_t len)
353 OVERLAPPED ov;
354 DWORD bytes_written;
355 HANDLE h;
357 memset (&ov, 0, sizeof (OVERLAPPED));
358 ov.hEvent = CreateEvent (0, FALSE, FALSE, 0);
359 h = (HANDLE) _get_osfhandle (scb->fd);
360 if (!WriteFile (h, buf, len, &bytes_written, &ov))
362 if (GetLastError () != ERROR_IO_PENDING
363 || !GetOverlappedResult (h, &ov, &bytes_written, TRUE))
364 bytes_written = -1;
367 CloseHandle (ov.hEvent);
368 return bytes_written;
371 /* On Windows, gdb_select is implemented using WaitForMulpleObjects.
372 A "select thread" is created for each file descriptor. These
373 threads looks for activity on the corresponding descriptor, using
374 whatever techniques are appropriate for the descriptor type. When
375 that activity occurs, the thread signals an appropriate event,
376 which wakes up WaitForMultipleObjects.
378 Each select thread is in one of two states: stopped or started.
379 Select threads begin in the stopped state. When gdb_select is
380 called, threads corresponding to the descriptors of interest are
381 started by calling a wait_handle function. Each thread that
382 notices activity signals the appropriate event and then reenters
383 the stopped state. Before gdb_select returns it calls the
384 wait_handle_done functions, which return the threads to the stopped
385 state. */
387 enum select_thread_state {
388 STS_STARTED,
389 STS_STOPPED
392 struct ser_console_state
394 /* Signaled by the select thread to indicate that data is available
395 on the file descriptor. */
396 HANDLE read_event;
397 /* Signaled by the select thread to indicate that an exception has
398 occurred on the file descriptor. */
399 HANDLE except_event;
400 /* Signaled by the select thread to indicate that it has entered the
401 started state. HAVE_STARTED and HAVE_STOPPED are never signaled
402 simultaneously. */
403 HANDLE have_started;
404 /* Signaled by the select thread to indicate that it has stopped,
405 either because data is available (and READ_EVENT is signaled),
406 because an exception has occurred (and EXCEPT_EVENT is signaled),
407 or because STOP_SELECT was signaled. */
408 HANDLE have_stopped;
410 /* Signaled by the main program to tell the select thread to enter
411 the started state. */
412 HANDLE start_select;
413 /* Signaled by the main program to tell the select thread to enter
414 the stopped state. */
415 HANDLE stop_select;
416 /* Signaled by the main program to tell the select thread to
417 exit. */
418 HANDLE exit_select;
420 /* The handle for the select thread. */
421 HANDLE thread;
422 /* The state of the select thread. This field is only accessed in
423 the main program, never by the select thread itself. */
424 enum select_thread_state thread_state;
427 /* Called by a select thread to enter the stopped state. This
428 function does not return until the thread has re-entered the
429 started state. */
430 static void
431 select_thread_wait (struct ser_console_state *state)
433 HANDLE wait_events[2];
435 /* There are two things that can wake us up: a request that we enter
436 the started state, or that we exit this thread. */
437 wait_events[0] = state->start_select;
438 wait_events[1] = state->exit_select;
439 if (WaitForMultipleObjects (2, wait_events, FALSE, INFINITE)
440 != WAIT_OBJECT_0)
441 /* Either the EXIT_SELECT event was signaled (requesting that the
442 thread exit) or an error has occurred. In either case, we exit
443 the thread. */
444 ExitThread (0);
446 /* We are now in the started state. */
447 SetEvent (state->have_started);
450 typedef DWORD WINAPI (*thread_fn_type)(void *);
452 /* Create a new select thread for SCB executing THREAD_FN. The STATE
453 will be filled in by this function before return. */
454 static void
455 create_select_thread (thread_fn_type thread_fn,
456 struct serial *scb,
457 struct ser_console_state *state)
459 DWORD threadId;
461 /* Create all of the events. These are all auto-reset events. */
462 state->read_event = CreateEvent (NULL, FALSE, FALSE, NULL);
463 state->except_event = CreateEvent (NULL, FALSE, FALSE, NULL);
464 state->have_started = CreateEvent (NULL, FALSE, FALSE, NULL);
465 state->have_stopped = CreateEvent (NULL, FALSE, FALSE, NULL);
466 state->start_select = CreateEvent (NULL, FALSE, FALSE, NULL);
467 state->stop_select = CreateEvent (NULL, FALSE, FALSE, NULL);
468 state->exit_select = CreateEvent (NULL, FALSE, FALSE, NULL);
470 state->thread = CreateThread (NULL, 0, thread_fn, scb, 0, &threadId);
471 /* The thread begins in the stopped state. */
472 state->thread_state = STS_STOPPED;
475 /* Destroy the select thread indicated by STATE. */
476 static void
477 destroy_select_thread (struct ser_console_state *state)
479 /* Ask the thread to exit. */
480 SetEvent (state->exit_select);
481 /* Wait until it does. */
482 WaitForSingleObject (state->thread, INFINITE);
484 /* Destroy the events. */
485 CloseHandle (state->read_event);
486 CloseHandle (state->except_event);
487 CloseHandle (state->have_started);
488 CloseHandle (state->have_stopped);
489 CloseHandle (state->start_select);
490 CloseHandle (state->stop_select);
491 CloseHandle (state->exit_select);
494 /* Called by gdb_select to start the select thread indicated by STATE.
495 This function does not return until the thread has started. */
496 static void
497 start_select_thread (struct ser_console_state *state)
499 /* Ask the thread to start. */
500 SetEvent (state->start_select);
501 /* Wait until it does. */
502 WaitForSingleObject (state->have_started, INFINITE);
503 /* The thread is now started. */
504 state->thread_state = STS_STARTED;
507 /* Called by gdb_select to stop the select thread indicated by STATE.
508 This function does not return until the thread has stopped. */
509 static void
510 stop_select_thread (struct ser_console_state *state)
512 /* If the thread is already in the stopped state, we have nothing to
513 do. Some of the wait_handle functions avoid calling
514 start_select_thread if they notice activity on the relevant file
515 descriptors. The wait_handle_done functions still call
516 stop_select_thread -- but it is already stopped. */
517 if (state->thread_state != STS_STARTED)
518 return;
519 /* Ask the thread to stop. */
520 SetEvent (state->stop_select);
521 /* Wait until it does. */
522 WaitForSingleObject (state->have_stopped, INFINITE);
523 /* The thread is now stopped. */
524 state->thread_state = STS_STOPPED;
527 static DWORD WINAPI
528 console_select_thread (void *arg)
530 struct serial *scb = (struct serial *) arg;
531 struct ser_console_state *state;
532 int event_index;
533 HANDLE h;
535 state = (struct ser_console_state *) scb->state;
536 h = (HANDLE) _get_osfhandle (scb->fd);
538 while (1)
540 HANDLE wait_events[2];
541 INPUT_RECORD record;
542 DWORD n_records;
544 select_thread_wait (state);
546 while (1)
548 wait_events[0] = state->stop_select;
549 wait_events[1] = h;
551 event_index = WaitForMultipleObjects (2, wait_events,
552 FALSE, INFINITE);
554 if (event_index == WAIT_OBJECT_0
555 || WaitForSingleObject (state->stop_select, 0) == WAIT_OBJECT_0)
556 break;
558 if (event_index != WAIT_OBJECT_0 + 1)
560 /* Wait must have failed; assume an error has occured, e.g.
561 the handle has been closed. */
562 SetEvent (state->except_event);
563 break;
566 /* We've got a pending event on the console. See if it's
567 of interest. */
568 if (!PeekConsoleInput (h, &record, 1, &n_records) || n_records != 1)
570 /* Something went wrong. Maybe the console is gone. */
571 SetEvent (state->except_event);
572 break;
575 if (record.EventType == KEY_EVENT && record.Event.KeyEvent.bKeyDown)
577 WORD keycode = record.Event.KeyEvent.wVirtualKeyCode;
579 /* Ignore events containing only control keys. We must
580 recognize "enhanced" keys which we are interested in
581 reading via getch, if they do not map to ASCII. But we
582 do not want to report input available for e.g. the
583 control key alone. */
585 if (record.Event.KeyEvent.uChar.AsciiChar != 0
586 || keycode == VK_PRIOR
587 || keycode == VK_NEXT
588 || keycode == VK_END
589 || keycode == VK_HOME
590 || keycode == VK_LEFT
591 || keycode == VK_UP
592 || keycode == VK_RIGHT
593 || keycode == VK_DOWN
594 || keycode == VK_INSERT
595 || keycode == VK_DELETE)
597 /* This is really a keypress. */
598 SetEvent (state->read_event);
599 break;
602 else if (record.EventType == MOUSE_EVENT)
604 SetEvent (state->read_event);
605 break;
608 /* Otherwise discard it and wait again. */
609 ReadConsoleInput (h, &record, 1, &n_records);
612 SetEvent(state->have_stopped);
614 return 0;
617 static int
618 fd_is_pipe (int fd)
620 if (PeekNamedPipe ((HANDLE) _get_osfhandle (fd), NULL, 0, NULL, NULL, NULL))
621 return 1;
622 else
623 return 0;
626 static int
627 fd_is_file (int fd)
629 if (GetFileType ((HANDLE) _get_osfhandle (fd)) == FILE_TYPE_DISK)
630 return 1;
631 else
632 return 0;
635 static DWORD WINAPI
636 pipe_select_thread (void *arg)
638 struct serial *scb = (struct serial *) arg;
639 struct ser_console_state *state;
640 HANDLE h;
642 state = (struct ser_console_state *) scb->state;
643 h = (HANDLE) _get_osfhandle (scb->fd);
645 while (1)
647 DWORD n_avail;
649 select_thread_wait (state);
651 /* Wait for something to happen on the pipe. */
652 while (1)
654 if (!PeekNamedPipe (h, NULL, 0, NULL, &n_avail, NULL))
656 SetEvent (state->except_event);
657 break;
660 if (n_avail > 0)
662 SetEvent (state->read_event);
663 break;
666 /* Delay 10ms before checking again, but allow the stop
667 event to wake us. */
668 if (WaitForSingleObject (state->stop_select, 10) == WAIT_OBJECT_0)
669 break;
672 SetEvent (state->have_stopped);
674 return 0;
677 static DWORD WINAPI
678 file_select_thread (void *arg)
680 struct serial *scb = (struct serial *) arg;
681 struct ser_console_state *state;
682 HANDLE h;
684 state = (struct ser_console_state *) scb->state;
685 h = (HANDLE) _get_osfhandle (scb->fd);
687 while (1)
689 select_thread_wait (state);
691 if (SetFilePointer (h, 0, NULL, FILE_CURRENT)
692 == INVALID_SET_FILE_POINTER)
693 SetEvent (state->except_event);
694 else
695 SetEvent (state->read_event);
697 SetEvent (state->have_stopped);
699 return 0;
702 static void
703 ser_console_wait_handle (struct serial *scb, HANDLE *read, HANDLE *except)
705 struct ser_console_state *state = (struct ser_console_state *) scb->state;
707 if (state == NULL)
709 thread_fn_type thread_fn;
710 int is_tty;
712 is_tty = isatty (scb->fd);
713 if (!is_tty && !fd_is_file (scb->fd) && !fd_is_pipe (scb->fd))
715 *read = NULL;
716 *except = NULL;
717 return;
720 state = XCNEW (struct ser_console_state);
721 scb->state = state;
723 if (is_tty)
724 thread_fn = console_select_thread;
725 else if (fd_is_pipe (scb->fd))
726 thread_fn = pipe_select_thread;
727 else
728 thread_fn = file_select_thread;
730 create_select_thread (thread_fn, scb, state);
733 *read = state->read_event;
734 *except = state->except_event;
736 /* Start from a blank state. */
737 ResetEvent (state->read_event);
738 ResetEvent (state->except_event);
739 ResetEvent (state->stop_select);
741 /* First check for a key already in the buffer. If there is one,
742 we don't need a thread. This also catches the second key of
743 multi-character returns from getch, for instance for arrow
744 keys. The second half is in a C library internal buffer,
745 and PeekConsoleInput will not find it. */
746 if (_kbhit ())
748 SetEvent (state->read_event);
749 return;
752 /* Otherwise, start the select thread. */
753 start_select_thread (state);
756 static void
757 ser_console_done_wait_handle (struct serial *scb)
759 struct ser_console_state *state = (struct ser_console_state *) scb->state;
761 if (state == NULL)
762 return;
764 stop_select_thread (state);
767 static void
768 ser_console_close (struct serial *scb)
770 struct ser_console_state *state = (struct ser_console_state *) scb->state;
772 if (scb->state)
774 destroy_select_thread (state);
775 xfree (scb->state);
779 struct ser_console_ttystate
781 int is_a_tty;
784 static serial_ttystate
785 ser_console_get_tty_state (struct serial *scb)
787 if (isatty (scb->fd))
789 struct ser_console_ttystate *state;
791 state = XNEW (struct ser_console_ttystate);
792 state->is_a_tty = 1;
793 return state;
795 else
796 return NULL;
799 struct pipe_state
801 /* Since we use the pipe_select_thread for our select emulation,
802 we need to place the state structure it requires at the front
803 of our state. */
804 struct ser_console_state wait;
806 /* The pex obj for our (one-stage) pipeline. */
807 struct pex_obj *pex;
809 /* Streams for the pipeline's input and output. */
810 FILE *input, *output;
813 static struct pipe_state *
814 make_pipe_state (void)
816 struct pipe_state *ps = XCNEW (struct pipe_state);
818 ps->wait.read_event = INVALID_HANDLE_VALUE;
819 ps->wait.except_event = INVALID_HANDLE_VALUE;
820 ps->wait.start_select = INVALID_HANDLE_VALUE;
821 ps->wait.stop_select = INVALID_HANDLE_VALUE;
823 return ps;
826 static void
827 free_pipe_state (struct pipe_state *ps)
829 int saved_errno = errno;
831 if (ps->wait.read_event != INVALID_HANDLE_VALUE)
832 destroy_select_thread (&ps->wait);
834 /* Close the pipe to the child. We must close the pipe before
835 calling pex_free because pex_free will wait for the child to exit
836 and the child will not exit until the pipe is closed. */
837 if (ps->input)
838 fclose (ps->input);
839 if (ps->pex)
841 pex_free (ps->pex);
842 /* pex_free closes ps->output. */
844 else if (ps->output)
845 fclose (ps->output);
847 xfree (ps);
849 errno = saved_errno;
852 struct pipe_state_destroyer
854 void operator() (pipe_state *ps) const
856 free_pipe_state (ps);
860 typedef std::unique_ptr<pipe_state, pipe_state_destroyer> pipe_state_up;
862 static int
863 pipe_windows_open (struct serial *scb, const char *name)
865 FILE *pex_stderr;
867 if (name == NULL)
868 error_no_arg (_("child command"));
870 gdb_argv argv (name);
872 if (! argv[0] || argv[0][0] == '\0')
873 error (_("missing child command"));
875 pipe_state_up ps (make_pipe_state ());
877 ps->pex = pex_init (PEX_USE_PIPES, "target remote pipe", NULL);
878 if (! ps->pex)
879 return -1;
880 ps->input = pex_input_pipe (ps->pex, 1);
881 if (! ps->input)
882 return -1;
885 int err;
886 const char *err_msg
887 = pex_run (ps->pex, PEX_SEARCH | PEX_BINARY_INPUT | PEX_BINARY_OUTPUT
888 | PEX_STDERR_TO_PIPE,
889 argv[0], argv.get (), NULL, NULL,
890 &err);
892 if (err_msg)
894 /* Our caller expects us to return -1, but all they'll do with
895 it generally is print the message based on errno. We have
896 all the same information here, plus err_msg provided by
897 pex_run, so we just raise the error here. */
898 if (err)
899 error (_("error starting child process '%s': %s: %s"),
900 name, err_msg, safe_strerror (err));
901 else
902 error (_("error starting child process '%s': %s"),
903 name, err_msg);
907 ps->output = pex_read_output (ps->pex, 1);
908 if (! ps->output)
909 return -1;
910 scb->fd = fileno (ps->output);
912 pex_stderr = pex_read_err (ps->pex, 1);
913 if (! pex_stderr)
914 return -1;
915 scb->error_fd = fileno (pex_stderr);
917 scb->state = ps.release ();
919 return 0;
922 static int
923 pipe_windows_fdopen (struct serial *scb, int fd)
925 struct pipe_state *ps;
927 ps = make_pipe_state ();
929 ps->input = fdopen (fd, "r+");
930 if (! ps->input)
931 goto fail;
933 ps->output = fdopen (fd, "r+");
934 if (! ps->output)
935 goto fail;
937 scb->fd = fd;
938 scb->state = (void *) ps;
940 return 0;
942 fail:
943 free_pipe_state (ps);
944 return -1;
947 static void
948 pipe_windows_close (struct serial *scb)
950 struct pipe_state *ps = (struct pipe_state *) scb->state;
952 /* In theory, we should try to kill the subprocess here, but the pex
953 interface doesn't give us enough information to do that. Usually
954 closing the input pipe will get the message across. */
956 free_pipe_state (ps);
960 static int
961 pipe_windows_read (struct serial *scb, size_t count)
963 HANDLE pipeline_out = (HANDLE) _get_osfhandle (scb->fd);
964 DWORD available;
965 DWORD bytes_read;
967 if (pipeline_out == INVALID_HANDLE_VALUE)
968 return -1;
970 if (! PeekNamedPipe (pipeline_out, NULL, 0, NULL, &available, NULL))
971 return -1;
973 if (count > available)
974 count = available;
976 if (! ReadFile (pipeline_out, scb->buf, count, &bytes_read, NULL))
977 return -1;
979 return bytes_read;
983 static int
984 pipe_windows_write (struct serial *scb, const void *buf, size_t count)
986 struct pipe_state *ps = (struct pipe_state *) scb->state;
987 HANDLE pipeline_in;
988 DWORD written;
990 int pipeline_in_fd = fileno (ps->input);
991 if (pipeline_in_fd < 0)
992 return -1;
994 pipeline_in = (HANDLE) _get_osfhandle (pipeline_in_fd);
995 if (pipeline_in == INVALID_HANDLE_VALUE)
996 return -1;
998 if (! WriteFile (pipeline_in, buf, count, &written, NULL))
999 return -1;
1001 return written;
1005 static void
1006 pipe_wait_handle (struct serial *scb, HANDLE *read, HANDLE *except)
1008 struct pipe_state *ps = (struct pipe_state *) scb->state;
1010 /* Have we allocated our events yet? */
1011 if (ps->wait.read_event == INVALID_HANDLE_VALUE)
1012 /* Start the thread. */
1013 create_select_thread (pipe_select_thread, scb, &ps->wait);
1015 *read = ps->wait.read_event;
1016 *except = ps->wait.except_event;
1018 /* Start from a blank state. */
1019 ResetEvent (ps->wait.read_event);
1020 ResetEvent (ps->wait.except_event);
1021 ResetEvent (ps->wait.stop_select);
1023 start_select_thread (&ps->wait);
1026 static void
1027 pipe_done_wait_handle (struct serial *scb)
1029 struct pipe_state *ps = (struct pipe_state *) scb->state;
1031 /* Have we allocated our events yet? */
1032 if (ps->wait.read_event == INVALID_HANDLE_VALUE)
1033 return;
1035 stop_select_thread (&ps->wait);
1038 static int
1039 pipe_avail (struct serial *scb, int fd)
1041 HANDLE h = (HANDLE) _get_osfhandle (fd);
1042 DWORD numBytes;
1043 BOOL r = PeekNamedPipe (h, NULL, 0, NULL, &numBytes, NULL);
1045 if (r == FALSE)
1046 numBytes = 0;
1047 return numBytes;
1051 gdb_pipe (int pdes[2])
1053 if (_pipe (pdes, 512, _O_BINARY | _O_NOINHERIT) == -1)
1054 return -1;
1055 return 0;
1058 struct net_windows_state
1060 struct ser_console_state base;
1062 HANDLE sock_event;
1065 /* Check whether the socket has any pending data to be read. If so,
1066 set the select thread's read event. On error, set the select
1067 thread's except event. If any event was set, return true,
1068 otherwise return false. */
1070 static int
1071 net_windows_socket_check_pending (struct serial *scb)
1073 struct net_windows_state *state = (struct net_windows_state *) scb->state;
1074 unsigned long available;
1076 if (ioctlsocket (scb->fd, FIONREAD, &available) != 0)
1078 /* The socket closed, or some other error. */
1079 SetEvent (state->base.except_event);
1080 return 1;
1082 else if (available > 0)
1084 SetEvent (state->base.read_event);
1085 return 1;
1088 return 0;
1091 static DWORD WINAPI
1092 net_windows_select_thread (void *arg)
1094 struct serial *scb = (struct serial *) arg;
1095 struct net_windows_state *state;
1096 int event_index;
1098 state = (struct net_windows_state *) scb->state;
1100 while (1)
1102 HANDLE wait_events[2];
1103 WSANETWORKEVENTS events;
1105 select_thread_wait (&state->base);
1107 wait_events[0] = state->base.stop_select;
1108 wait_events[1] = state->sock_event;
1110 /* Wait for something to happen on the socket. */
1111 while (1)
1113 event_index = WaitForMultipleObjects (2, wait_events, FALSE, INFINITE);
1115 if (event_index == WAIT_OBJECT_0
1116 || WaitForSingleObject (state->base.stop_select, 0) == WAIT_OBJECT_0)
1118 /* We have been requested to stop. */
1119 break;
1122 if (event_index != WAIT_OBJECT_0 + 1)
1124 /* Some error has occured. Assume that this is an error
1125 condition. */
1126 SetEvent (state->base.except_event);
1127 break;
1130 /* Enumerate the internal network events, and reset the
1131 object that signalled us to catch the next event. */
1132 if (WSAEnumNetworkEvents (scb->fd, state->sock_event, &events) != 0)
1134 /* Something went wrong. Maybe the socket is gone. */
1135 SetEvent (state->base.except_event);
1136 break;
1139 if (events.lNetworkEvents & FD_READ)
1141 if (net_windows_socket_check_pending (scb))
1142 break;
1144 /* Spurious wakeup. That is, the socket's event was
1145 signalled before we last called recv. */
1148 if (events.lNetworkEvents & FD_CLOSE)
1150 SetEvent (state->base.except_event);
1151 break;
1155 SetEvent (state->base.have_stopped);
1157 return 0;
1160 static void
1161 net_windows_wait_handle (struct serial *scb, HANDLE *read, HANDLE *except)
1163 struct net_windows_state *state = (struct net_windows_state *) scb->state;
1165 /* Start from a clean slate. */
1166 ResetEvent (state->base.read_event);
1167 ResetEvent (state->base.except_event);
1168 ResetEvent (state->base.stop_select);
1170 *read = state->base.read_event;
1171 *except = state->base.except_event;
1173 /* Check any pending events. Otherwise, start the select
1174 thread. */
1175 if (!net_windows_socket_check_pending (scb))
1176 start_select_thread (&state->base);
1179 static void
1180 net_windows_done_wait_handle (struct serial *scb)
1182 struct net_windows_state *state = (struct net_windows_state *) scb->state;
1184 stop_select_thread (&state->base);
1187 static int
1188 net_windows_open (struct serial *scb, const char *name)
1190 struct net_windows_state *state;
1191 int ret;
1193 ret = net_open (scb, name);
1194 if (ret != 0)
1195 return ret;
1197 state = XCNEW (struct net_windows_state);
1198 scb->state = state;
1200 /* Associate an event with the socket. */
1201 state->sock_event = CreateEvent (0, TRUE, FALSE, 0);
1202 WSAEventSelect (scb->fd, state->sock_event, FD_READ | FD_CLOSE);
1204 /* Start the thread. */
1205 create_select_thread (net_windows_select_thread, scb, &state->base);
1207 return 0;
1211 static void
1212 net_windows_close (struct serial *scb)
1214 struct net_windows_state *state = (struct net_windows_state *) scb->state;
1216 destroy_select_thread (&state->base);
1217 CloseHandle (state->sock_event);
1219 xfree (scb->state);
1221 net_close (scb);
1224 /* The serial port driver. */
1226 static const struct serial_ops hardwire_ops =
1228 "hardwire",
1229 ser_windows_open,
1230 ser_windows_close,
1231 NULL,
1232 ser_base_readchar,
1233 ser_base_write,
1234 ser_windows_flush_output,
1235 ser_windows_flush_input,
1236 ser_windows_send_break,
1237 ser_windows_raw,
1238 /* These are only used for stdin; we do not need them for serial
1239 ports, so supply the standard dummies. */
1240 ser_base_get_tty_state,
1241 ser_base_copy_tty_state,
1242 ser_base_set_tty_state,
1243 ser_base_print_tty_state,
1244 ser_windows_setbaudrate,
1245 ser_windows_setstopbits,
1246 ser_windows_setparity,
1247 ser_windows_drain_output,
1248 ser_base_async,
1249 ser_windows_read_prim,
1250 ser_windows_write_prim,
1251 NULL,
1252 ser_windows_wait_handle
1255 /* The dummy serial driver used for terminals. We only provide the
1256 TTY-related methods. */
1258 static const struct serial_ops tty_ops =
1260 "terminal",
1261 NULL,
1262 ser_console_close,
1263 NULL,
1264 NULL,
1265 NULL,
1266 NULL,
1267 NULL,
1268 NULL,
1269 NULL,
1270 ser_console_get_tty_state,
1271 ser_base_copy_tty_state,
1272 ser_base_set_tty_state,
1273 ser_base_print_tty_state,
1274 NULL,
1275 NULL,
1276 NULL,
1277 ser_base_drain_output,
1278 NULL,
1279 NULL,
1280 NULL,
1281 NULL,
1282 ser_console_wait_handle,
1283 ser_console_done_wait_handle
1286 /* The pipe interface. */
1288 static const struct serial_ops pipe_ops =
1290 "pipe",
1291 pipe_windows_open,
1292 pipe_windows_close,
1293 pipe_windows_fdopen,
1294 ser_base_readchar,
1295 ser_base_write,
1296 ser_base_flush_output,
1297 ser_base_flush_input,
1298 ser_base_send_break,
1299 ser_base_raw,
1300 ser_base_get_tty_state,
1301 ser_base_copy_tty_state,
1302 ser_base_set_tty_state,
1303 ser_base_print_tty_state,
1304 ser_base_setbaudrate,
1305 ser_base_setstopbits,
1306 ser_base_setparity,
1307 ser_base_drain_output,
1308 ser_base_async,
1309 pipe_windows_read,
1310 pipe_windows_write,
1311 pipe_avail,
1312 pipe_wait_handle,
1313 pipe_done_wait_handle
1316 /* The TCP/UDP socket driver. */
1318 static const struct serial_ops tcp_ops =
1320 "tcp",
1321 net_windows_open,
1322 net_windows_close,
1323 NULL,
1324 ser_base_readchar,
1325 ser_base_write,
1326 ser_base_flush_output,
1327 ser_base_flush_input,
1328 ser_tcp_send_break,
1329 ser_base_raw,
1330 ser_base_get_tty_state,
1331 ser_base_copy_tty_state,
1332 ser_base_set_tty_state,
1333 ser_base_print_tty_state,
1334 ser_base_setbaudrate,
1335 ser_base_setstopbits,
1336 ser_base_setparity,
1337 ser_base_drain_output,
1338 ser_base_async,
1339 net_read_prim,
1340 net_write_prim,
1341 NULL,
1342 net_windows_wait_handle,
1343 net_windows_done_wait_handle
1346 void _initialize_ser_windows ();
1347 void
1348 _initialize_ser_windows ()
1350 WSADATA wsa_data;
1352 HMODULE hm = NULL;
1354 /* First find out if kernel32 exports CancelIo function. */
1355 hm = LoadLibrary ("kernel32.dll");
1356 if (hm)
1358 CancelIo = (CancelIo_ftype *) GetProcAddress (hm, "CancelIo");
1359 FreeLibrary (hm);
1361 else
1362 CancelIo = NULL;
1364 serial_add_interface (&hardwire_ops);
1365 serial_add_interface (&tty_ops);
1366 serial_add_interface (&pipe_ops);
1368 /* If WinSock works, register the TCP/UDP socket driver. */
1370 if (WSAStartup (MAKEWORD (1, 0), &wsa_data) != 0)
1371 /* WinSock is unavailable. */
1372 return;
1374 serial_add_interface (&tcp_ops);