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