Set GDB version number to 8.3.1.
[external/binutils.git] / gdb / inflow.c
1 /* Low level interface to ptrace, for GDB when running under Unix.
2    Copyright (C) 1986-2019 Free Software Foundation, Inc.
3
4    This file is part of GDB.
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
18
19 #include "defs.h"
20 #include "frame.h"
21 #include "inferior.h"
22 #include "command.h"
23 #include "serial.h"
24 #include "terminal.h"
25 #include "target.h"
26 #include "gdbthread.h"
27 #include "observable.h"
28 #include <signal.h>
29 #include <fcntl.h>
30 #include "gdb_select.h"
31
32 #include "inflow.h"
33 #include "gdbcmd.h"
34 #ifdef HAVE_TERMIOS_H
35 #include <termios.h>
36 #endif
37 #include "common/job-control.h"
38
39 #ifdef HAVE_SYS_IOCTL_H
40 #include <sys/ioctl.h>
41 #endif
42
43 #ifndef O_NOCTTY
44 #define O_NOCTTY 0
45 #endif
46
47 static void pass_signal (int);
48
49 static void child_terminal_ours_1 (target_terminal_state);
50 \f
51 /* Record terminal status separately for debugger and inferior.  */
52
53 static struct serial *stdin_serial;
54
55 /* Terminal related info we need to keep track of.  Each inferior
56    holds an instance of this structure --- we save it whenever the
57    corresponding inferior stops, and restore it to the terminal when
58    the inferior is resumed in the foreground.  */
59 struct terminal_info
60 {
61   /* The name of the tty (from the `tty' command) that we gave to the
62      inferior when it was started.  */
63   char *run_terminal;
64
65   /* TTY state.  We save it whenever the inferior stops, and restore
66      it when it resumes in the foreground.  */
67   serial_ttystate ttystate;
68
69 #ifdef HAVE_TERMIOS_H
70   /* The terminal's foreground process group.  Saved whenever the
71      inferior stops.  This is the pgrp displayed by "info terminal".
72      Note that this may be not the inferior's actual process group,
73      since each inferior that we spawn has its own process group, and
74      only one can be in the foreground at a time.  When the inferior
75      resumes, if we can determine the inferior's actual pgrp, then we
76      make that the foreground pgrp instead of what was saved here.
77      While it's a bit arbitrary which inferior's pgrp ends up in the
78      foreground when we resume several inferiors, this at least makes
79      'resume inf1+inf2' + 'stop all' + 'resume inf2' end up with
80      inf2's pgrp in the foreground instead of inf1's (which would be
81      problematic since it would be left stopped: Ctrl-C wouldn't work,
82      for example).  */
83   pid_t process_group;
84 #endif
85
86   /* fcntl flags.  Saved and restored just like ttystate.  */
87   int tflags;
88 };
89
90 /* Our own tty state, which we restore every time we need to deal with
91    the terminal.  This is set once, when GDB first starts, and then
92    whenever we enter/leave TUI mode (gdb_save_tty_state).  The
93    settings of flags which readline saves and restores are
94    unimportant.  */
95 static struct terminal_info our_terminal_info;
96
97 /* Snapshot of the initial tty state taken during initialization of
98    GDB, before readline/ncurses have had a chance to change it.  This
99    is used as the initial tty state given to each new spawned
100    inferior.  Unlike our_terminal_info, this is only ever set
101    once.  */
102 static serial_ttystate initial_gdb_ttystate;
103
104 static struct terminal_info *get_inflow_inferior_data (struct inferior *);
105
106 /* While the inferior is running, we want SIGINT and SIGQUIT to go to the
107    inferior only.  If we have job control, that takes care of it.  If not,
108    we save our handlers in these two variables and set SIGINT and SIGQUIT
109    to SIG_IGN.  */
110
111 static sighandler_t sigint_ours;
112 #ifdef SIGQUIT
113 static sighandler_t sigquit_ours;
114 #endif
115
116 /* The name of the tty (from the `tty' command) that we're giving to
117    the inferior when starting it up.  This is only (and should only
118    be) used as a transient global by new_tty_prefork,
119    create_tty_session, new_tty and new_tty_postfork, all called from
120    fork_inferior, while forking a new child.  */
121 static const char *inferior_thisrun_terminal;
122
123 /* Track who owns GDB's terminal (is it GDB or some inferior?).  While
124    target_terminal::is_ours() etc. tracks the core's intention and is
125    independent of the target backend, this tracks the actual state of
126    GDB's own tty.  So for example,
127
128      (target_terminal::is_inferior () && gdb_tty_state == terminal_is_ours)
129
130    is true when the (native) inferior is not sharing a terminal with
131    GDB (e.g., because we attached to an inferior that is running on a
132    different terminal).  */
133 static target_terminal_state gdb_tty_state = target_terminal_state::is_ours;
134
135 /* See terminal.h.  */
136
137 void
138 set_initial_gdb_ttystate (void)
139 {
140   /* Note we can't do any of this in _initialize_inflow because at
141      that point stdin_serial has not been created yet.  */
142
143   initial_gdb_ttystate = serial_get_tty_state (stdin_serial);
144
145   if (initial_gdb_ttystate != NULL)
146     {
147       our_terminal_info.ttystate
148         = serial_copy_tty_state (stdin_serial, initial_gdb_ttystate);
149 #ifdef F_GETFL
150       our_terminal_info.tflags = fcntl (0, F_GETFL, 0);
151 #endif
152 #ifdef HAVE_TERMIOS_H
153       our_terminal_info.process_group = tcgetpgrp (0);
154 #endif
155     }
156 }
157
158 /* Does GDB have a terminal (on stdin)?  */
159
160 static int
161 gdb_has_a_terminal (void)
162 {
163   return initial_gdb_ttystate != NULL;
164 }
165
166 /* Macro for printing errors from ioctl operations */
167
168 #define OOPSY(what)     \
169   if (result == -1)     \
170     fprintf_unfiltered(gdb_stderr, "[%s failed in terminal_inferior: %s]\n", \
171             what, safe_strerror (errno))
172
173 /* Initialize the terminal settings we record for the inferior,
174    before we actually run the inferior.  */
175
176 void
177 child_terminal_init (struct target_ops *self)
178 {
179   if (!gdb_has_a_terminal ())
180     return;
181
182   inferior *inf = current_inferior ();
183   terminal_info *tinfo = get_inflow_inferior_data (inf);
184
185 #ifdef HAVE_TERMIOS_H
186   /* A child we spawn should be a process group leader (PGID==PID) at
187      this point, though that may not be true if we're attaching to an
188      existing process.  */
189   tinfo->process_group = inf->pid;
190 #endif
191
192   xfree (tinfo->ttystate);
193   tinfo->ttystate = serial_copy_tty_state (stdin_serial, initial_gdb_ttystate);
194 }
195
196 /* Save the terminal settings again.  This is necessary for the TUI
197    when it switches to TUI or non-TUI mode;  curses changes the terminal
198    and gdb must be able to restore it correctly.  */
199
200 void
201 gdb_save_tty_state (void)
202 {
203   if (gdb_has_a_terminal ())
204     {
205       xfree (our_terminal_info.ttystate);
206       our_terminal_info.ttystate = serial_get_tty_state (stdin_serial);
207     }
208 }
209
210 /* Try to determine whether TTY is GDB's input terminal.  Returns
211    TRIBOOL_UNKNOWN if we can't tell.  */
212
213 static tribool
214 is_gdb_terminal (const char *tty)
215 {
216   struct stat gdb_tty;
217   struct stat other_tty;
218   int res;
219
220   res = stat (tty, &other_tty);
221   if (res == -1)
222     return TRIBOOL_UNKNOWN;
223
224   res = fstat (STDIN_FILENO, &gdb_tty);
225   if (res == -1)
226     return TRIBOOL_UNKNOWN;
227
228   return ((gdb_tty.st_dev == other_tty.st_dev
229            && gdb_tty.st_ino == other_tty.st_ino)
230           ? TRIBOOL_TRUE
231           : TRIBOOL_FALSE);
232 }
233
234 /* Helper for sharing_input_terminal.  Try to determine whether
235    inferior INF is using the same TTY for input as GDB is.  Returns
236    TRIBOOL_UNKNOWN if we can't tell.  */
237
238 static tribool
239 sharing_input_terminal_1 (inferior *inf)
240 {
241   /* Using host-dependent code here is fine, because the
242      child_terminal_foo functions are meant to be used by child/native
243      targets.  */
244 #if defined (__linux__) || defined (__sun__)
245   char buf[100];
246
247   xsnprintf (buf, sizeof (buf), "/proc/%d/fd/0", inf->pid);
248   return is_gdb_terminal (buf);
249 #else
250   return TRIBOOL_UNKNOWN;
251 #endif
252 }
253
254 /* Return true if the inferior is using the same TTY for input as GDB
255    is.  If this is true, then we save/restore terminal flags/state.
256
257    This is necessary because if inf->attach_flag is set, we don't
258    offhand know whether we are sharing a terminal with the inferior or
259    not.  Attaching a process without a terminal is one case where we
260    do not; attaching a process which we ran from the same shell as GDB
261    via `&' is one case where we do.
262
263    If we can't determine, we assume the TTY is being shared.  This
264    works OK if you're only debugging one inferior.  However, if you're
265    debugging more than one inferior, and e.g., one is spawned by GDB
266    with "run" (sharing terminal with GDB), and another is attached to
267    (and running on a different terminal, as is most common), then it
268    matters, because we can only restore the terminal settings of one
269    of the inferiors, and in that scenario, we want to restore the
270    settings of the "run"'ed inferior.
271
272    Note, this is not the same as determining whether GDB and the
273    inferior are in the same session / connected to the same
274    controlling tty.  An inferior (fork child) may call setsid,
275    disconnecting itself from the ctty, while still leaving
276    stdin/stdout/stderr associated with the original terminal.  If
277    we're debugging that process, we should also save/restore terminal
278    settings.  */
279
280 static bool
281 sharing_input_terminal (inferior *inf)
282 {
283   terminal_info *tinfo = get_inflow_inferior_data (inf);
284
285   tribool res = sharing_input_terminal_1 (inf);
286
287   if (res == TRIBOOL_UNKNOWN)
288     {
289       /* As fallback, if we can't determine by stat'ing the inferior's
290          tty directly (because it's not supported on this host) and
291          the child was spawned, check whether run_terminal is our tty.
292          This isn't ideal, since this is checking the child's
293          controlling terminal, not the input terminal (which may have
294          been redirected), but is still better than nothing.  A false
295          positive ("set inferior-tty" points to our terminal, but I/O
296          was redirected) is much more likely than a false negative
297          ("set inferior-tty" points to some other terminal, and then
298          output was redirected to our terminal), and with a false
299          positive we just end up trying to save/restore terminal
300          settings when we didn't need to or we actually can't.  */
301       if (tinfo->run_terminal != NULL)
302         res = is_gdb_terminal (tinfo->run_terminal);
303
304       /* If we still can't determine, assume yes.  */
305       if (res == TRIBOOL_UNKNOWN)
306         return true;
307     }
308
309   return res == TRIBOOL_TRUE;
310 }
311
312 /* Put the inferior's terminal settings into effect.  This is
313    preparation for starting or resuming the inferior.  */
314
315 void
316 child_terminal_inferior (struct target_ops *self)
317 {
318   /* If we resume more than one inferior in the foreground on GDB's
319      terminal, then the first inferior's terminal settings "win".
320      Note that every child process is put in its own process group, so
321      the first process that ends up resumed ends up determining which
322      process group the kernel forwards Ctrl-C/Ctrl-Z (SIGINT/SIGTTOU)
323      to.  */
324   if (gdb_tty_state == target_terminal_state::is_inferior)
325     return;
326
327   inferior *inf = current_inferior ();
328   terminal_info *tinfo = get_inflow_inferior_data (inf);
329
330   if (gdb_has_a_terminal ()
331       && tinfo->ttystate != NULL
332       && sharing_input_terminal (inf))
333     {
334       int result;
335
336       /* Ignore SIGTTOU since it will happen when we try to set the
337          terminal's state (if gdb_tty_state is currently
338          ours_for_output).  */
339       scoped_ignore_sigttou ignore_sigttou;
340
341 #ifdef F_GETFL
342       result = fcntl (0, F_SETFL, tinfo->tflags);
343       OOPSY ("fcntl F_SETFL");
344 #endif
345
346       result = serial_set_tty_state (stdin_serial, tinfo->ttystate);
347       OOPSY ("setting tty state");
348
349       if (!job_control)
350         {
351           sigint_ours = signal (SIGINT, SIG_IGN);
352 #ifdef SIGQUIT
353           sigquit_ours = signal (SIGQUIT, SIG_IGN);
354 #endif
355         }
356
357       if (job_control)
358         {
359 #ifdef HAVE_TERMIOS_H
360           /* If we can't tell the inferior's actual process group,
361              then restore whatever was the foreground pgrp the last
362              time the inferior was running.  See also comments
363              describing terminal_state::process_group.  */
364 #ifdef HAVE_GETPGID
365           result = tcsetpgrp (0, getpgid (inf->pid));
366 #else
367           result = tcsetpgrp (0, tinfo->process_group);
368 #endif
369           if (result == -1)
370             {
371 #if 0
372               /* This fails if either GDB has no controlling terminal,
373                  e.g., running under 'setsid(1)', or if the inferior
374                  is not attached to GDB's controlling terminal.  E.g.,
375                  if it called setsid to create a new session or used
376                  the TIOCNOTTY ioctl, or simply if we've attached to a
377                  process running on another terminal and we couldn't
378                  tell whether it was sharing GDB's terminal (and so
379                  assumed yes).  */
380               fprintf_unfiltered
381                 (gdb_stderr,
382                  "[tcsetpgrp failed in child_terminal_inferior: %s]\n",
383                  safe_strerror (errno));
384 #endif
385             }
386 #endif
387         }
388
389       gdb_tty_state = target_terminal_state::is_inferior;
390     }
391 }
392
393 /* Put some of our terminal settings into effect,
394    enough to get proper results from our output,
395    but do not change into or out of RAW mode
396    so that no input is discarded.
397
398    After doing this, either terminal_ours or terminal_inferior
399    should be called to get back to a normal state of affairs.
400
401    N.B. The implementation is (currently) no different than
402    child_terminal_ours.  See child_terminal_ours_1.  */
403
404 void
405 child_terminal_ours_for_output (struct target_ops *self)
406 {
407   child_terminal_ours_1 (target_terminal_state::is_ours_for_output);
408 }
409
410 /* Put our terminal settings into effect.
411    First record the inferior's terminal settings
412    so they can be restored properly later.
413
414    N.B. Targets that want to use this with async support must build that
415    support on top of this (e.g., the caller still needs to add stdin to the
416    event loop).  E.g., see linux_nat_terminal_ours.  */
417
418 void
419 child_terminal_ours (struct target_ops *self)
420 {
421   child_terminal_ours_1 (target_terminal_state::is_ours);
422 }
423
424 /* Save the current terminal settings in the inferior's terminal_info
425    cache.  */
426
427 void
428 child_terminal_save_inferior (struct target_ops *self)
429 {
430   /* Avoid attempting all the ioctl's when running in batch.  */
431   if (!gdb_has_a_terminal ())
432     return;
433
434   inferior *inf = current_inferior ();
435   terminal_info *tinfo = get_inflow_inferior_data (inf);
436
437   /* No need to save/restore if the inferior is not sharing GDB's
438      tty.  */
439   if (!sharing_input_terminal (inf))
440     return;
441
442   xfree (tinfo->ttystate);
443   tinfo->ttystate = serial_get_tty_state (stdin_serial);
444
445 #ifdef HAVE_TERMIOS_H
446   tinfo->process_group = tcgetpgrp (0);
447 #endif
448
449 #ifdef F_GETFL
450   tinfo->tflags = fcntl (0, F_GETFL, 0);
451 #endif
452 }
453
454 /* Switch terminal state to DESIRED_STATE, either is_ours, or
455    is_ours_for_output.  */
456
457 static void
458 child_terminal_ours_1 (target_terminal_state desired_state)
459 {
460   gdb_assert (desired_state != target_terminal_state::is_inferior);
461
462   /* Avoid attempting all the ioctl's when running in batch.  */
463   if (!gdb_has_a_terminal ())
464     return;
465
466   if (gdb_tty_state != desired_state)
467     {
468       int result ATTRIBUTE_UNUSED;
469
470       /* Ignore SIGTTOU since it will happen when we try to set the
471          terminal's pgrp.  */
472       scoped_ignore_sigttou ignore_sigttou;
473
474       /* Set tty state to our_ttystate.  */
475       serial_set_tty_state (stdin_serial, our_terminal_info.ttystate);
476
477       /* If we only want output, then leave the inferior's pgrp in the
478          foreground, so that Ctrl-C/Ctrl-Z reach the inferior
479          directly.  */
480       if (job_control && desired_state == target_terminal_state::is_ours)
481         {
482 #ifdef HAVE_TERMIOS_H
483           result = tcsetpgrp (0, our_terminal_info.process_group);
484 #if 0
485           /* This fails on Ultrix with EINVAL if you run the testsuite
486              in the background with nohup, and then log out.  GDB never
487              used to check for an error here, so perhaps there are other
488              such situations as well.  */
489           if (result == -1)
490             fprintf_unfiltered (gdb_stderr,
491                                 "[tcsetpgrp failed in child_terminal_ours: %s]\n",
492                                 safe_strerror (errno));
493 #endif
494 #endif /* termios */
495         }
496
497       if (!job_control && desired_state == target_terminal_state::is_ours)
498         {
499           signal (SIGINT, sigint_ours);
500 #ifdef SIGQUIT
501           signal (SIGQUIT, sigquit_ours);
502 #endif
503         }
504
505 #ifdef F_GETFL
506       result = fcntl (0, F_SETFL, our_terminal_info.tflags);
507 #endif
508
509       gdb_tty_state = desired_state;
510     }
511 }
512
513 /* Interrupt the inferior.  Implementation of target_interrupt for
514    child/native targets.  */
515
516 void
517 child_interrupt (struct target_ops *self)
518 {
519   /* Interrupt the first inferior that has a resumed thread.  */
520   thread_info *resumed = NULL;
521   for (thread_info *thr : all_non_exited_threads ())
522     {
523       if (thr->executing)
524         {
525           resumed = thr;
526           break;
527         }
528       if (thr->suspend.waitstatus_pending_p)
529         resumed = thr;
530     }
531
532   if (resumed != NULL)
533     {
534       /* Note that unlike pressing Ctrl-C on the controlling terminal,
535          here we only interrupt one process, not the whole process
536          group.  This is because interrupting a process group (with
537          either Ctrl-C or with kill(3) with negative PID) sends a
538          SIGINT to each process in the process group, and we may not
539          be debugging all processes in the process group.  */
540 #ifndef _WIN32
541       kill (resumed->inf->pid, SIGINT);
542 #endif
543     }
544 }
545
546 /* Pass a Ctrl-C to the inferior as-if a Ctrl-C was pressed while the
547    inferior was in the foreground.  Implementation of
548    target_pass_ctrlc for child/native targets.  */
549
550 void
551 child_pass_ctrlc (struct target_ops *self)
552 {
553   gdb_assert (!target_terminal::is_ours ());
554
555 #ifdef HAVE_TERMIOS_H
556   if (job_control)
557     {
558       pid_t term_pgrp = tcgetpgrp (0);
559
560       /* If there's any inferior sharing our terminal, pass the SIGINT
561          to the terminal's foreground process group.  This acts just
562          like the user typed a ^C on the terminal while the inferior
563          was in the foreground.  Note that using a negative process
564          number in kill() is a System V-ism.  The proper BSD interface
565          is killpg().  However, all modern BSDs support the System V
566          interface too.  */
567
568       if (term_pgrp != -1 && term_pgrp != our_terminal_info.process_group)
569         {
570           kill (-term_pgrp, SIGINT);
571           return;
572         }
573     }
574 #endif
575
576   /* Otherwise, pass the Ctrl-C to the first inferior that was resumed
577      in the foreground.  */
578   for (inferior *inf : all_inferiors ())
579     {
580       if (inf->terminal_state != target_terminal_state::is_ours)
581         {
582           gdb_assert (inf->pid != 0);
583
584 #ifndef _WIN32
585           kill (inf->pid, SIGINT);
586 #endif
587           return;
588         }
589     }
590
591   /* If no inferior was resumed in the foreground, then how did the
592      !is_ours assert above pass?  */
593   gdb_assert_not_reached ("no inferior resumed in the fg found");
594 }
595
596 /* Per-inferior data key.  */
597 static const struct inferior_data *inflow_inferior_data;
598
599 static void
600 inflow_inferior_data_cleanup (struct inferior *inf, void *arg)
601 {
602   struct terminal_info *info = (struct terminal_info *) arg;
603
604   xfree (info->run_terminal);
605   xfree (info->ttystate);
606   xfree (info);
607 }
608
609 /* Get the current svr4 data.  If none is found yet, add it now.  This
610    function always returns a valid object.  */
611
612 static struct terminal_info *
613 get_inflow_inferior_data (struct inferior *inf)
614 {
615   struct terminal_info *info;
616
617   info = (struct terminal_info *) inferior_data (inf, inflow_inferior_data);
618   if (info == NULL)
619     {
620       info = XCNEW (struct terminal_info);
621       set_inferior_data (inf, inflow_inferior_data, info);
622     }
623
624   return info;
625 }
626
627 /* This is a "inferior_exit" observer.  Releases the TERMINAL_INFO member
628    of the inferior structure.  This field is private to inflow.c, and
629    its type is opaque to the rest of GDB.  PID is the target pid of
630    the inferior that is about to be removed from the inferior
631    list.  */
632
633 static void
634 inflow_inferior_exit (struct inferior *inf)
635 {
636   struct terminal_info *info;
637
638   inf->terminal_state = target_terminal_state::is_ours;
639
640   info = (struct terminal_info *) inferior_data (inf, inflow_inferior_data);
641   if (info != NULL)
642     {
643       xfree (info->run_terminal);
644       xfree (info->ttystate);
645       xfree (info);
646       set_inferior_data (inf, inflow_inferior_data, NULL);
647     }
648 }
649
650 void
651 copy_terminal_info (struct inferior *to, struct inferior *from)
652 {
653   struct terminal_info *tinfo_to, *tinfo_from;
654
655   tinfo_to = get_inflow_inferior_data (to);
656   tinfo_from = get_inflow_inferior_data (from);
657
658   xfree (tinfo_to->run_terminal);
659   xfree (tinfo_to->ttystate);
660
661   *tinfo_to = *tinfo_from;
662
663   if (tinfo_from->run_terminal)
664     tinfo_to->run_terminal
665       = xstrdup (tinfo_from->run_terminal);
666
667   if (tinfo_from->ttystate)
668     tinfo_to->ttystate
669       = serial_copy_tty_state (stdin_serial, tinfo_from->ttystate);
670
671   to->terminal_state = from->terminal_state;
672 }
673
674 /* See terminal.h.  */
675
676 void
677 swap_terminal_info (inferior *a, inferior *b)
678 {
679   terminal_info *info_a
680     = (terminal_info *) inferior_data (a, inflow_inferior_data);
681   terminal_info *info_b
682     = (terminal_info *) inferior_data (a, inflow_inferior_data);
683
684   set_inferior_data (a, inflow_inferior_data, info_b);
685   set_inferior_data (b, inflow_inferior_data, info_a);
686
687   std::swap (a->terminal_state, b->terminal_state);
688 }
689
690 void
691 info_terminal_command (const char *arg, int from_tty)
692 {
693   target_terminal::info (arg, from_tty);
694 }
695
696 void
697 child_terminal_info (struct target_ops *self, const char *args, int from_tty)
698 {
699   struct inferior *inf;
700   struct terminal_info *tinfo;
701
702   if (!gdb_has_a_terminal ())
703     {
704       printf_filtered (_("This GDB does not control a terminal.\n"));
705       return;
706     }
707
708   if (inferior_ptid == null_ptid)
709     return;
710
711   inf = current_inferior ();
712   tinfo = get_inflow_inferior_data (inf);
713
714   printf_filtered (_("Inferior's terminal status "
715                      "(currently saved by GDB):\n"));
716
717   /* First the fcntl flags.  */
718   {
719     int flags;
720
721     flags = tinfo->tflags;
722
723     printf_filtered ("File descriptor flags = ");
724
725 #ifndef O_ACCMODE
726 #define O_ACCMODE (O_RDONLY | O_WRONLY | O_RDWR)
727 #endif
728     /* (O_ACCMODE) parens are to avoid Ultrix header file bug.  */
729     switch (flags & (O_ACCMODE))
730       {
731       case O_RDONLY:
732         printf_filtered ("O_RDONLY");
733         break;
734       case O_WRONLY:
735         printf_filtered ("O_WRONLY");
736         break;
737       case O_RDWR:
738         printf_filtered ("O_RDWR");
739         break;
740       }
741     flags &= ~(O_ACCMODE);
742
743 #ifdef O_NONBLOCK
744     if (flags & O_NONBLOCK)
745       printf_filtered (" | O_NONBLOCK");
746     flags &= ~O_NONBLOCK;
747 #endif
748
749 #if defined (O_NDELAY)
750     /* If O_NDELAY and O_NONBLOCK are defined to the same thing, we will
751        print it as O_NONBLOCK, which is good cause that is what POSIX
752        has, and the flag will already be cleared by the time we get here.  */
753     if (flags & O_NDELAY)
754       printf_filtered (" | O_NDELAY");
755     flags &= ~O_NDELAY;
756 #endif
757
758     if (flags & O_APPEND)
759       printf_filtered (" | O_APPEND");
760     flags &= ~O_APPEND;
761
762 #if defined (O_BINARY)
763     if (flags & O_BINARY)
764       printf_filtered (" | O_BINARY");
765     flags &= ~O_BINARY;
766 #endif
767
768     if (flags)
769       printf_filtered (" | 0x%x", flags);
770     printf_filtered ("\n");
771   }
772
773 #ifdef HAVE_TERMIOS_H
774   printf_filtered ("Process group = %d\n", (int) tinfo->process_group);
775 #endif
776
777   serial_print_tty_state (stdin_serial, tinfo->ttystate, gdb_stdout);
778 }
779 \f
780 /* NEW_TTY_PREFORK is called before forking a new child process,
781    so we can record the state of ttys in the child to be formed.
782    TTYNAME is null if we are to share the terminal with gdb;
783    or points to a string containing the name of the desired tty.
784
785    NEW_TTY is called in new child processes under Unix, which will
786    become debugger target processes.  This actually switches to
787    the terminal specified in the NEW_TTY_PREFORK call.  */
788
789 void
790 new_tty_prefork (const char *ttyname)
791 {
792   /* Save the name for later, for determining whether we and the child
793      are sharing a tty.  */
794   inferior_thisrun_terminal = ttyname;
795 }
796
797 #if !defined(__GO32__) && !defined(_WIN32)
798 /* If RESULT, assumed to be the return value from a system call, is
799    negative, print the error message indicated by errno and exit.
800    MSG should identify the operation that failed.  */
801 static void
802 check_syscall (const char *msg, int result)
803 {
804   if (result < 0)
805     {
806       print_sys_errmsg (msg, errno);
807       _exit (1);
808     }
809 }
810 #endif
811
812 void
813 new_tty (void)
814 {
815   if (inferior_thisrun_terminal == 0)
816     return;
817 #if !defined(__GO32__) && !defined(_WIN32)
818   int tty;
819
820 #ifdef TIOCNOTTY
821   /* Disconnect the child process from our controlling terminal.  On some
822      systems (SVR4 for example), this may cause a SIGTTOU, so temporarily
823      ignore SIGTTOU.  */
824   tty = open ("/dev/tty", O_RDWR);
825   if (tty > 0)
826     {
827       scoped_ignore_sigttou ignore_sigttou;
828
829       ioctl (tty, TIOCNOTTY, 0);
830       close (tty);
831     }
832 #endif
833
834   /* Now open the specified new terminal.  */
835   tty = open (inferior_thisrun_terminal, O_RDWR | O_NOCTTY);
836   check_syscall (inferior_thisrun_terminal, tty);
837
838   /* Avoid use of dup2; doesn't exist on all systems.  */
839   if (tty != 0)
840     {
841       close (0);
842       check_syscall ("dup'ing tty into fd 0", dup (tty));
843     }
844   if (tty != 1)
845     {
846       close (1);
847       check_syscall ("dup'ing tty into fd 1", dup (tty));
848     }
849   if (tty != 2)
850     {
851       close (2);
852       check_syscall ("dup'ing tty into fd 2", dup (tty));
853     }
854
855 #ifdef TIOCSCTTY
856   /* Make tty our new controlling terminal.  */
857   if (ioctl (tty, TIOCSCTTY, 0) == -1)
858     /* Mention GDB in warning because it will appear in the inferior's
859        terminal instead of GDB's.  */
860     warning (_("GDB: Failed to set controlling terminal: %s"),
861              safe_strerror (errno));
862 #endif
863
864   if (tty > 2)
865     close (tty);
866 #endif /* !go32 && !win32 */
867 }
868
869 /* NEW_TTY_POSTFORK is called after forking a new child process, and
870    adding it to the inferior table, to store the TTYNAME being used by
871    the child, or null if it sharing the terminal with gdb.  */
872
873 void
874 new_tty_postfork (void)
875 {
876   /* Save the name for later, for determining whether we and the child
877      are sharing a tty.  */
878
879   if (inferior_thisrun_terminal)
880     {
881       struct inferior *inf = current_inferior ();
882       struct terminal_info *tinfo = get_inflow_inferior_data (inf);
883
884       tinfo->run_terminal = xstrdup (inferior_thisrun_terminal);
885     }
886
887   inferior_thisrun_terminal = NULL;
888 }
889
890 \f
891 /* Call set_sigint_trap when you need to pass a signal on to an attached
892    process when handling SIGINT.  */
893
894 static void
895 pass_signal (int signo)
896 {
897 #ifndef _WIN32
898   kill (inferior_ptid.pid (), SIGINT);
899 #endif
900 }
901
902 static sighandler_t osig;
903 static int osig_set;
904
905 void
906 set_sigint_trap (void)
907 {
908   struct inferior *inf = current_inferior ();
909   struct terminal_info *tinfo = get_inflow_inferior_data (inf);
910
911   if (inf->attach_flag || tinfo->run_terminal)
912     {
913       osig = signal (SIGINT, pass_signal);
914       osig_set = 1;
915     }
916   else
917     osig_set = 0;
918 }
919
920 void
921 clear_sigint_trap (void)
922 {
923   if (osig_set)
924     {
925       signal (SIGINT, osig);
926       osig_set = 0;
927     }
928 }
929 \f
930
931 /* Create a new session if the inferior will run in a different tty.
932    A session is UNIX's way of grouping processes that share a controlling
933    terminal, so a new one is needed if the inferior terminal will be
934    different from GDB's.
935
936    Returns the session id of the new session, 0 if no session was created
937    or -1 if an error occurred.  */
938 pid_t
939 create_tty_session (void)
940 {
941 #ifdef HAVE_SETSID
942   pid_t ret;
943
944   if (!job_control || inferior_thisrun_terminal == 0)
945     return 0;
946
947   ret = setsid ();
948   if (ret == -1)
949     warning (_("Failed to create new terminal session: setsid: %s"),
950              safe_strerror (errno));
951
952   return ret;
953 #else
954   return 0;
955 #endif /* HAVE_SETSID */
956 }
957
958 /* Get all the current tty settings (including whether we have a
959    tty at all!).  We can't do this in _initialize_inflow because
960    serial_fdopen() won't work until the serial_ops_list is
961    initialized, but we don't want to do it lazily either, so
962    that we can guarantee stdin_serial is opened if there is
963    a terminal.  */
964 void
965 initialize_stdin_serial (void)
966 {
967   stdin_serial = serial_fdopen (0);
968 }
969
970 void
971 _initialize_inflow (void)
972 {
973   add_info ("terminal", info_terminal_command,
974             _("Print inferior's saved terminal status."));
975
976   /* OK, figure out whether we have job control.  */
977   have_job_control ();
978
979   gdb::observers::inferior_exit.attach (inflow_inferior_exit);
980
981   inflow_inferior_data
982     = register_inferior_data_with_cleanup (NULL, inflow_inferior_data_cleanup);
983 }