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