Support command-line redirection in native MS-Windows debugging
[external/binutils.git] / gdb / ser-base.c
1 /* Generic serial interface functions.
2
3    Copyright (C) 1992-2016 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
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.
11
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.
16
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/>.  */
19
20 #include "defs.h"
21 #include "serial.h"
22 #include "ser-base.h"
23 #include "event-loop.h"
24
25 #include "gdb_select.h"
26 #include "gdb_sys_time.h"
27 #ifdef USE_WIN32API
28 #include <winsock2.h>
29 #endif
30
31
32 static timer_handler_func push_event;
33 static handler_func fd_event;
34
35 /* Event handling for ASYNC serial code.
36
37    At any time the SERIAL device either: has an empty FIFO and is
38    waiting on a FD event; or has a non-empty FIFO/error condition and
39    is constantly scheduling timer events.
40
41    ASYNC only stops pestering its client when it is de-async'ed or it
42    is told to go away.  */
43
44 /* Value of scb->async_state: */
45 enum {
46   /* >= 0 (TIMER_SCHEDULED) */
47   /* The ID of the currently scheduled timer event.  This state is
48      rarely encountered.  Timer events are one-off so as soon as the
49      event is delivered the state is shanged to NOTHING_SCHEDULED.  */
50   FD_SCHEDULED = -1,
51   /* The fd_event() handler is scheduled.  It is called when ever the
52      file descriptor becomes ready.  */
53   NOTHING_SCHEDULED = -2
54   /* Either no task is scheduled (just going into ASYNC mode) or a
55      timer event has just gone off and the current state has been
56      forced into nothing scheduled.  */
57 };
58
59 /* Identify and schedule the next ASYNC task based on scb->async_state
60    and scb->buf* (the input FIFO).  A state machine is used to avoid
61    the need to make redundant calls into the event-loop - the next
62    scheduled task is only changed when needed.  */
63
64 static void
65 reschedule (struct serial *scb)
66 {
67   if (serial_is_async_p (scb))
68     {
69       int next_state;
70
71       switch (scb->async_state)
72         {
73         case FD_SCHEDULED:
74           if (scb->bufcnt == 0)
75             next_state = FD_SCHEDULED;
76           else
77             {
78               delete_file_handler (scb->fd);
79               next_state = create_timer (0, push_event, scb);
80             }
81           break;
82         case NOTHING_SCHEDULED:
83           if (scb->bufcnt == 0)
84             {
85               add_file_handler (scb->fd, fd_event, scb);
86               next_state = FD_SCHEDULED;
87             }
88           else
89             {
90               next_state = create_timer (0, push_event, scb);
91             }
92           break;
93         default: /* TIMER SCHEDULED */
94           if (scb->bufcnt == 0)
95             {
96               delete_timer (scb->async_state);
97               add_file_handler (scb->fd, fd_event, scb);
98               next_state = FD_SCHEDULED;
99             }
100           else
101             next_state = scb->async_state;
102           break;
103         }
104       if (serial_debug_p (scb))
105         {
106           switch (next_state)
107             {
108             case FD_SCHEDULED:
109               if (scb->async_state != FD_SCHEDULED)
110                 fprintf_unfiltered (gdb_stdlog, "[fd%d->fd-scheduled]\n",
111                                     scb->fd);
112               break;
113             default: /* TIMER SCHEDULED */
114               if (scb->async_state == FD_SCHEDULED)
115                 fprintf_unfiltered (gdb_stdlog, "[fd%d->timer-scheduled]\n",
116                                     scb->fd);
117               break;
118             }
119         }
120       scb->async_state = next_state;
121     }
122 }
123
124 /* Run the SCB's async handle, and reschedule, if the handler doesn't
125    close SCB.  */
126
127 static void
128 run_async_handler_and_reschedule (struct serial *scb)
129 {
130   int is_open;
131
132   /* Take a reference, so a serial_close call within the handler
133      doesn't make SCB a dangling pointer.  */
134   serial_ref (scb);
135
136   /* Run the handler.  */
137   scb->async_handler (scb, scb->async_context);
138
139   is_open = serial_is_open (scb);
140   serial_unref (scb);
141
142   /* Get ready for more, if not already closed.  */
143   if (is_open)
144     reschedule (scb);
145 }
146
147 /* FD_EVENT: This is scheduled when the input FIFO is empty (and there
148    is no pending error).  As soon as data arrives, it is read into the
149    input FIFO and the client notified.  The client should then drain
150    the FIFO using readchar().  If the FIFO isn't immediatly emptied,
151    push_event() is used to nag the client until it is.  */
152
153 static void
154 fd_event (int error, void *context)
155 {
156   struct serial *scb = (struct serial *) context;
157   if (error != 0)
158     {
159       scb->bufcnt = SERIAL_ERROR;
160     }
161   else if (scb->bufcnt == 0)
162     {
163       /* Prime the input FIFO.  The readchar() function is used to
164          pull characters out of the buffer.  See also
165          generic_readchar().  */
166       int nr;
167
168       do
169         {
170           nr = scb->ops->read_prim (scb, BUFSIZ);
171         }
172       while (nr < 0 && errno == EINTR);
173
174       if (nr == 0)
175         {
176           scb->bufcnt = SERIAL_EOF;
177         }
178       else if (nr > 0)
179         {
180           scb->bufcnt = nr;
181           scb->bufp = scb->buf;
182         }
183       else
184         {
185           scb->bufcnt = SERIAL_ERROR;
186         }
187     }
188   run_async_handler_and_reschedule (scb);
189 }
190
191 /* PUSH_EVENT: The input FIFO is non-empty (or there is a pending
192    error).  Nag the client until all the data has been read.  In the
193    case of errors, the client will need to close or de-async the
194    device before naging stops.  */
195
196 static void
197 push_event (void *context)
198 {
199   struct serial *scb = (struct serial *) context;
200
201   scb->async_state = NOTHING_SCHEDULED; /* Timers are one-off */
202   run_async_handler_and_reschedule (scb);
203 }
204
205 /* Wait for input on scb, with timeout seconds.  Returns 0 on success,
206    otherwise SERIAL_TIMEOUT or SERIAL_ERROR.  */
207
208 static int
209 ser_base_wait_for (struct serial *scb, int timeout)
210 {
211   while (1)
212     {
213       int numfds;
214       struct timeval tv;
215       fd_set readfds, exceptfds;
216       int nfds;
217
218       /* NOTE: Some OS's can scramble the READFDS when the select()
219          call fails (ex the kernel with Red Hat 5.2).  Initialize all
220          arguments before each call.  */
221
222       tv.tv_sec = timeout;
223       tv.tv_usec = 0;
224
225       FD_ZERO (&readfds);
226       FD_ZERO (&exceptfds);
227       FD_SET (scb->fd, &readfds);
228       FD_SET (scb->fd, &exceptfds);
229
230       QUIT;
231
232       nfds = scb->fd + 1;
233       if (timeout >= 0)
234         numfds = interruptible_select (nfds, &readfds, 0, &exceptfds, &tv);
235       else
236         numfds = interruptible_select (nfds, &readfds, 0, &exceptfds, 0);
237
238       if (numfds <= 0)
239         {
240           if (numfds == 0)
241             return SERIAL_TIMEOUT;
242           else if (errno == EINTR)
243             continue;
244           else
245             return SERIAL_ERROR;        /* Got an error from select or
246                                            poll.  */
247         }
248
249       return 0;
250     }
251 }
252
253 /* Read any error output we might have.  */
254
255 static void
256 ser_base_read_error_fd (struct serial *scb, int close_fd)
257 {
258   if (scb->error_fd != -1)
259     {
260       ssize_t s;
261       char buf[GDB_MI_MSG_WIDTH + 1];
262
263       for (;;)
264         {
265           char *current;
266           char *newline;
267           int to_read = GDB_MI_MSG_WIDTH;
268           int num_bytes = -1;
269
270           if (scb->ops->avail)
271             num_bytes = (scb->ops->avail)(scb, scb->error_fd);
272
273           if (num_bytes != -1)
274             to_read = (num_bytes < to_read) ? num_bytes : to_read;
275
276           if (to_read == 0)
277             break;
278
279           s = read (scb->error_fd, &buf, to_read);
280           if ((s == -1) || (s == 0 && !close_fd))
281             break;
282
283           if (s == 0 && close_fd)
284             {
285               /* End of file.  */
286               close (scb->error_fd);
287               scb->error_fd = -1;
288               break;
289             }
290
291           /* In theory, embedded newlines are not a problem.
292              But for MI, we want each output line to have just
293              one newline for legibility.  So output things
294              in newline chunks.  */
295           gdb_assert (s > 0 && s <= GDB_MI_MSG_WIDTH);
296           buf[s] = '\0';
297           current = buf;
298           while ((newline = strstr (current, "\n")) != NULL)
299             {
300               *newline = '\0';
301               fputs_unfiltered (current, gdb_stderr);
302               fputs_unfiltered ("\n", gdb_stderr);
303               current = newline + 1;
304             }
305
306           fputs_unfiltered (current, gdb_stderr);
307        }
308     }
309 }
310
311 /* Read a character with user-specified timeout.  TIMEOUT is number of seconds
312    to wait, or -1 to wait forever.  Use timeout of 0 to effect a poll.  Returns
313    char if successful.  Returns -2 if timeout expired, EOF if line dropped
314    dead, or -3 for any other error (see errno in that case).  */
315
316 static int
317 do_ser_base_readchar (struct serial *scb, int timeout)
318 {
319   int status;
320   int delta;
321
322   /* We have to be able to keep the GUI alive here, so we break the
323      original timeout into steps of 1 second, running the "keep the
324      GUI alive" hook each time through the loop.
325
326      Also, timeout = 0 means to poll, so we just set the delta to 0,
327      so we will only go through the loop once.  */
328
329   delta = (timeout == 0 ? 0 : 1);
330   while (1)
331     {
332       /* N.B. The UI may destroy our world (for instance by calling
333          remote_stop,) in which case we want to get out of here as
334          quickly as possible.  It is not safe to touch scb, since
335          someone else might have freed it.  The
336          deprecated_ui_loop_hook signals that we should exit by
337          returning 1.  */
338
339       if (deprecated_ui_loop_hook)
340         {
341           if (deprecated_ui_loop_hook (0))
342             return SERIAL_TIMEOUT;
343         }
344
345       status = ser_base_wait_for (scb, delta);
346       if (timeout > 0)
347         timeout -= delta;
348
349       /* If we got a character or an error back from wait_for, then we can 
350          break from the loop before the timeout is completed.  */
351       if (status != SERIAL_TIMEOUT)
352         break;
353
354       /* If we have exhausted the original timeout, then generate
355          a SERIAL_TIMEOUT, and pass it out of the loop.  */
356       else if (timeout == 0)
357         {
358           status = SERIAL_TIMEOUT;
359           break;
360         }
361
362       /* We also need to check and consume the stderr because it could
363          come before the stdout for some stubs.  If we just sit and wait
364          for stdout, we would hit a deadlock for that case.  */
365       ser_base_read_error_fd (scb, 0);
366     }
367
368   if (status < 0)
369     return status;
370
371   do
372     {
373       status = scb->ops->read_prim (scb, BUFSIZ);
374     }
375   while (status < 0 && errno == EINTR);
376
377   if (status <= 0)
378     {
379       if (status == 0)
380         return SERIAL_EOF;
381       else
382         /* Got an error from read.  */
383         return SERIAL_ERROR;    
384     }
385
386   scb->bufcnt = status;
387   scb->bufcnt--;
388   scb->bufp = scb->buf;
389   return *scb->bufp++;
390 }
391
392 /* Perform operations common to both old and new readchar.  */
393
394 /* Return the next character from the input FIFO.  If the FIFO is
395    empty, call the SERIAL specific routine to try and read in more
396    characters.
397
398    Initially data from the input FIFO is returned (fd_event()
399    pre-reads the input into that FIFO.  Once that has been emptied,
400    further data is obtained by polling the input FD using the device
401    specific readchar() function.  Note: reschedule() is called after
402    every read.  This is because there is no guarentee that the lower
403    level fd_event() poll_event() code (which also calls reschedule())
404    will be called.  */
405
406 int
407 generic_readchar (struct serial *scb, int timeout,
408                   int (do_readchar) (struct serial *scb, int timeout))
409 {
410   int ch;
411   if (scb->bufcnt > 0)
412     {
413       ch = *scb->bufp;
414       scb->bufcnt--;
415       scb->bufp++;
416     }
417   else if (scb->bufcnt < 0)
418     {
419       /* Some errors/eof are are sticky.  */
420       ch = scb->bufcnt;
421     }
422   else
423     {
424       ch = do_readchar (scb, timeout);
425       if (ch < 0)
426         {
427           switch ((enum serial_rc) ch)
428             {
429             case SERIAL_EOF:
430             case SERIAL_ERROR:
431               /* Make the error/eof stick.  */
432               scb->bufcnt = ch;
433               break;
434             case SERIAL_TIMEOUT:
435               scb->bufcnt = 0;
436               break;
437             }
438         }
439     }
440
441   /* Read any error output we might have.  */
442   ser_base_read_error_fd (scb, 1);
443
444   reschedule (scb);
445   return ch;
446 }
447
448 int
449 ser_base_readchar (struct serial *scb, int timeout)
450 {
451   return generic_readchar (scb, timeout, do_ser_base_readchar);
452 }
453
454 int
455 ser_base_write (struct serial *scb, const void *buf, size_t count)
456 {
457   const char *str = (const char *) buf;
458   int cc;
459
460   while (count > 0)
461     {
462       QUIT;
463
464       cc = scb->ops->write_prim (scb, str, count);
465
466       if (cc < 0)
467         {
468           if (errno == EINTR)
469             continue;
470           return 1;
471         }
472       count -= cc;
473       str += cc;
474     }
475   return 0;
476 }
477
478 int
479 ser_base_flush_output (struct serial *scb)
480 {
481   return 0;
482 }
483
484 int
485 ser_base_flush_input (struct serial *scb)
486 {
487   if (scb->bufcnt >= 0)
488     {
489       scb->bufcnt = 0;
490       scb->bufp = scb->buf;
491       return 0;
492     }
493   else
494     return SERIAL_ERROR;
495 }
496
497 int
498 ser_base_send_break (struct serial *scb)
499 {
500   return 0;
501 }
502
503 int
504 ser_base_drain_output (struct serial *scb)
505 {
506   return 0;
507 }
508
509 void
510 ser_base_raw (struct serial *scb)
511 {
512   return;                       /* Always in raw mode.  */
513 }
514
515 serial_ttystate
516 ser_base_get_tty_state (struct serial *scb)
517 {
518   /* Allocate a dummy.  */
519   return (serial_ttystate) XNEW (int);
520 }
521
522 serial_ttystate
523 ser_base_copy_tty_state (struct serial *scb, serial_ttystate ttystate)
524 {
525   /* Allocate another dummy.  */
526   return (serial_ttystate) XNEW (int);
527 }
528
529 int
530 ser_base_set_tty_state (struct serial *scb, serial_ttystate ttystate)
531 {
532   return 0;
533 }
534
535 int
536 ser_base_noflush_set_tty_state (struct serial *scb,
537                                 serial_ttystate new_ttystate,
538                                 serial_ttystate old_ttystate)
539 {
540   return 0;
541 }
542
543 void
544 ser_base_print_tty_state (struct serial *scb, 
545                           serial_ttystate ttystate,
546                           struct ui_file *stream)
547 {
548   /* Nothing to print.  */
549   return;
550 }
551
552 int
553 ser_base_setbaudrate (struct serial *scb, int rate)
554 {
555   return 0;                     /* Never fails!  */
556 }
557
558 int
559 ser_base_setstopbits (struct serial *scb, int num)
560 {
561   return 0;                     /* Never fails!  */
562 }
563
564 /* Implement the "setparity" serial_ops callback.  */
565
566 int
567 ser_base_setparity (struct serial *scb, int parity)
568 {
569   return 0;                     /* Never fails!  */
570 }
571
572 /* Put the SERIAL device into/out-of ASYNC mode.  */
573
574 void
575 ser_base_async (struct serial *scb,
576                 int async_p)
577 {
578   if (async_p)
579     {
580       /* Force a re-schedule.  */
581       scb->async_state = NOTHING_SCHEDULED;
582       if (serial_debug_p (scb))
583         fprintf_unfiltered (gdb_stdlog, "[fd%d->asynchronous]\n",
584                             scb->fd);
585       reschedule (scb);
586     }
587   else
588     {
589       if (serial_debug_p (scb))
590         fprintf_unfiltered (gdb_stdlog, "[fd%d->synchronous]\n",
591                             scb->fd);
592       /* De-schedule whatever tasks are currently scheduled.  */
593       switch (scb->async_state)
594         {
595         case FD_SCHEDULED:
596           delete_file_handler (scb->fd);
597           break;
598         case NOTHING_SCHEDULED:
599           break;
600         default: /* TIMER SCHEDULED */
601           delete_timer (scb->async_state);
602           break;
603         }
604     }
605 }