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