* breakpoint.c: Move defaults of watchpoint related macros into
[platform/upstream/binutils.git] / gdb / procfs.c
1 /* Machine independent support for SVR4 /proc (process file system) for GDB.
2    Copyright 1991, 1992, 1993, 1994, 1995 Free Software Foundation, Inc.
3    Written by Fred Fish at Cygnus Support.
4
5 This file is part of GDB.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
20
21
22 /*                      N  O  T  E  S
23
24 For information on the details of using /proc consult section proc(4)
25 in the UNIX System V Release 4 System Administrator's Reference Manual.
26
27 The general register and floating point register sets are manipulated by
28 separate ioctl's.  This file makes the assumption that if FP0_REGNUM is
29 defined, then support for the floating point register set is desired,
30 regardless of whether or not the actual target has floating point hardware.
31
32  */
33
34
35 #include "defs.h"
36
37 #include <sys/types.h>
38 #include <time.h>
39 #include <sys/fault.h>
40 #include <sys/syscall.h>
41 #include <sys/procfs.h>
42 #include <fcntl.h>
43 #include <errno.h>
44 #include <string.h>
45 #include <stropts.h>
46 #include <poll.h>
47 #include <unistd.h>
48 #include <sys/stat.h>
49
50 #include "inferior.h"
51 #include "target.h"
52 #include "command.h"
53 #include "gdbcore.h"
54 #include "thread.h"
55
56 #define MAX_SYSCALLS    256     /* Maximum number of syscalls for table */
57
58 #ifndef PROC_NAME_FMT
59 #define PROC_NAME_FMT "/proc/%05d"
60 #endif
61
62 extern struct target_ops procfs_ops;            /* Forward declaration */
63
64 #if 1   /* FIXME: Gross and ugly hack to resolve coredep.c global */
65 CORE_ADDR kernel_u_addr;
66 #endif
67
68 #ifdef BROKEN_SIGINFO_H         /* Workaround broken SGS <sys/siginfo.h> */
69 #undef si_pid
70 #define si_pid _data._proc.pid
71 #undef si_uid
72 #define si_uid _data._proc._pdata._kill.uid
73 #endif /* BROKEN_SIGINFO_H */
74
75 /*  All access to the inferior, either one started by gdb or one that has
76     been attached to, is controlled by an instance of a procinfo structure,
77     defined below.  Since gdb currently only handles one inferior at a time,
78     the procinfo structure for the inferior is statically allocated and
79     only one exists at any given time.  There is a separate procinfo
80     structure for use by the "info proc" command, so that we can print
81     useful information about any random process without interfering with
82     the inferior's procinfo information. */
83
84 struct procinfo {
85   struct procinfo *next;
86   int pid;                      /* Process ID of inferior */
87   int fd;                       /* File descriptor for /proc entry */
88   char *pathname;               /* Pathname to /proc entry */
89   int had_event;                /* poll/select says something happened */
90   int was_stopped;              /* Nonzero if was stopped prior to attach */
91   int nopass_next_sigstop;      /* Don't pass a sigstop on next resume */
92   prrun_t prrun;                /* Control state when it is run */
93   prstatus_t prstatus;          /* Current process status info */
94   gregset_t gregset;            /* General register set */
95   fpregset_t fpregset;          /* Floating point register set */
96   fltset_t fltset;              /* Current traced hardware fault set */
97   sigset_t trace;               /* Current traced signal set */
98   sysset_t exitset;             /* Current traced system call exit set */
99   sysset_t entryset;            /* Current traced system call entry set */
100   fltset_t saved_fltset;        /* Saved traced hardware fault set */
101   sigset_t saved_trace;         /* Saved traced signal set */
102   sigset_t saved_sighold;       /* Saved held signal set */
103   sysset_t saved_exitset;       /* Saved traced system call exit set */
104   sysset_t saved_entryset;      /* Saved traced system call entry set */
105 };
106
107 /* List of inferior process information */
108 static struct procinfo *procinfo_list = NULL;
109
110 static struct pollfd *poll_list; /* pollfds used for waiting on /proc */
111
112 static int num_poll_list = 0;   /* Number of entries in poll_list */
113
114 static int last_resume_pid = -1; /* Last pid used with procfs_resume */
115
116 /*  Much of the information used in the /proc interface, particularly for
117     printing status information, is kept as tables of structures of the
118     following form.  These tables can be used to map numeric values to
119     their symbolic names and to a string that describes their specific use. */
120
121 struct trans {
122   int value;                    /* The numeric value */
123   char *name;                   /* The equivalent symbolic value */
124   char *desc;                   /* Short description of value */
125 };
126
127 /*  Translate bits in the pr_flags member of the prstatus structure, into the
128     names and desc information. */
129
130 static struct trans pr_flag_table[] =
131 {
132 #if defined (PR_STOPPED)
133   { PR_STOPPED, "PR_STOPPED", "Process is stopped" },
134 #endif
135 #if defined (PR_ISTOP)
136   { PR_ISTOP, "PR_ISTOP", "Stopped on an event of interest" },
137 #endif
138 #if defined (PR_DSTOP)
139   { PR_DSTOP, "PR_DSTOP", "A stop directive is in effect" },
140 #endif
141 #if defined (PR_ASLEEP)
142   { PR_ASLEEP, "PR_ASLEEP", "Sleeping in an interruptible system call" },
143 #endif
144 #if defined (PR_FORK)
145   { PR_FORK, "PR_FORK", "Inherit-on-fork is in effect" },
146 #endif
147 #if defined (PR_RLC)
148   { PR_RLC, "PR_RLC", "Run-on-last-close is in effect" },
149 #endif
150 #if defined (PR_PTRACE)
151   { PR_PTRACE, "PR_PTRACE", "Process is being controlled by ptrace" },
152 #endif
153 #if defined (PR_PCINVAL)
154   { PR_PCINVAL, "PR_PCINVAL", "PC refers to an invalid virtual address" },
155 #endif
156 #if defined (PR_ISSYS)
157   { PR_ISSYS, "PR_ISSYS", "Is a system process" },
158 #endif
159 #if defined (PR_STEP)
160   { PR_STEP, "PR_STEP", "Process has single step pending" },
161 #endif
162 #if defined (PR_KLC)
163   { PR_KLC, "PR_KLC", "Kill-on-last-close is in effect" },
164 #endif
165 #if defined (PR_ASYNC)
166   { PR_ASYNC, "PR_ASYNC", "Asynchronous stop is in effect" },
167 #endif
168 #if defined (PR_PCOMPAT)
169   { PR_PCOMPAT, "PR_PCOMPAT", "Ptrace compatibility mode in effect" },
170 #endif
171   { 0, NULL, NULL }
172 };
173
174 /*  Translate values in the pr_why field of the prstatus struct. */
175
176 static struct trans pr_why_table[] =
177 {
178 #if defined (PR_REQUESTED)
179   { PR_REQUESTED, "PR_REQUESTED", "Directed to stop via PIOCSTOP/PIOCWSTOP" },
180 #endif
181 #if defined (PR_SIGNALLED)
182   { PR_SIGNALLED, "PR_SIGNALLED", "Receipt of a traced signal" },
183 #endif
184 #if defined (PR_FAULTED)
185   { PR_FAULTED, "PR_FAULTED", "Incurred a traced hardware fault" },
186 #endif
187 #if defined (PR_SYSENTRY)
188   { PR_SYSENTRY, "PR_SYSENTRY", "Entry to a traced system call" },
189 #endif
190 #if defined (PR_SYSEXIT)
191   { PR_SYSEXIT, "PR_SYSEXIT", "Exit from a traced system call" },
192 #endif
193 #if defined (PR_JOBCONTROL)
194   { PR_JOBCONTROL, "PR_JOBCONTROL", "Default job control stop signal action" },
195 #endif
196 #if defined (PR_SUSPENDED)
197   { PR_SUSPENDED, "PR_SUSPENDED", "Process suspended" },
198 #endif
199   { 0, NULL, NULL }
200 };
201
202 /*  Hardware fault translation table. */
203
204 static struct trans faults_table[] =
205 {
206 #if defined (FLTILL)
207   { FLTILL, "FLTILL", "Illegal instruction" },
208 #endif
209 #if defined (FLTPRIV)
210   { FLTPRIV, "FLTPRIV", "Privileged instruction" },
211 #endif
212 #if defined (FLTBPT)
213   { FLTBPT, "FLTBPT", "Breakpoint trap" },
214 #endif
215 #if defined (FLTTRACE)
216   { FLTTRACE, "FLTTRACE", "Trace trap" },
217 #endif
218 #if defined (FLTACCESS)
219   { FLTACCESS, "FLTACCESS", "Memory access fault" },
220 #endif
221 #if defined (FLTBOUNDS)
222   { FLTBOUNDS, "FLTBOUNDS", "Memory bounds violation" },
223 #endif
224 #if defined (FLTIOVF)
225   { FLTIOVF, "FLTIOVF", "Integer overflow" },
226 #endif
227 #if defined (FLTIZDIV)
228   { FLTIZDIV, "FLTIZDIV", "Integer zero divide" },
229 #endif
230 #if defined (FLTFPE)
231   { FLTFPE, "FLTFPE", "Floating-point exception" },
232 #endif
233 #if defined (FLTSTACK)
234   { FLTSTACK, "FLTSTACK", "Unrecoverable stack fault" },
235 #endif
236 #if defined (FLTPAGE)
237   { FLTPAGE, "FLTPAGE", "Recoverable page fault" },
238 #endif
239   { 0, NULL, NULL }
240 };
241
242 /* Translation table for signal generation information.  See UNIX System
243    V Release 4 Programmer's Reference Manual, siginfo(5).  */
244
245 static struct sigcode {
246   int signo;
247   int code;
248   char *codename;
249   char *desc;
250 } siginfo_table[] = {
251 #if defined (SIGILL) && defined (ILL_ILLOPC)
252   { SIGILL, ILL_ILLOPC, "ILL_ILLOPC", "Illegal opcode" },
253 #endif
254 #if defined (SIGILL) && defined (ILL_ILLOPN)
255   { SIGILL, ILL_ILLOPN, "ILL_ILLOPN", "Illegal operand", },
256 #endif
257 #if defined (SIGILL) && defined (ILL_ILLADR)
258   { SIGILL, ILL_ILLADR, "ILL_ILLADR", "Illegal addressing mode" },
259 #endif
260 #if defined (SIGILL) && defined (ILL_ILLTRP)
261   { SIGILL, ILL_ILLTRP, "ILL_ILLTRP", "Illegal trap" },
262 #endif
263 #if defined (SIGILL) && defined (ILL_PRVOPC)
264   { SIGILL, ILL_PRVOPC, "ILL_PRVOPC", "Privileged opcode" },
265 #endif
266 #if defined (SIGILL) && defined (ILL_PRVREG)
267   { SIGILL, ILL_PRVREG, "ILL_PRVREG", "Privileged register" },
268 #endif
269 #if defined (SIGILL) && defined (ILL_COPROC)
270   { SIGILL, ILL_COPROC, "ILL_COPROC", "Coprocessor error" },
271 #endif
272 #if defined (SIGILL) && defined (ILL_BADSTK)
273   { SIGILL, ILL_BADSTK, "ILL_BADSTK", "Internal stack error" },
274 #endif
275 #if defined (SIGFPE) && defined (FPE_INTDIV)
276   { SIGFPE, FPE_INTDIV, "FPE_INTDIV", "Integer divide by zero" },
277 #endif
278 #if defined (SIGFPE) && defined (FPE_INTOVF)
279   { SIGFPE, FPE_INTOVF, "FPE_INTOVF", "Integer overflow" },
280 #endif
281 #if defined (SIGFPE) && defined (FPE_FLTDIV)
282   { SIGFPE, FPE_FLTDIV, "FPE_FLTDIV", "Floating point divide by zero" },
283 #endif
284 #if defined (SIGFPE) && defined (FPE_FLTOVF)
285   { SIGFPE, FPE_FLTOVF, "FPE_FLTOVF", "Floating point overflow" },
286 #endif
287 #if defined (SIGFPE) && defined (FPE_FLTUND)
288   { SIGFPE, FPE_FLTUND, "FPE_FLTUND", "Floating point underflow" },
289 #endif
290 #if defined (SIGFPE) && defined (FPE_FLTRES)
291   { SIGFPE, FPE_FLTRES, "FPE_FLTRES", "Floating point inexact result" },
292 #endif
293 #if defined (SIGFPE) && defined (FPE_FLTINV)
294   { SIGFPE, FPE_FLTINV, "FPE_FLTINV", "Invalid floating point operation" },
295 #endif
296 #if defined (SIGFPE) && defined (FPE_FLTSUB)
297   { SIGFPE, FPE_FLTSUB, "FPE_FLTSUB", "Subscript out of range" },
298 #endif
299 #if defined (SIGSEGV) && defined (SEGV_MAPERR)
300   { SIGSEGV, SEGV_MAPERR, "SEGV_MAPERR", "Address not mapped to object" },
301 #endif
302 #if defined (SIGSEGV) && defined (SEGV_ACCERR)
303   { SIGSEGV, SEGV_ACCERR, "SEGV_ACCERR", "Invalid permissions for object" },
304 #endif
305 #if defined (SIGBUS) && defined (BUS_ADRALN)
306   { SIGBUS, BUS_ADRALN, "BUS_ADRALN", "Invalid address alignment" },
307 #endif
308 #if defined (SIGBUS) && defined (BUS_ADRERR)
309   { SIGBUS, BUS_ADRERR, "BUS_ADRERR", "Non-existent physical address" },
310 #endif
311 #if defined (SIGBUS) && defined (BUS_OBJERR)
312   { SIGBUS, BUS_OBJERR, "BUS_OBJERR", "Object specific hardware error" },
313 #endif
314 #if defined (SIGTRAP) && defined (TRAP_BRKPT)
315   { SIGTRAP, TRAP_BRKPT, "TRAP_BRKPT", "Process breakpoint" },
316 #endif
317 #if defined (SIGTRAP) && defined (TRAP_TRACE)
318   { SIGTRAP, TRAP_TRACE, "TRAP_TRACE", "Process trace trap" },
319 #endif
320 #if defined (SIGCLD) && defined (CLD_EXITED)
321   { SIGCLD, CLD_EXITED, "CLD_EXITED", "Child has exited" },
322 #endif
323 #if defined (SIGCLD) && defined (CLD_KILLED)
324   { SIGCLD, CLD_KILLED, "CLD_KILLED", "Child was killed" },
325 #endif
326 #if defined (SIGCLD) && defined (CLD_DUMPED)
327   { SIGCLD, CLD_DUMPED, "CLD_DUMPED", "Child has terminated abnormally" },
328 #endif
329 #if defined (SIGCLD) && defined (CLD_TRAPPED)
330   { SIGCLD, CLD_TRAPPED, "CLD_TRAPPED", "Traced child has trapped" },
331 #endif
332 #if defined (SIGCLD) && defined (CLD_STOPPED)
333   { SIGCLD, CLD_STOPPED, "CLD_STOPPED", "Child has stopped" },
334 #endif
335 #if defined (SIGCLD) && defined (CLD_CONTINUED)
336   { SIGCLD, CLD_CONTINUED, "CLD_CONTINUED", "Stopped child had continued" },
337 #endif
338 #if defined (SIGPOLL) && defined (POLL_IN)
339   { SIGPOLL, POLL_IN, "POLL_IN", "Input input available" },
340 #endif
341 #if defined (SIGPOLL) && defined (POLL_OUT)
342   { SIGPOLL, POLL_OUT, "POLL_OUT", "Output buffers available" },
343 #endif
344 #if defined (SIGPOLL) && defined (POLL_MSG)
345   { SIGPOLL, POLL_MSG, "POLL_MSG", "Input message available" },
346 #endif
347 #if defined (SIGPOLL) && defined (POLL_ERR)
348   { SIGPOLL, POLL_ERR, "POLL_ERR", "I/O error" },
349 #endif
350 #if defined (SIGPOLL) && defined (POLL_PRI)
351   { SIGPOLL, POLL_PRI, "POLL_PRI", "High priority input available" },
352 #endif
353 #if defined (SIGPOLL) && defined (POLL_HUP)
354   { SIGPOLL, POLL_HUP, "POLL_HUP", "Device disconnected" },
355 #endif
356   { 0, 0, NULL, NULL }
357 };
358
359 static char *syscall_table[MAX_SYSCALLS];
360
361 /* Prototypes for local functions */
362
363 static void set_proc_siginfo PARAMS ((struct procinfo *, int));
364
365 static void init_syscall_table PARAMS ((void));
366
367 static char *syscallname PARAMS ((int));
368
369 static char *signalname PARAMS ((int));
370
371 static char *errnoname PARAMS ((int));
372
373 static int proc_address_to_fd PARAMS ((struct procinfo *, CORE_ADDR, int));
374
375 static int open_proc_file PARAMS ((int, struct procinfo *, int));
376
377 static void close_proc_file PARAMS ((struct procinfo *));
378
379 static void unconditionally_kill_inferior PARAMS ((struct procinfo *));
380
381 static NORETURN void proc_init_failed PARAMS ((struct procinfo *, char *)) ATTR_NORETURN;
382
383 static void info_proc PARAMS ((char *, int));
384
385 static void info_proc_flags PARAMS ((struct procinfo *, int));
386
387 static void info_proc_stop PARAMS ((struct procinfo *, int));
388
389 static void info_proc_siginfo PARAMS ((struct procinfo *, int));
390
391 static void info_proc_syscalls PARAMS ((struct procinfo *, int));
392
393 static void info_proc_mappings PARAMS ((struct procinfo *, int));
394
395 static void info_proc_signals PARAMS ((struct procinfo *, int));
396
397 static void info_proc_faults PARAMS ((struct procinfo *, int));
398
399 static char *mappingflags PARAMS ((long));
400
401 static char *lookupname PARAMS ((struct trans *, unsigned int, char *));
402
403 static char *lookupdesc PARAMS ((struct trans *, unsigned int));
404
405 static int do_attach PARAMS ((int pid));
406
407 static void do_detach PARAMS ((int siggnal));
408
409 static void procfs_create_inferior PARAMS ((char *, char *, char **));
410
411 static void procfs_notice_signals PARAMS ((int pid));
412
413 static struct procinfo *find_procinfo PARAMS ((pid_t pid, int okfail));
414
415 /* External function prototypes that can't be easily included in any
416    header file because the args are typedefs in system include files. */
417
418 extern void supply_gregset PARAMS ((gregset_t *));
419
420 extern void fill_gregset PARAMS ((gregset_t *, int));
421
422 extern void supply_fpregset PARAMS ((fpregset_t *));
423
424 extern void fill_fpregset PARAMS ((fpregset_t *, int));
425
426 /*
427
428 LOCAL FUNCTION
429
430         find_procinfo -- convert a process id to a struct procinfo
431
432 SYNOPSIS
433
434         static struct procinfo * find_procinfo (pid_t pid, int okfail);
435
436 DESCRIPTION
437         
438         Given a process id, look it up in the procinfo chain.  Returns
439         a struct procinfo *.  If can't find pid, then call error(),
440         unless okfail is set, in which case, return NULL;
441  */
442
443 static struct procinfo *
444 find_procinfo (pid, okfail)
445      pid_t pid;
446      int okfail;
447 {
448   struct procinfo *procinfo;
449
450   for (procinfo = procinfo_list; procinfo; procinfo = procinfo->next)
451     if (procinfo->pid == pid)
452       return procinfo;
453
454   if (okfail)
455     return NULL;
456
457   error ("procfs (find_procinfo):  Couldn't locate pid %d", pid);
458 }
459
460 /*
461
462 LOCAL MACRO
463
464         current_procinfo -- convert inferior_pid to a struct procinfo
465
466 SYNOPSIS
467
468         static struct procinfo * current_procinfo;
469
470 DESCRIPTION
471         
472         Looks up inferior_pid in the procinfo chain.  Always returns a
473         struct procinfo *.  If process can't be found, we error() out.
474  */
475
476 #define current_procinfo find_procinfo (inferior_pid, 0)
477
478 /*
479
480 LOCAL FUNCTION
481
482         add_fd -- Add the fd to the poll/select list
483
484 SYNOPSIS
485
486         static void add_fd (struct procinfo *);
487
488 DESCRIPTION
489         
490         Add the fd of the supplied procinfo to the list of fds used for
491         poll/select operations.
492  */
493
494 static void
495 add_fd (pi)
496      struct procinfo *pi;
497 {
498   if (num_poll_list <= 0)
499     poll_list = (struct pollfd *) xmalloc (sizeof (struct pollfd));
500   else
501     poll_list = (struct pollfd *) xrealloc (poll_list,
502                                             (num_poll_list + 1)
503                                             * sizeof (struct pollfd));
504   poll_list[num_poll_list].fd = pi->fd;
505   poll_list[num_poll_list].events = POLLPRI;
506
507   num_poll_list++;
508 }
509
510 static void
511 remove_fd (pi)
512      struct procinfo *pi;
513 {
514   int i;
515
516   for (i = 0; i < num_poll_list; i++)
517     {
518       if (poll_list[i].fd == pi->fd)
519         {
520           if (i != num_poll_list - 1)
521             memcpy (poll_list, poll_list + i + 1,
522                     (num_poll_list - i - 1) * sizeof (struct pollfd));
523
524           num_poll_list--;
525
526           if (num_poll_list == 0)
527             free (poll_list);
528           else
529             poll_list = (struct pollfd *) xrealloc (poll_list,
530                                                     num_poll_list
531                                                     * sizeof (struct pollfd));
532           return;
533         }
534     }
535 }
536
537 #define LOSING_POLL unixware_sux
538
539 static struct procinfo *
540 wait_fd ()
541 {
542   struct procinfo *pi;
543   int num_fds;
544   int i;
545
546   set_sigint_trap ();   /* Causes SIGINT to be passed on to the
547                            attached process. */
548   set_sigio_trap ();
549
550 #ifndef LOSING_POLL
551   num_fds = poll (poll_list, num_poll_list, -1);
552 #else
553   pi = current_procinfo;
554
555   while (ioctl (pi->fd, PIOCWSTOP, &pi->prstatus) < 0)
556     {
557       if (errno == ENOENT)
558         {
559           /* Process exited.  */
560           pi->prstatus.pr_flags = 0;
561           break;
562         }
563       else if (errno != EINTR)
564         {
565           print_sys_errmsg (pi->pathname, errno);
566           error ("PIOCWSTOP failed");
567         }
568     }
569   pi->had_event = 1;
570 #endif  
571   
572   clear_sigint_trap ();
573   clear_sigio_trap ();
574
575 #ifndef LOSING_POLL
576
577   if (num_fds <= 0)
578     {
579       print_sys_errmsg ("poll failed\n", errno);
580       error ("Poll failed, returned %d", num_fds);
581     }
582
583   for (i = 0; i < num_poll_list && num_fds > 0; i++)
584     {
585       if ((poll_list[i].revents & (POLLPRI|POLLERR|POLLHUP|POLLNVAL)) == 0)
586         continue;
587       for (pi = procinfo_list; pi; pi = pi->next)
588         {
589           if (poll_list[i].fd == pi->fd)
590             {
591               if (ioctl (pi->fd, PIOCSTATUS, &pi->prstatus) < 0)
592                 {
593                   print_sys_errmsg (pi->pathname, errno);
594                   error ("PIOCSTATUS failed");
595                 }
596               num_fds--;
597               pi->had_event = 1;
598               break;
599             }
600         }
601       if (!pi)
602         error ("procfs_wait: Couldn't find procinfo for fd %d\n",
603                poll_list[i].fd);
604     }
605 #endif /* LOSING_POLL */
606
607   return pi;
608 }
609
610 /*
611
612 LOCAL FUNCTION
613
614         lookupdesc -- translate a value to a summary desc string
615
616 SYNOPSIS
617
618         static char *lookupdesc (struct trans *transp, unsigned int val);
619
620 DESCRIPTION
621         
622         Given a pointer to a translation table and a value to be translated,
623         lookup the desc string and return it.
624  */
625
626 static char *
627 lookupdesc (transp, val)
628      struct trans *transp;
629      unsigned int val;
630 {
631   char *desc;
632   
633   for (desc = NULL; transp -> name != NULL; transp++)
634     {
635       if (transp -> value == val)
636         {
637           desc = transp -> desc;
638           break;
639         }
640     }
641
642   /* Didn't find a translation for the specified value, set a default one. */
643
644   if (desc == NULL)
645     {
646       desc = "Unknown";
647     }
648   return (desc);
649 }
650
651 /*
652
653 LOCAL FUNCTION
654
655         lookupname -- translate a value to symbolic name
656
657 SYNOPSIS
658
659         static char *lookupname (struct trans *transp, unsigned int val,
660                                  char *prefix);
661
662 DESCRIPTION
663         
664         Given a pointer to a translation table, a value to be translated,
665         and a default prefix to return if the value can't be translated,
666         match the value with one of the translation table entries and
667         return a pointer to the symbolic name.
668
669         If no match is found it just returns the value as a printable string,
670         with the given prefix.  The previous such value, if any, is freed
671         at this time.
672  */
673
674 static char *
675 lookupname (transp, val, prefix)
676      struct trans *transp;
677      unsigned int val;
678      char *prefix;
679 {
680   static char *locbuf;
681   char *name;
682   
683   for (name = NULL; transp -> name != NULL; transp++)
684     {
685       if (transp -> value == val)
686         {
687           name = transp -> name;
688           break;
689         }
690     }
691
692   /* Didn't find a translation for the specified value, build a default
693      one using the specified prefix and return it.  The lifetime of
694      the value is only until the next one is needed. */
695
696   if (name == NULL)
697     {
698       if (locbuf != NULL)
699         {
700           free (locbuf);
701         }
702       locbuf = xmalloc (strlen (prefix) + 16);
703       sprintf (locbuf, "%s %u", prefix, val);
704       name = locbuf;
705     }
706   return (name);
707 }
708
709 static char *
710 sigcodename (sip)
711      siginfo_t *sip;
712 {
713   struct sigcode *scp;
714   char *name = NULL;
715   static char locbuf[32];
716   
717   for (scp = siginfo_table; scp -> codename != NULL; scp++)
718     {
719       if ((scp -> signo == sip -> si_signo) &&
720           (scp -> code == sip -> si_code))
721         {
722           name = scp -> codename;
723           break;
724         }
725     }
726   if (name == NULL)
727     {
728       sprintf (locbuf, "sigcode %u", sip -> si_signo);
729       name = locbuf;
730     }
731   return (name);
732 }
733
734 static char *
735 sigcodedesc (sip)
736      siginfo_t *sip;
737 {
738   struct sigcode *scp;
739   char *desc = NULL;
740   
741   for (scp = siginfo_table; scp -> codename != NULL; scp++)
742     {
743       if ((scp -> signo == sip -> si_signo) &&
744           (scp -> code == sip -> si_code))
745         {
746           desc = scp -> desc;
747           break;
748         }
749     }
750   if (desc == NULL)
751     {
752       desc = "Unrecognized signal or trap use";
753     }
754   return (desc);
755 }
756
757 /*
758
759 LOCAL FUNCTION
760
761         syscallname - translate a system call number into a system call name
762
763 SYNOPSIS
764
765         char *syscallname (int syscallnum)
766
767 DESCRIPTION
768
769         Given a system call number, translate it into the printable name
770         of a system call, or into "syscall <num>" if it is an unknown
771         number.
772  */
773
774 static char *
775 syscallname (syscallnum)
776      int syscallnum;
777 {
778   static char locbuf[32];
779   char *rtnval;
780   
781   if (syscallnum >= 0 && syscallnum < MAX_SYSCALLS)
782     {
783       rtnval = syscall_table[syscallnum];
784     }
785   else
786     {
787       sprintf (locbuf, "syscall %u", syscallnum);
788       rtnval = locbuf;
789     }
790   return (rtnval);
791 }
792
793 /*
794
795 LOCAL FUNCTION
796
797         init_syscall_table - initialize syscall translation table
798
799 SYNOPSIS
800
801         void init_syscall_table (void)
802
803 DESCRIPTION
804
805         Dynamically initialize the translation table to convert system
806         call numbers into printable system call names.  Done once per
807         gdb run, on initialization.
808
809 NOTES
810
811         This is awfully ugly, but preprocessor tricks to make it prettier
812         tend to be nonportable.
813  */
814
815 static void
816 init_syscall_table ()
817 {
818 #if defined (SYS_exit)
819   syscall_table[SYS_exit] = "exit";
820 #endif
821 #if defined (SYS_fork)
822   syscall_table[SYS_fork] = "fork";
823 #endif
824 #if defined (SYS_read)
825   syscall_table[SYS_read] = "read";
826 #endif
827 #if defined (SYS_write)
828   syscall_table[SYS_write] = "write";
829 #endif
830 #if defined (SYS_open)
831   syscall_table[SYS_open] = "open";
832 #endif
833 #if defined (SYS_close)
834   syscall_table[SYS_close] = "close";
835 #endif
836 #if defined (SYS_wait)
837   syscall_table[SYS_wait] = "wait";
838 #endif
839 #if defined (SYS_creat)
840   syscall_table[SYS_creat] = "creat";
841 #endif
842 #if defined (SYS_link)
843   syscall_table[SYS_link] = "link";
844 #endif
845 #if defined (SYS_unlink)
846   syscall_table[SYS_unlink] = "unlink";
847 #endif
848 #if defined (SYS_exec)
849   syscall_table[SYS_exec] = "exec";
850 #endif
851 #if defined (SYS_execv)
852   syscall_table[SYS_execv] = "execv";
853 #endif
854 #if defined (SYS_execve)
855   syscall_table[SYS_execve] = "execve";
856 #endif
857 #if defined (SYS_chdir)
858   syscall_table[SYS_chdir] = "chdir";
859 #endif
860 #if defined (SYS_time)
861   syscall_table[SYS_time] = "time";
862 #endif
863 #if defined (SYS_mknod)
864   syscall_table[SYS_mknod] = "mknod";
865 #endif
866 #if defined (SYS_chmod)
867   syscall_table[SYS_chmod] = "chmod";
868 #endif
869 #if defined (SYS_chown)
870   syscall_table[SYS_chown] = "chown";
871 #endif
872 #if defined (SYS_brk)
873   syscall_table[SYS_brk] = "brk";
874 #endif
875 #if defined (SYS_stat)
876   syscall_table[SYS_stat] = "stat";
877 #endif
878 #if defined (SYS_lseek)
879   syscall_table[SYS_lseek] = "lseek";
880 #endif
881 #if defined (SYS_getpid)
882   syscall_table[SYS_getpid] = "getpid";
883 #endif
884 #if defined (SYS_mount)
885   syscall_table[SYS_mount] = "mount";
886 #endif
887 #if defined (SYS_umount)
888   syscall_table[SYS_umount] = "umount";
889 #endif
890 #if defined (SYS_setuid)
891   syscall_table[SYS_setuid] = "setuid";
892 #endif
893 #if defined (SYS_getuid)
894   syscall_table[SYS_getuid] = "getuid";
895 #endif
896 #if defined (SYS_stime)
897   syscall_table[SYS_stime] = "stime";
898 #endif
899 #if defined (SYS_ptrace)
900   syscall_table[SYS_ptrace] = "ptrace";
901 #endif
902 #if defined (SYS_alarm)
903   syscall_table[SYS_alarm] = "alarm";
904 #endif
905 #if defined (SYS_fstat)
906   syscall_table[SYS_fstat] = "fstat";
907 #endif
908 #if defined (SYS_pause)
909   syscall_table[SYS_pause] = "pause";
910 #endif
911 #if defined (SYS_utime)
912   syscall_table[SYS_utime] = "utime";
913 #endif
914 #if defined (SYS_stty)
915   syscall_table[SYS_stty] = "stty";
916 #endif
917 #if defined (SYS_gtty)
918   syscall_table[SYS_gtty] = "gtty";
919 #endif
920 #if defined (SYS_access)
921   syscall_table[SYS_access] = "access";
922 #endif
923 #if defined (SYS_nice)
924   syscall_table[SYS_nice] = "nice";
925 #endif
926 #if defined (SYS_statfs)
927   syscall_table[SYS_statfs] = "statfs";
928 #endif
929 #if defined (SYS_sync)
930   syscall_table[SYS_sync] = "sync";
931 #endif
932 #if defined (SYS_kill)
933   syscall_table[SYS_kill] = "kill";
934 #endif
935 #if defined (SYS_fstatfs)
936   syscall_table[SYS_fstatfs] = "fstatfs";
937 #endif
938 #if defined (SYS_pgrpsys)
939   syscall_table[SYS_pgrpsys] = "pgrpsys";
940 #endif
941 #if defined (SYS_xenix)
942   syscall_table[SYS_xenix] = "xenix";
943 #endif
944 #if defined (SYS_dup)
945   syscall_table[SYS_dup] = "dup";
946 #endif
947 #if defined (SYS_pipe)
948   syscall_table[SYS_pipe] = "pipe";
949 #endif
950 #if defined (SYS_times)
951   syscall_table[SYS_times] = "times";
952 #endif
953 #if defined (SYS_profil)
954   syscall_table[SYS_profil] = "profil";
955 #endif
956 #if defined (SYS_plock)
957   syscall_table[SYS_plock] = "plock";
958 #endif
959 #if defined (SYS_setgid)
960   syscall_table[SYS_setgid] = "setgid";
961 #endif
962 #if defined (SYS_getgid)
963   syscall_table[SYS_getgid] = "getgid";
964 #endif
965 #if defined (SYS_signal)
966   syscall_table[SYS_signal] = "signal";
967 #endif
968 #if defined (SYS_msgsys)
969   syscall_table[SYS_msgsys] = "msgsys";
970 #endif
971 #if defined (SYS_sys3b)
972   syscall_table[SYS_sys3b] = "sys3b";
973 #endif
974 #if defined (SYS_acct)
975   syscall_table[SYS_acct] = "acct";
976 #endif
977 #if defined (SYS_shmsys)
978   syscall_table[SYS_shmsys] = "shmsys";
979 #endif
980 #if defined (SYS_semsys)
981   syscall_table[SYS_semsys] = "semsys";
982 #endif
983 #if defined (SYS_ioctl)
984   syscall_table[SYS_ioctl] = "ioctl";
985 #endif
986 #if defined (SYS_uadmin)
987   syscall_table[SYS_uadmin] = "uadmin";
988 #endif
989 #if defined (SYS_utssys)
990   syscall_table[SYS_utssys] = "utssys";
991 #endif
992 #if defined (SYS_fsync)
993   syscall_table[SYS_fsync] = "fsync";
994 #endif
995 #if defined (SYS_umask)
996   syscall_table[SYS_umask] = "umask";
997 #endif
998 #if defined (SYS_chroot)
999   syscall_table[SYS_chroot] = "chroot";
1000 #endif
1001 #if defined (SYS_fcntl)
1002   syscall_table[SYS_fcntl] = "fcntl";
1003 #endif
1004 #if defined (SYS_ulimit)
1005   syscall_table[SYS_ulimit] = "ulimit";
1006 #endif
1007 #if defined (SYS_rfsys)
1008   syscall_table[SYS_rfsys] = "rfsys";
1009 #endif
1010 #if defined (SYS_rmdir)
1011   syscall_table[SYS_rmdir] = "rmdir";
1012 #endif
1013 #if defined (SYS_mkdir)
1014   syscall_table[SYS_mkdir] = "mkdir";
1015 #endif
1016 #if defined (SYS_getdents)
1017   syscall_table[SYS_getdents] = "getdents";
1018 #endif
1019 #if defined (SYS_sysfs)
1020   syscall_table[SYS_sysfs] = "sysfs";
1021 #endif
1022 #if defined (SYS_getmsg)
1023   syscall_table[SYS_getmsg] = "getmsg";
1024 #endif
1025 #if defined (SYS_putmsg)
1026   syscall_table[SYS_putmsg] = "putmsg";
1027 #endif
1028 #if defined (SYS_poll)
1029   syscall_table[SYS_poll] = "poll";
1030 #endif
1031 #if defined (SYS_lstat)
1032   syscall_table[SYS_lstat] = "lstat";
1033 #endif
1034 #if defined (SYS_symlink)
1035   syscall_table[SYS_symlink] = "symlink";
1036 #endif
1037 #if defined (SYS_readlink)
1038   syscall_table[SYS_readlink] = "readlink";
1039 #endif
1040 #if defined (SYS_setgroups)
1041   syscall_table[SYS_setgroups] = "setgroups";
1042 #endif
1043 #if defined (SYS_getgroups)
1044   syscall_table[SYS_getgroups] = "getgroups";
1045 #endif
1046 #if defined (SYS_fchmod)
1047   syscall_table[SYS_fchmod] = "fchmod";
1048 #endif
1049 #if defined (SYS_fchown)
1050   syscall_table[SYS_fchown] = "fchown";
1051 #endif
1052 #if defined (SYS_sigprocmask)
1053   syscall_table[SYS_sigprocmask] = "sigprocmask";
1054 #endif
1055 #if defined (SYS_sigsuspend)
1056   syscall_table[SYS_sigsuspend] = "sigsuspend";
1057 #endif
1058 #if defined (SYS_sigaltstack)
1059   syscall_table[SYS_sigaltstack] = "sigaltstack";
1060 #endif
1061 #if defined (SYS_sigaction)
1062   syscall_table[SYS_sigaction] = "sigaction";
1063 #endif
1064 #if defined (SYS_sigpending)
1065   syscall_table[SYS_sigpending] = "sigpending";
1066 #endif
1067 #if defined (SYS_context)
1068   syscall_table[SYS_context] = "context";
1069 #endif
1070 #if defined (SYS_evsys)
1071   syscall_table[SYS_evsys] = "evsys";
1072 #endif
1073 #if defined (SYS_evtrapret)
1074   syscall_table[SYS_evtrapret] = "evtrapret";
1075 #endif
1076 #if defined (SYS_statvfs)
1077   syscall_table[SYS_statvfs] = "statvfs";
1078 #endif
1079 #if defined (SYS_fstatvfs)
1080   syscall_table[SYS_fstatvfs] = "fstatvfs";
1081 #endif
1082 #if defined (SYS_nfssys)
1083   syscall_table[SYS_nfssys] = "nfssys";
1084 #endif
1085 #if defined (SYS_waitsys)
1086   syscall_table[SYS_waitsys] = "waitsys";
1087 #endif
1088 #if defined (SYS_sigsendsys)
1089   syscall_table[SYS_sigsendsys] = "sigsendsys";
1090 #endif
1091 #if defined (SYS_hrtsys)
1092   syscall_table[SYS_hrtsys] = "hrtsys";
1093 #endif
1094 #if defined (SYS_acancel)
1095   syscall_table[SYS_acancel] = "acancel";
1096 #endif
1097 #if defined (SYS_async)
1098   syscall_table[SYS_async] = "async";
1099 #endif
1100 #if defined (SYS_priocntlsys)
1101   syscall_table[SYS_priocntlsys] = "priocntlsys";
1102 #endif
1103 #if defined (SYS_pathconf)
1104   syscall_table[SYS_pathconf] = "pathconf";
1105 #endif
1106 #if defined (SYS_mincore)
1107   syscall_table[SYS_mincore] = "mincore";
1108 #endif
1109 #if defined (SYS_mmap)
1110   syscall_table[SYS_mmap] = "mmap";
1111 #endif
1112 #if defined (SYS_mprotect)
1113   syscall_table[SYS_mprotect] = "mprotect";
1114 #endif
1115 #if defined (SYS_munmap)
1116   syscall_table[SYS_munmap] = "munmap";
1117 #endif
1118 #if defined (SYS_fpathconf)
1119   syscall_table[SYS_fpathconf] = "fpathconf";
1120 #endif
1121 #if defined (SYS_vfork)
1122   syscall_table[SYS_vfork] = "vfork";
1123 #endif
1124 #if defined (SYS_fchdir)
1125   syscall_table[SYS_fchdir] = "fchdir";
1126 #endif
1127 #if defined (SYS_readv)
1128   syscall_table[SYS_readv] = "readv";
1129 #endif
1130 #if defined (SYS_writev)
1131   syscall_table[SYS_writev] = "writev";
1132 #endif
1133 #if defined (SYS_xstat)
1134   syscall_table[SYS_xstat] = "xstat";
1135 #endif
1136 #if defined (SYS_lxstat)
1137   syscall_table[SYS_lxstat] = "lxstat";
1138 #endif
1139 #if defined (SYS_fxstat)
1140   syscall_table[SYS_fxstat] = "fxstat";
1141 #endif
1142 #if defined (SYS_xmknod)
1143   syscall_table[SYS_xmknod] = "xmknod";
1144 #endif
1145 #if defined (SYS_clocal)
1146   syscall_table[SYS_clocal] = "clocal";
1147 #endif
1148 #if defined (SYS_setrlimit)
1149   syscall_table[SYS_setrlimit] = "setrlimit";
1150 #endif
1151 #if defined (SYS_getrlimit)
1152   syscall_table[SYS_getrlimit] = "getrlimit";
1153 #endif
1154 #if defined (SYS_lchown)
1155   syscall_table[SYS_lchown] = "lchown";
1156 #endif
1157 #if defined (SYS_memcntl)
1158   syscall_table[SYS_memcntl] = "memcntl";
1159 #endif
1160 #if defined (SYS_getpmsg)
1161   syscall_table[SYS_getpmsg] = "getpmsg";
1162 #endif
1163 #if defined (SYS_putpmsg)
1164   syscall_table[SYS_putpmsg] = "putpmsg";
1165 #endif
1166 #if defined (SYS_rename)
1167   syscall_table[SYS_rename] = "rename";
1168 #endif
1169 #if defined (SYS_uname)
1170   syscall_table[SYS_uname] = "uname";
1171 #endif
1172 #if defined (SYS_setegid)
1173   syscall_table[SYS_setegid] = "setegid";
1174 #endif
1175 #if defined (SYS_sysconfig)
1176   syscall_table[SYS_sysconfig] = "sysconfig";
1177 #endif
1178 #if defined (SYS_adjtime)
1179   syscall_table[SYS_adjtime] = "adjtime";
1180 #endif
1181 #if defined (SYS_systeminfo)
1182   syscall_table[SYS_systeminfo] = "systeminfo";
1183 #endif
1184 #if defined (SYS_seteuid)
1185   syscall_table[SYS_seteuid] = "seteuid";
1186 #endif
1187 #if defined (SYS_sproc)
1188   syscall_table[SYS_sproc] = "sproc";
1189 #endif
1190 }
1191
1192 /*
1193
1194 LOCAL FUNCTION
1195
1196         procfs_kill_inferior - kill any currently inferior
1197
1198 SYNOPSIS
1199
1200         void procfs_kill_inferior (void)
1201
1202 DESCRIPTION
1203
1204         Kill any current inferior.
1205
1206 NOTES
1207
1208         Kills even attached inferiors.  Presumably the user has already
1209         been prompted that the inferior is an attached one rather than
1210         one started by gdb.  (FIXME?)
1211
1212 */
1213
1214 static void
1215 procfs_kill_inferior ()
1216 {
1217   target_mourn_inferior ();
1218 }
1219
1220 /*
1221
1222 LOCAL FUNCTION
1223
1224         unconditionally_kill_inferior - terminate the inferior
1225
1226 SYNOPSIS
1227
1228         static void unconditionally_kill_inferior (struct procinfo *)
1229
1230 DESCRIPTION
1231
1232         Kill the specified inferior.
1233
1234 NOTE
1235
1236         A possibly useful enhancement would be to first try sending
1237         the inferior a terminate signal, politely asking it to commit
1238         suicide, before we murder it (we could call that
1239         politely_kill_inferior()).
1240
1241 */
1242
1243 static void
1244 unconditionally_kill_inferior (pi)
1245      struct procinfo *pi;
1246 {
1247   int signo;
1248   int ppid;
1249   
1250   ppid = pi->prstatus.pr_ppid;
1251
1252   signo = SIGKILL;
1253
1254 #ifdef PROCFS_NEED_PIOCSSIG_FOR_KILL
1255   /* Alpha OSF/1 procfs needs a PIOCSSIG call with a SIGKILL signal
1256      to kill the inferior, otherwise it might remain stopped with a
1257      pending SIGKILL.
1258      We do not check the result of the PIOCSSIG, the inferior might have
1259      died already.  */
1260   {
1261     struct siginfo newsiginfo;
1262
1263     memset ((char *) &newsiginfo, 0, sizeof (newsiginfo));
1264     newsiginfo.si_signo = signo;
1265     newsiginfo.si_code = 0;
1266     newsiginfo.si_errno = 0;
1267     newsiginfo.si_pid = getpid ();
1268     newsiginfo.si_uid = getuid ();
1269     ioctl (pi->fd, PIOCSSIG, &newsiginfo);
1270   }
1271 #else
1272   ioctl (pi->fd, PIOCKILL, &signo);
1273 #endif
1274
1275   close_proc_file (pi);
1276
1277 /* Only wait() for our direct children.  Our grandchildren zombies are killed
1278    by the death of their parents.  */
1279
1280   if (ppid == getpid())
1281     wait ((int *) 0);
1282 }
1283
1284 /*
1285
1286 LOCAL FUNCTION
1287
1288         procfs_xfer_memory -- copy data to or from inferior memory space
1289
1290 SYNOPSIS
1291
1292         int procfs_xfer_memory (CORE_ADDR memaddr, char *myaddr, int len,
1293                 int dowrite, struct target_ops target)
1294
1295 DESCRIPTION
1296
1297         Copy LEN bytes to/from inferior's memory starting at MEMADDR
1298         from/to debugger memory starting at MYADDR.  Copy from inferior
1299         if DOWRITE is zero or to inferior if DOWRITE is nonzero.
1300   
1301         Returns the length copied, which is either the LEN argument or
1302         zero.  This xfer function does not do partial moves, since procfs_ops
1303         doesn't allow memory operations to cross below us in the target stack
1304         anyway.
1305
1306 NOTES
1307
1308         The /proc interface makes this an almost trivial task.
1309  */
1310
1311 static int
1312 procfs_xfer_memory (memaddr, myaddr, len, dowrite, target)
1313      CORE_ADDR memaddr;
1314      char *myaddr;
1315      int len;
1316      int dowrite;
1317      struct target_ops *target; /* ignored */
1318 {
1319   int nbytes = 0;
1320   struct procinfo *pi;
1321
1322   pi = current_procinfo;
1323
1324   if (lseek(pi->fd, (off_t) memaddr, 0) == (off_t) memaddr)
1325     {
1326       if (dowrite)
1327         {
1328           nbytes = write (pi->fd, myaddr, len);
1329         }
1330       else
1331         {
1332           nbytes = read (pi->fd, myaddr, len);
1333         }
1334       if (nbytes < 0)
1335         {
1336           nbytes = 0;
1337         }
1338     }
1339   return (nbytes);
1340 }
1341
1342 /*
1343
1344 LOCAL FUNCTION
1345
1346         procfs_store_registers -- copy register values back to inferior
1347
1348 SYNOPSIS
1349
1350         void procfs_store_registers (int regno)
1351
1352 DESCRIPTION
1353
1354         Store our current register values back into the inferior.  If
1355         REGNO is -1 then store all the register, otherwise store just
1356         the value specified by REGNO.
1357
1358 NOTES
1359
1360         If we are storing only a single register, we first have to get all
1361         the current values from the process, overwrite the desired register
1362         in the gregset with the one we want from gdb's registers, and then
1363         send the whole set back to the process.  For writing all the
1364         registers, all we have to do is generate the gregset and send it to
1365         the process.
1366
1367         Also note that the process has to be stopped on an event of interest
1368         for this to work, which basically means that it has to have been
1369         run under the control of one of the other /proc ioctl calls and not
1370         ptrace.  Since we don't use ptrace anyway, we don't worry about this
1371         fine point, but it is worth noting for future reference.
1372
1373         Gdb is confused about what this function is supposed to return.
1374         Some versions return a value, others return nothing.  Some are
1375         declared to return a value and actually return nothing.  Gdb ignores
1376         anything returned.  (FIXME)
1377
1378  */
1379
1380 static void
1381 procfs_store_registers (regno)
1382      int regno;
1383 {
1384   struct procinfo *pi;
1385
1386   pi = current_procinfo;
1387
1388   if (regno != -1)
1389     {
1390       ioctl (pi->fd, PIOCGREG, &pi->gregset);
1391     }
1392   fill_gregset (&pi->gregset, regno);
1393   ioctl (pi->fd, PIOCSREG, &pi->gregset);
1394
1395 #if defined (FP0_REGNUM)
1396
1397   /* Now repeat everything using the floating point register set, if the
1398      target has floating point hardware. Since we ignore the returned value,
1399      we'll never know whether it worked or not anyway. */
1400
1401   if (regno != -1)
1402     {
1403       ioctl (pi->fd, PIOCGFPREG, &pi->fpregset);
1404     }
1405   fill_fpregset (&pi->fpregset, regno);
1406   ioctl (pi->fd, PIOCSFPREG, &pi->fpregset);
1407
1408 #endif  /* FP0_REGNUM */
1409
1410 }
1411
1412 /*
1413
1414 LOCAL FUNCTION
1415
1416         create_procinfo - initialize access to a /proc entry
1417
1418 SYNOPSIS
1419
1420         struct procinfo * create_procinfo (int pid)
1421
1422 DESCRIPTION
1423
1424         Allocate a procinfo structure, open the /proc file and then set up the
1425         set of signals and faults that are to be traced.  Returns a pointer to
1426         the new procinfo structure.
1427
1428 NOTES
1429
1430         If proc_init_failed ever gets called, control returns to the command
1431         processing loop via the standard error handling code.
1432
1433  */
1434
1435 static struct procinfo *
1436 create_procinfo (pid)
1437      int pid;
1438 {
1439   struct procinfo *pi;
1440
1441   pi = find_procinfo (pid, 1);
1442   if (pi != NULL)
1443     return pi;                  /* All done!  It already exists */
1444
1445   pi = (struct procinfo *) xmalloc (sizeof (struct procinfo));
1446
1447   if (!open_proc_file (pid, pi, O_RDWR))
1448     proc_init_failed (pi, "can't open process file");
1449
1450   /* Add new process to process info list */
1451
1452   pi->next = procinfo_list;
1453   procinfo_list = pi;
1454
1455   add_fd (pi);                  /* Add to list for poll/select */
1456
1457   memset ((char *) &pi->prrun, 0, sizeof (pi->prrun));
1458   prfillset (&pi->prrun.pr_trace);
1459   procfs_notice_signals (pid);
1460   prfillset (&pi->prrun.pr_fault);
1461   prdelset (&pi->prrun.pr_fault, FLTPAGE);
1462
1463 #ifdef PROCFS_DONT_TRACE_FAULTS
1464   premptyset (&pi->prrun.pr_fault);
1465 #endif
1466
1467   if (ioctl (pi->fd, PIOCWSTOP, &pi->prstatus) < 0)
1468     proc_init_failed (pi, "PIOCWSTOP failed");
1469
1470   if (ioctl (pi->fd, PIOCSFAULT, &pi->prrun.pr_fault) < 0)
1471     proc_init_failed (pi, "PIOCSFAULT failed");
1472
1473   return pi;
1474 }
1475
1476 /*
1477
1478 LOCAL FUNCTION
1479
1480         procfs_init_inferior - initialize target vector and access to a
1481         /proc entry
1482
1483 SYNOPSIS
1484
1485         void procfs_init_inferior (int pid)
1486
1487 DESCRIPTION
1488
1489         When gdb starts an inferior, this function is called in the parent
1490         process immediately after the fork.  It waits for the child to stop
1491         on the return from the exec system call (the child itself takes care
1492         of ensuring that this is set up), then sets up the set of signals
1493         and faults that are to be traced.
1494
1495 NOTES
1496
1497         If proc_init_failed ever gets called, control returns to the command
1498         processing loop via the standard error handling code.
1499
1500  */
1501
1502 static void
1503 procfs_init_inferior (pid)
1504      int pid;
1505 {
1506   push_target (&procfs_ops);
1507
1508   create_procinfo (pid);
1509   add_thread (pid);             /* Setup initial thread */
1510
1511 #ifdef START_INFERIOR_TRAPS_EXPECTED
1512   startup_inferior (START_INFERIOR_TRAPS_EXPECTED);
1513 #else
1514   /* One trap to exec the shell, one to exec the program being debugged.  */
1515   startup_inferior (2);
1516 #endif
1517 }
1518
1519 /*
1520
1521 GLOBAL FUNCTION
1522
1523         procfs_notice_signals
1524
1525 SYNOPSIS
1526
1527         static void procfs_notice_signals (int pid);
1528
1529 DESCRIPTION
1530
1531         When the user changes the state of gdb's signal handling via the
1532         "handle" command, this function gets called to see if any change
1533         in the /proc interface is required.  It is also called internally
1534         by other /proc interface functions to initialize the state of
1535         the traced signal set.
1536
1537         One thing it does is that signals for which the state is "nostop",
1538         "noprint", and "pass", have their trace bits reset in the pr_trace
1539         field, so that they are no longer traced.  This allows them to be
1540         delivered directly to the inferior without the debugger ever being
1541         involved.
1542  */
1543
1544 static void
1545 procfs_notice_signals (pid)
1546      int pid;
1547 {
1548   int signo;
1549   struct procinfo *pi;
1550
1551   pi = find_procinfo (pid, 0);
1552
1553   for (signo = 0; signo < NSIG; signo++)
1554     {
1555       if (signal_stop_state (target_signal_from_host (signo)) == 0 &&
1556           signal_print_state (target_signal_from_host (signo)) == 0 &&
1557           signal_pass_state (target_signal_from_host (signo)) == 1)
1558         {
1559           prdelset (&pi->prrun.pr_trace, signo);
1560         }
1561       else
1562         {
1563           praddset (&pi->prrun.pr_trace, signo);
1564         }
1565     }
1566   if (ioctl (pi->fd, PIOCSTRACE, &pi->prrun.pr_trace))
1567     {
1568       print_sys_errmsg ("PIOCSTRACE failed", errno);
1569     }
1570 }
1571
1572 /*
1573
1574 LOCAL FUNCTION
1575
1576         proc_set_exec_trap -- arrange for exec'd child to halt at startup
1577
1578 SYNOPSIS
1579
1580         void proc_set_exec_trap (void)
1581
1582 DESCRIPTION
1583
1584         This function is called in the child process when starting up
1585         an inferior, prior to doing the exec of the actual inferior.
1586         It sets the child process's exitset to make exit from the exec
1587         system call an event of interest to stop on, and then simply
1588         returns.  The child does the exec, the system call returns, and
1589         the child stops at the first instruction, ready for the gdb
1590         parent process to take control of it.
1591
1592 NOTE
1593
1594         We need to use all local variables since the child may be sharing
1595         it's data space with the parent, if vfork was used rather than
1596         fork.
1597
1598         Also note that we want to turn off the inherit-on-fork flag in
1599         the child process so that any grand-children start with all
1600         tracing flags cleared.
1601  */
1602
1603 static void
1604 proc_set_exec_trap ()
1605 {
1606   sysset_t exitset;
1607   sysset_t entryset;
1608   auto char procname[32];
1609   int fd;
1610   
1611   sprintf (procname, PROC_NAME_FMT, getpid ());
1612   if ((fd = open (procname, O_RDWR)) < 0)
1613     {
1614       perror (procname);
1615       gdb_flush (gdb_stderr);
1616       _exit (127);
1617     }
1618   premptyset (&exitset);
1619   premptyset (&entryset);
1620
1621 #ifdef PIOCSSPCACT
1622   /* Under Alpha OSF/1 we have to use a PIOCSSPCACT ioctl to trace
1623      exits from exec system calls because of the user level loader.  */
1624   {
1625     int prfs_flags;
1626
1627     if (ioctl (fd, PIOCGSPCACT, &prfs_flags) < 0)
1628       {
1629         perror (procname);
1630         gdb_flush (gdb_stderr);
1631         _exit (127);
1632       }
1633     prfs_flags |= PRFS_STOPEXEC;
1634     if (ioctl (fd, PIOCSSPCACT, &prfs_flags) < 0)
1635       {
1636         perror (procname);
1637         gdb_flush (gdb_stderr);
1638         _exit (127);
1639       }
1640   }
1641 #else
1642   /* GW: Rationale...
1643      Not all systems with /proc have all the exec* syscalls with the same
1644      names.  On the SGI, for example, there is no SYS_exec, but there
1645      *is* a SYS_execv.  So, we try to account for that. */
1646
1647 #ifdef SYS_exec
1648   praddset (&exitset, SYS_exec);
1649 #endif
1650 #ifdef SYS_execve
1651   praddset (&exitset, SYS_execve);
1652 #endif
1653 #ifdef SYS_execv
1654   praddset (&exitset, SYS_execv);
1655 #endif
1656
1657   if (ioctl (fd, PIOCSEXIT, &exitset) < 0)
1658     {
1659       perror (procname);
1660       gdb_flush (gdb_stderr);
1661       _exit (127);
1662     }
1663 #endif
1664
1665   praddset (&entryset, SYS_exit);
1666
1667   if (ioctl (fd, PIOCSENTRY, &entryset) < 0)
1668     {
1669       perror (procname);
1670       gdb_flush (gdb_stderr);
1671       _exit (126);
1672     }
1673
1674   /* Turn off inherit-on-fork flag so that all grand-children of gdb
1675      start with tracing flags cleared. */
1676
1677 #if defined (PIOCRESET) /* New method */
1678   {
1679       long pr_flags;
1680       pr_flags = PR_FORK;
1681       ioctl (fd, PIOCRESET, &pr_flags);
1682   }
1683 #else
1684 #if defined (PIOCRFORK) /* Original method */
1685   ioctl (fd, PIOCRFORK, NULL);
1686 #endif
1687 #endif
1688
1689   /* Turn on run-on-last-close flag so that this process will not hang
1690      if GDB goes away for some reason.  */
1691
1692 #if defined (PIOCSET)   /* New method */
1693   {
1694       long pr_flags;
1695       pr_flags = PR_RLC;
1696       (void) ioctl (fd, PIOCSET, &pr_flags);
1697   }
1698 #else
1699 #if defined (PIOCSRLC)  /* Original method */
1700   (void) ioctl (fd, PIOCSRLC, 0);
1701 #endif
1702 #endif
1703 }
1704
1705 /*
1706
1707 GLOBAL FUNCTION
1708
1709         proc_iterate_over_mappings -- call function for every mapped space
1710
1711 SYNOPSIS
1712
1713         int proc_iterate_over_mappings (int (*func)())
1714
1715 DESCRIPTION
1716
1717         Given a pointer to a function, call that function for every
1718         mapped address space, passing it an open file descriptor for
1719         the file corresponding to that mapped address space (if any)
1720         and the base address of the mapped space.  Quit when we hit
1721         the end of the mappings or the function returns nonzero.
1722  */
1723
1724 int
1725 proc_iterate_over_mappings (func)
1726      int (*func) PARAMS ((int, CORE_ADDR));
1727 {
1728   int nmap;
1729   int fd;
1730   int funcstat = 0;
1731   struct prmap *prmaps;
1732   struct prmap *prmap;
1733   struct procinfo *pi;
1734
1735   pi = current_procinfo;
1736
1737   if (ioctl (pi->fd, PIOCNMAP, &nmap) == 0)
1738     {
1739       prmaps = (struct prmap *) alloca ((nmap + 1) * sizeof (*prmaps));
1740       if (ioctl (pi->fd, PIOCMAP, prmaps) == 0)
1741         {
1742           for (prmap = prmaps; prmap -> pr_size && funcstat == 0; ++prmap)
1743             {
1744               fd = proc_address_to_fd (pi, (CORE_ADDR) prmap -> pr_vaddr, 0);
1745               funcstat = (*func) (fd, (CORE_ADDR) prmap -> pr_vaddr);
1746               close (fd);
1747             }
1748         }
1749     }
1750   return (funcstat);
1751 }
1752
1753 #if 0   /* Currently unused */
1754 /*
1755
1756 GLOBAL FUNCTION
1757
1758         proc_base_address -- find base address for segment containing address
1759
1760 SYNOPSIS
1761
1762         CORE_ADDR proc_base_address (CORE_ADDR addr)
1763
1764 DESCRIPTION
1765
1766         Given an address of a location in the inferior, find and return
1767         the base address of the mapped segment containing that address.
1768
1769         This is used for example, by the shared library support code,
1770         where we have the pc value for some location in the shared library
1771         where we are stopped, and need to know the base address of the
1772         segment containing that address.
1773 */
1774
1775 CORE_ADDR
1776 proc_base_address (addr)
1777      CORE_ADDR addr;
1778 {
1779   int nmap;
1780   struct prmap *prmaps;
1781   struct prmap *prmap;
1782   CORE_ADDR baseaddr = 0;
1783   struct procinfo *pi;
1784
1785   pi = current_procinfo;
1786
1787   if (ioctl (pi->fd, PIOCNMAP, &nmap) == 0)
1788     {
1789       prmaps = (struct prmap *) alloca ((nmap + 1) * sizeof (*prmaps));
1790       if (ioctl (pi->fd, PIOCMAP, prmaps) == 0)
1791         {
1792           for (prmap = prmaps; prmap -> pr_size; ++prmap)
1793             {
1794               if ((prmap -> pr_vaddr <= (caddr_t) addr) &&
1795                   (prmap -> pr_vaddr + prmap -> pr_size > (caddr_t) addr))
1796                 {
1797                   baseaddr = (CORE_ADDR) prmap -> pr_vaddr;
1798                   break;
1799                 }
1800             }
1801         }
1802     }
1803   return (baseaddr);
1804 }
1805
1806 #endif  /* 0 */
1807
1808 /*
1809
1810 LOCAL FUNCTION
1811
1812         proc_address_to_fd -- return open fd for file mapped to address
1813
1814 SYNOPSIS
1815
1816         int proc_address_to_fd (struct procinfo *pi, CORE_ADDR addr, complain)
1817
1818 DESCRIPTION
1819
1820         Given an address in the current inferior's address space, use the
1821         /proc interface to find an open file descriptor for the file that
1822         this address was mapped in from.  Return -1 if there is no current
1823         inferior.  Print a warning message if there is an inferior but
1824         the address corresponds to no file (IE a bogus address).
1825
1826 */
1827
1828 static int
1829 proc_address_to_fd (pi, addr, complain)
1830      struct procinfo *pi;
1831      CORE_ADDR addr;
1832      int complain;
1833 {
1834   int fd = -1;
1835
1836   if ((fd = ioctl (pi->fd, PIOCOPENM, (caddr_t *) &addr)) < 0)
1837     {
1838       if (complain)
1839         {
1840           print_sys_errmsg (pi->pathname, errno);
1841           warning ("can't find mapped file for address 0x%x", addr);
1842         }
1843     }
1844   return (fd);
1845 }
1846
1847
1848 /* Attach to process PID, then initialize for debugging it
1849    and wait for the trace-trap that results from attaching.  */
1850
1851 static void
1852 procfs_attach (args, from_tty)
1853      char *args;
1854      int from_tty;
1855 {
1856   char *exec_file;
1857   int pid;
1858
1859   if (!args)
1860     error_no_arg ("process-id to attach");
1861
1862   pid = atoi (args);
1863
1864   if (pid == getpid())          /* Trying to masturbate? */
1865     error ("I refuse to debug myself!");
1866
1867   if (from_tty)
1868     {
1869       exec_file = (char *) get_exec_file (0);
1870
1871       if (exec_file)
1872         printf_unfiltered ("Attaching to program `%s', %s\n", exec_file, target_pid_to_str (pid));
1873       else
1874         printf_unfiltered ("Attaching to %s\n", target_pid_to_str (pid));
1875
1876       gdb_flush (gdb_stdout);
1877     }
1878
1879   do_attach (pid);
1880   inferior_pid = pid;
1881   push_target (&procfs_ops);
1882 }
1883
1884
1885 /* Take a program previously attached to and detaches it.
1886    The program resumes execution and will no longer stop
1887    on signals, etc.  We'd better not have left any breakpoints
1888    in the program or it'll die when it hits one.  For this
1889    to work, it may be necessary for the process to have been
1890    previously attached.  It *might* work if the program was
1891    started via the normal ptrace (PTRACE_TRACEME).  */
1892
1893 static void
1894 procfs_detach (args, from_tty)
1895      char *args;
1896      int from_tty;
1897 {
1898   int siggnal = 0;
1899
1900   if (from_tty)
1901     {
1902       char *exec_file = get_exec_file (0);
1903       if (exec_file == 0)
1904         exec_file = "";
1905       printf_unfiltered ("Detaching from program: %s %s\n",
1906               exec_file, target_pid_to_str (inferior_pid));
1907       gdb_flush (gdb_stdout);
1908     }
1909   if (args)
1910     siggnal = atoi (args);
1911   
1912   do_detach (siggnal);
1913   inferior_pid = 0;
1914   unpush_target (&procfs_ops);          /* Pop out of handling an inferior */
1915 }
1916
1917 /* Get ready to modify the registers array.  On machines which store
1918    individual registers, this doesn't need to do anything.  On machines
1919    which store all the registers in one fell swoop, this makes sure
1920    that registers contains all the registers from the program being
1921    debugged.  */
1922
1923 static void
1924 procfs_prepare_to_store ()
1925 {
1926 #ifdef CHILD_PREPARE_TO_STORE
1927   CHILD_PREPARE_TO_STORE ();
1928 #endif
1929 }
1930
1931 /* Print status information about what we're accessing.  */
1932
1933 static void
1934 procfs_files_info (ignore)
1935      struct target_ops *ignore;
1936 {
1937   printf_unfiltered ("\tUsing the running image of %s %s via /proc.\n",
1938           attach_flag? "attached": "child", target_pid_to_str (inferior_pid));
1939 }
1940
1941 /* ARGSUSED */
1942 static void
1943 procfs_open (arg, from_tty)
1944      char *arg;
1945      int from_tty;
1946 {
1947   error ("Use the \"run\" command to start a Unix child process.");
1948 }
1949
1950 /*
1951
1952 LOCAL FUNCTION
1953
1954         do_attach -- attach to an already existing process
1955
1956 SYNOPSIS
1957
1958         int do_attach (int pid)
1959
1960 DESCRIPTION
1961
1962         Attach to an already existing process with the specified process
1963         id.  If the process is not already stopped, query whether to
1964         stop it or not.
1965
1966 NOTES
1967
1968         The option of stopping at attach time is specific to the /proc
1969         versions of gdb.  Versions using ptrace force the attachee
1970         to stop.  (I have changed this version to do so, too.  All you
1971         have to do is "continue" to make it go on. -- gnu@cygnus.com)
1972
1973 */
1974
1975 static int
1976 do_attach (pid)
1977      int pid;
1978 {
1979   int result;
1980   struct procinfo *pi;
1981
1982   pi = (struct procinfo *) xmalloc (sizeof (struct procinfo));
1983
1984   if (!open_proc_file (pid, pi, O_RDWR))
1985     {
1986       free (pi);
1987       perror_with_name (pi->pathname);
1988       /* NOTREACHED */
1989     }
1990   
1991   /* Add new process to process info list */
1992
1993   pi->next = procinfo_list;
1994   procinfo_list = pi;
1995
1996   add_fd (pi);                  /* Add to list for poll/select */
1997
1998   /*  Get current status of process and if it is not already stopped,
1999       then stop it.  Remember whether or not it was stopped when we first
2000       examined it. */
2001   
2002   if (ioctl (pi->fd, PIOCSTATUS, &pi->prstatus) < 0)
2003     {
2004       print_sys_errmsg (pi->pathname, errno);
2005       close_proc_file (pi);
2006       error ("PIOCSTATUS failed");
2007     }
2008   if (pi->prstatus.pr_flags & (PR_STOPPED | PR_ISTOP))
2009     {
2010       pi->was_stopped = 1;
2011     }
2012   else
2013     {
2014       pi->was_stopped = 0;
2015       if (1 || query ("Process is currently running, stop it? "))
2016         {
2017           /* Make it run again when we close it.  */
2018 #if defined (PIOCSET)   /* New method */
2019           {
2020               long pr_flags;
2021               pr_flags = PR_RLC;
2022               result = ioctl (pi->fd, PIOCSET, &pr_flags);
2023           }
2024 #else
2025 #if defined (PIOCSRLC)  /* Original method */
2026           result = ioctl (pi->fd, PIOCSRLC, 0);
2027 #endif
2028 #endif
2029           if (result < 0)
2030             {
2031               print_sys_errmsg (pi->pathname, errno);
2032               close_proc_file (pi);
2033               error ("PIOCSRLC or PIOCSET failed");
2034             }
2035           if (ioctl (pi->fd, PIOCSTOP, &pi->prstatus) < 0)
2036             {
2037               print_sys_errmsg (pi->pathname, errno);
2038               close_proc_file (pi);
2039               error ("PIOCSTOP failed");
2040             }
2041           pi->nopass_next_sigstop = 1;
2042         }
2043       else
2044         {
2045           printf_unfiltered ("Ok, gdb will wait for %s to stop.\n", target_pid_to_str (pid));
2046         }
2047     }
2048
2049   /*  Remember some things about the inferior that we will, or might, change
2050       so that we can restore them when we detach. */
2051   
2052   ioctl (pi->fd, PIOCGTRACE, &pi->saved_trace);
2053   ioctl (pi->fd, PIOCGHOLD, &pi->saved_sighold);
2054   ioctl (pi->fd, PIOCGFAULT, &pi->saved_fltset);
2055   ioctl (pi->fd, PIOCGENTRY, &pi->saved_entryset);
2056   ioctl (pi->fd, PIOCGEXIT, &pi->saved_exitset);
2057   
2058   /* Set up trace and fault sets, as gdb expects them. */
2059   
2060   memset (&pi->prrun, 0, sizeof (pi->prrun));
2061   prfillset (&pi->prrun.pr_trace);
2062   procfs_notice_signals (pid);
2063   prfillset (&pi->prrun.pr_fault);
2064   prdelset (&pi->prrun.pr_fault, FLTPAGE);
2065
2066 #ifdef PROCFS_DONT_TRACE_FAULTS
2067   premptyset (&pi->prrun.pr_fault);
2068 #endif
2069
2070   if (ioctl (pi->fd, PIOCSFAULT, &pi->prrun.pr_fault))
2071     {
2072       print_sys_errmsg ("PIOCSFAULT failed", errno);
2073     }
2074   if (ioctl (pi->fd, PIOCSTRACE, &pi->prrun.pr_trace))
2075     {
2076       print_sys_errmsg ("PIOCSTRACE failed", errno);
2077     }
2078   attach_flag = 1;
2079   return (pid);
2080 }
2081
2082 /*
2083
2084 LOCAL FUNCTION
2085
2086         do_detach -- detach from an attached-to process
2087
2088 SYNOPSIS
2089
2090         void do_detach (int signal)
2091
2092 DESCRIPTION
2093
2094         Detach from the current attachee.
2095
2096         If signal is non-zero, the attachee is started running again and sent
2097         the specified signal.
2098
2099         If signal is zero and the attachee was not already stopped when we
2100         attached to it, then we make it runnable again when we detach.
2101
2102         Otherwise, we query whether or not to make the attachee runnable
2103         again, since we may simply want to leave it in the state it was in
2104         when we attached.
2105
2106         We report any problems, but do not consider them errors, since we
2107         MUST detach even if some things don't seem to go right.  This may not
2108         be the ideal situation.  (FIXME).
2109  */
2110
2111 static void
2112 do_detach (signal)
2113      int signal;
2114 {
2115   int result;
2116   struct procinfo *pi;
2117
2118   pi = current_procinfo;
2119
2120   if (signal)
2121     {
2122       set_proc_siginfo (pi, signal);
2123     }
2124   if (ioctl (pi->fd, PIOCSEXIT, &pi->saved_exitset) < 0)
2125     {
2126       print_sys_errmsg (pi->pathname, errno);
2127       printf_unfiltered ("PIOCSEXIT failed.\n");
2128     }
2129   if (ioctl (pi->fd, PIOCSENTRY, &pi->saved_entryset) < 0)
2130     {
2131       print_sys_errmsg (pi->pathname, errno);
2132       printf_unfiltered ("PIOCSENTRY failed.\n");
2133     }
2134   if (ioctl (pi->fd, PIOCSTRACE, &pi->saved_trace) < 0)
2135     {
2136       print_sys_errmsg (pi->pathname, errno);
2137       printf_unfiltered ("PIOCSTRACE failed.\n");
2138     }
2139   if (ioctl (pi->fd, PIOCSHOLD, &pi->saved_sighold) < 0)
2140     {
2141       print_sys_errmsg (pi->pathname, errno);
2142       printf_unfiltered ("PIOSCHOLD failed.\n");
2143     }
2144   if (ioctl (pi->fd, PIOCSFAULT, &pi->saved_fltset) < 0)
2145     {
2146       print_sys_errmsg (pi->pathname, errno);
2147       printf_unfiltered ("PIOCSFAULT failed.\n");
2148     }
2149   if (ioctl (pi->fd, PIOCSTATUS, &pi->prstatus) < 0)
2150     {
2151       print_sys_errmsg (pi->pathname, errno);
2152       printf_unfiltered ("PIOCSTATUS failed.\n");
2153     }
2154   else
2155     {
2156       if (signal || (pi->prstatus.pr_flags & (PR_STOPPED | PR_ISTOP)))
2157         {
2158           if (signal || !pi->was_stopped ||
2159               query ("Was stopped when attached, make it runnable again? "))
2160             {
2161               /* Clear any pending signal if we want to detach without
2162                  a signal.  */
2163               if (signal == 0)
2164                 set_proc_siginfo (pi, signal);
2165
2166               /* Clear any fault that might have stopped it.  */
2167               if (ioctl (pi->fd, PIOCCFAULT, 0))
2168                 {
2169                   print_sys_errmsg (pi->pathname, errno);
2170                   printf_unfiltered ("PIOCCFAULT failed.\n");
2171                 }
2172
2173               /* Make it run again when we close it.  */
2174 #if defined (PIOCSET)           /* New method */
2175               {
2176                 long pr_flags;
2177                 pr_flags = PR_RLC;
2178                 result = ioctl (pi->fd, PIOCSET, &pr_flags);
2179               }
2180 #else
2181 #if defined (PIOCSRLC)          /* Original method */
2182               result = ioctl (pi->fd, PIOCSRLC, 0);
2183 #endif
2184 #endif
2185               if (result)
2186                 {
2187                   print_sys_errmsg (pi->pathname, errno);
2188                   printf_unfiltered ("PIOCSRLC or PIOCSET failed.\n");
2189                 }
2190             }
2191         }
2192     }
2193   close_proc_file (pi);
2194   attach_flag = 0;
2195 }
2196
2197 /*  emulate wait() as much as possible.
2198     Wait for child to do something.  Return pid of child, or -1 in case
2199     of error; store status in *OURSTATUS.
2200
2201     Not sure why we can't
2202     just use wait(), but it seems to have problems when applied to a
2203     process being controlled with the /proc interface.
2204
2205     We have a race problem here with no obvious solution.  We need to let
2206     the inferior run until it stops on an event of interest, which means
2207     that we need to use the PIOCWSTOP ioctl.  However, we cannot use this
2208     ioctl if the process is already stopped on something that is not an
2209     event of interest, or the call will hang indefinitely.  Thus we first
2210     use PIOCSTATUS to see if the process is not stopped.  If not, then we
2211     use PIOCWSTOP.  But during the window between the two, if the process
2212     stops for any reason that is not an event of interest (such as a job
2213     control signal) then gdb will hang.  One possible workaround is to set
2214     an alarm to wake up every minute of so and check to see if the process
2215     is still running, and if so, then reissue the PIOCWSTOP.  But this is
2216     a real kludge, so has not been implemented.  FIXME: investigate
2217     alternatives.
2218
2219     FIXME:  Investigate why wait() seems to have problems with programs
2220     being control by /proc routines.  */
2221
2222 static int
2223 procfs_wait (pid, ourstatus)
2224      int pid;
2225      struct target_waitstatus *ourstatus;
2226 {
2227   short what;
2228   short why;
2229   int statval = 0;
2230   int checkerr = 0;
2231   int rtnval = -1;
2232   struct procinfo *pi;
2233
2234   if (pid != -1)                /* Non-specific process? */
2235     pi = NULL;
2236   else
2237     for (pi = procinfo_list; pi; pi = pi->next)
2238       if (pi->had_event)
2239         break;
2240
2241   if (!pi)
2242     {
2243     wait_again:
2244
2245       pi = wait_fd ();
2246     }
2247
2248   if (pid != -1)
2249     for (pi = procinfo_list; pi; pi = pi->next)
2250       if (pi->pid == pid && pi->had_event)
2251         break;
2252
2253   if (!pi && !checkerr)
2254     goto wait_again;
2255
2256   if (!checkerr && !(pi->prstatus.pr_flags & (PR_STOPPED | PR_ISTOP)))
2257     {
2258       if (ioctl (pi->fd, PIOCWSTOP, &pi->prstatus) < 0)
2259         {
2260           checkerr++;
2261         }
2262     }    
2263   if (checkerr)
2264     {
2265       if (errno == ENOENT)
2266         {
2267           rtnval = wait (&statval);
2268           if (rtnval != inferior_pid)
2269             {
2270               print_sys_errmsg (pi->pathname, errno);
2271               error ("PIOCWSTOP, wait failed, returned %d", rtnval);
2272               /* NOTREACHED */
2273             }
2274         }
2275       else
2276         {
2277           print_sys_errmsg (pi->pathname, errno);
2278           error ("PIOCSTATUS or PIOCWSTOP failed.");
2279           /* NOTREACHED */
2280         }
2281     }
2282   else if (pi->prstatus.pr_flags & (PR_STOPPED | PR_ISTOP))
2283     {
2284       rtnval = pi->prstatus.pr_pid;
2285       why = pi->prstatus.pr_why;
2286       what = pi->prstatus.pr_what;
2287
2288       switch (why)
2289         {
2290         case PR_SIGNALLED:
2291           statval = (what << 8) | 0177;
2292           break;
2293         case PR_SYSENTRY:
2294           if (what != SYS_exit)
2295             error ("PR_SYSENTRY, unknown system call %d", what);
2296
2297           pi->prrun.pr_flags = PRCFAULT;
2298
2299           if (ioctl (pi->fd, PIOCRUN, &pi->prrun) != 0)
2300             perror_with_name (pi->pathname);
2301
2302           rtnval = wait (&statval);
2303
2304           break;
2305         case PR_SYSEXIT:
2306           switch (what)
2307             {
2308 #ifdef SYS_exec
2309             case SYS_exec:
2310 #endif
2311 #ifdef SYS_execve
2312             case SYS_execve:
2313 #endif
2314 #ifdef SYS_execv
2315             case SYS_execv:
2316 #endif
2317               statval = (SIGTRAP << 8) | 0177;
2318               break;
2319 #ifdef SYS_sproc
2320             case SYS_sproc:
2321 /* We've just detected the completion of an sproc system call.  Now we need to
2322    setup a procinfo struct for this thread, and notify the thread system of the
2323    new arrival.  */
2324
2325 /* If sproc failed, then nothing interesting happened.  Continue the process and
2326    go back to sleep. */
2327
2328               if (pi->prstatus.pr_errno != 0)
2329                 {
2330                   pi->prrun.pr_flags &= PRSTEP;
2331                   pi->prrun.pr_flags |= PRCFAULT;
2332
2333                   if (ioctl (pi->fd, PIOCRUN, &pi->prrun) != 0)
2334                     perror_with_name (pi->pathname);
2335
2336                   goto wait_again;
2337                 }
2338
2339 /* At this point, the new thread is stopped at it's first instruction, and
2340    the parent is stopped at the exit from sproc.  */
2341
2342 /* Notify the caller of the arrival of a new thread. */
2343               create_procinfo (pi->prstatus.pr_rval1);
2344
2345               rtnval = pi->prstatus.pr_rval1;
2346               statval = (SIGTRAP << 8) | 0177;
2347
2348               break;
2349             case SYS_fork:
2350 #ifdef SYS_vfork
2351             case SYS_vfork:
2352 #endif
2353 /* At this point, we've detected the completion of a fork (or vfork) call in
2354    our child.  The grandchild is also stopped because we set inherit-on-fork
2355    earlier.  (Note that nobody has the grandchilds' /proc file open at this
2356    point.)  We will release the grandchild from the debugger by opening it's
2357    /proc file and then closing it.  Since run-on-last-close is set, the
2358    grandchild continues on its' merry way.  */
2359
2360               {
2361                 struct procinfo *pitemp;
2362
2363                 pitemp = create_procinfo (pi->prstatus.pr_rval1);
2364                 if (pitemp)
2365                   close_proc_file (pitemp);
2366
2367                 if (ioctl (pi->fd, PIOCRUN, &pi->prrun) != 0)
2368                   perror_with_name (pi->pathname);
2369               }
2370               goto wait_again;
2371 #endif /* SYS_sproc */
2372
2373             default:
2374               error ("PIOCSTATUS (PR_SYSEXIT):  Unknown system call %d", what); 
2375             }
2376           break;
2377         case PR_REQUESTED:
2378           statval = (SIGSTOP << 8) | 0177;
2379           break;
2380         case PR_JOBCONTROL:
2381           statval = (what << 8) | 0177;
2382           break;
2383         case PR_FAULTED:
2384           switch (what)
2385             {
2386 #ifdef FLTWATCH
2387             case FLTWATCH:
2388               statval = (SIGTRAP << 8) | 0177;
2389               break;
2390 #endif
2391 #ifdef FLTKWATCH
2392             case FLTKWATCH:
2393               statval = (SIGTRAP << 8) | 0177;
2394               break;
2395 #endif
2396 #ifndef FAULTED_USE_SIGINFO
2397               /* Irix, contrary to the documentation, fills in 0 for si_signo.
2398                  Solaris fills in si_signo.  I'm not sure about others.  */
2399             case FLTPRIV:
2400             case FLTILL:
2401               statval = (SIGILL << 8) | 0177;
2402               break;
2403             case FLTBPT:
2404             case FLTTRACE:
2405               statval = (SIGTRAP << 8) | 0177;
2406               break;          
2407             case FLTSTACK:
2408             case FLTACCESS:
2409             case FLTBOUNDS:
2410               statval = (SIGSEGV << 8) | 0177;
2411               break;
2412             case FLTIOVF:
2413             case FLTIZDIV:
2414             case FLTFPE:
2415               statval = (SIGFPE << 8) | 0177;
2416               break;
2417             case FLTPAGE:               /* Recoverable page fault */
2418 #endif /* not FAULTED_USE_SIGINFO */
2419             default:
2420               /* Use the signal which the kernel assigns.  This is better than
2421                  trying to second-guess it from the fault.  In fact, I suspect
2422                  that FLTACCESS can be either SIGSEGV or SIGBUS.  */
2423               statval = ((pi->prstatus.pr_info.si_signo) << 8) | 0177;
2424               break;
2425             }
2426           break;
2427         default:
2428           error ("PIOCWSTOP, unknown why %d, what %d", why, what);
2429         }
2430 /* Stop all the other threads when any of them stops.  */
2431
2432       {
2433         struct procinfo *procinfo;
2434
2435         for (procinfo = procinfo_list; procinfo; procinfo = procinfo->next)
2436           {
2437             if (!procinfo->had_event)
2438               if (ioctl (procinfo->fd, PIOCSTOP, &procinfo->prstatus) < 0)
2439                 {
2440                   print_sys_errmsg (procinfo->pathname, errno);
2441                   error ("PIOCSTOP failed");
2442                 }
2443           }
2444       }
2445     }
2446   else
2447     {
2448       error ("PIOCWSTOP, stopped for unknown/unhandled reason, flags %#x", 
2449              pi->prstatus.pr_flags);
2450     }
2451
2452   store_waitstatus (ourstatus, statval);
2453
2454   if (rtnval == -1)             /* No more children to wait for */
2455     {
2456       fprintf_unfiltered (gdb_stderr, "Child process unexpectedly missing.\n");
2457       /* Claim it exited with unknown signal.  */
2458       ourstatus->kind = TARGET_WAITKIND_SIGNALLED;
2459       ourstatus->value.sig = TARGET_SIGNAL_UNKNOWN;
2460       return rtnval;
2461     }
2462
2463   pi->had_event = 0;            /* Indicate that we've seen this one */
2464   return (rtnval);
2465 }
2466
2467 /*
2468
2469 LOCAL FUNCTION
2470
2471         set_proc_siginfo - set a process's current signal info
2472
2473 SYNOPSIS
2474
2475         void set_proc_siginfo (struct procinfo *pip, int signo);
2476
2477 DESCRIPTION
2478
2479         Given a pointer to a process info struct in PIP and a signal number
2480         in SIGNO, set the process's current signal and its associated signal
2481         information.  The signal will be delivered to the process immediately
2482         after execution is resumed, even if it is being held.  In addition,
2483         this particular delivery will not cause another PR_SIGNALLED stop
2484         even if the signal is being traced.
2485
2486         If we are not delivering the same signal that the prstatus siginfo
2487         struct contains information about, then synthesize a siginfo struct
2488         to match the signal we are doing to deliver, make it of the type
2489         "generated by a user process", and send this synthesized copy.  When
2490         used to set the inferior's signal state, this will be required if we
2491         are not currently stopped because of a traced signal, or if we decide
2492         to continue with a different signal.
2493
2494         Note that when continuing the inferior from a stop due to receipt
2495         of a traced signal, we either have set PRCSIG to clear the existing
2496         signal, or we have to call this function to do a PIOCSSIG with either
2497         the existing siginfo struct from pr_info, or one we have synthesized
2498         appropriately for the signal we want to deliver.  Otherwise if the
2499         signal is still being traced, the inferior will immediately stop
2500         again.
2501
2502         See siginfo(5) for more details.
2503 */
2504
2505 static void
2506 set_proc_siginfo (pip, signo)
2507      struct procinfo *pip;
2508      int signo;
2509 {
2510   struct siginfo newsiginfo;
2511   struct siginfo *sip;
2512
2513 #ifdef PROCFS_DONT_PIOCSSIG_CURSIG
2514   /* With Alpha OSF/1 procfs, the kernel gets really confused if it
2515      receives a PIOCSSIG with a signal identical to the current signal,
2516      it messes up the current signal. Work around the kernel bug.  */
2517   if (signo == pip -> prstatus.pr_cursig)
2518     return;
2519 #endif
2520
2521   if (signo == pip -> prstatus.pr_info.si_signo)
2522     {
2523       sip = &pip -> prstatus.pr_info;
2524     }
2525   else
2526     {
2527       memset ((char *) &newsiginfo, 0, sizeof (newsiginfo));
2528       sip = &newsiginfo;
2529       sip -> si_signo = signo;
2530       sip -> si_code = 0;
2531       sip -> si_errno = 0;
2532       sip -> si_pid = getpid ();
2533       sip -> si_uid = getuid ();
2534     }
2535   if (ioctl (pip -> fd, PIOCSSIG, sip) < 0)
2536     {
2537       print_sys_errmsg (pip -> pathname, errno);
2538       warning ("PIOCSSIG failed");
2539     }
2540 }
2541
2542 /* Resume execution of process PID.  If STEP is nozero, then
2543    just single step it.  If SIGNAL is nonzero, restart it with that
2544    signal activated.  */
2545
2546 static void
2547 procfs_resume (pid, step, signo)
2548      int pid;
2549      int step;
2550      enum target_signal signo;
2551 {
2552   int signal_to_pass;
2553   struct procinfo *pi, *procinfo;
2554
2555   pi = find_procinfo (pid == -1 ? inferior_pid : pid, 0);
2556
2557   errno = 0;
2558   pi->prrun.pr_flags = PRSTRACE | PRSFAULT | PRCFAULT;
2559
2560 #if 0
2561   /* It should not be necessary.  If the user explicitly changes the value,
2562      value_assign calls write_register_bytes, which writes it.  */
2563 /*      It may not be absolutely necessary to specify the PC value for
2564         restarting, but to be safe we use the value that gdb considers
2565         to be current.  One case where this might be necessary is if the
2566         user explicitly changes the PC value that gdb considers to be
2567         current.  FIXME:  Investigate if this is necessary or not.  */
2568
2569 #ifdef PRSVADDR_BROKEN
2570 /* Can't do this under Solaris running on a Sparc, as there seems to be no
2571    place to put nPC.  In fact, if you use this, nPC seems to be set to some
2572    random garbage.  We have to rely on the fact that PC and nPC have been
2573    written previously via PIOCSREG during a register flush. */
2574
2575   pi->prrun.pr_vaddr = (caddr_t) *(int *) &registers[REGISTER_BYTE (PC_REGNUM)];
2576   pi->prrun.pr_flags != PRSVADDR;
2577 #endif
2578 #endif
2579
2580   if (signo == TARGET_SIGNAL_STOP && pi->nopass_next_sigstop)
2581     /* When attaching to a child process, if we forced it to stop with
2582        a PIOCSTOP, then we will have set the nopass_next_sigstop flag.
2583        Upon resuming the first time after such a stop, we explicitly
2584        inhibit sending it another SIGSTOP, which would be the normal
2585        result of default signal handling.  One potential drawback to
2586        this is that we will also ignore any attempt to by the user
2587        to explicitly continue after the attach with a SIGSTOP.  Ultimately
2588        this problem should be dealt with by making the routines that
2589        deal with the inferior a little smarter, and possibly even allow
2590        an inferior to continue running at the same time as gdb.  (FIXME?)  */
2591     signal_to_pass = 0;
2592   else if (signo == TARGET_SIGNAL_TSTP
2593            && pi->prstatus.pr_cursig == SIGTSTP
2594            && pi->prstatus.pr_action.sa_handler == SIG_DFL)
2595
2596     /* We are about to pass the inferior a SIGTSTP whose action is
2597        SIG_DFL.  The SIG_DFL action for a SIGTSTP is to stop
2598        (notifying the parent via wait()), and then keep going from the
2599        same place when the parent is ready for you to keep going.  So
2600        under the debugger, it should do nothing (as if the program had
2601        been stopped and then later resumed.  Under ptrace, this
2602        happens for us, but under /proc, the system obligingly stops
2603        the process, and wait_for_inferior would have no way of
2604        distinguishing that type of stop (which indicates that we
2605        should just start it again), with a stop due to the pr_trace
2606        field of the prrun_t struct.
2607
2608        Note that if the SIGTSTP is being caught, we *do* need to pass it,
2609        because the handler needs to get executed.  */
2610     signal_to_pass = 0;
2611   else
2612     signal_to_pass = target_signal_to_host (signo);
2613
2614   if (signal_to_pass)
2615     {
2616       set_proc_siginfo (pi, signal_to_pass);
2617     }
2618   else
2619     {
2620       pi->prrun.pr_flags |= PRCSIG;
2621     }
2622   pi->nopass_next_sigstop = 0;
2623   if (step)
2624     {
2625       pi->prrun.pr_flags |= PRSTEP;
2626     }
2627   if (ioctl (pi->fd, PIOCRUN, &pi->prrun) != 0)
2628     {
2629       perror_with_name (pi->pathname);
2630       /* NOTREACHED */
2631     }
2632
2633   pi->had_event = 0;
2634
2635   /* Continue all the other threads that haven't had an event of
2636      interest.  */
2637
2638   if (pid == -1)
2639     for (procinfo = procinfo_list; procinfo; procinfo = procinfo->next)
2640       {
2641         if (pi != procinfo && !procinfo->had_event)
2642           {
2643             procinfo->prrun.pr_flags &= PRSTEP;
2644             procinfo->prrun.pr_flags |= PRCFAULT | PRCSIG;
2645             ioctl (procinfo->fd, PIOCSTATUS, &procinfo->prstatus);
2646             if (ioctl (procinfo->fd, PIOCRUN, &procinfo->prrun) < 0)
2647               {
2648                 if (ioctl (procinfo->fd, PIOCSTATUS, &procinfo->prstatus) < 0)
2649                   {
2650                     fprintf_unfiltered(gdb_stderr, "PIOCSTATUS failed, errno=%d\n", errno);
2651                   }
2652                 print_sys_errmsg (procinfo->pathname, errno);
2653                 error ("PIOCRUN failed");
2654               }
2655             ioctl (procinfo->fd, PIOCSTATUS, &procinfo->prstatus);
2656           }
2657       }
2658 }
2659
2660 /*
2661
2662 LOCAL FUNCTION
2663
2664         procfs_fetch_registers -- fetch current registers from inferior
2665
2666 SYNOPSIS
2667
2668         void procfs_fetch_registers (int regno)
2669
2670 DESCRIPTION
2671
2672         Read the current values of the inferior's registers, both the
2673         general register set and floating point registers (if supported)
2674         and update gdb's idea of their current values.
2675
2676 */
2677
2678 static void
2679 procfs_fetch_registers (regno)
2680      int regno;
2681 {
2682   struct procinfo *pi;
2683
2684   pi = current_procinfo;
2685
2686   if (ioctl (pi->fd, PIOCGREG, &pi->gregset) != -1)
2687     {
2688       supply_gregset (&pi->gregset);
2689     }
2690 #if defined (FP0_REGNUM)
2691   if (ioctl (pi->fd, PIOCGFPREG, &pi->fpregset) != -1)
2692     {
2693       supply_fpregset (&pi->fpregset);
2694     }
2695 #endif
2696 }
2697
2698 /*
2699
2700 LOCAL FUNCTION
2701
2702         proc_init_failed - called whenever /proc access initialization
2703 fails
2704
2705 SYNOPSIS
2706
2707         static void proc_init_failed (struct procinfo *pi, char *why)
2708
2709 DESCRIPTION
2710
2711         This function is called whenever initialization of access to a /proc
2712         entry fails.  It prints a suitable error message, does some cleanup,
2713         and then invokes the standard error processing routine which dumps
2714         us back into the command loop.
2715  */
2716
2717 static void
2718 proc_init_failed (pi, why)
2719      struct procinfo *pi;
2720      char *why;
2721 {
2722   print_sys_errmsg (pi->pathname, errno);
2723   kill (pi->pid, SIGKILL);
2724   close_proc_file (pi);
2725   error (why);
2726   /* NOTREACHED */
2727 }
2728
2729 /*
2730
2731 LOCAL FUNCTION
2732
2733         close_proc_file - close any currently open /proc entry
2734
2735 SYNOPSIS
2736
2737         static void close_proc_file (struct procinfo *pip)
2738
2739 DESCRIPTION
2740
2741         Close any currently open /proc entry and mark the process information
2742         entry as invalid.  In order to ensure that we don't try to reuse any
2743         stale information, the pid, fd, and pathnames are explicitly
2744         invalidated, which may be overkill.
2745
2746  */
2747
2748 static void
2749 close_proc_file (pip)
2750      struct procinfo *pip;
2751 {
2752   struct procinfo *procinfo;
2753
2754   remove_fd (pip);              /* Remove fd from poll/select list */
2755
2756   close (pip -> fd);
2757
2758   free (pip -> pathname);
2759
2760   /* Unlink pip from the procinfo chain.  Note pip might not be on the list. */
2761
2762   if (procinfo_list == pip)
2763     procinfo_list = pip->next;
2764   else
2765     for (procinfo = procinfo_list; procinfo; procinfo = procinfo->next)
2766       if (procinfo->next == pip)
2767         procinfo->next = pip->next;
2768
2769   free (pip);
2770 }
2771
2772 /*
2773
2774 LOCAL FUNCTION
2775
2776         open_proc_file - open a /proc entry for a given process id
2777
2778 SYNOPSIS
2779
2780         static int open_proc_file (int pid, struct procinfo *pip, int mode)
2781
2782 DESCRIPTION
2783
2784         Given a process id and a mode, close the existing open /proc
2785         entry (if any) and open one for the new process id, in the
2786         specified mode.  Once it is open, then mark the local process
2787         information structure as valid, which guarantees that the pid,
2788         fd, and pathname fields match an open /proc entry.  Returns
2789         zero if the open fails, nonzero otherwise.
2790
2791         Note that the pathname is left intact, even when the open fails,
2792         so that callers can use it to construct meaningful error messages
2793         rather than just "file open failed".
2794  */
2795
2796 static int
2797 open_proc_file (pid, pip, mode)
2798      int pid;
2799      struct procinfo *pip;
2800      int mode;
2801 {
2802   pip -> next = NULL;
2803   pip -> had_event = 0;
2804   pip -> pathname = xmalloc (32);
2805   pip -> pid = pid;
2806
2807   sprintf (pip -> pathname, PROC_NAME_FMT, pid);
2808   if ((pip -> fd = open (pip -> pathname, mode)) < 0)
2809     return 0;
2810
2811   return 1;
2812 }
2813
2814 static char *
2815 mappingflags (flags)
2816      long flags;
2817 {
2818   static char asciiflags[8];
2819   
2820   strcpy (asciiflags, "-------");
2821 #if defined (MA_PHYS)
2822   if (flags & MA_PHYS)   asciiflags[0] = 'd';
2823 #endif
2824   if (flags & MA_STACK)  asciiflags[1] = 's';
2825   if (flags & MA_BREAK)  asciiflags[2] = 'b';
2826   if (flags & MA_SHARED) asciiflags[3] = 's';
2827   if (flags & MA_READ)   asciiflags[4] = 'r';
2828   if (flags & MA_WRITE)  asciiflags[5] = 'w';
2829   if (flags & MA_EXEC)   asciiflags[6] = 'x';
2830   return (asciiflags);
2831 }
2832
2833 static void
2834 info_proc_flags (pip, summary)
2835      struct procinfo *pip;
2836      int summary;
2837 {
2838   struct trans *transp;
2839
2840   printf_filtered ("%-32s", "Process status flags:");
2841   if (!summary)
2842     {
2843       printf_filtered ("\n\n");
2844     }
2845   for (transp = pr_flag_table; transp -> name != NULL; transp++)
2846     {
2847       if (pip -> prstatus.pr_flags & transp -> value)
2848         {
2849           if (summary)
2850             {
2851               printf_filtered ("%s ", transp -> name);
2852             }
2853           else
2854             {
2855               printf_filtered ("\t%-16s %s.\n", transp -> name, transp -> desc);
2856             }
2857         }
2858     }
2859   printf_filtered ("\n");
2860 }
2861
2862 static void
2863 info_proc_stop (pip, summary)
2864      struct procinfo *pip;
2865      int summary;
2866 {
2867   struct trans *transp;
2868   int why;
2869   int what;
2870
2871   why = pip -> prstatus.pr_why;
2872   what = pip -> prstatus.pr_what;
2873
2874   if (pip -> prstatus.pr_flags & PR_STOPPED)
2875     {
2876       printf_filtered ("%-32s", "Reason for stopping:");
2877       if (!summary)
2878         {
2879           printf_filtered ("\n\n");
2880         }
2881       for (transp = pr_why_table; transp -> name != NULL; transp++)
2882         {
2883           if (why == transp -> value)
2884             {
2885               if (summary)
2886                 {
2887                   printf_filtered ("%s ", transp -> name);
2888                 }
2889               else
2890                 {
2891                   printf_filtered ("\t%-16s %s.\n",
2892                                    transp -> name, transp -> desc);
2893                 }
2894               break;
2895             }
2896         }
2897       
2898       /* Use the pr_why field to determine what the pr_what field means, and
2899          print more information. */
2900       
2901       switch (why)
2902         {
2903           case PR_REQUESTED:
2904             /* pr_what is unused for this case */
2905             break;
2906           case PR_JOBCONTROL:
2907           case PR_SIGNALLED:
2908             if (summary)
2909               {
2910                 printf_filtered ("%s ", signalname (what));
2911               }
2912             else
2913               {
2914                 printf_filtered ("\t%-16s %s.\n", signalname (what),
2915                                  safe_strsignal (what));
2916               }
2917             break;
2918           case PR_SYSENTRY:
2919             if (summary)
2920               {
2921                 printf_filtered ("%s ", syscallname (what));
2922               }
2923             else
2924               {
2925                 printf_filtered ("\t%-16s %s.\n", syscallname (what),
2926                                  "Entered this system call");
2927               }
2928             break;
2929           case PR_SYSEXIT:
2930             if (summary)
2931               {
2932                 printf_filtered ("%s ", syscallname (what));
2933               }
2934             else
2935               {
2936                 printf_filtered ("\t%-16s %s.\n", syscallname (what),
2937                                  "Returned from this system call");
2938               }
2939             break;
2940           case PR_FAULTED:
2941             if (summary)
2942               {
2943                 printf_filtered ("%s ",
2944                                  lookupname (faults_table, what, "fault"));
2945               }
2946             else
2947               {
2948                 printf_filtered ("\t%-16s %s.\n",
2949                                  lookupname (faults_table, what, "fault"),
2950                                  lookupdesc (faults_table, what));
2951               }
2952             break;
2953           }
2954       printf_filtered ("\n");
2955     }
2956 }
2957
2958 static void
2959 info_proc_siginfo (pip, summary)
2960      struct procinfo *pip;
2961      int summary;
2962 {
2963   struct siginfo *sip;
2964
2965   if ((pip -> prstatus.pr_flags & PR_STOPPED) &&
2966       (pip -> prstatus.pr_why == PR_SIGNALLED ||
2967        pip -> prstatus.pr_why == PR_FAULTED))
2968     {
2969       printf_filtered ("%-32s", "Additional signal/fault info:");
2970       sip = &pip -> prstatus.pr_info;
2971       if (summary)
2972         {
2973           printf_filtered ("%s ", signalname (sip -> si_signo));
2974           if (sip -> si_errno > 0)
2975             {
2976               printf_filtered ("%s ", errnoname (sip -> si_errno));
2977             }
2978           if (sip -> si_code <= 0)
2979             {
2980               printf_filtered ("sent by %s, uid %d ",
2981                                target_pid_to_str (sip -> si_pid),
2982                                sip -> si_uid);
2983             }
2984           else
2985             {
2986               printf_filtered ("%s ", sigcodename (sip));
2987               if ((sip -> si_signo == SIGILL) ||
2988                   (sip -> si_signo == SIGFPE) ||
2989                   (sip -> si_signo == SIGSEGV) ||
2990                   (sip -> si_signo == SIGBUS))
2991                 {
2992                   printf_filtered ("addr=%#lx ",
2993                                    (unsigned long) sip -> si_addr);
2994                 }
2995               else if ((sip -> si_signo == SIGCHLD))
2996                 {
2997                   printf_filtered ("child %s, status %u ",
2998                                    target_pid_to_str (sip -> si_pid),
2999                                    sip -> si_status);
3000                 }
3001               else if ((sip -> si_signo == SIGPOLL))
3002                 {
3003                   printf_filtered ("band %u ", sip -> si_band);
3004                 }
3005             }
3006         }
3007       else
3008         {
3009           printf_filtered ("\n\n");
3010           printf_filtered ("\t%-16s %s.\n", signalname (sip -> si_signo),
3011                            safe_strsignal (sip -> si_signo));
3012           if (sip -> si_errno > 0)
3013             {
3014               printf_filtered ("\t%-16s %s.\n",
3015                                errnoname (sip -> si_errno),
3016                                safe_strerror (sip -> si_errno));
3017             }
3018           if (sip -> si_code <= 0)
3019             {
3020               printf_filtered ("\t%-16u %s\n", sip -> si_pid, /* XXX need target_pid_to_str() */
3021                                "PID of process sending signal");
3022               printf_filtered ("\t%-16u %s\n", sip -> si_uid,
3023                                "UID of process sending signal");
3024             }
3025           else
3026             {
3027               printf_filtered ("\t%-16s %s.\n", sigcodename (sip),
3028                                sigcodedesc (sip));
3029               if ((sip -> si_signo == SIGILL) ||
3030                   (sip -> si_signo == SIGFPE))
3031                 {
3032                   printf_filtered ("\t%#-16lx %s.\n",
3033                                    (unsigned long) sip -> si_addr,
3034                                    "Address of faulting instruction");
3035                 }
3036               else if ((sip -> si_signo == SIGSEGV) ||
3037                        (sip -> si_signo == SIGBUS))
3038                 {
3039                   printf_filtered ("\t%#-16lx %s.\n",
3040                                    (unsigned long) sip -> si_addr,
3041                                    "Address of faulting memory reference");
3042                 }
3043               else if ((sip -> si_signo == SIGCHLD))
3044                 {
3045                   printf_filtered ("\t%-16u %s.\n", sip -> si_pid, /* XXX need target_pid_to_str() */
3046                                    "Child process ID");
3047                   printf_filtered ("\t%-16u %s.\n", sip -> si_status,
3048                                    "Child process exit value or signal");
3049                 }
3050               else if ((sip -> si_signo == SIGPOLL))
3051                 {
3052                   printf_filtered ("\t%-16u %s.\n", sip -> si_band,
3053                                    "Band event for POLL_{IN,OUT,MSG}");
3054                 }
3055             }
3056         }
3057       printf_filtered ("\n");
3058     }
3059 }
3060
3061 static void
3062 info_proc_syscalls (pip, summary)
3063      struct procinfo *pip;
3064      int summary;
3065 {
3066   int syscallnum;
3067
3068   if (!summary)
3069     {
3070
3071 #if 0   /* FIXME:  Needs to use gdb-wide configured info about system calls. */
3072       if (pip -> prstatus.pr_flags & PR_ASLEEP)
3073         {
3074           int syscallnum = pip -> prstatus.pr_reg[R_D0];
3075           if (summary)
3076             {
3077               printf_filtered ("%-32s", "Sleeping in system call:");
3078               printf_filtered ("%s", syscallname (syscallnum));
3079             }
3080           else
3081             {
3082               printf_filtered ("Sleeping in system call '%s'.\n",
3083                                syscallname (syscallnum));
3084             }
3085         }
3086 #endif
3087
3088       if (ioctl (pip -> fd, PIOCGENTRY, &pip -> entryset) < 0)
3089         {
3090           print_sys_errmsg (pip -> pathname, errno);
3091           error ("PIOCGENTRY failed");
3092         }
3093       
3094       if (ioctl (pip -> fd, PIOCGEXIT, &pip -> exitset) < 0)
3095         {
3096           print_sys_errmsg (pip -> pathname, errno);
3097           error ("PIOCGEXIT failed");
3098         }
3099       
3100       printf_filtered ("System call tracing information:\n\n");
3101       
3102       printf_filtered ("\t%-12s %-8s %-8s\n",
3103                        "System call",
3104                        "Entry",
3105                        "Exit");
3106       for (syscallnum = 0; syscallnum < MAX_SYSCALLS; syscallnum++)
3107         {
3108           QUIT;
3109           if (syscall_table[syscallnum] != NULL)
3110             {
3111               printf_filtered ("\t%-12s ", syscall_table[syscallnum]);
3112               printf_filtered ("%-8s ",
3113                                prismember (&pip -> entryset, syscallnum)
3114                                ? "on" : "off");
3115               printf_filtered ("%-8s ",
3116                                prismember (&pip -> exitset, syscallnum)
3117                                ? "on" : "off");
3118               printf_filtered ("\n");
3119             }
3120           }
3121       printf_filtered ("\n");
3122     }
3123 }
3124
3125 static char *
3126 signalname (signo)
3127      int signo;
3128 {
3129   const char *name;
3130   static char locbuf[32];
3131
3132   name = strsigno (signo);
3133   if (name == NULL)
3134     {
3135       sprintf (locbuf, "Signal %d", signo);
3136     }
3137   else
3138     {
3139       sprintf (locbuf, "%s (%d)", name, signo);
3140     }
3141   return (locbuf);
3142 }
3143
3144 static char *
3145 errnoname (errnum)
3146      int errnum;
3147 {
3148   const char *name;
3149   static char locbuf[32];
3150
3151   name = strerrno (errnum);
3152   if (name == NULL)
3153     {
3154       sprintf (locbuf, "Errno %d", errnum);
3155     }
3156   else
3157     {
3158       sprintf (locbuf, "%s (%d)", name, errnum);
3159     }
3160   return (locbuf);
3161 }
3162
3163 static void
3164 info_proc_signals (pip, summary)
3165      struct procinfo *pip;
3166      int summary;
3167 {
3168   int signo;
3169
3170   if (!summary)
3171     {
3172       if (ioctl (pip -> fd, PIOCGTRACE, &pip -> trace) < 0)
3173         {
3174           print_sys_errmsg (pip -> pathname, errno);
3175           error ("PIOCGTRACE failed");
3176         }
3177       
3178       printf_filtered ("Disposition of signals:\n\n");
3179       printf_filtered ("\t%-15s %-8s %-8s %-8s  %s\n\n",
3180                        "Signal", "Trace", "Hold", "Pending", "Description");
3181       for (signo = 0; signo < NSIG; signo++)
3182         {
3183           QUIT;
3184           printf_filtered ("\t%-15s ", signalname (signo));
3185           printf_filtered ("%-8s ",
3186                            prismember (&pip -> trace, signo)
3187                            ? "on" : "off");
3188           printf_filtered ("%-8s ",
3189                            prismember (&pip -> prstatus.pr_sighold, signo)
3190                            ? "on" : "off");
3191
3192 #ifdef PROCFS_SIGPEND_OFFSET
3193           /* Alpha OSF/1 numbers the pending signals from 1.  */
3194           printf_filtered ("%-8s ",
3195                            (signo ? prismember (&pip -> prstatus.pr_sigpend,
3196                                                 signo - 1)
3197                                   : 0)
3198                            ? "yes" : "no");
3199 #else
3200           printf_filtered ("%-8s ",
3201                            prismember (&pip -> prstatus.pr_sigpend, signo)
3202                            ? "yes" : "no");
3203 #endif
3204           printf_filtered (" %s\n", safe_strsignal (signo));
3205         }
3206       printf_filtered ("\n");
3207     }
3208 }
3209
3210 static void
3211 info_proc_faults (pip, summary)
3212      struct procinfo *pip;
3213      int summary;
3214 {
3215   struct trans *transp;
3216
3217   if (!summary)
3218     {
3219       if (ioctl (pip -> fd, PIOCGFAULT, &pip -> fltset) < 0)
3220         {
3221           print_sys_errmsg (pip -> pathname, errno);
3222           error ("PIOCGFAULT failed");
3223         }
3224       
3225       printf_filtered ("Current traced hardware fault set:\n\n");
3226       printf_filtered ("\t%-12s %-8s\n", "Fault", "Trace");
3227
3228       for (transp = faults_table; transp -> name != NULL; transp++)
3229         {
3230           QUIT;
3231           printf_filtered ("\t%-12s ", transp -> name);
3232           printf_filtered ("%-8s", prismember (&pip -> fltset, transp -> value)
3233                            ? "on" : "off");
3234           printf_filtered ("\n");
3235         }
3236       printf_filtered ("\n");
3237     }
3238 }
3239
3240 static void
3241 info_proc_mappings (pip, summary)
3242      struct procinfo *pip;
3243      int summary;
3244 {
3245   int nmap;
3246   struct prmap *prmaps;
3247   struct prmap *prmap;
3248
3249   if (!summary)
3250     {
3251       printf_filtered ("Mapped address spaces:\n\n");
3252 #ifdef BFD_HOST_64_BIT
3253       printf_filtered ("  %18s %18s %10s %10s %7s\n",
3254 #else
3255       printf_filtered ("\t%10s %10s %10s %10s %7s\n",
3256 #endif
3257                        "Start Addr",
3258                        "  End Addr",
3259                        "      Size",
3260                        "    Offset",
3261                        "Flags");
3262       if (ioctl (pip -> fd, PIOCNMAP, &nmap) == 0)
3263         {
3264           prmaps = (struct prmap *) alloca ((nmap + 1) * sizeof (*prmaps));
3265           if (ioctl (pip -> fd, PIOCMAP, prmaps) == 0)
3266             {
3267               for (prmap = prmaps; prmap -> pr_size; ++prmap)
3268                 {
3269 #ifdef BFD_HOST_64_BIT
3270                   printf_filtered ("  %#18lx %#18lx %#10x %#10x %7s\n",
3271 #else
3272                   printf_filtered ("\t%#10lx %#10lx %#10x %#10x %7s\n",
3273 #endif
3274                                    (unsigned long)prmap -> pr_vaddr,
3275                                    (unsigned long)prmap -> pr_vaddr
3276                                      + prmap -> pr_size - 1,
3277                                    prmap -> pr_size,
3278                                    prmap -> pr_off,
3279                                    mappingflags (prmap -> pr_mflags));
3280                 }
3281             }
3282         }
3283       printf_filtered ("\n");
3284     }
3285 }
3286
3287 /*
3288
3289 LOCAL FUNCTION
3290
3291         info_proc -- implement the "info proc" command
3292
3293 SYNOPSIS
3294
3295         void info_proc (char *args, int from_tty)
3296
3297 DESCRIPTION
3298
3299         Implement gdb's "info proc" command by using the /proc interface
3300         to print status information about any currently running process.
3301
3302         Examples of the use of "info proc" are:
3303
3304         info proc               (prints summary info for current inferior)
3305         info proc 123           (prints summary info for process with pid 123)
3306         info proc mappings      (prints address mappings)
3307         info proc times         (prints process/children times)
3308         info proc id            (prints pid, ppid, gid, sid, etc)
3309                 FIXME:  i proc id not implemented.
3310         info proc status        (prints general process state info)
3311                 FIXME:  i proc status not implemented.
3312         info proc signals       (prints info about signal handling)
3313         info proc all           (prints all info)
3314
3315  */
3316
3317 static void
3318 info_proc (args, from_tty)
3319      char *args;
3320      int from_tty;
3321 {
3322   int pid;
3323   struct procinfo *pip;
3324   struct cleanup *old_chain;
3325   char **argv;
3326   int argsize;
3327   int summary = 1;
3328   int flags = 0;
3329   int syscalls = 0;
3330   int signals = 0;
3331   int faults = 0;
3332   int mappings = 0;
3333   int times = 0;
3334   int id = 0;
3335   int status = 0;
3336   int all = 0;
3337
3338   old_chain = make_cleanup (null_cleanup, 0);
3339
3340   /* Default to using the current inferior if no pid specified.  Note
3341      that inferior_pid may be 0, hence we set okerr.  */
3342
3343   pip = find_procinfo (inferior_pid, 1);
3344
3345   if (args != NULL)
3346     {
3347       if ((argv = buildargv (args)) == NULL)
3348         {
3349           nomem (0);
3350         }
3351       make_cleanup (freeargv, (char *) argv);
3352
3353       while (*argv != NULL)
3354         {
3355           argsize = strlen (*argv);
3356           if (argsize >= 1 && strncmp (*argv, "all", argsize) == 0)
3357             {
3358               summary = 0;
3359               all = 1;
3360             }
3361           else if (argsize >= 2 && strncmp (*argv, "faults", argsize) == 0)
3362             {
3363               summary = 0;
3364               faults = 1;
3365             }
3366           else if (argsize >= 2 && strncmp (*argv, "flags", argsize) == 0)
3367             {
3368               summary = 0;
3369               flags = 1;
3370             }
3371           else if (argsize >= 1 && strncmp (*argv, "id", argsize) == 0)
3372             {
3373               summary = 0;
3374               id = 1;
3375             }
3376           else if (argsize >= 1 && strncmp (*argv, "mappings", argsize) == 0)
3377             {
3378               summary = 0;
3379               mappings = 1;
3380             }
3381           else if (argsize >= 2 && strncmp (*argv, "signals", argsize) == 0)
3382             {
3383               summary = 0;
3384               signals = 1;
3385             }
3386           else if (argsize >= 2 && strncmp (*argv, "status", argsize) == 0)
3387             {
3388               summary = 0;
3389               status = 1;
3390             }
3391           else if (argsize >= 2 && strncmp (*argv, "syscalls", argsize) == 0)
3392             {
3393               summary = 0;
3394               syscalls = 1;
3395             }
3396           else if (argsize >= 1 && strncmp (*argv, "times", argsize) == 0)
3397             {
3398               summary = 0;
3399               times = 1;
3400             }
3401           else if ((pid = atoi (*argv)) > 0)
3402             {
3403               pip = (struct procinfo *) xmalloc (sizeof (struct procinfo));
3404               memset (pip, 0, sizeof (*pip));
3405
3406               pip->pid = pid;
3407               if (!open_proc_file (pid, pip, O_RDONLY))
3408                 {
3409                   perror_with_name (pip -> pathname);
3410                   /* NOTREACHED */
3411                 }
3412               make_cleanup (close_proc_file, pip);
3413             }
3414           else if (**argv != '\000')
3415             {
3416               error ("Unrecognized or ambiguous keyword `%s'.", *argv);
3417             }
3418           argv++;
3419         }
3420     }
3421
3422   /* If we don't have a valid open process at this point, then we have no
3423      inferior or didn't specify a specific pid. */
3424
3425   if (!pip)
3426     {
3427       error ("\
3428 No process.  Start debugging a program or specify an explicit process ID.");
3429     }
3430   if (ioctl (pip -> fd, PIOCSTATUS, &(pip -> prstatus)) < 0)
3431     {
3432       print_sys_errmsg (pip -> pathname, errno);
3433       error ("PIOCSTATUS failed");
3434     }
3435
3436   /* Print verbose information of the requested type(s), or just a summary
3437      of the information for all types. */
3438
3439   printf_filtered ("\nInformation for %s:\n\n", pip -> pathname);
3440   if (summary || all || flags)
3441     {
3442       info_proc_flags (pip, summary);
3443     }
3444   if (summary || all)
3445     {
3446       info_proc_stop (pip, summary);
3447     }
3448   if (summary || all || signals || faults)
3449     {
3450       info_proc_siginfo (pip, summary);
3451     }
3452   if (summary || all || syscalls)
3453     {
3454       info_proc_syscalls (pip, summary);
3455     }
3456   if (summary || all || mappings)
3457     {
3458       info_proc_mappings (pip, summary);
3459     }
3460   if (summary || all || signals)
3461     {
3462       info_proc_signals (pip, summary);
3463     }
3464   if (summary || all || faults)
3465     {
3466       info_proc_faults (pip, summary);
3467     }
3468   printf_filtered ("\n");
3469
3470   /* All done, deal with closing any temporary process info structure,
3471      freeing temporary memory , etc. */
3472
3473   do_cleanups (old_chain);
3474 }
3475
3476 /*
3477
3478 LOCAL FUNCTION
3479
3480         procfs_set_sproc_trap -- arrange for child to stop on sproc().
3481
3482 SYNOPSIS
3483
3484         void procfs_set_sproc_trap (struct procinfo *)
3485
3486 DESCRIPTION
3487
3488         This function sets up a trap on sproc system call exits so that we can
3489         detect the arrival of a new thread.  We are called with the new thread
3490         stopped prior to it's first instruction.
3491
3492         Also note that we turn on the inherit-on-fork flag in the child process
3493         so that any grand-children start with all tracing flags set.
3494  */
3495
3496 #ifdef SYS_sproc
3497
3498 static void
3499 procfs_set_sproc_trap (pi)
3500      struct procinfo *pi;
3501 {
3502   sysset_t exitset;
3503   
3504   if (ioctl (pi->fd, PIOCGEXIT, &exitset) < 0)
3505     {
3506       print_sys_errmsg (pi->pathname, errno);
3507       error ("PIOCGEXIT failed");
3508     }
3509
3510   praddset (&exitset, SYS_sproc);
3511
3512   /* We trap on fork() and vfork() in order to disable debugging in our grand-
3513      children and descendant processes.  At this time, GDB can only handle
3514      threads (multiple processes, one address space).  forks (and execs) result
3515      in the creation of multiple address spaces, which GDB can't handle yet.  */
3516
3517   praddset (&exitset, SYS_fork);
3518 #ifdef SYS_vfork
3519   praddset (&exitset, SYS_vfork);
3520 #endif
3521
3522   if (ioctl (pi->fd, PIOCSEXIT, &exitset) < 0)
3523     {
3524       print_sys_errmsg (pi->pathname, errno);
3525       error ("PIOCSEXIT failed");
3526     }
3527
3528   /* Turn on inherit-on-fork flag so that all grand-children of gdb start with
3529      tracing flags set. */
3530
3531 #ifdef PIOCSET                  /* New method */
3532   {
3533       long pr_flags;
3534       pr_flags = PR_FORK;
3535       ioctl (pi->fd, PIOCSET, &pr_flags);
3536   }
3537 #else
3538 #ifdef PIOCSFORK                /* Original method */
3539   ioctl (pi->fd, PIOCSFORK, NULL);
3540 #endif
3541 #endif
3542 }
3543 #endif  /* SYS_sproc */
3544
3545 /* Fork an inferior process, and start debugging it with /proc.  */
3546
3547 static void
3548 procfs_create_inferior (exec_file, allargs, env)
3549      char *exec_file;
3550      char *allargs;
3551      char **env;
3552 {
3553   char *shell_file = getenv ("SHELL");
3554   char *tryname;
3555   if (shell_file != NULL && strchr (shell_file, '/') == NULL)
3556     {
3557
3558       /* We will be looking down the PATH to find shell_file.  If we
3559          just do this the normal way (via execlp, which operates by
3560          attempting an exec for each element of the PATH until it
3561          finds one which succeeds), then there will be an exec for
3562          each failed attempt, each of which will cause a PR_SYSEXIT
3563          stop, and we won't know how to distinguish the PR_SYSEXIT's
3564          for these failed execs with the ones for successful execs
3565          (whether the exec has succeeded is stored at that time in the
3566          carry bit or some such architecture-specific and
3567          non-ABI-specified place).
3568
3569          So I can't think of anything better than to search the PATH
3570          now.  This has several disadvantages: (1) There is a race
3571          condition; if we find a file now and it is deleted before we
3572          exec it, we lose, even if the deletion leaves a valid file
3573          further down in the PATH, (2) there is no way to know exactly
3574          what an executable (in the sense of "capable of being
3575          exec'd") file is.  Using access() loses because it may lose
3576          if the caller is the superuser; failing to use it loses if
3577          there are ACLs or some such.  */
3578
3579       char *p;
3580       char *p1;
3581       /* FIXME-maybe: might want "set path" command so user can change what
3582          path is used from within GDB.  */
3583       char *path = getenv ("PATH");
3584       int len;
3585       struct stat statbuf;
3586
3587       if (path == NULL)
3588         path = "/bin:/usr/bin";
3589
3590       tryname = alloca (strlen (path) + strlen (shell_file) + 2);
3591       for (p = path; p != NULL; p = p1 ? p1 + 1: NULL)
3592         {
3593           p1 = strchr (p, ':');
3594           if (p1 != NULL)
3595             len = p1 - p;
3596           else
3597             len = strlen (p);
3598           strncpy (tryname, p, len);
3599           tryname[len] = '\0';
3600           strcat (tryname, "/");
3601           strcat (tryname, shell_file);
3602           if (access (tryname, X_OK) < 0)
3603             continue;
3604           if (stat (tryname, &statbuf) < 0)
3605             continue;
3606           if (!S_ISREG (statbuf.st_mode))
3607             /* We certainly need to reject directories.  I'm not quite
3608                as sure about FIFOs, sockets, etc., but I kind of doubt
3609                that people want to exec() these things.  */
3610             continue;
3611           break;
3612         }
3613       if (p == NULL)
3614         /* Not found.  This must be an error rather than merely passing
3615            the file to execlp(), because execlp() would try all the
3616            exec()s, causing GDB to get confused.  */
3617         error ("Can't find shell %s in PATH", shell_file);
3618
3619       shell_file = tryname;
3620     }
3621
3622   fork_inferior (exec_file, allargs, env,
3623                  proc_set_exec_trap, procfs_init_inferior, shell_file);
3624
3625   /* We are at the first instruction we care about.  */
3626   /* Pedal to the metal... */
3627
3628   /* Setup traps on exit from sproc() */
3629
3630 #ifdef SYS_sproc
3631   procfs_set_sproc_trap (current_procinfo);
3632 #endif
3633
3634   proceed ((CORE_ADDR) -1, TARGET_SIGNAL_0, 0);
3635 }
3636
3637 /* Clean up after the inferior dies.  */
3638
3639 static void
3640 procfs_mourn_inferior ()
3641 {
3642   struct procinfo *pi;
3643   struct procinfo *next_pi;
3644
3645   for (pi = procinfo_list; pi; pi = next_pi)
3646     {
3647       next_pi = pi->next;
3648       unconditionally_kill_inferior (pi);
3649     }
3650
3651   unpush_target (&procfs_ops);
3652   generic_mourn_inferior ();
3653 }
3654
3655
3656 /* Mark our target-struct as eligible for stray "run" and "attach" commands.  */
3657 static int
3658 procfs_can_run ()
3659 {
3660   return(1);
3661 }
3662 #ifdef TARGET_HAS_HARDWARE_WATCHPOINTS
3663 \f
3664 /* Insert a watchpoint */
3665 int
3666 procfs_set_watchpoint(pid, addr, len, rw)
3667      int                pid;
3668      CORE_ADDR          addr;
3669      int                len;
3670      int                rw;
3671 {
3672   struct procinfo       *pi;
3673   prwatch_t             wpt;
3674
3675   pi = find_procinfo (pid == -1 ? inferior_pid : pid, 0);
3676   wpt.pr_vaddr = (caddr_t)addr;
3677   wpt.pr_size = len;
3678   wpt.pr_wflags = ((rw & 1) ? MA_READ : 0) | ((rw & 2) ? MA_WRITE : 0);
3679   if (ioctl (pi->fd, PIOCSWATCH, &wpt) < 0)
3680     {
3681       if (errno == E2BIG)
3682         return -1;
3683       /* Currently it sometimes happens that the same watchpoint gets
3684          deleted twice - don't die in this case (FIXME please) */
3685       if (errno == ESRCH && len == 0)
3686         return 0;
3687       print_sys_errmsg (pi->pathname, errno);
3688       error ("PIOCSWATCH failed");
3689     }
3690   return 0;
3691 }
3692
3693 int
3694 procfs_stopped_by_watchpoint(pid)
3695     int                 pid;
3696 {
3697   struct procinfo       *pi;
3698   short                 what;
3699   short                 why;
3700
3701   pi = find_procinfo (pid == -1 ? inferior_pid : pid, 0);
3702   if (pi->prstatus.pr_flags & (PR_STOPPED | PR_ISTOP))
3703     {
3704       why = pi->prstatus.pr_why;
3705       what = pi->prstatus.pr_what;
3706       if (why == PR_FAULTED 
3707 #if defined (FLTWATCH) && defined (FLTKWATCH)
3708           && (what == FLTWATCH) || (what == FLTKWATCH)
3709 #else
3710 #ifdef FLTWATCH
3711           && (what == FLTWATCH) 
3712 #endif
3713 #ifdef FLTKWATCH
3714           && (what == FLTKWATCH)
3715 #endif
3716 #endif
3717           )
3718         return what;
3719     }
3720   return 0;
3721 }
3722 #endif
3723
3724 /* Send a SIGINT to the process group.  This acts just like the user typed a
3725    ^C on the controlling terminal.
3726
3727    XXX - This may not be correct for all systems.  Some may want to use
3728    killpg() instead of kill (-pgrp). */
3729
3730 void
3731 procfs_stop ()
3732 {
3733   extern pid_t inferior_process_group;
3734
3735   kill (-inferior_process_group, SIGINT);
3736 }
3737
3738 \f
3739 struct target_ops procfs_ops = {
3740   "procfs",                     /* to_shortname */
3741   "Unix /proc child process",   /* to_longname */
3742   "Unix /proc child process (started by the \"run\" command).", /* to_doc */
3743   procfs_open,                  /* to_open */
3744   0,                            /* to_close */
3745   procfs_attach,                        /* to_attach */
3746   procfs_detach,                /* to_detach */
3747   procfs_resume,                        /* to_resume */
3748   procfs_wait,                  /* to_wait */
3749   procfs_fetch_registers,       /* to_fetch_registers */
3750   procfs_store_registers,       /* to_store_registers */
3751   procfs_prepare_to_store,      /* to_prepare_to_store */
3752   procfs_xfer_memory,           /* to_xfer_memory */
3753   procfs_files_info,            /* to_files_info */
3754   memory_insert_breakpoint,     /* to_insert_breakpoint */
3755   memory_remove_breakpoint,     /* to_remove_breakpoint */
3756   terminal_init_inferior,       /* to_terminal_init */
3757   terminal_inferior,            /* to_terminal_inferior */
3758   terminal_ours_for_output,     /* to_terminal_ours_for_output */
3759   terminal_ours,                /* to_terminal_ours */
3760   child_terminal_info,          /* to_terminal_info */
3761   procfs_kill_inferior,         /* to_kill */
3762   0,                            /* to_load */
3763   0,                            /* to_lookup_symbol */
3764   procfs_create_inferior,       /* to_create_inferior */
3765   procfs_mourn_inferior,        /* to_mourn_inferior */
3766   procfs_can_run,               /* to_can_run */
3767   procfs_notice_signals,        /* to_notice_signals */
3768   procfs_stop,                  /* to_stop */
3769   process_stratum,              /* to_stratum */
3770   0,                            /* to_next */
3771   1,                            /* to_has_all_memory */
3772   1,                            /* to_has_memory */
3773   1,                            /* to_has_stack */
3774   1,                            /* to_has_registers */
3775   1,                            /* to_has_execution */
3776   0,                            /* sections */
3777   0,                            /* sections_end */
3778   OPS_MAGIC                     /* to_magic */
3779 };
3780
3781 void
3782 _initialize_procfs ()
3783 {
3784 #ifdef HAVE_OPTIONAL_PROC_FS
3785   char procname[32];
3786   int fd;
3787
3788   /* If we have an optional /proc filesystem (e.g. under OSF/1),
3789      don't add procfs support if we cannot access the running
3790      GDB via /proc.  */
3791   sprintf (procname, PROC_NAME_FMT, getpid ());
3792   if ((fd = open (procname, O_RDONLY)) < 0)
3793     return;
3794   close (fd);
3795 #endif
3796
3797   add_target (&procfs_ops);
3798
3799   add_info ("proc", info_proc, 
3800 "Show process status information using /proc entry.\n\
3801 Specify process id or use current inferior by default.\n\
3802 Specify keywords for detailed information; default is summary.\n\
3803 Keywords are: `all', `faults', `flags', `id', `mappings', `signals',\n\
3804 `status', `syscalls', and `times'.\n\
3805 Unambiguous abbreviations may be used.");
3806
3807   init_syscall_table ();
3808 }