Home | History | Annotate | Line # | Download | only in gdb
inflow.c revision 1.1.1.6
      1 /* Low level interface to ptrace, for GDB when running under Unix.
      2    Copyright (C) 1986-2020 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 "inflow.h"
     33 #include "gdbcmd.h"
     34 #ifdef HAVE_TERMIOS_H
     35 #include <termios.h>
     36 #endif
     37 #include "gdbsupport/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 
     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   char *run_terminal = nullptr;
     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 sighandler_t sigint_ours;
    118 #ifdef SIGQUIT
    119 static 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 const char *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     fprintf_unfiltered(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 /* Try to determine whether TTY is GDB's input terminal.  Returns
    217    TRIBOOL_UNKNOWN if we can't tell.  */
    218 
    219 static tribool
    220 is_gdb_terminal (const char *tty)
    221 {
    222   struct stat gdb_tty;
    223   struct stat other_tty;
    224   int res;
    225 
    226   res = stat (tty, &other_tty);
    227   if (res == -1)
    228     return TRIBOOL_UNKNOWN;
    229 
    230   res = fstat (STDIN_FILENO, &gdb_tty);
    231   if (res == -1)
    232     return TRIBOOL_UNKNOWN;
    233 
    234   return ((gdb_tty.st_dev == other_tty.st_dev
    235 	   && gdb_tty.st_ino == other_tty.st_ino)
    236 	  ? TRIBOOL_TRUE
    237 	  : TRIBOOL_FALSE);
    238 }
    239 
    240 /* Helper for sharing_input_terminal.  Try to determine whether
    241    inferior INF is using the same TTY for input as GDB is.  Returns
    242    TRIBOOL_UNKNOWN if we can't tell.  */
    243 
    244 static tribool
    245 sharing_input_terminal_1 (inferior *inf)
    246 {
    247   /* Using host-dependent code here is fine, because the
    248      child_terminal_foo functions are meant to be used by child/native
    249      targets.  */
    250 #if defined (__linux__) || defined (__sun__)
    251   char buf[100];
    252 
    253   xsnprintf (buf, sizeof (buf), "/proc/%d/fd/0", inf->pid);
    254   return is_gdb_terminal (buf);
    255 #else
    256   return TRIBOOL_UNKNOWN;
    257 #endif
    258 }
    259 
    260 /* Return true if the inferior is using the same TTY for input as GDB
    261    is.  If this is true, then we save/restore terminal flags/state.
    262 
    263    This is necessary because if inf->attach_flag is set, we don't
    264    offhand know whether we are sharing a terminal with the inferior or
    265    not.  Attaching a process without a terminal is one case where we
    266    do not; attaching a process which we ran from the same shell as GDB
    267    via `&' is one case where we do.
    268 
    269    If we can't determine, we assume the TTY is being shared.  This
    270    works OK if you're only debugging one inferior.  However, if you're
    271    debugging more than one inferior, and e.g., one is spawned by GDB
    272    with "run" (sharing terminal with GDB), and another is attached to
    273    (and running on a different terminal, as is most common), then it
    274    matters, because we can only restore the terminal settings of one
    275    of the inferiors, and in that scenario, we want to restore the
    276    settings of the "run"'ed inferior.
    277 
    278    Note, this is not the same as determining whether GDB and the
    279    inferior are in the same session / connected to the same
    280    controlling tty.  An inferior (fork child) may call setsid,
    281    disconnecting itself from the ctty, while still leaving
    282    stdin/stdout/stderr associated with the original terminal.  If
    283    we're debugging that process, we should also save/restore terminal
    284    settings.  */
    285 
    286 static bool
    287 sharing_input_terminal (inferior *inf)
    288 {
    289   terminal_info *tinfo = get_inflow_inferior_data (inf);
    290 
    291   tribool res = sharing_input_terminal_1 (inf);
    292 
    293   if (res == TRIBOOL_UNKNOWN)
    294     {
    295       /* As fallback, if we can't determine by stat'ing the inferior's
    296 	 tty directly (because it's not supported on this host) and
    297 	 the child was spawned, check whether run_terminal is our tty.
    298 	 This isn't ideal, since this is checking the child's
    299 	 controlling terminal, not the input terminal (which may have
    300 	 been redirected), but is still better than nothing.  A false
    301 	 positive ("set inferior-tty" points to our terminal, but I/O
    302 	 was redirected) is much more likely than a false negative
    303 	 ("set inferior-tty" points to some other terminal, and then
    304 	 output was redirected to our terminal), and with a false
    305 	 positive we just end up trying to save/restore terminal
    306 	 settings when we didn't need to or we actually can't.  */
    307       if (tinfo->run_terminal != NULL)
    308 	res = is_gdb_terminal (tinfo->run_terminal);
    309 
    310       /* If we still can't determine, assume yes.  */
    311       if (res == TRIBOOL_UNKNOWN)
    312 	return true;
    313     }
    314 
    315   return res == TRIBOOL_TRUE;
    316 }
    317 
    318 /* Put the inferior's terminal settings into effect.  This is
    319    preparation for starting or resuming the inferior.  */
    320 
    321 void
    322 child_terminal_inferior (struct target_ops *self)
    323 {
    324   /* If we resume more than one inferior in the foreground on GDB's
    325      terminal, then the first inferior's terminal settings "win".
    326      Note that every child process is put in its own process group, so
    327      the first process that ends up resumed ends up determining which
    328      process group the kernel forwards Ctrl-C/Ctrl-Z (SIGINT/SIGTTOU)
    329      to.  */
    330   if (gdb_tty_state == target_terminal_state::is_inferior)
    331     return;
    332 
    333   inferior *inf = current_inferior ();
    334   terminal_info *tinfo = get_inflow_inferior_data (inf);
    335 
    336   if (gdb_has_a_terminal ()
    337       && tinfo->ttystate != NULL
    338       && sharing_input_terminal (inf))
    339     {
    340       int result;
    341 
    342       /* Ignore SIGTTOU since it will happen when we try to set the
    343 	 terminal's state (if gdb_tty_state is currently
    344 	 ours_for_output).  */
    345       scoped_ignore_sigttou ignore_sigttou;
    346 
    347 #ifdef F_GETFL
    348       result = fcntl (0, F_SETFL, tinfo->tflags);
    349       OOPSY ("fcntl F_SETFL");
    350 #endif
    351 
    352       result = serial_set_tty_state (stdin_serial, tinfo->ttystate);
    353       OOPSY ("setting tty state");
    354 
    355       if (!job_control)
    356 	{
    357 	  sigint_ours = signal (SIGINT, SIG_IGN);
    358 #ifdef SIGQUIT
    359 	  sigquit_ours = signal (SIGQUIT, SIG_IGN);
    360 #endif
    361 	}
    362 
    363       if (job_control)
    364 	{
    365 #ifdef HAVE_TERMIOS_H
    366 	  /* If we can't tell the inferior's actual process group,
    367 	     then restore whatever was the foreground pgrp the last
    368 	     time the inferior was running.  See also comments
    369 	     describing terminal_state::process_group.  */
    370 #ifdef HAVE_GETPGID
    371 	  result = tcsetpgrp (0, getpgid (inf->pid));
    372 #else
    373 	  result = tcsetpgrp (0, tinfo->process_group);
    374 #endif
    375 	  if (result == -1)
    376 	    {
    377 #if 0
    378 	      /* This fails if either GDB has no controlling terminal,
    379 		 e.g., running under 'setsid(1)', or if the inferior
    380 		 is not attached to GDB's controlling terminal.  E.g.,
    381 		 if it called setsid to create a new session or used
    382 		 the TIOCNOTTY ioctl, or simply if we've attached to a
    383 		 process running on another terminal and we couldn't
    384 		 tell whether it was sharing GDB's terminal (and so
    385 		 assumed yes).  */
    386 	      fprintf_unfiltered
    387 		(gdb_stderr,
    388 		 "[tcsetpgrp failed in child_terminal_inferior: %s]\n",
    389 		 safe_strerror (errno));
    390 #endif
    391 	    }
    392 #endif
    393 	}
    394 
    395       gdb_tty_state = target_terminal_state::is_inferior;
    396     }
    397 }
    398 
    399 /* Put some of our terminal settings into effect,
    400    enough to get proper results from our output,
    401    but do not change into or out of RAW mode
    402    so that no input is discarded.
    403 
    404    After doing this, either terminal_ours or terminal_inferior
    405    should be called to get back to a normal state of affairs.
    406 
    407    N.B. The implementation is (currently) no different than
    408    child_terminal_ours.  See child_terminal_ours_1.  */
    409 
    410 void
    411 child_terminal_ours_for_output (struct target_ops *self)
    412 {
    413   child_terminal_ours_1 (target_terminal_state::is_ours_for_output);
    414 }
    415 
    416 /* Put our terminal settings into effect.
    417    First record the inferior's terminal settings
    418    so they can be restored properly later.
    419 
    420    N.B. Targets that want to use this with async support must build that
    421    support on top of this (e.g., the caller still needs to add stdin to the
    422    event loop).  E.g., see linux_nat_terminal_ours.  */
    423 
    424 void
    425 child_terminal_ours (struct target_ops *self)
    426 {
    427   child_terminal_ours_1 (target_terminal_state::is_ours);
    428 }
    429 
    430 /* Save the current terminal settings in the inferior's terminal_info
    431    cache.  */
    432 
    433 void
    434 child_terminal_save_inferior (struct target_ops *self)
    435 {
    436   /* Avoid attempting all the ioctl's when running in batch.  */
    437   if (!gdb_has_a_terminal ())
    438     return;
    439 
    440   inferior *inf = current_inferior ();
    441   terminal_info *tinfo = get_inflow_inferior_data (inf);
    442 
    443   /* No need to save/restore if the inferior is not sharing GDB's
    444      tty.  */
    445   if (!sharing_input_terminal (inf))
    446     return;
    447 
    448   xfree (tinfo->ttystate);
    449   tinfo->ttystate = serial_get_tty_state (stdin_serial);
    450 
    451 #ifdef HAVE_TERMIOS_H
    452   tinfo->process_group = tcgetpgrp (0);
    453 #endif
    454 
    455 #ifdef F_GETFL
    456   tinfo->tflags = fcntl (0, F_GETFL, 0);
    457 #endif
    458 }
    459 
    460 /* Switch terminal state to DESIRED_STATE, either is_ours, or
    461    is_ours_for_output.  */
    462 
    463 static void
    464 child_terminal_ours_1 (target_terminal_state desired_state)
    465 {
    466   gdb_assert (desired_state != target_terminal_state::is_inferior);
    467 
    468   /* Avoid attempting all the ioctl's when running in batch.  */
    469   if (!gdb_has_a_terminal ())
    470     return;
    471 
    472   if (gdb_tty_state != desired_state)
    473     {
    474       int result ATTRIBUTE_UNUSED;
    475 
    476       /* Ignore SIGTTOU since it will happen when we try to set the
    477 	 terminal's pgrp.  */
    478       scoped_ignore_sigttou ignore_sigttou;
    479 
    480       /* Set tty state to our_ttystate.  */
    481       serial_set_tty_state (stdin_serial, our_terminal_info.ttystate);
    482 
    483       /* If we only want output, then leave the inferior's pgrp in the
    484 	 foreground, so that Ctrl-C/Ctrl-Z reach the inferior
    485 	 directly.  */
    486       if (job_control && desired_state == target_terminal_state::is_ours)
    487 	{
    488 #ifdef HAVE_TERMIOS_H
    489 	  result = tcsetpgrp (0, our_terminal_info.process_group);
    490 #if 0
    491 	  /* This fails on Ultrix with EINVAL if you run the testsuite
    492 	     in the background with nohup, and then log out.  GDB never
    493 	     used to check for an error here, so perhaps there are other
    494 	     such situations as well.  */
    495 	  if (result == -1)
    496 	    fprintf_unfiltered (gdb_stderr,
    497 				"[tcsetpgrp failed in child_terminal_ours: %s]\n",
    498 				safe_strerror (errno));
    499 #endif
    500 #endif /* termios */
    501 	}
    502 
    503       if (!job_control && desired_state == target_terminal_state::is_ours)
    504 	{
    505 	  signal (SIGINT, sigint_ours);
    506 #ifdef SIGQUIT
    507 	  signal (SIGQUIT, sigquit_ours);
    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->suspend.waitstatus_pending_p)
    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 struct inferior_key<terminal_info> inflow_inferior_data;
    604 
    605 terminal_info::~terminal_info ()
    606 {
    607   xfree (run_terminal);
    608   xfree (ttystate);
    609 }
    610 
    611 /* Get the current svr4 data.  If none is found yet, add it now.  This
    612    function always returns a valid object.  */
    613 
    614 static struct terminal_info *
    615 get_inflow_inferior_data (struct inferior *inf)
    616 {
    617   struct terminal_info *info;
    618 
    619   info = inflow_inferior_data.get (inf);
    620   if (info == NULL)
    621     info = inflow_inferior_data.emplace (inf);
    622 
    623   return info;
    624 }
    625 
    626 /* This is a "inferior_exit" observer.  Releases the TERMINAL_INFO member
    627    of the inferior structure.  This field is private to inflow.c, and
    628    its type is opaque to the rest of GDB.  PID is the target pid of
    629    the inferior that is about to be removed from the inferior
    630    list.  */
    631 
    632 static void
    633 inflow_inferior_exit (struct inferior *inf)
    634 {
    635   inf->terminal_state = target_terminal_state::is_ours;
    636   inflow_inferior_data.clear (inf);
    637 }
    638 
    639 void
    640 copy_terminal_info (struct inferior *to, struct inferior *from)
    641 {
    642   struct terminal_info *tinfo_to, *tinfo_from;
    643 
    644   tinfo_to = get_inflow_inferior_data (to);
    645   tinfo_from = get_inflow_inferior_data (from);
    646 
    647   xfree (tinfo_to->run_terminal);
    648   xfree (tinfo_to->ttystate);
    649 
    650   *tinfo_to = *tinfo_from;
    651 
    652   if (tinfo_from->run_terminal)
    653     tinfo_to->run_terminal
    654       = xstrdup (tinfo_from->run_terminal);
    655 
    656   if (tinfo_from->ttystate)
    657     tinfo_to->ttystate
    658       = serial_copy_tty_state (stdin_serial, tinfo_from->ttystate);
    659 
    660   to->terminal_state = from->terminal_state;
    661 }
    662 
    663 /* See terminal.h.  */
    664 
    665 void
    666 swap_terminal_info (inferior *a, inferior *b)
    667 {
    668   terminal_info *info_a = inflow_inferior_data.get (a);
    669   terminal_info *info_b = inflow_inferior_data.get (b);
    670 
    671   inflow_inferior_data.set (a, info_b);
    672   inflow_inferior_data.set (b, info_a);
    673 
    674   std::swap (a->terminal_state, b->terminal_state);
    675 }
    676 
    677 static void
    678 info_terminal_command (const char *arg, int from_tty)
    679 {
    680   target_terminal::info (arg, from_tty);
    681 }
    682 
    683 void
    684 child_terminal_info (struct target_ops *self, const char *args, int from_tty)
    685 {
    686   struct inferior *inf;
    687   struct terminal_info *tinfo;
    688 
    689   if (!gdb_has_a_terminal ())
    690     {
    691       printf_filtered (_("This GDB does not control a terminal.\n"));
    692       return;
    693     }
    694 
    695   if (inferior_ptid == null_ptid)
    696     return;
    697 
    698   inf = current_inferior ();
    699   tinfo = get_inflow_inferior_data (inf);
    700 
    701   printf_filtered (_("Inferior's terminal status "
    702 		     "(currently saved by GDB):\n"));
    703 
    704   /* First the fcntl flags.  */
    705   {
    706     int flags;
    707 
    708     flags = tinfo->tflags;
    709 
    710     printf_filtered ("File descriptor flags = ");
    711 
    712 #ifndef O_ACCMODE
    713 #define O_ACCMODE (O_RDONLY | O_WRONLY | O_RDWR)
    714 #endif
    715     /* (O_ACCMODE) parens are to avoid Ultrix header file bug.  */
    716     switch (flags & (O_ACCMODE))
    717       {
    718       case O_RDONLY:
    719 	printf_filtered ("O_RDONLY");
    720 	break;
    721       case O_WRONLY:
    722 	printf_filtered ("O_WRONLY");
    723 	break;
    724       case O_RDWR:
    725 	printf_filtered ("O_RDWR");
    726 	break;
    727       }
    728     flags &= ~(O_ACCMODE);
    729 
    730 #ifdef O_NONBLOCK
    731     if (flags & O_NONBLOCK)
    732       printf_filtered (" | O_NONBLOCK");
    733     flags &= ~O_NONBLOCK;
    734 #endif
    735 
    736 #if defined (O_NDELAY)
    737     /* If O_NDELAY and O_NONBLOCK are defined to the same thing, we will
    738        print it as O_NONBLOCK, which is good cause that is what POSIX
    739        has, and the flag will already be cleared by the time we get here.  */
    740     if (flags & O_NDELAY)
    741       printf_filtered (" | O_NDELAY");
    742     flags &= ~O_NDELAY;
    743 #endif
    744 
    745     if (flags & O_APPEND)
    746       printf_filtered (" | O_APPEND");
    747     flags &= ~O_APPEND;
    748 
    749 #if defined (O_BINARY)
    750     if (flags & O_BINARY)
    751       printf_filtered (" | O_BINARY");
    752     flags &= ~O_BINARY;
    753 #endif
    754 
    755     if (flags)
    756       printf_filtered (" | 0x%x", flags);
    757     printf_filtered ("\n");
    758   }
    759 
    760 #ifdef HAVE_TERMIOS_H
    761   printf_filtered ("Process group = %d\n", (int) tinfo->process_group);
    762 #endif
    763 
    764   serial_print_tty_state (stdin_serial, tinfo->ttystate, gdb_stdout);
    765 }
    766 
    767 /* NEW_TTY_PREFORK is called before forking a new child process,
    769    so we can record the state of ttys in the child to be formed.
    770    TTYNAME is null if we are to share the terminal with gdb;
    771    or points to a string containing the name of the desired tty.
    772 
    773    NEW_TTY is called in new child processes under Unix, which will
    774    become debugger target processes.  This actually switches to
    775    the terminal specified in the NEW_TTY_PREFORK call.  */
    776 
    777 void
    778 new_tty_prefork (const char *ttyname)
    779 {
    780   /* Save the name for later, for determining whether we and the child
    781      are sharing a tty.  */
    782   inferior_thisrun_terminal = ttyname;
    783 }
    784 
    785 #if !defined(__GO32__) && !defined(_WIN32)
    786 /* If RESULT, assumed to be the return value from a system call, is
    787    negative, print the error message indicated by errno and exit.
    788    MSG should identify the operation that failed.  */
    789 static void
    790 check_syscall (const char *msg, int result)
    791 {
    792   if (result < 0)
    793     {
    794       print_sys_errmsg (msg, errno);
    795       _exit (1);
    796     }
    797 }
    798 #endif
    799 
    800 void
    801 new_tty (void)
    802 {
    803   if (inferior_thisrun_terminal == 0)
    804     return;
    805 #if !defined(__GO32__) && !defined(_WIN32)
    806   int tty;
    807 
    808 #ifdef TIOCNOTTY
    809   /* Disconnect the child process from our controlling terminal.  On some
    810      systems (SVR4 for example), this may cause a SIGTTOU, so temporarily
    811      ignore SIGTTOU.  */
    812   tty = open ("/dev/tty", O_RDWR);
    813   if (tty > 0)
    814     {
    815       scoped_ignore_sigttou ignore_sigttou;
    816 
    817       ioctl (tty, TIOCNOTTY, 0);
    818       close (tty);
    819     }
    820 #endif
    821 
    822   /* Now open the specified new terminal.  */
    823   tty = open (inferior_thisrun_terminal, O_RDWR | O_NOCTTY);
    824   check_syscall (inferior_thisrun_terminal, tty);
    825 
    826   /* Avoid use of dup2; doesn't exist on all systems.  */
    827   if (tty != 0)
    828     {
    829       close (0);
    830       check_syscall ("dup'ing tty into fd 0", dup (tty));
    831     }
    832   if (tty != 1)
    833     {
    834       close (1);
    835       check_syscall ("dup'ing tty into fd 1", dup (tty));
    836     }
    837   if (tty != 2)
    838     {
    839       close (2);
    840       check_syscall ("dup'ing tty into fd 2", dup (tty));
    841     }
    842 
    843 #ifdef TIOCSCTTY
    844   /* Make tty our new controlling terminal.  */
    845   if (ioctl (tty, TIOCSCTTY, 0) == -1)
    846     /* Mention GDB in warning because it will appear in the inferior's
    847        terminal instead of GDB's.  */
    848     warning (_("GDB: Failed to set controlling terminal: %s"),
    849 	     safe_strerror (errno));
    850 #endif
    851 
    852   if (tty > 2)
    853     close (tty);
    854 #endif /* !go32 && !win32 */
    855 }
    856 
    857 /* NEW_TTY_POSTFORK is called after forking a new child process, and
    858    adding it to the inferior table, to store the TTYNAME being used by
    859    the child, or null if it sharing the terminal with gdb.  */
    860 
    861 void
    862 new_tty_postfork (void)
    863 {
    864   /* Save the name for later, for determining whether we and the child
    865      are sharing a tty.  */
    866 
    867   if (inferior_thisrun_terminal)
    868     {
    869       struct inferior *inf = current_inferior ();
    870       struct terminal_info *tinfo = get_inflow_inferior_data (inf);
    871 
    872       tinfo->run_terminal = xstrdup (inferior_thisrun_terminal);
    873     }
    874 
    875   inferior_thisrun_terminal = NULL;
    876 }
    877 
    878 
    879 /* Call set_sigint_trap when you need to pass a signal on to an attached
    881    process when handling SIGINT.  */
    882 
    883 static void
    884 pass_signal (int signo)
    885 {
    886 #ifndef _WIN32
    887   kill (inferior_ptid.pid (), SIGINT);
    888 #endif
    889 }
    890 
    891 static sighandler_t osig;
    892 static int osig_set;
    893 
    894 void
    895 set_sigint_trap (void)
    896 {
    897   struct inferior *inf = current_inferior ();
    898   struct terminal_info *tinfo = get_inflow_inferior_data (inf);
    899 
    900   if (inf->attach_flag || tinfo->run_terminal)
    901     {
    902       osig = signal (SIGINT, pass_signal);
    903       osig_set = 1;
    904     }
    905   else
    906     osig_set = 0;
    907 }
    908 
    909 void
    910 clear_sigint_trap (void)
    911 {
    912   if (osig_set)
    913     {
    914       signal (SIGINT, osig);
    915       osig_set = 0;
    916     }
    917 }
    918 
    919 
    921 /* Create a new session if the inferior will run in a different tty.
    922    A session is UNIX's way of grouping processes that share a controlling
    923    terminal, so a new one is needed if the inferior terminal will be
    924    different from GDB's.
    925 
    926    Returns the session id of the new session, 0 if no session was created
    927    or -1 if an error occurred.  */
    928 pid_t
    929 create_tty_session (void)
    930 {
    931 #ifdef HAVE_SETSID
    932   pid_t ret;
    933 
    934   if (!job_control || inferior_thisrun_terminal == 0)
    935     return 0;
    936 
    937   ret = setsid ();
    938   if (ret == -1)
    939     warning (_("Failed to create new terminal session: setsid: %s"),
    940 	     safe_strerror (errno));
    941 
    942   return ret;
    943 #else
    944   return 0;
    945 #endif /* HAVE_SETSID */
    946 }
    947 
    948 /* Get all the current tty settings (including whether we have a
    949    tty at all!).  We can't do this in _initialize_inflow because
    950    serial_fdopen() won't work until the serial_ops_list is
    951    initialized, but we don't want to do it lazily either, so
    952    that we can guarantee stdin_serial is opened if there is
    953    a terminal.  */
    954 void
    955 initialize_stdin_serial (void)
    956 {
    957   stdin_serial = serial_fdopen (0);
    958 }
    959 
    960 void _initialize_inflow ();
    961 void
    962 _initialize_inflow ()
    963 {
    964   add_info ("terminal", info_terminal_command,
    965 	    _("Print inferior's saved terminal status."));
    966 
    967   /* OK, figure out whether we have job control.  */
    968   have_job_control ();
    969 
    970   gdb::observers::inferior_exit.attach (inflow_inferior_exit);
    971 }
    972