1/* Low level interface to ptrace, for GDB when running under Unix.
2   Copyright 1986, 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995,
3   1996, 1998, 1999, 2000, 2001, 2002, 2003, 2004
4   Free Software Foundation, Inc.
5
6   This file is part of GDB.
7
8   This program is free software; you can redistribute it and/or modify
9   it under the terms of the GNU General Public License as published by
10   the Free Software Foundation; either version 2 of the License, or
11   (at your option) any later version.
12
13   This program is distributed in the hope that it will be useful,
14   but WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16   GNU General Public License for more details.
17
18   You should have received a copy of the GNU General Public License
19   along with this program; if not, write to the Free Software
20   Foundation, Inc., 59 Temple Place - Suite 330,
21   Boston, MA 02111-1307, USA.  */
22
23#include "defs.h"
24#include "frame.h"
25#include "inferior.h"
26#include "command.h"
27#include "serial.h"
28#include "terminal.h"
29#include "target.h"
30#include "gdbthread.h"
31
32#include "gdb_string.h"
33#include <signal.h>
34#include <fcntl.h>
35#ifdef HAVE_SYS_SELECT_H
36#include <sys/select.h>
37#endif
38
39#include "inflow.h"
40
41#ifdef HAVE_SYS_IOCTL_H
42#include <sys/ioctl.h>
43#endif
44
45#ifndef O_NOCTTY
46#define O_NOCTTY 0
47#endif
48
49#if defined (SIGIO) && defined (FASYNC) && defined (FD_SET) && defined (F_SETOWN)
50static void handle_sigio (int);
51#endif
52
53extern void _initialize_inflow (void);
54
55static void pass_signal (int);
56
57static void kill_command (char *, int);
58
59static void terminal_ours_1 (int);
60
61/* Record terminal status separately for debugger and inferior.  */
62
63static struct serial *stdin_serial;
64
65/* TTY state for the inferior.  We save it whenever the inferior stops, and
66   restore it when it resumes.  */
67static serial_ttystate inferior_ttystate;
68
69/* Our own tty state, which we restore every time we need to deal with the
70   terminal.  We only set it once, when GDB first starts.  The settings of
71   flags which readline saves and restores and unimportant.  */
72static serial_ttystate our_ttystate;
73
74/* fcntl flags for us and the inferior.  Saved and restored just like
75   {our,inferior}_ttystate.  */
76static int tflags_inferior;
77static int tflags_ours;
78
79#ifdef PROCESS_GROUP_TYPE
80/* Process group for us and the inferior.  Saved and restored just like
81   {our,inferior}_ttystate.  */
82PROCESS_GROUP_TYPE our_process_group;
83PROCESS_GROUP_TYPE inferior_process_group;
84#endif
85
86/* While the inferior is running, we want SIGINT and SIGQUIT to go to the
87   inferior only.  If we have job control, that takes care of it.  If not,
88   we save our handlers in these two variables and set SIGINT and SIGQUIT
89   to SIG_IGN.  */
90
91static void (*sigint_ours) ();
92static void (*sigquit_ours) ();
93
94/* The name of the tty (from the `tty' command) that we gave to the inferior
95   when it was last started.  */
96
97static char *inferior_thisrun_terminal;
98
99/* Nonzero if our terminal settings are in effect.  Zero if the
100   inferior's settings are in effect.  Ignored if !gdb_has_a_terminal
101   ().  */
102
103int terminal_is_ours;
104
105enum
106  {
107    yes, no, have_not_checked
108  }
109gdb_has_a_terminal_flag = have_not_checked;
110
111/* Does GDB have a terminal (on stdin)?  */
112int
113gdb_has_a_terminal (void)
114{
115  switch (gdb_has_a_terminal_flag)
116    {
117    case yes:
118      return 1;
119    case no:
120      return 0;
121    case have_not_checked:
122      /* Get all the current tty settings (including whether we have a
123         tty at all!).  Can't do this in _initialize_inflow because
124         serial_fdopen() won't work until the serial_ops_list is
125         initialized.  */
126
127#ifdef F_GETFL
128      tflags_ours = fcntl (0, F_GETFL, 0);
129#endif
130
131      gdb_has_a_terminal_flag = no;
132      stdin_serial = serial_fdopen (0);
133      if (stdin_serial != NULL)
134	{
135	  our_ttystate = serial_get_tty_state (stdin_serial);
136
137	  if (our_ttystate != NULL)
138	    {
139	      gdb_has_a_terminal_flag = yes;
140#ifdef HAVE_TERMIOS
141	      our_process_group = tcgetpgrp (0);
142#endif
143#ifdef HAVE_TERMIO
144	      our_process_group = getpgrp ();
145#endif
146#ifdef HAVE_SGTTY
147	      ioctl (0, TIOCGPGRP, &our_process_group);
148#endif
149	    }
150	}
151
152      return gdb_has_a_terminal_flag == yes;
153    default:
154      /* "Can't happen".  */
155      return 0;
156    }
157}
158
159/* Macro for printing errors from ioctl operations */
160
161#define	OOPSY(what)	\
162  if (result == -1)	\
163    fprintf_unfiltered(gdb_stderr, "[%s failed in terminal_inferior: %s]\n", \
164	    what, safe_strerror (errno))
165
166static void terminal_ours_1 (int);
167
168/* Initialize the terminal settings we record for the inferior,
169   before we actually run the inferior.  */
170
171void
172terminal_init_inferior_with_pgrp (int pgrp)
173{
174  if (gdb_has_a_terminal ())
175    {
176      /* We could just as well copy our_ttystate (if we felt like
177         adding a new function serial_copy_tty_state()).  */
178      if (inferior_ttystate)
179	xfree (inferior_ttystate);
180      inferior_ttystate = serial_get_tty_state (stdin_serial);
181
182#ifdef PROCESS_GROUP_TYPE
183      inferior_process_group = pgrp;
184#endif
185
186      /* Make sure that next time we call terminal_inferior (which will be
187         before the program runs, as it needs to be), we install the new
188         process group.  */
189      terminal_is_ours = 1;
190    }
191}
192
193/* Save the terminal settings again.  This is necessary for the TUI
194   when it switches to TUI or non-TUI mode;  curses changes the terminal
195   and gdb must be able to restore it correctly.  */
196
197void
198terminal_save_ours (void)
199{
200  if (gdb_has_a_terminal ())
201    {
202      /* We could just as well copy our_ttystate (if we felt like adding
203         a new function serial_copy_tty_state).  */
204      if (our_ttystate)
205        xfree (our_ttystate);
206      our_ttystate = serial_get_tty_state (stdin_serial);
207    }
208}
209
210void
211terminal_init_inferior (void)
212{
213#ifdef PROCESS_GROUP_TYPE
214  /* This is for Lynx, and should be cleaned up by having Lynx be a separate
215     debugging target with a version of target_terminal_init_inferior which
216     passes in the process group to a generic routine which does all the work
217     (and the non-threaded child_terminal_init_inferior can just pass in
218     inferior_ptid to the same routine).  */
219  /* We assume INFERIOR_PID is also the child's process group.  */
220  terminal_init_inferior_with_pgrp (PIDGET (inferior_ptid));
221#endif /* PROCESS_GROUP_TYPE */
222}
223
224/* Put the inferior's terminal settings into effect.
225   This is preparation for starting or resuming the inferior.  */
226
227void
228terminal_inferior (void)
229{
230  if (gdb_has_a_terminal () && terminal_is_ours
231      && inferior_ttystate != NULL
232      && inferior_thisrun_terminal == 0)
233    {
234      int result;
235
236#ifdef F_GETFL
237      /* Is there a reason this is being done twice?  It happens both
238         places we use F_SETFL, so I'm inclined to think perhaps there
239         is some reason, however perverse.  Perhaps not though...  */
240      result = fcntl (0, F_SETFL, tflags_inferior);
241      result = fcntl (0, F_SETFL, tflags_inferior);
242      OOPSY ("fcntl F_SETFL");
243#endif
244
245      /* Because we were careful to not change in or out of raw mode in
246         terminal_ours, we will not change in our out of raw mode with
247         this call, so we don't flush any input.  */
248      result = serial_set_tty_state (stdin_serial, inferior_ttystate);
249      OOPSY ("setting tty state");
250
251      if (!job_control)
252	{
253	  sigint_ours = (void (*)()) signal (SIGINT, SIG_IGN);
254#ifdef SIGQUIT
255	  sigquit_ours = (void (*)()) signal (SIGQUIT, SIG_IGN);
256#endif
257	}
258
259      /* If attach_flag is set, we don't know whether we are sharing a
260         terminal with the inferior or not.  (attaching a process
261         without a terminal is one case where we do not; attaching a
262         process which we ran from the same shell as GDB via `&' is
263         one case where we do, I think (but perhaps this is not
264         `sharing' in the sense that we need to save and restore tty
265         state)).  I don't know if there is any way to tell whether we
266         are sharing a terminal.  So what we do is to go through all
267         the saving and restoring of the tty state, but ignore errors
268         setting the process group, which will happen if we are not
269         sharing a terminal).  */
270
271      if (job_control)
272	{
273#ifdef HAVE_TERMIOS
274	  result = tcsetpgrp (0, inferior_process_group);
275	  if (!attach_flag)
276	    OOPSY ("tcsetpgrp");
277#endif
278
279#ifdef HAVE_SGTTY
280	  result = ioctl (0, TIOCSPGRP, &inferior_process_group);
281	  if (!attach_flag)
282	    OOPSY ("TIOCSPGRP");
283#endif
284	}
285
286    }
287  terminal_is_ours = 0;
288}
289
290/* Put some of our terminal settings into effect,
291   enough to get proper results from our output,
292   but do not change into or out of RAW mode
293   so that no input is discarded.
294
295   After doing this, either terminal_ours or terminal_inferior
296   should be called to get back to a normal state of affairs.  */
297
298void
299terminal_ours_for_output (void)
300{
301  terminal_ours_1 (1);
302}
303
304/* Put our terminal settings into effect.
305   First record the inferior's terminal settings
306   so they can be restored properly later.  */
307
308void
309terminal_ours (void)
310{
311  terminal_ours_1 (0);
312}
313
314/* output_only is not used, and should not be used unless we introduce
315   separate terminal_is_ours and terminal_is_ours_for_output
316   flags.  */
317
318static void
319terminal_ours_1 (int output_only)
320{
321  /* Checking inferior_thisrun_terminal is necessary so that
322     if GDB is running in the background, it won't block trying
323     to do the ioctl()'s below.  Checking gdb_has_a_terminal
324     avoids attempting all the ioctl's when running in batch.  */
325  if (inferior_thisrun_terminal != 0 || gdb_has_a_terminal () == 0)
326    return;
327
328  if (!terminal_is_ours)
329    {
330#ifdef SIGTTOU
331      /* Ignore this signal since it will happen when we try to set the
332         pgrp.  */
333      void (*osigttou) () = NULL;
334#endif
335      int result;
336
337      terminal_is_ours = 1;
338
339#ifdef SIGTTOU
340      if (job_control)
341	osigttou = (void (*)()) signal (SIGTTOU, SIG_IGN);
342#endif
343
344      if (inferior_ttystate)
345	xfree (inferior_ttystate);
346      inferior_ttystate = serial_get_tty_state (stdin_serial);
347#ifdef HAVE_TERMIOS
348      inferior_process_group = tcgetpgrp (0);
349#endif
350#ifdef HAVE_TERMIO
351      inferior_process_group = getpgrp ();
352#endif
353#ifdef HAVE_SGTTY
354      ioctl (0, TIOCGPGRP, &inferior_process_group);
355#endif
356
357      /* Here we used to set ICANON in our ttystate, but I believe this
358         was an artifact from before when we used readline.  Readline sets
359         the tty state when it needs to.
360         FIXME-maybe: However, query() expects non-raw mode and doesn't
361         use readline.  Maybe query should use readline (on the other hand,
362         this only matters for HAVE_SGTTY, not termio or termios, I think).  */
363
364      /* Set tty state to our_ttystate.  We don't change in our out of raw
365         mode, to avoid flushing input.  We need to do the same thing
366         regardless of output_only, because we don't have separate
367         terminal_is_ours and terminal_is_ours_for_output flags.  It's OK,
368         though, since readline will deal with raw mode when/if it needs to.
369       */
370
371      serial_noflush_set_tty_state (stdin_serial, our_ttystate,
372				    inferior_ttystate);
373
374      if (job_control)
375	{
376#ifdef HAVE_TERMIOS
377	  result = tcsetpgrp (0, our_process_group);
378#if 0
379	  /* This fails on Ultrix with EINVAL if you run the testsuite
380	     in the background with nohup, and then log out.  GDB never
381	     used to check for an error here, so perhaps there are other
382	     such situations as well.  */
383	  if (result == -1)
384	    fprintf_unfiltered (gdb_stderr, "[tcsetpgrp failed in terminal_ours: %s]\n",
385				safe_strerror (errno));
386#endif
387#endif /* termios */
388
389#ifdef HAVE_SGTTY
390	  result = ioctl (0, TIOCSPGRP, &our_process_group);
391#endif
392	}
393
394#ifdef SIGTTOU
395      if (job_control)
396	signal (SIGTTOU, osigttou);
397#endif
398
399      if (!job_control)
400	{
401	  signal (SIGINT, sigint_ours);
402#ifdef SIGQUIT
403	  signal (SIGQUIT, sigquit_ours);
404#endif
405	}
406
407#ifdef F_GETFL
408      tflags_inferior = fcntl (0, F_GETFL, 0);
409
410      /* Is there a reason this is being done twice?  It happens both
411         places we use F_SETFL, so I'm inclined to think perhaps there
412         is some reason, however perverse.  Perhaps not though...  */
413      result = fcntl (0, F_SETFL, tflags_ours);
414      result = fcntl (0, F_SETFL, tflags_ours);
415#endif
416
417      result = result;		/* lint */
418    }
419}
420
421void
422term_info (char *arg, int from_tty)
423{
424  target_terminal_info (arg, from_tty);
425}
426
427void
428child_terminal_info (char *args, int from_tty)
429{
430  if (!gdb_has_a_terminal ())
431    {
432      printf_filtered ("This GDB does not control a terminal.\n");
433      return;
434    }
435
436  printf_filtered ("Inferior's terminal status (currently saved by GDB):\n");
437
438  /* First the fcntl flags.  */
439  {
440    int flags;
441
442    flags = tflags_inferior;
443
444    printf_filtered ("File descriptor flags = ");
445
446#ifndef O_ACCMODE
447#define O_ACCMODE (O_RDONLY | O_WRONLY | O_RDWR)
448#endif
449    /* (O_ACCMODE) parens are to avoid Ultrix header file bug */
450    switch (flags & (O_ACCMODE))
451      {
452      case O_RDONLY:
453	printf_filtered ("O_RDONLY");
454	break;
455      case O_WRONLY:
456	printf_filtered ("O_WRONLY");
457	break;
458      case O_RDWR:
459	printf_filtered ("O_RDWR");
460	break;
461      }
462    flags &= ~(O_ACCMODE);
463
464#ifdef O_NONBLOCK
465    if (flags & O_NONBLOCK)
466      printf_filtered (" | O_NONBLOCK");
467    flags &= ~O_NONBLOCK;
468#endif
469
470#if defined (O_NDELAY)
471    /* If O_NDELAY and O_NONBLOCK are defined to the same thing, we will
472       print it as O_NONBLOCK, which is good cause that is what POSIX
473       has, and the flag will already be cleared by the time we get here.  */
474    if (flags & O_NDELAY)
475      printf_filtered (" | O_NDELAY");
476    flags &= ~O_NDELAY;
477#endif
478
479    if (flags & O_APPEND)
480      printf_filtered (" | O_APPEND");
481    flags &= ~O_APPEND;
482
483#if defined (O_BINARY)
484    if (flags & O_BINARY)
485      printf_filtered (" | O_BINARY");
486    flags &= ~O_BINARY;
487#endif
488
489    if (flags)
490      printf_filtered (" | 0x%x", flags);
491    printf_filtered ("\n");
492  }
493
494#ifdef PROCESS_GROUP_TYPE
495  printf_filtered ("Process group = %d\n",
496		   (int) inferior_process_group);
497#endif
498
499  serial_print_tty_state (stdin_serial, inferior_ttystate, gdb_stdout);
500}
501
502/* NEW_TTY_PREFORK is called before forking a new child process,
503   so we can record the state of ttys in the child to be formed.
504   TTYNAME is null if we are to share the terminal with gdb;
505   or points to a string containing the name of the desired tty.
506
507   NEW_TTY is called in new child processes under Unix, which will
508   become debugger target processes.  This actually switches to
509   the terminal specified in the NEW_TTY_PREFORK call.  */
510
511void
512new_tty_prefork (char *ttyname)
513{
514  /* Save the name for later, for determining whether we and the child
515     are sharing a tty.  */
516  inferior_thisrun_terminal = ttyname;
517}
518
519void
520new_tty (void)
521{
522  int tty;
523
524  if (inferior_thisrun_terminal == 0)
525    return;
526#if !defined(__GO32__) && !defined(_WIN32)
527#ifdef TIOCNOTTY
528  /* Disconnect the child process from our controlling terminal.  On some
529     systems (SVR4 for example), this may cause a SIGTTOU, so temporarily
530     ignore SIGTTOU. */
531  tty = open ("/dev/tty", O_RDWR);
532  if (tty > 0)
533    {
534      void (*osigttou) ();
535
536      osigttou = (void (*)()) signal (SIGTTOU, SIG_IGN);
537      ioctl (tty, TIOCNOTTY, 0);
538      close (tty);
539      signal (SIGTTOU, osigttou);
540    }
541#endif
542
543  /* Now open the specified new terminal.  */
544  tty = open (inferior_thisrun_terminal, O_RDWR | O_NOCTTY);
545  if (tty == -1)
546    {
547      print_sys_errmsg (inferior_thisrun_terminal, errno);
548      _exit (1);
549    }
550
551  /* Avoid use of dup2; doesn't exist on all systems.  */
552  if (tty != 0)
553    {
554      close (0);
555      dup (tty);
556    }
557  if (tty != 1)
558    {
559      close (1);
560      dup (tty);
561    }
562  if (tty != 2)
563    {
564      close (2);
565      dup (tty);
566    }
567  if (tty > 2)
568    close (tty);
569#endif /* !go32 && !win32 */
570}
571
572/* Kill the inferior process.  Make us have no inferior.  */
573
574static void
575kill_command (char *arg, int from_tty)
576{
577  /* FIXME:  This should not really be inferior_ptid (or target_has_execution).
578     It should be a distinct flag that indicates that a target is active, cuz
579     some targets don't have processes! */
580
581  if (ptid_equal (inferior_ptid, null_ptid))
582    error ("The program is not being run.");
583  if (!query ("Kill the program being debugged? "))
584    error ("Not confirmed.");
585  target_kill ();
586
587  init_thread_list ();		/* Destroy thread info */
588
589  /* Killing off the inferior can leave us with a core file.  If so,
590     print the state we are left in.  */
591  if (target_has_stack)
592    {
593      printf_filtered ("In %s,\n", target_longname);
594      if (deprecated_selected_frame == NULL)
595	fputs_filtered ("No selected stack frame.\n", gdb_stdout);
596      else
597	print_stack_frame (get_selected_frame (), 1, SRC_AND_LOC);
598    }
599  bfd_cache_close_all ();
600}
601
602/* Call set_sigint_trap when you need to pass a signal on to an attached
603   process when handling SIGINT */
604
605static void
606pass_signal (int signo)
607{
608#ifndef _WIN32
609  kill (PIDGET (inferior_ptid), SIGINT);
610#endif
611}
612
613static void (*osig) ();
614
615void
616set_sigint_trap (void)
617{
618  if (attach_flag || inferior_thisrun_terminal)
619    {
620      osig = (void (*)()) signal (SIGINT, pass_signal);
621    }
622}
623
624void
625clear_sigint_trap (void)
626{
627  if (attach_flag || inferior_thisrun_terminal)
628    {
629      signal (SIGINT, osig);
630    }
631}
632
633#if defined (SIGIO) && defined (FASYNC) && defined (FD_SET) && defined (F_SETOWN)
634static void (*old_sigio) ();
635
636static void
637handle_sigio (int signo)
638{
639  int numfds;
640  fd_set readfds;
641
642  signal (SIGIO, handle_sigio);
643
644  FD_ZERO (&readfds);
645  FD_SET (target_activity_fd, &readfds);
646  numfds = select (target_activity_fd + 1, &readfds, NULL, NULL, NULL);
647  if (numfds >= 0 && FD_ISSET (target_activity_fd, &readfds))
648    {
649#ifndef _WIN32
650      if ((*target_activity_function) ())
651	kill (PIDGET (inferior_ptid), SIGINT);
652#endif
653    }
654}
655
656static int old_fcntl_flags;
657
658void
659set_sigio_trap (void)
660{
661  if (target_activity_function)
662    {
663      old_sigio = (void (*)()) signal (SIGIO, handle_sigio);
664      fcntl (target_activity_fd, F_SETOWN, getpid ());
665      old_fcntl_flags = fcntl (target_activity_fd, F_GETFL, 0);
666      fcntl (target_activity_fd, F_SETFL, old_fcntl_flags | FASYNC);
667    }
668}
669
670void
671clear_sigio_trap (void)
672{
673  if (target_activity_function)
674    {
675      signal (SIGIO, old_sigio);
676      fcntl (target_activity_fd, F_SETFL, old_fcntl_flags);
677    }
678}
679#else /* No SIGIO.  */
680void
681set_sigio_trap (void)
682{
683  if (target_activity_function)
684    internal_error (__FILE__, __LINE__, "failed internal consistency check");
685}
686
687void
688clear_sigio_trap (void)
689{
690  if (target_activity_function)
691    internal_error (__FILE__, __LINE__, "failed internal consistency check");
692}
693#endif /* No SIGIO.  */
694
695
696/* This is here because this is where we figure out whether we (probably)
697   have job control.  Just using job_control only does part of it because
698   setpgid or setpgrp might not exist on a system without job control.
699   It might be considered misplaced (on the other hand, process groups and
700   job control are closely related to ttys).
701
702   For a more clean implementation, in libiberty, put a setpgid which merely
703   calls setpgrp and a setpgrp which does nothing (any system with job control
704   will have one or the other).  */
705int
706gdb_setpgid (void)
707{
708  int retval = 0;
709
710  if (job_control)
711    {
712#if defined (HAVE_TERMIOS) || defined (TIOCGPGRP)
713#ifdef HAVE_SETPGID
714      /* The call setpgid (0, 0) is supposed to work and mean the same
715         thing as this, but on Ultrix 4.2A it fails with EPERM (and
716         setpgid (getpid (), getpid ()) succeeds).  */
717      retval = setpgid (getpid (), getpid ());
718#else
719#ifdef HAVE_SETPGRP
720#ifdef SETPGRP_VOID
721      retval = setpgrp ();
722#else
723      retval = setpgrp (getpid (), getpid ());
724#endif
725#endif /* HAVE_SETPGRP */
726#endif /* HAVE_SETPGID */
727#endif /* defined (HAVE_TERMIOS) || defined (TIOCGPGRP) */
728    }
729
730  return retval;
731}
732
733void
734_initialize_inflow (void)
735{
736  add_info ("terminal", term_info,
737	    "Print inferior's saved terminal status.");
738
739  add_com ("kill", class_run, kill_command,
740	   "Kill execution of program being debugged.");
741
742  inferior_ptid = null_ptid;
743
744  terminal_is_ours = 1;
745
746  /* OK, figure out whether we have job control.  If neither termios nor
747     sgtty (i.e. termio or go32), leave job_control 0.  */
748
749#if defined (HAVE_TERMIOS)
750  /* Do all systems with termios have the POSIX way of identifying job
751     control?  I hope so.  */
752#ifdef _POSIX_JOB_CONTROL
753  job_control = 1;
754#else
755#ifdef _SC_JOB_CONTROL
756  job_control = sysconf (_SC_JOB_CONTROL);
757#else
758  job_control = 0;		/* have to assume the worst */
759#endif /* _SC_JOB_CONTROL */
760#endif /* _POSIX_JOB_CONTROL */
761#endif /* HAVE_TERMIOS */
762
763#ifdef HAVE_SGTTY
764#ifdef TIOCGPGRP
765  job_control = 1;
766#else
767  job_control = 0;
768#endif /* TIOCGPGRP */
769#endif /* sgtty */
770}
771