* NEWS: Mention native Windows support.
[external/binutils.git] / gdb / ser-mingw.c
1 /* Serial interface for local (hardwired) serial ports on Windows systems
2
3    Copyright (C) 2006
4    Free Software Foundation, Inc.
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
10    the Free Software Foundation; either version 2 of the License, or
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
19    along with this program; if not, write to the Free Software
20    Foundation, Inc., 51 Franklin Street, Fifth Floor,
21    Boston, MA 02110-1301, USA.  */
22
23 #include "defs.h"
24 #include "serial.h"
25 #include "ser-base.h"
26 #include "ser-tcp.h"
27
28 #include <windows.h>
29
30 #include <fcntl.h>
31 #include <unistd.h>
32 #include <sys/types.h>
33
34 #include "gdb_assert.h"
35 #include "gdb_string.h"
36
37 void _initialize_ser_windows (void);
38
39 struct ser_windows_state
40 {
41   int in_progress;
42   OVERLAPPED ov;
43   DWORD lastCommMask;
44   HANDLE except_event;
45 };
46
47 /* Open up a real live device for serial I/O.  */
48
49 static int
50 ser_windows_open (struct serial *scb, const char *name)
51 {
52   HANDLE h;
53   struct ser_windows_state *state;
54   COMMTIMEOUTS timeouts;
55
56   /* Only allow COM ports.  */
57   if (strncmp (name, "COM", 3) != 0)
58     {
59       errno = ENOENT;
60       return -1;
61     }
62
63   h = CreateFile (name, GENERIC_READ | GENERIC_WRITE, 0, NULL,
64                   OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
65   if (h == INVALID_HANDLE_VALUE)
66     {
67       errno = ENOENT;
68       return -1;
69     }
70
71   scb->fd = _open_osfhandle ((long) h, O_RDWR);
72   if (scb->fd < 0)
73     {
74       errno = ENOENT;
75       return -1;
76     }
77
78   if (!SetCommMask (h, EV_RXCHAR))
79     {
80       errno = EINVAL;
81       return -1;
82     }
83
84   timeouts.ReadIntervalTimeout = MAXDWORD;
85   timeouts.ReadTotalTimeoutConstant = 0;
86   timeouts.ReadTotalTimeoutMultiplier = 0;
87   timeouts.WriteTotalTimeoutConstant = 0;
88   timeouts.WriteTotalTimeoutMultiplier = 0;
89   if (!SetCommTimeouts (h, &timeouts))
90     {
91       errno = EINVAL;
92       return -1;
93     }
94
95   state = xmalloc (sizeof (struct ser_windows_state));
96   memset (state, 0, sizeof (struct ser_windows_state));
97   scb->state = state;
98
99   /* Create a manual reset event to watch the input buffer.  */
100   state->ov.hEvent = CreateEvent (0, TRUE, FALSE, 0);
101
102   /* Create a (currently unused) handle to record exceptions.  */
103   state->except_event = CreateEvent (0, TRUE, FALSE, 0);
104
105   return 0;
106 }
107
108 /* Wait for the output to drain away, as opposed to flushing (discarding)
109    it.  */
110
111 static int
112 ser_windows_drain_output (struct serial *scb)
113 {
114   HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
115
116   return (FlushFileBuffers (h) != 0) ? 0 : -1;
117 }
118
119 static int
120 ser_windows_flush_output (struct serial *scb)
121 {
122   HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
123
124   return (PurgeComm (h, PURGE_TXCLEAR) != 0) ? 0 : -1;
125 }
126
127 static int
128 ser_windows_flush_input (struct serial *scb)
129 {
130   HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
131
132   return (PurgeComm (h, PURGE_RXCLEAR) != 0) ? 0 : -1;
133 }
134
135 static int
136 ser_windows_send_break (struct serial *scb)
137 {
138   HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
139
140   if (SetCommBreak (h) == 0)
141     return -1;
142
143   /* Delay for 250 milliseconds.  */
144   Sleep (250);
145
146   if (ClearCommBreak (h))
147     return -1;
148
149   return 0;
150 }
151
152 static void
153 ser_windows_raw (struct serial *scb)
154 {
155   HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
156   DCB state;
157
158   if (GetCommState (h, &state) == 0)
159     return;
160
161   state.fParity = FALSE;
162   state.fOutxCtsFlow = FALSE;
163   state.fOutxDsrFlow = FALSE;
164   state.fDtrControl = DTR_CONTROL_ENABLE;
165   state.fDsrSensitivity = FALSE;
166   state.fOutX = FALSE;
167   state.fInX = FALSE;
168   state.fNull = FALSE;
169   state.fAbortOnError = FALSE;
170   state.ByteSize = 8;
171   state.Parity = NOPARITY;
172
173   scb->current_timeout = 0;
174
175   if (SetCommState (h, &state) == 0)
176     warning (_("SetCommState failed\n"));
177 }
178
179 static int
180 ser_windows_setstopbits (struct serial *scb, int num)
181 {
182   HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
183   DCB state;
184
185   if (GetCommState (h, &state) == 0)
186     return -1;
187
188   switch (num)
189     {
190     case SERIAL_1_STOPBITS:
191       state.StopBits = ONESTOPBIT;
192       break;
193     case SERIAL_1_AND_A_HALF_STOPBITS:
194       state.StopBits = ONE5STOPBITS;
195       break;
196     case SERIAL_2_STOPBITS:
197       state.StopBits = TWOSTOPBITS;
198       break;
199     default:
200       return 1;
201     }
202
203   return (SetCommState (h, &state) != 0) ? 0 : -1;
204 }
205
206 static int
207 ser_windows_setbaudrate (struct serial *scb, int rate)
208 {
209   HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
210   DCB state;
211
212   if (GetCommState (h, &state) == 0)
213     return -1;
214
215   state.BaudRate = rate;
216
217   return (SetCommState (h, &state) != 0) ? 0 : -1;
218 }
219
220 static void
221 ser_windows_close (struct serial *scb)
222 {
223   struct ser_windows_state *state;
224
225   /* Stop any pending selects.  */
226   CancelIo ((HANDLE) _get_osfhandle (scb->fd));
227   state = scb->state;
228   CloseHandle (state->ov.hEvent);
229   CloseHandle (state->except_event);
230
231   if (scb->fd < 0)
232     return;
233
234   close (scb->fd);
235   scb->fd = -1;
236
237   xfree (scb->state);
238 }
239
240 static void
241 ser_windows_wait_handle (struct serial *scb, HANDLE *read, HANDLE *except)
242 {
243   struct ser_windows_state *state;
244   COMSTAT status;
245   DWORD errors;
246   HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
247
248   state = scb->state;
249
250   *except = state->except_event;
251   *read = state->ov.hEvent;
252
253   if (state->in_progress)
254     return;
255
256   /* Reset the mask - we are only interested in any characters which
257      arrive after this point, not characters which might have arrived
258      and already been read.  */
259
260   /* This really, really shouldn't be necessary - just the second one.
261      But otherwise an internal flag for EV_RXCHAR does not get
262      cleared, and we get a duplicated event, if the last batch
263      of characters included at least two arriving close together.  */
264   if (!SetCommMask (h, 0))
265     warning (_("ser_windows_wait_handle: reseting mask failed"));
266
267   if (!SetCommMask (h, EV_RXCHAR))
268     warning (_("ser_windows_wait_handle: reseting mask failed (2)"));
269
270   /* There's a potential race condition here; we must check cbInQue
271      and not wait if that's nonzero.  */
272
273   ClearCommError (h, &errors, &status);
274   if (status.cbInQue > 0)
275     {
276       SetEvent (state->ov.hEvent);
277       return;
278     }
279
280   state->in_progress = 1;
281   ResetEvent (state->ov.hEvent);
282   state->lastCommMask = -2;
283   if (WaitCommEvent (h, &state->lastCommMask, &state->ov))
284     {
285       gdb_assert (state->lastCommMask & EV_RXCHAR);
286       SetEvent (state->ov.hEvent);
287     }
288   else
289     gdb_assert (GetLastError () == ERROR_IO_PENDING);
290 }
291
292 static int
293 ser_windows_read_prim (struct serial *scb, size_t count)
294 {
295   struct ser_windows_state *state;
296   OVERLAPPED ov;
297   DWORD bytes_read, bytes_read_tmp;
298   HANDLE h;
299   gdb_byte *p;
300
301   state = scb->state;
302   if (state->in_progress)
303     {
304       WaitForSingleObject (state->ov.hEvent, INFINITE);
305       state->in_progress = 0;
306       ResetEvent (state->ov.hEvent);
307     }
308
309   memset (&ov, 0, sizeof (OVERLAPPED));
310   ov.hEvent = CreateEvent (0, FALSE, FALSE, 0);
311   h = (HANDLE) _get_osfhandle (scb->fd);
312
313   if (!ReadFile (h, scb->buf, /* count */ 1, &bytes_read, &ov))
314     {
315       if (GetLastError () != ERROR_IO_PENDING
316           || !GetOverlappedResult (h, &ov, &bytes_read, TRUE))
317         bytes_read = -1;
318     }
319
320   CloseHandle (ov.hEvent);
321   return bytes_read;
322 }
323
324 static int
325 ser_windows_write_prim (struct serial *scb, const void *buf, size_t len)
326 {
327   struct ser_windows_state *state;
328   OVERLAPPED ov;
329   DWORD bytes_written;
330   HANDLE h;
331
332   memset (&ov, 0, sizeof (OVERLAPPED));
333   ov.hEvent = CreateEvent (0, FALSE, FALSE, 0);
334   h = (HANDLE) _get_osfhandle (scb->fd);
335   if (!WriteFile (h, buf, len, &bytes_written, &ov))
336     {
337       if (GetLastError () != ERROR_IO_PENDING
338           || !GetOverlappedResult (h, &ov, &bytes_written, TRUE))
339         bytes_written = -1;
340     }
341
342   CloseHandle (ov.hEvent);
343   return bytes_written;
344 }
345
346 struct ser_console_state
347 {
348   HANDLE read_event;
349   HANDLE except_event;
350
351   HANDLE start_select;
352   HANDLE stop_select;
353 };
354
355 static DWORD WINAPI
356 console_select_thread (void *arg)
357 {
358   struct serial *scb = arg;
359   struct ser_console_state *state, state_copy;
360   int event_index, fd;
361   HANDLE h;
362
363   /* Copy useful information out of the control block, to make sure
364      that we do not race with freeing it.  */
365   state_copy = *(struct ser_console_state *) scb->state;
366   state = &state_copy;
367   fd = scb->fd;
368
369   h = (HANDLE) _get_osfhandle (fd);
370
371   while (1)
372     {
373       HANDLE wait_events[2];
374       INPUT_RECORD record;
375       DWORD n_records;
376
377       wait_events[0] = state->start_select;
378       wait_events[1] = state->stop_select;
379
380       if (WaitForMultipleObjects (2, wait_events, FALSE, INFINITE) != WAIT_OBJECT_0)
381         {
382           CloseHandle (state->stop_select);
383           return 0;
384         }
385
386     retry:
387       wait_events[0] = state->stop_select;
388       wait_events[1] = h;
389
390       event_index = WaitForMultipleObjects (2, wait_events, FALSE, INFINITE);
391
392       if (event_index == WAIT_OBJECT_0
393           || WaitForSingleObject (state->stop_select, 0) == WAIT_OBJECT_0)
394         {
395           CloseHandle (state->stop_select);
396           return 0;
397         }
398
399       if (event_index != WAIT_OBJECT_0 + 1)
400         {
401           /* Wait must have failed; assume an error has occured, e.g.
402              the handle has been closed.  */
403           SetEvent (state->except_event);
404           continue;
405         }
406
407       /* We've got a pending event on the console.  See if it's
408          of interest.  */
409       if (!PeekConsoleInput (h, &record, 1, &n_records) || n_records != 1)
410         {
411           /* Something went wrong.  Maybe the console is gone.  */
412           SetEvent (state->except_event);
413           continue;
414         }
415
416       if (record.EventType == KEY_EVENT && record.Event.KeyEvent.bKeyDown)
417         {
418           /* This is really a keypress.  */
419           SetEvent (state->read_event);
420           continue;
421         }
422
423       /* Otherwise discard it and wait again.  */
424       ReadConsoleInput (h, &record, 1, &n_records);
425       goto retry;
426     }
427 }
428
429 static int
430 fd_is_pipe (int fd)
431 {
432   if (PeekNamedPipe ((HANDLE) _get_osfhandle (fd), NULL, 0, NULL, NULL, NULL))
433     return 1;
434   else
435     return 0;
436 }
437
438 static DWORD WINAPI
439 pipe_select_thread (void *arg)
440 {
441   struct serial *scb = arg;
442   struct ser_console_state *state, state_copy;
443   int event_index, fd;
444   HANDLE h;
445
446   /* Copy useful information out of the control block, to make sure
447      that we do not race with freeing it.  */
448   state_copy = *(struct ser_console_state *) scb->state;
449   state = &state_copy;
450   fd = scb->fd;
451
452   h = (HANDLE) _get_osfhandle (fd);
453
454   while (1)
455     {
456       HANDLE wait_events[2];
457       DWORD n_avail;
458
459       wait_events[0] = state->start_select;
460       wait_events[1] = state->stop_select;
461
462       if (WaitForMultipleObjects (2, wait_events, FALSE, INFINITE) != WAIT_OBJECT_0)
463         {
464           CloseHandle (state->stop_select);
465           return 0;
466         }
467
468     retry:
469       if (!PeekNamedPipe (h, NULL, 0, NULL, &n_avail, NULL))
470         {
471           SetEvent (state->except_event);
472           continue;
473         }
474
475       if (n_avail > 0)
476         {
477           SetEvent (state->read_event);
478           continue;
479         }
480
481       if (WaitForSingleObject (state->stop_select, 0) == WAIT_OBJECT_0)
482         {
483           CloseHandle (state->stop_select);
484           return 0;
485         }
486
487       Sleep (10);
488       goto retry;
489     }
490 }
491
492 static void
493 ser_console_wait_handle (struct serial *scb, HANDLE *read, HANDLE *except)
494 {
495   struct ser_console_state *state = scb->state;
496
497   if (state == NULL)
498     {
499       DWORD threadId;
500       int is_tty;
501
502       is_tty = isatty (scb->fd);
503       if (!is_tty && !fd_is_pipe (scb->fd))
504         {
505           *read = NULL;
506           *except = NULL;
507           return;
508         }
509
510       state = xmalloc (sizeof (struct ser_console_state));
511       memset (state, 0, sizeof (struct ser_console_state));
512       scb->state = state;
513
514       /* Create auto reset events to wake and terminate the select thread.  */
515       state->start_select = CreateEvent (0, FALSE, FALSE, 0);
516       state->stop_select = CreateEvent (0, FALSE, FALSE, 0);
517
518       /* Create our own events to report read and exceptions separately.
519          The exception event is currently never used.  */
520       state->read_event = CreateEvent (0, FALSE, FALSE, 0);
521       state->except_event = CreateEvent (0, FALSE, FALSE, 0);
522
523       /* And finally start the select thread.  */
524       if (is_tty)
525         CreateThread (NULL, 0, console_select_thread, scb, 0, &threadId);
526       else
527         CreateThread (NULL, 0, pipe_select_thread, scb, 0, &threadId);
528     }
529
530   ResetEvent (state->read_event);
531   ResetEvent (state->except_event);
532
533   SetEvent (state->start_select);
534
535   *read = state->read_event;
536   *except = state->except_event;
537 }
538
539 static void
540 ser_console_close (struct serial *scb)
541 {
542   struct ser_console_state *state = scb->state;
543
544   if (scb->state)
545     {
546       SetEvent (state->stop_select);
547
548       CloseHandle (state->read_event);
549       CloseHandle (state->except_event);
550
551       xfree (scb->state);
552     }
553 }
554
555 struct ser_console_ttystate
556 {
557   int is_a_tty;
558 };
559
560 static serial_ttystate
561 ser_console_get_tty_state (struct serial *scb)
562 {
563   if (isatty (scb->fd))
564     {
565       struct ser_console_ttystate *state;
566       state = (struct ser_console_ttystate *) xmalloc (sizeof *state);
567       state->is_a_tty = 1;
568       return state;
569     }
570   else
571     return NULL;
572 }
573
574 struct net_windows_state
575 {
576   HANDLE read_event;
577   HANDLE except_event;
578
579   HANDLE start_select;
580   HANDLE stop_select;
581   HANDLE sock_event;
582 };
583
584 static DWORD WINAPI
585 net_windows_select_thread (void *arg)
586 {
587   struct serial *scb = arg;
588   struct net_windows_state *state, state_copy;
589   int event_index, fd;
590
591   /* Copy useful information out of the control block, to make sure
592      that we do not race with freeing it.  */
593   state_copy = *(struct net_windows_state *) scb->state;
594   state = &state_copy;
595   fd = scb->fd;
596
597   while (1)
598     {
599       HANDLE wait_events[2];
600       WSANETWORKEVENTS events;
601
602       wait_events[0] = state->start_select;
603       wait_events[1] = state->stop_select;
604
605       if (WaitForMultipleObjects (2, wait_events, FALSE, INFINITE) != WAIT_OBJECT_0)
606         {
607           CloseHandle (state->stop_select);
608           return 0;
609         }
610
611       wait_events[0] = state->stop_select;
612       wait_events[1] = state->sock_event;
613
614       event_index = WaitForMultipleObjects (2, wait_events, FALSE, INFINITE);
615
616       if (event_index == WAIT_OBJECT_0
617           || WaitForSingleObject (state->stop_select, 0) == WAIT_OBJECT_0)
618         {
619           CloseHandle (state->stop_select);
620           return 0;
621         }
622
623       if (event_index != WAIT_OBJECT_0 + 1)
624         {
625           /* Some error has occured.  Assume that this is an error
626              condition.  */
627           SetEvent (state->except_event);
628           continue;
629         }
630
631       /* Enumerate the internal network events, and reset the object that
632          signalled us to catch the next event.  */
633       WSAEnumNetworkEvents (fd, state->sock_event, &events);
634
635       if (events.lNetworkEvents & FD_READ)
636         SetEvent (state->read_event);
637
638       if (events.lNetworkEvents & FD_CLOSE)
639         SetEvent (state->except_event);
640     }
641 }
642
643 static void
644 net_windows_wait_handle (struct serial *scb, HANDLE *read, HANDLE *except)
645 {
646   struct net_windows_state *state = scb->state;
647
648   ResetEvent (state->read_event);
649   ResetEvent (state->except_event);
650
651   SetEvent (state->start_select);
652
653   *read = state->read_event;
654   *except = state->except_event;
655 }
656
657 static int
658 net_windows_open (struct serial *scb, const char *name)
659 {
660   struct net_windows_state *state;
661   int ret;
662   DWORD threadId;
663
664   ret = net_open (scb, name);
665   if (ret != 0)
666     return ret;
667
668   state = xmalloc (sizeof (struct net_windows_state));
669   memset (state, 0, sizeof (struct net_windows_state));
670   scb->state = state;
671
672   /* Create auto reset events to wake and terminate the select thread.  */
673   state->start_select = CreateEvent (0, FALSE, FALSE, 0);
674   state->stop_select = CreateEvent (0, FALSE, FALSE, 0);
675
676   /* Associate an event with the socket.  */
677   state->sock_event = CreateEvent (0, TRUE, FALSE, 0);
678   WSAEventSelect (scb->fd, state->sock_event, FD_READ | FD_CLOSE);
679
680   /* Create our own events to report read and close separately.  */
681   state->read_event = CreateEvent (0, FALSE, FALSE, 0);
682   state->except_event = CreateEvent (0, FALSE, FALSE, 0);
683
684   /* And finally start the select thread.  */
685   CreateThread (NULL, 0, net_windows_select_thread, scb, 0, &threadId);
686
687   return 0;
688 }
689
690
691 static void
692 net_windows_close (struct serial *scb)
693 {
694   struct net_windows_state *state = scb->state;
695
696   SetEvent (state->stop_select);
697
698   CloseHandle (state->read_event);
699   CloseHandle (state->except_event);
700   CloseHandle (state->start_select);
701   CloseHandle (state->sock_event);
702
703   xfree (scb->state);
704
705   net_close (scb);
706 }
707
708 void
709 _initialize_ser_windows (void)
710 {
711   WSADATA wsa_data;
712   struct serial_ops *ops;
713
714   /* First register the serial port driver.  */
715
716   ops = XMALLOC (struct serial_ops);
717   memset (ops, 0, sizeof (struct serial_ops));
718   ops->name = "hardwire";
719   ops->next = 0;
720   ops->open = ser_windows_open;
721   ops->close = ser_windows_close;
722
723   ops->flush_output = ser_windows_flush_output;
724   ops->flush_input = ser_windows_flush_input;
725   ops->send_break = ser_windows_send_break;
726
727   /* These are only used for stdin; we do not need them for serial
728      ports, so supply the standard dummies.  */
729   ops->get_tty_state = ser_base_get_tty_state;
730   ops->set_tty_state = ser_base_set_tty_state;
731   ops->print_tty_state = ser_base_print_tty_state;
732   ops->noflush_set_tty_state = ser_base_noflush_set_tty_state;
733
734   ops->go_raw = ser_windows_raw;
735   ops->setbaudrate = ser_windows_setbaudrate;
736   ops->setstopbits = ser_windows_setstopbits;
737   ops->drain_output = ser_windows_drain_output;
738   ops->readchar = ser_base_readchar;
739   ops->write = ser_base_write;
740   ops->async = ser_base_async;
741   ops->read_prim = ser_windows_read_prim;
742   ops->write_prim = ser_windows_write_prim;
743   ops->wait_handle = ser_windows_wait_handle;
744
745   serial_add_interface (ops);
746
747   /* Next create the dummy serial driver used for terminals.  We only
748      provide the TTY-related methods.  */
749
750   ops = XMALLOC (struct serial_ops);
751   memset (ops, 0, sizeof (struct serial_ops));
752
753   ops->name = "terminal";
754   ops->next = 0;
755
756   ops->close = ser_console_close;
757   ops->get_tty_state = ser_console_get_tty_state;
758   ops->set_tty_state = ser_base_set_tty_state;
759   ops->print_tty_state = ser_base_print_tty_state;
760   ops->noflush_set_tty_state = ser_base_noflush_set_tty_state;
761   ops->drain_output = ser_base_drain_output;
762   ops->wait_handle = ser_console_wait_handle;
763
764   serial_add_interface (ops);
765
766   /* If WinSock works, register the TCP/UDP socket driver.  */
767
768   if (WSAStartup (MAKEWORD (1, 0), &wsa_data) != 0)
769     /* WinSock is unavailable.  */
770     return;
771
772   ops = XMALLOC (struct serial_ops);
773   memset (ops, 0, sizeof (struct serial_ops));
774   ops->name = "tcp";
775   ops->next = 0;
776   ops->open = net_windows_open;
777   ops->close = net_windows_close;
778   ops->readchar = ser_base_readchar;
779   ops->write = ser_base_write;
780   ops->flush_output = ser_base_flush_output;
781   ops->flush_input = ser_base_flush_input;
782   ops->send_break = ser_base_send_break;
783   ops->go_raw = ser_base_raw;
784   ops->get_tty_state = ser_base_get_tty_state;
785   ops->set_tty_state = ser_base_set_tty_state;
786   ops->print_tty_state = ser_base_print_tty_state;
787   ops->noflush_set_tty_state = ser_base_noflush_set_tty_state;
788   ops->setbaudrate = ser_base_setbaudrate;
789   ops->setstopbits = ser_base_setstopbits;
790   ops->drain_output = ser_base_drain_output;
791   ops->async = ser_base_async;
792   ops->read_prim = net_read_prim;
793   ops->write_prim = net_write_prim;
794   ops->wait_handle = net_windows_wait_handle;
795   serial_add_interface (ops);
796 }