ignore invalid DOF provider sections
[binutils-gdb.git] / gdb / ser-mingw.c
bloba6ec374be9541b61ac3fd748f5930097bd273c8b
1 /* Serial interface for local (hardwired) serial ports on Windows systems
3 Copyright (C) 2006-2015 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"
34 void _initialize_ser_windows (void);
36 struct ser_windows_state
38 int in_progress;
39 OVERLAPPED ov;
40 DWORD lastCommMask;
41 HANDLE except_event;
44 /* CancelIo is not available for Windows 95 OS, so we need to use
45 LoadLibrary/GetProcAddress to avoid a startup failure. */
46 #define CancelIo dyn_CancelIo
47 static BOOL WINAPI (*CancelIo) (HANDLE);
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 = xmalloc (sizeof (struct ser_windows_state));
91 memset (state, 0, sizeof (struct ser_windows_state));
92 scb->state = state;
94 /* Create a manual reset event to watch the input buffer. */
95 state->ov.hEvent = CreateEvent (0, TRUE, FALSE, 0);
97 /* Create a (currently unused) handle to record exceptions. */
98 state->except_event = CreateEvent (0, TRUE, FALSE, 0);
100 return 0;
103 /* Wait for the output to drain away, as opposed to flushing (discarding)
104 it. */
106 static int
107 ser_windows_drain_output (struct serial *scb)
109 HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
111 return (FlushFileBuffers (h) != 0) ? 0 : -1;
114 static int
115 ser_windows_flush_output (struct serial *scb)
117 HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
119 return (PurgeComm (h, PURGE_TXCLEAR) != 0) ? 0 : -1;
122 static int
123 ser_windows_flush_input (struct serial *scb)
125 HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
127 return (PurgeComm (h, PURGE_RXCLEAR) != 0) ? 0 : -1;
130 static int
131 ser_windows_send_break (struct serial *scb)
133 HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
135 if (SetCommBreak (h) == 0)
136 return -1;
138 /* Delay for 250 milliseconds. */
139 Sleep (250);
141 if (ClearCommBreak (h))
142 return -1;
144 return 0;
147 static void
148 ser_windows_raw (struct serial *scb)
150 HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
151 DCB state;
153 if (GetCommState (h, &state) == 0)
154 return;
156 state.fOutxCtsFlow = FALSE;
157 state.fOutxDsrFlow = FALSE;
158 state.fDtrControl = DTR_CONTROL_ENABLE;
159 state.fDsrSensitivity = FALSE;
160 state.fOutX = FALSE;
161 state.fInX = FALSE;
162 state.fNull = FALSE;
163 state.fAbortOnError = FALSE;
164 state.ByteSize = 8;
166 scb->current_timeout = 0;
168 if (SetCommState (h, &state) == 0)
169 warning (_("SetCommState failed"));
172 static int
173 ser_windows_setstopbits (struct serial *scb, int num)
175 HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
176 DCB state;
178 if (GetCommState (h, &state) == 0)
179 return -1;
181 switch (num)
183 case SERIAL_1_STOPBITS:
184 state.StopBits = ONESTOPBIT;
185 break;
186 case SERIAL_1_AND_A_HALF_STOPBITS:
187 state.StopBits = ONE5STOPBITS;
188 break;
189 case SERIAL_2_STOPBITS:
190 state.StopBits = TWOSTOPBITS;
191 break;
192 default:
193 return 1;
196 return (SetCommState (h, &state) != 0) ? 0 : -1;
199 /* Implement the "setparity" serial_ops callback. */
201 static int
202 ser_windows_setparity (struct serial *scb, int parity)
204 HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
205 DCB state;
207 if (GetCommState (h, &state) == 0)
208 return -1;
210 switch (parity)
212 case GDBPARITY_NONE:
213 state.Parity = NOPARITY;
214 state.fParity = FALSE;
215 break;
216 case GDBPARITY_ODD:
217 state.Parity = ODDPARITY;
218 state.fParity = TRUE;
219 break;
220 case GDBPARITY_EVEN:
221 state.Parity = EVENPARITY;
222 state.fParity = TRUE;
223 break;
224 default:
225 internal_warning (__FILE__, __LINE__,
226 "Incorrect parity value: %d", parity);
227 return -1;
230 return (SetCommState (h, &state) != 0) ? 0 : -1;
233 static int
234 ser_windows_setbaudrate (struct serial *scb, int rate)
236 HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
237 DCB state;
239 if (GetCommState (h, &state) == 0)
240 return -1;
242 state.BaudRate = rate;
244 return (SetCommState (h, &state) != 0) ? 0 : -1;
247 static void
248 ser_windows_close (struct serial *scb)
250 struct ser_windows_state *state;
252 /* Stop any pending selects. On Windows 95 OS, CancelIo function does
253 not exist. In that case, it can be replaced by a call to CloseHandle,
254 but this is not necessary here as we do close the Windows handle
255 by calling close (scb->fd) below. */
256 if (CancelIo)
257 CancelIo ((HANDLE) _get_osfhandle (scb->fd));
258 state = scb->state;
259 CloseHandle (state->ov.hEvent);
260 CloseHandle (state->except_event);
262 if (scb->fd < 0)
263 return;
265 close (scb->fd);
266 scb->fd = -1;
268 xfree (scb->state);
271 static void
272 ser_windows_wait_handle (struct serial *scb, HANDLE *read, HANDLE *except)
274 struct ser_windows_state *state;
275 COMSTAT status;
276 DWORD errors;
277 HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
279 state = scb->state;
281 *except = state->except_event;
282 *read = state->ov.hEvent;
284 if (state->in_progress)
285 return;
287 /* Reset the mask - we are only interested in any characters which
288 arrive after this point, not characters which might have arrived
289 and already been read. */
291 /* This really, really shouldn't be necessary - just the second one.
292 But otherwise an internal flag for EV_RXCHAR does not get
293 cleared, and we get a duplicated event, if the last batch
294 of characters included at least two arriving close together. */
295 if (!SetCommMask (h, 0))
296 warning (_("ser_windows_wait_handle: reseting mask failed"));
298 if (!SetCommMask (h, EV_RXCHAR))
299 warning (_("ser_windows_wait_handle: reseting mask failed (2)"));
301 /* There's a potential race condition here; we must check cbInQue
302 and not wait if that's nonzero. */
304 ClearCommError (h, &errors, &status);
305 if (status.cbInQue > 0)
307 SetEvent (state->ov.hEvent);
308 return;
311 state->in_progress = 1;
312 ResetEvent (state->ov.hEvent);
313 state->lastCommMask = -2;
314 if (WaitCommEvent (h, &state->lastCommMask, &state->ov))
316 gdb_assert (state->lastCommMask & EV_RXCHAR);
317 SetEvent (state->ov.hEvent);
319 else
320 gdb_assert (GetLastError () == ERROR_IO_PENDING);
323 static int
324 ser_windows_read_prim (struct serial *scb, size_t count)
326 struct ser_windows_state *state;
327 OVERLAPPED ov;
328 DWORD bytes_read, bytes_read_tmp;
329 HANDLE h;
330 gdb_byte *p;
332 state = scb->state;
333 if (state->in_progress)
335 WaitForSingleObject (state->ov.hEvent, INFINITE);
336 state->in_progress = 0;
337 ResetEvent (state->ov.hEvent);
340 memset (&ov, 0, sizeof (OVERLAPPED));
341 ov.hEvent = CreateEvent (0, FALSE, FALSE, 0);
342 h = (HANDLE) _get_osfhandle (scb->fd);
344 if (!ReadFile (h, scb->buf, /* count */ 1, &bytes_read, &ov))
346 if (GetLastError () != ERROR_IO_PENDING
347 || !GetOverlappedResult (h, &ov, &bytes_read, TRUE))
348 bytes_read = -1;
351 CloseHandle (ov.hEvent);
352 return bytes_read;
355 static int
356 ser_windows_write_prim (struct serial *scb, const void *buf, size_t len)
358 struct ser_windows_state *state;
359 OVERLAPPED ov;
360 DWORD bytes_written;
361 HANDLE h;
363 memset (&ov, 0, sizeof (OVERLAPPED));
364 ov.hEvent = CreateEvent (0, FALSE, FALSE, 0);
365 h = (HANDLE) _get_osfhandle (scb->fd);
366 if (!WriteFile (h, buf, len, &bytes_written, &ov))
368 if (GetLastError () != ERROR_IO_PENDING
369 || !GetOverlappedResult (h, &ov, &bytes_written, TRUE))
370 bytes_written = -1;
373 CloseHandle (ov.hEvent);
374 return bytes_written;
377 /* On Windows, gdb_select is implemented using WaitForMulpleObjects.
378 A "select thread" is created for each file descriptor. These
379 threads looks for activity on the corresponding descriptor, using
380 whatever techniques are appropriate for the descriptor type. When
381 that activity occurs, the thread signals an appropriate event,
382 which wakes up WaitForMultipleObjects.
384 Each select thread is in one of two states: stopped or started.
385 Select threads begin in the stopped state. When gdb_select is
386 called, threads corresponding to the descriptors of interest are
387 started by calling a wait_handle function. Each thread that
388 notices activity signals the appropriate event and then reenters
389 the stopped state. Before gdb_select returns it calls the
390 wait_handle_done functions, which return the threads to the stopped
391 state. */
393 enum select_thread_state {
394 STS_STARTED,
395 STS_STOPPED
398 struct ser_console_state
400 /* Signaled by the select thread to indicate that data is available
401 on the file descriptor. */
402 HANDLE read_event;
403 /* Signaled by the select thread to indicate that an exception has
404 occurred on the file descriptor. */
405 HANDLE except_event;
406 /* Signaled by the select thread to indicate that it has entered the
407 started state. HAVE_STARTED and HAVE_STOPPED are never signaled
408 simultaneously. */
409 HANDLE have_started;
410 /* Signaled by the select thread to indicate that it has stopped,
411 either because data is available (and READ_EVENT is signaled),
412 because an exception has occurred (and EXCEPT_EVENT is signaled),
413 or because STOP_SELECT was signaled. */
414 HANDLE have_stopped;
416 /* Signaled by the main program to tell the select thread to enter
417 the started state. */
418 HANDLE start_select;
419 /* Signaled by the main program to tell the select thread to enter
420 the stopped state. */
421 HANDLE stop_select;
422 /* Signaled by the main program to tell the select thread to
423 exit. */
424 HANDLE exit_select;
426 /* The handle for the select thread. */
427 HANDLE thread;
428 /* The state of the select thread. This field is only accessed in
429 the main program, never by the select thread itself. */
430 enum select_thread_state thread_state;
433 /* Called by a select thread to enter the stopped state. This
434 function does not return until the thread has re-entered the
435 started state. */
436 static void
437 select_thread_wait (struct ser_console_state *state)
439 HANDLE wait_events[2];
441 /* There are two things that can wake us up: a request that we enter
442 the started state, or that we exit this thread. */
443 wait_events[0] = state->start_select;
444 wait_events[1] = state->exit_select;
445 if (WaitForMultipleObjects (2, wait_events, FALSE, INFINITE)
446 != WAIT_OBJECT_0)
447 /* Either the EXIT_SELECT event was signaled (requesting that the
448 thread exit) or an error has occurred. In either case, we exit
449 the thread. */
450 ExitThread (0);
452 /* We are now in the started state. */
453 SetEvent (state->have_started);
456 typedef DWORD WINAPI (*thread_fn_type)(void *);
458 /* Create a new select thread for SCB executing THREAD_FN. The STATE
459 will be filled in by this function before return. */
460 static void
461 create_select_thread (thread_fn_type thread_fn,
462 struct serial *scb,
463 struct ser_console_state *state)
465 DWORD threadId;
467 /* Create all of the events. These are all auto-reset events. */
468 state->read_event = CreateEvent (NULL, FALSE, FALSE, NULL);
469 state->except_event = CreateEvent (NULL, FALSE, FALSE, NULL);
470 state->have_started = CreateEvent (NULL, FALSE, FALSE, NULL);
471 state->have_stopped = CreateEvent (NULL, FALSE, FALSE, NULL);
472 state->start_select = CreateEvent (NULL, FALSE, FALSE, NULL);
473 state->stop_select = CreateEvent (NULL, FALSE, FALSE, NULL);
474 state->exit_select = CreateEvent (NULL, FALSE, FALSE, NULL);
476 state->thread = CreateThread (NULL, 0, thread_fn, scb, 0, &threadId);
477 /* The thread begins in the stopped state. */
478 state->thread_state = STS_STOPPED;
481 /* Destroy the select thread indicated by STATE. */
482 static void
483 destroy_select_thread (struct ser_console_state *state)
485 /* Ask the thread to exit. */
486 SetEvent (state->exit_select);
487 /* Wait until it does. */
488 WaitForSingleObject (state->thread, INFINITE);
490 /* Destroy the events. */
491 CloseHandle (state->read_event);
492 CloseHandle (state->except_event);
493 CloseHandle (state->have_started);
494 CloseHandle (state->have_stopped);
495 CloseHandle (state->start_select);
496 CloseHandle (state->stop_select);
497 CloseHandle (state->exit_select);
500 /* Called by gdb_select to start the select thread indicated by STATE.
501 This function does not return until the thread has started. */
502 static void
503 start_select_thread (struct ser_console_state *state)
505 /* Ask the thread to start. */
506 SetEvent (state->start_select);
507 /* Wait until it does. */
508 WaitForSingleObject (state->have_started, INFINITE);
509 /* The thread is now started. */
510 state->thread_state = STS_STARTED;
513 /* Called by gdb_select to stop the select thread indicated by STATE.
514 This function does not return until the thread has stopped. */
515 static void
516 stop_select_thread (struct ser_console_state *state)
518 /* If the thread is already in the stopped state, we have nothing to
519 do. Some of the wait_handle functions avoid calling
520 start_select_thread if they notice activity on the relevant file
521 descriptors. The wait_handle_done functions still call
522 stop_select_thread -- but it is already stopped. */
523 if (state->thread_state != STS_STARTED)
524 return;
525 /* Ask the thread to stop. */
526 SetEvent (state->stop_select);
527 /* Wait until it does. */
528 WaitForSingleObject (state->have_stopped, INFINITE);
529 /* The thread is now stopped. */
530 state->thread_state = STS_STOPPED;
533 static DWORD WINAPI
534 console_select_thread (void *arg)
536 struct serial *scb = arg;
537 struct ser_console_state *state;
538 int event_index;
539 HANDLE h;
541 state = scb->state;
542 h = (HANDLE) _get_osfhandle (scb->fd);
544 while (1)
546 HANDLE wait_events[2];
547 INPUT_RECORD record;
548 DWORD n_records;
550 select_thread_wait (state);
552 while (1)
554 wait_events[0] = state->stop_select;
555 wait_events[1] = h;
557 event_index = WaitForMultipleObjects (2, wait_events,
558 FALSE, INFINITE);
560 if (event_index == WAIT_OBJECT_0
561 || WaitForSingleObject (state->stop_select, 0) == WAIT_OBJECT_0)
562 break;
564 if (event_index != WAIT_OBJECT_0 + 1)
566 /* Wait must have failed; assume an error has occured, e.g.
567 the handle has been closed. */
568 SetEvent (state->except_event);
569 break;
572 /* We've got a pending event on the console. See if it's
573 of interest. */
574 if (!PeekConsoleInput (h, &record, 1, &n_records) || n_records != 1)
576 /* Something went wrong. Maybe the console is gone. */
577 SetEvent (state->except_event);
578 break;
581 if (record.EventType == KEY_EVENT && record.Event.KeyEvent.bKeyDown)
583 WORD keycode = record.Event.KeyEvent.wVirtualKeyCode;
585 /* Ignore events containing only control keys. We must
586 recognize "enhanced" keys which we are interested in
587 reading via getch, if they do not map to ASCII. But we
588 do not want to report input available for e.g. the
589 control key alone. */
591 if (record.Event.KeyEvent.uChar.AsciiChar != 0
592 || keycode == VK_PRIOR
593 || keycode == VK_NEXT
594 || keycode == VK_END
595 || keycode == VK_HOME
596 || keycode == VK_LEFT
597 || keycode == VK_UP
598 || keycode == VK_RIGHT
599 || keycode == VK_DOWN
600 || keycode == VK_INSERT
601 || keycode == VK_DELETE)
603 /* This is really a keypress. */
604 SetEvent (state->read_event);
605 break;
609 /* Otherwise discard it and wait again. */
610 ReadConsoleInput (h, &record, 1, &n_records);
613 SetEvent(state->have_stopped);
615 return 0;
618 static int
619 fd_is_pipe (int fd)
621 if (PeekNamedPipe ((HANDLE) _get_osfhandle (fd), NULL, 0, NULL, NULL, NULL))
622 return 1;
623 else
624 return 0;
627 static int
628 fd_is_file (int fd)
630 if (GetFileType ((HANDLE) _get_osfhandle (fd)) == FILE_TYPE_DISK)
631 return 1;
632 else
633 return 0;
636 static DWORD WINAPI
637 pipe_select_thread (void *arg)
639 struct serial *scb = arg;
640 struct ser_console_state *state;
641 int event_index;
642 HANDLE h;
644 state = scb->state;
645 h = (HANDLE) _get_osfhandle (scb->fd);
647 while (1)
649 DWORD n_avail;
651 select_thread_wait (state);
653 /* Wait for something to happen on the pipe. */
654 while (1)
656 if (!PeekNamedPipe (h, NULL, 0, NULL, &n_avail, NULL))
658 SetEvent (state->except_event);
659 break;
662 if (n_avail > 0)
664 SetEvent (state->read_event);
665 break;
668 /* Delay 10ms before checking again, but allow the stop
669 event to wake us. */
670 if (WaitForSingleObject (state->stop_select, 10) == WAIT_OBJECT_0)
671 break;
674 SetEvent (state->have_stopped);
676 return 0;
679 static DWORD WINAPI
680 file_select_thread (void *arg)
682 struct serial *scb = arg;
683 struct ser_console_state *state;
684 int event_index;
685 HANDLE h;
687 state = scb->state;
688 h = (HANDLE) _get_osfhandle (scb->fd);
690 while (1)
692 select_thread_wait (state);
694 if (SetFilePointer (h, 0, NULL, FILE_CURRENT)
695 == INVALID_SET_FILE_POINTER)
696 SetEvent (state->except_event);
697 else
698 SetEvent (state->read_event);
700 SetEvent (state->have_stopped);
702 return 0;
705 static void
706 ser_console_wait_handle (struct serial *scb, HANDLE *read, HANDLE *except)
708 struct ser_console_state *state = scb->state;
710 if (state == NULL)
712 thread_fn_type thread_fn;
713 int is_tty;
715 is_tty = isatty (scb->fd);
716 if (!is_tty && !fd_is_file (scb->fd) && !fd_is_pipe (scb->fd))
718 *read = NULL;
719 *except = NULL;
720 return;
723 state = xmalloc (sizeof (struct ser_console_state));
724 memset (state, 0, sizeof (struct ser_console_state));
725 scb->state = state;
727 if (is_tty)
728 thread_fn = console_select_thread;
729 else if (fd_is_pipe (scb->fd))
730 thread_fn = pipe_select_thread;
731 else
732 thread_fn = file_select_thread;
734 create_select_thread (thread_fn, scb, state);
737 *read = state->read_event;
738 *except = state->except_event;
740 /* Start from a blank state. */
741 ResetEvent (state->read_event);
742 ResetEvent (state->except_event);
743 ResetEvent (state->stop_select);
745 /* First check for a key already in the buffer. If there is one,
746 we don't need a thread. This also catches the second key of
747 multi-character returns from getch, for instance for arrow
748 keys. The second half is in a C library internal buffer,
749 and PeekConsoleInput will not find it. */
750 if (_kbhit ())
752 SetEvent (state->read_event);
753 return;
756 /* Otherwise, start the select thread. */
757 start_select_thread (state);
760 static void
761 ser_console_done_wait_handle (struct serial *scb)
763 struct ser_console_state *state = scb->state;
765 if (state == NULL)
766 return;
768 stop_select_thread (state);
771 static void
772 ser_console_close (struct serial *scb)
774 struct ser_console_state *state = scb->state;
776 if (scb->state)
778 destroy_select_thread (state);
779 xfree (scb->state);
783 struct ser_console_ttystate
785 int is_a_tty;
788 static serial_ttystate
789 ser_console_get_tty_state (struct serial *scb)
791 if (isatty (scb->fd))
793 struct ser_console_ttystate *state;
795 state = (struct ser_console_ttystate *) xmalloc (sizeof *state);
796 state->is_a_tty = 1;
797 return state;
799 else
800 return NULL;
803 struct pipe_state
805 /* Since we use the pipe_select_thread for our select emulation,
806 we need to place the state structure it requires at the front
807 of our state. */
808 struct ser_console_state wait;
810 /* The pex obj for our (one-stage) pipeline. */
811 struct pex_obj *pex;
813 /* Streams for the pipeline's input and output. */
814 FILE *input, *output;
817 static struct pipe_state *
818 make_pipe_state (void)
820 struct pipe_state *ps = XNEW (struct pipe_state);
822 memset (ps, 0, sizeof (*ps));
823 ps->wait.read_event = INVALID_HANDLE_VALUE;
824 ps->wait.except_event = INVALID_HANDLE_VALUE;
825 ps->wait.start_select = INVALID_HANDLE_VALUE;
826 ps->wait.stop_select = INVALID_HANDLE_VALUE;
828 return ps;
831 static void
832 free_pipe_state (struct pipe_state *ps)
834 int saved_errno = errno;
836 if (ps->wait.read_event != INVALID_HANDLE_VALUE)
837 destroy_select_thread (&ps->wait);
839 /* Close the pipe to the child. We must close the pipe before
840 calling pex_free because pex_free will wait for the child to exit
841 and the child will not exit until the pipe is closed. */
842 if (ps->input)
843 fclose (ps->input);
844 if (ps->pex)
846 pex_free (ps->pex);
847 /* pex_free closes ps->output. */
849 else if (ps->output)
850 fclose (ps->output);
852 xfree (ps);
854 errno = saved_errno;
857 static void
858 cleanup_pipe_state (void *untyped)
860 struct pipe_state *ps = untyped;
862 free_pipe_state (ps);
865 static int
866 pipe_windows_open (struct serial *scb, const char *name)
868 struct pipe_state *ps;
869 FILE *pex_stderr;
870 char **argv;
871 struct cleanup *back_to;
873 if (name == NULL)
874 error_no_arg (_("child command"));
876 argv = gdb_buildargv (name);
877 back_to = make_cleanup_freeargv (argv);
879 if (! argv[0] || argv[0][0] == '\0')
880 error (_("missing child command"));
882 ps = make_pipe_state ();
883 make_cleanup (cleanup_pipe_state, ps);
885 ps->pex = pex_init (PEX_USE_PIPES, "target remote pipe", NULL);
886 if (! ps->pex)
887 goto fail;
888 ps->input = pex_input_pipe (ps->pex, 1);
889 if (! ps->input)
890 goto fail;
893 int err;
894 const char *err_msg
895 = pex_run (ps->pex, PEX_SEARCH | PEX_BINARY_INPUT | PEX_BINARY_OUTPUT
896 | PEX_STDERR_TO_PIPE,
897 argv[0], argv, NULL, NULL,
898 &err);
900 if (err_msg)
902 /* Our caller expects us to return -1, but all they'll do with
903 it generally is print the message based on errno. We have
904 all the same information here, plus err_msg provided by
905 pex_run, so we just raise the error here. */
906 if (err)
907 error (_("error starting child process '%s': %s: %s"),
908 name, err_msg, safe_strerror (err));
909 else
910 error (_("error starting child process '%s': %s"),
911 name, err_msg);
915 ps->output = pex_read_output (ps->pex, 1);
916 if (! ps->output)
917 goto fail;
918 scb->fd = fileno (ps->output);
920 pex_stderr = pex_read_err (ps->pex, 1);
921 if (! pex_stderr)
922 goto fail;
923 scb->error_fd = fileno (pex_stderr);
925 scb->state = (void *) ps;
927 discard_cleanups (back_to);
928 return 0;
930 fail:
931 do_cleanups (back_to);
932 return -1;
935 static int
936 pipe_windows_fdopen (struct serial *scb, int fd)
938 struct pipe_state *ps;
940 ps = make_pipe_state ();
942 ps->input = fdopen (fd, "r+");
943 if (! ps->input)
944 goto fail;
946 ps->output = fdopen (fd, "r+");
947 if (! ps->output)
948 goto fail;
950 scb->fd = fd;
951 scb->state = (void *) ps;
953 return 0;
955 fail:
956 free_pipe_state (ps);
957 return -1;
960 static void
961 pipe_windows_close (struct serial *scb)
963 struct pipe_state *ps = scb->state;
965 /* In theory, we should try to kill the subprocess here, but the pex
966 interface doesn't give us enough information to do that. Usually
967 closing the input pipe will get the message across. */
969 free_pipe_state (ps);
973 static int
974 pipe_windows_read (struct serial *scb, size_t count)
976 HANDLE pipeline_out = (HANDLE) _get_osfhandle (scb->fd);
977 DWORD available;
978 DWORD bytes_read;
980 if (pipeline_out == INVALID_HANDLE_VALUE)
981 return -1;
983 if (! PeekNamedPipe (pipeline_out, NULL, 0, NULL, &available, NULL))
984 return -1;
986 if (count > available)
987 count = available;
989 if (! ReadFile (pipeline_out, scb->buf, count, &bytes_read, NULL))
990 return -1;
992 return bytes_read;
996 static int
997 pipe_windows_write (struct serial *scb, const void *buf, size_t count)
999 struct pipe_state *ps = scb->state;
1000 HANDLE pipeline_in;
1001 DWORD written;
1003 int pipeline_in_fd = fileno (ps->input);
1004 if (pipeline_in_fd < 0)
1005 return -1;
1007 pipeline_in = (HANDLE) _get_osfhandle (pipeline_in_fd);
1008 if (pipeline_in == INVALID_HANDLE_VALUE)
1009 return -1;
1011 if (! WriteFile (pipeline_in, buf, count, &written, NULL))
1012 return -1;
1014 return written;
1018 static void
1019 pipe_wait_handle (struct serial *scb, HANDLE *read, HANDLE *except)
1021 struct pipe_state *ps = scb->state;
1023 /* Have we allocated our events yet? */
1024 if (ps->wait.read_event == INVALID_HANDLE_VALUE)
1025 /* Start the thread. */
1026 create_select_thread (pipe_select_thread, scb, &ps->wait);
1028 *read = ps->wait.read_event;
1029 *except = ps->wait.except_event;
1031 /* Start from a blank state. */
1032 ResetEvent (ps->wait.read_event);
1033 ResetEvent (ps->wait.except_event);
1034 ResetEvent (ps->wait.stop_select);
1036 start_select_thread (&ps->wait);
1039 static void
1040 pipe_done_wait_handle (struct serial *scb)
1042 struct pipe_state *ps = scb->state;
1044 /* Have we allocated our events yet? */
1045 if (ps->wait.read_event == INVALID_HANDLE_VALUE)
1046 return;
1048 stop_select_thread (&ps->wait);
1051 static int
1052 pipe_avail (struct serial *scb, int fd)
1054 HANDLE h = (HANDLE) _get_osfhandle (fd);
1055 DWORD numBytes;
1056 BOOL r = PeekNamedPipe (h, NULL, 0, NULL, &numBytes, NULL);
1058 if (r == FALSE)
1059 numBytes = 0;
1060 return numBytes;
1064 gdb_pipe (int pdes[2])
1066 if (_pipe (pdes, 512, _O_BINARY | _O_NOINHERIT) == -1)
1067 return -1;
1068 return 0;
1071 struct net_windows_state
1073 struct ser_console_state base;
1075 HANDLE sock_event;
1078 /* Check whether the socket has any pending data to be read. If so,
1079 set the select thread's read event. On error, set the select
1080 thread's except event. If any event was set, return true,
1081 otherwise return false. */
1083 static int
1084 net_windows_socket_check_pending (struct serial *scb)
1086 struct net_windows_state *state = scb->state;
1087 unsigned long available;
1089 if (ioctlsocket (scb->fd, FIONREAD, &available) != 0)
1091 /* The socket closed, or some other error. */
1092 SetEvent (state->base.except_event);
1093 return 1;
1095 else if (available > 0)
1097 SetEvent (state->base.read_event);
1098 return 1;
1101 return 0;
1104 static DWORD WINAPI
1105 net_windows_select_thread (void *arg)
1107 struct serial *scb = arg;
1108 struct net_windows_state *state;
1109 int event_index;
1111 state = scb->state;
1113 while (1)
1115 HANDLE wait_events[2];
1116 WSANETWORKEVENTS events;
1118 select_thread_wait (&state->base);
1120 wait_events[0] = state->base.stop_select;
1121 wait_events[1] = state->sock_event;
1123 /* Wait for something to happen on the socket. */
1124 while (1)
1126 event_index = WaitForMultipleObjects (2, wait_events, FALSE, INFINITE);
1128 if (event_index == WAIT_OBJECT_0
1129 || WaitForSingleObject (state->base.stop_select, 0) == WAIT_OBJECT_0)
1131 /* We have been requested to stop. */
1132 break;
1135 if (event_index != WAIT_OBJECT_0 + 1)
1137 /* Some error has occured. Assume that this is an error
1138 condition. */
1139 SetEvent (state->base.except_event);
1140 break;
1143 /* Enumerate the internal network events, and reset the
1144 object that signalled us to catch the next event. */
1145 if (WSAEnumNetworkEvents (scb->fd, state->sock_event, &events) != 0)
1147 /* Something went wrong. Maybe the socket is gone. */
1148 SetEvent (state->base.except_event);
1149 break;
1152 if (events.lNetworkEvents & FD_READ)
1154 if (net_windows_socket_check_pending (scb))
1155 break;
1157 /* Spurious wakeup. That is, the socket's event was
1158 signalled before we last called recv. */
1161 if (events.lNetworkEvents & FD_CLOSE)
1163 SetEvent (state->base.except_event);
1164 break;
1168 SetEvent (state->base.have_stopped);
1170 return 0;
1173 static void
1174 net_windows_wait_handle (struct serial *scb, HANDLE *read, HANDLE *except)
1176 struct net_windows_state *state = scb->state;
1178 /* Start from a clean slate. */
1179 ResetEvent (state->base.read_event);
1180 ResetEvent (state->base.except_event);
1181 ResetEvent (state->base.stop_select);
1183 *read = state->base.read_event;
1184 *except = state->base.except_event;
1186 /* Check any pending events. Otherwise, start the select
1187 thread. */
1188 if (!net_windows_socket_check_pending (scb))
1189 start_select_thread (&state->base);
1192 static void
1193 net_windows_done_wait_handle (struct serial *scb)
1195 struct net_windows_state *state = scb->state;
1197 stop_select_thread (&state->base);
1200 static int
1201 net_windows_open (struct serial *scb, const char *name)
1203 struct net_windows_state *state;
1204 int ret;
1205 DWORD threadId;
1207 ret = net_open (scb, name);
1208 if (ret != 0)
1209 return ret;
1211 state = xmalloc (sizeof (struct net_windows_state));
1212 memset (state, 0, sizeof (struct net_windows_state));
1213 scb->state = state;
1215 /* Associate an event with the socket. */
1216 state->sock_event = CreateEvent (0, TRUE, FALSE, 0);
1217 WSAEventSelect (scb->fd, state->sock_event, FD_READ | FD_CLOSE);
1219 /* Start the thread. */
1220 create_select_thread (net_windows_select_thread, scb, &state->base);
1222 return 0;
1226 static void
1227 net_windows_close (struct serial *scb)
1229 struct net_windows_state *state = scb->state;
1231 destroy_select_thread (&state->base);
1232 CloseHandle (state->sock_event);
1234 xfree (scb->state);
1236 net_close (scb);
1239 /* The serial port driver. */
1241 static const struct serial_ops hardwire_ops =
1243 "hardwire",
1244 ser_windows_open,
1245 ser_windows_close,
1246 NULL,
1247 ser_base_readchar,
1248 ser_base_write,
1249 ser_windows_flush_output,
1250 ser_windows_flush_input,
1251 ser_windows_send_break,
1252 ser_windows_raw,
1253 /* These are only used for stdin; we do not need them for serial
1254 ports, so supply the standard dummies. */
1255 ser_base_get_tty_state,
1256 ser_base_copy_tty_state,
1257 ser_base_set_tty_state,
1258 ser_base_print_tty_state,
1259 ser_base_noflush_set_tty_state,
1260 ser_windows_setbaudrate,
1261 ser_windows_setstopbits,
1262 ser_windows_setparity,
1263 ser_windows_drain_output,
1264 ser_base_async,
1265 ser_windows_read_prim,
1266 ser_windows_write_prim,
1267 NULL,
1268 ser_windows_wait_handle
1271 /* The dummy serial driver used for terminals. We only provide the
1272 TTY-related methods. */
1274 static const struct serial_ops tty_ops =
1276 "terminal",
1277 NULL,
1278 ser_console_close,
1279 NULL,
1280 NULL,
1281 NULL,
1282 NULL,
1283 NULL,
1284 NULL,
1285 NULL,
1286 ser_console_get_tty_state,
1287 ser_base_copy_tty_state,
1288 ser_base_set_tty_state,
1289 ser_base_print_tty_state,
1290 ser_base_noflush_set_tty_state,
1291 NULL,
1292 NULL,
1293 NULL,
1294 ser_base_drain_output,
1295 NULL,
1296 NULL,
1297 NULL,
1298 NULL,
1299 ser_console_wait_handle,
1300 ser_console_done_wait_handle
1303 /* The pipe interface. */
1305 static const struct serial_ops pipe_ops =
1307 "pipe",
1308 pipe_windows_open,
1309 pipe_windows_close,
1310 pipe_windows_fdopen,
1311 ser_base_readchar,
1312 ser_base_write,
1313 ser_base_flush_output,
1314 ser_base_flush_input,
1315 ser_base_send_break,
1316 ser_base_raw,
1317 ser_base_get_tty_state,
1318 ser_base_copy_tty_state,
1319 ser_base_set_tty_state,
1320 ser_base_print_tty_state,
1321 ser_base_noflush_set_tty_state,
1322 ser_base_setbaudrate,
1323 ser_base_setstopbits,
1324 ser_base_setparity,
1325 ser_base_drain_output,
1326 ser_base_async,
1327 pipe_windows_read,
1328 pipe_windows_write,
1329 pipe_avail,
1330 pipe_wait_handle,
1331 pipe_done_wait_handle
1334 /* The TCP/UDP socket driver. */
1336 static const struct serial_ops tcp_ops =
1338 "tcp",
1339 net_windows_open,
1340 net_windows_close,
1341 NULL,
1342 ser_base_readchar,
1343 ser_base_write,
1344 ser_base_flush_output,
1345 ser_base_flush_input,
1346 ser_tcp_send_break,
1347 ser_base_raw,
1348 ser_base_get_tty_state,
1349 ser_base_copy_tty_state,
1350 ser_base_set_tty_state,
1351 ser_base_print_tty_state,
1352 ser_base_noflush_set_tty_state,
1353 ser_base_setbaudrate,
1354 ser_base_setstopbits,
1355 ser_base_setparity,
1356 ser_base_drain_output,
1357 ser_base_async,
1358 net_read_prim,
1359 net_write_prim,
1360 NULL,
1361 net_windows_wait_handle,
1362 net_windows_done_wait_handle
1365 void
1366 _initialize_ser_windows (void)
1368 WSADATA wsa_data;
1369 struct serial_ops *ops;
1371 HMODULE hm = NULL;
1373 /* First find out if kernel32 exports CancelIo function. */
1374 hm = LoadLibrary ("kernel32.dll");
1375 if (hm)
1377 CancelIo = (void *) GetProcAddress (hm, "CancelIo");
1378 FreeLibrary (hm);
1380 else
1381 CancelIo = NULL;
1383 serial_add_interface (&hardwire_ops);
1384 serial_add_interface (&tty_ops);
1385 serial_add_interface (&pipe_ops);
1387 /* If WinSock works, register the TCP/UDP socket driver. */
1389 if (WSAStartup (MAKEWORD (1, 0), &wsa_data) != 0)
1390 /* WinSock is unavailable. */
1391 return;
1393 serial_add_interface (&tcp_ops);