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