Add tests for PR ld/16452 and PR ld/16457
[platform/upstream/binutils.git] / gdb / linux-tdep.c
1 /* Target-dependent code for GNU/Linux, architecture independent.
2
3    Copyright (C) 2009-2014 Free Software Foundation, Inc.
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 3 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, see <http://www.gnu.org/licenses/>.  */
19
20 #include "defs.h"
21 #include "gdbtypes.h"
22 #include "linux-tdep.h"
23 #include "auxv.h"
24 #include "target.h"
25 #include "gdbthread.h"
26 #include "gdbcore.h"
27 #include "regcache.h"
28 #include "regset.h"
29 #include "elf/common.h"
30 #include "elf-bfd.h"            /* for elfcore_write_* */
31 #include "inferior.h"
32 #include "cli/cli-utils.h"
33 #include "arch-utils.h"
34 #include "gdb_obstack.h"
35 #include "observer.h"
36
37 #include <ctype.h>
38
39 /* This enum represents the signals' numbers on a generic architecture
40    running the Linux kernel.  The definition of "generic" comes from
41    the file <include/uapi/asm-generic/signal.h>, from the Linux kernel
42    tree, which is the "de facto" implementation of signal numbers to
43    be used by new architecture ports.
44
45    For those architectures which have differences between the generic
46    standard (e.g., Alpha), we define the different signals (and *only*
47    those) in the specific target-dependent file (e.g.,
48    alpha-linux-tdep.c, for Alpha).  Please refer to the architecture's
49    tdep file for more information.
50
51    ARM deserves a special mention here.  On the file
52    <arch/arm/include/uapi/asm/signal.h>, it defines only one different
53    (and ARM-only) signal, which is SIGSWI, with the same number as
54    SIGRTMIN.  This signal is used only for a very specific target,
55    called ArthurOS (from RISCOS).  Therefore, we do not handle it on
56    the ARM-tdep file, and we can safely use the generic signal handler
57    here for ARM targets.
58
59    As stated above, this enum is derived from
60    <include/uapi/asm-generic/signal.h>, from the Linux kernel
61    tree.  */
62
63 enum
64   {
65     LINUX_SIGHUP = 1,
66     LINUX_SIGINT = 2,
67     LINUX_SIGQUIT = 3,
68     LINUX_SIGILL = 4,
69     LINUX_SIGTRAP = 5,
70     LINUX_SIGABRT = 6,
71     LINUX_SIGIOT = 6,
72     LINUX_SIGBUS = 7,
73     LINUX_SIGFPE = 8,
74     LINUX_SIGKILL = 9,
75     LINUX_SIGUSR1 = 10,
76     LINUX_SIGSEGV = 11,
77     LINUX_SIGUSR2 = 12,
78     LINUX_SIGPIPE = 13,
79     LINUX_SIGALRM = 14,
80     LINUX_SIGTERM = 15,
81     LINUX_SIGSTKFLT = 16,
82     LINUX_SIGCHLD = 17,
83     LINUX_SIGCONT = 18,
84     LINUX_SIGSTOP = 19,
85     LINUX_SIGTSTP = 20,
86     LINUX_SIGTTIN = 21,
87     LINUX_SIGTTOU = 22,
88     LINUX_SIGURG = 23,
89     LINUX_SIGXCPU = 24,
90     LINUX_SIGXFSZ = 25,
91     LINUX_SIGVTALRM = 26,
92     LINUX_SIGPROF = 27,
93     LINUX_SIGWINCH = 28,
94     LINUX_SIGIO = 29,
95     LINUX_SIGPOLL = LINUX_SIGIO,
96     LINUX_SIGPWR = 30,
97     LINUX_SIGSYS = 31,
98     LINUX_SIGUNUSED = 31,
99
100     LINUX_SIGRTMIN = 32,
101     LINUX_SIGRTMAX = 64,
102   };
103
104 static struct gdbarch_data *linux_gdbarch_data_handle;
105
106 struct linux_gdbarch_data
107   {
108     struct type *siginfo_type;
109   };
110
111 static void *
112 init_linux_gdbarch_data (struct gdbarch *gdbarch)
113 {
114   return GDBARCH_OBSTACK_ZALLOC (gdbarch, struct linux_gdbarch_data);
115 }
116
117 static struct linux_gdbarch_data *
118 get_linux_gdbarch_data (struct gdbarch *gdbarch)
119 {
120   return gdbarch_data (gdbarch, linux_gdbarch_data_handle);
121 }
122
123 /* Per-inferior data key.  */
124 static const struct inferior_data *linux_inferior_data;
125
126 /* Linux-specific cached data.  This is used by GDB for caching
127    purposes for each inferior.  This helps reduce the overhead of
128    transfering data from a remote target to the local host.  */
129 struct linux_info
130 {
131   /* Cache of the inferior's vsyscall/vDSO mapping range.  Only valid
132      if VSYSCALL_RANGE_P is positive.  This is cached because getting
133      at this info requires an auxv lookup (which is itself cached),
134      and looking through the inferior's mappings (which change
135      throughout execution and therefore cannot be cached).  */
136   struct mem_range vsyscall_range;
137
138   /* Zero if we haven't tried looking up the vsyscall's range before
139      yet.  Positive if we tried looking it up, and found it.  Negative
140      if we tried looking it up but failed.  */
141   int vsyscall_range_p;
142 };
143
144 /* Frees whatever allocated space there is to be freed and sets INF's
145    linux cache data pointer to NULL.  */
146
147 static void
148 invalidate_linux_cache_inf (struct inferior *inf)
149 {
150   struct linux_info *info;
151
152   info = inferior_data (inf, linux_inferior_data);
153   if (info != NULL)
154     {
155       xfree (info);
156       set_inferior_data (inf, linux_inferior_data, NULL);
157     }
158 }
159
160 /* Handles the cleanup of the linux cache for inferior INF.  ARG is
161    ignored.  Callback for the inferior_appeared and inferior_exit
162    events.  */
163
164 static void
165 linux_inferior_data_cleanup (struct inferior *inf, void *arg)
166 {
167   invalidate_linux_cache_inf (inf);
168 }
169
170 /* Fetch the linux cache info for INF.  This function always returns a
171    valid INFO pointer.  */
172
173 static struct linux_info *
174 get_linux_inferior_data (void)
175 {
176   struct linux_info *info;
177   struct inferior *inf = current_inferior ();
178
179   info = inferior_data (inf, linux_inferior_data);
180   if (info == NULL)
181     {
182       info = XCNEW (struct linux_info);
183       set_inferior_data (inf, linux_inferior_data, info);
184     }
185
186   return info;
187 }
188
189 /* This function is suitable for architectures that don't
190    extend/override the standard siginfo structure.  */
191
192 struct type *
193 linux_get_siginfo_type (struct gdbarch *gdbarch)
194 {
195   struct linux_gdbarch_data *linux_gdbarch_data;
196   struct type *int_type, *uint_type, *long_type, *void_ptr_type;
197   struct type *uid_type, *pid_type;
198   struct type *sigval_type, *clock_type;
199   struct type *siginfo_type, *sifields_type;
200   struct type *type;
201
202   linux_gdbarch_data = get_linux_gdbarch_data (gdbarch);
203   if (linux_gdbarch_data->siginfo_type != NULL)
204     return linux_gdbarch_data->siginfo_type;
205
206   int_type = arch_integer_type (gdbarch, gdbarch_int_bit (gdbarch),
207                                 0, "int");
208   uint_type = arch_integer_type (gdbarch, gdbarch_int_bit (gdbarch),
209                                  1, "unsigned int");
210   long_type = arch_integer_type (gdbarch, gdbarch_long_bit (gdbarch),
211                                  0, "long");
212   void_ptr_type = lookup_pointer_type (builtin_type (gdbarch)->builtin_void);
213
214   /* sival_t */
215   sigval_type = arch_composite_type (gdbarch, NULL, TYPE_CODE_UNION);
216   TYPE_NAME (sigval_type) = xstrdup ("sigval_t");
217   append_composite_type_field (sigval_type, "sival_int", int_type);
218   append_composite_type_field (sigval_type, "sival_ptr", void_ptr_type);
219
220   /* __pid_t */
221   pid_type = arch_type (gdbarch, TYPE_CODE_TYPEDEF,
222                         TYPE_LENGTH (int_type), "__pid_t");
223   TYPE_TARGET_TYPE (pid_type) = int_type;
224   TYPE_TARGET_STUB (pid_type) = 1;
225
226   /* __uid_t */
227   uid_type = arch_type (gdbarch, TYPE_CODE_TYPEDEF,
228                         TYPE_LENGTH (uint_type), "__uid_t");
229   TYPE_TARGET_TYPE (uid_type) = uint_type;
230   TYPE_TARGET_STUB (uid_type) = 1;
231
232   /* __clock_t */
233   clock_type = arch_type (gdbarch, TYPE_CODE_TYPEDEF,
234                           TYPE_LENGTH (long_type), "__clock_t");
235   TYPE_TARGET_TYPE (clock_type) = long_type;
236   TYPE_TARGET_STUB (clock_type) = 1;
237
238   /* _sifields */
239   sifields_type = arch_composite_type (gdbarch, NULL, TYPE_CODE_UNION);
240
241   {
242     const int si_max_size = 128;
243     int si_pad_size;
244     int size_of_int = gdbarch_int_bit (gdbarch) / HOST_CHAR_BIT;
245
246     /* _pad */
247     if (gdbarch_ptr_bit (gdbarch) == 64)
248       si_pad_size = (si_max_size / size_of_int) - 4;
249     else
250       si_pad_size = (si_max_size / size_of_int) - 3;
251     append_composite_type_field (sifields_type, "_pad",
252                                  init_vector_type (int_type, si_pad_size));
253   }
254
255   /* _kill */
256   type = arch_composite_type (gdbarch, NULL, TYPE_CODE_STRUCT);
257   append_composite_type_field (type, "si_pid", pid_type);
258   append_composite_type_field (type, "si_uid", uid_type);
259   append_composite_type_field (sifields_type, "_kill", type);
260
261   /* _timer */
262   type = arch_composite_type (gdbarch, NULL, TYPE_CODE_STRUCT);
263   append_composite_type_field (type, "si_tid", int_type);
264   append_composite_type_field (type, "si_overrun", int_type);
265   append_composite_type_field (type, "si_sigval", sigval_type);
266   append_composite_type_field (sifields_type, "_timer", type);
267
268   /* _rt */
269   type = arch_composite_type (gdbarch, NULL, TYPE_CODE_STRUCT);
270   append_composite_type_field (type, "si_pid", pid_type);
271   append_composite_type_field (type, "si_uid", uid_type);
272   append_composite_type_field (type, "si_sigval", sigval_type);
273   append_composite_type_field (sifields_type, "_rt", type);
274
275   /* _sigchld */
276   type = arch_composite_type (gdbarch, NULL, TYPE_CODE_STRUCT);
277   append_composite_type_field (type, "si_pid", pid_type);
278   append_composite_type_field (type, "si_uid", uid_type);
279   append_composite_type_field (type, "si_status", int_type);
280   append_composite_type_field (type, "si_utime", clock_type);
281   append_composite_type_field (type, "si_stime", clock_type);
282   append_composite_type_field (sifields_type, "_sigchld", type);
283
284   /* _sigfault */
285   type = arch_composite_type (gdbarch, NULL, TYPE_CODE_STRUCT);
286   append_composite_type_field (type, "si_addr", void_ptr_type);
287   append_composite_type_field (sifields_type, "_sigfault", type);
288
289   /* _sigpoll */
290   type = arch_composite_type (gdbarch, NULL, TYPE_CODE_STRUCT);
291   append_composite_type_field (type, "si_band", long_type);
292   append_composite_type_field (type, "si_fd", int_type);
293   append_composite_type_field (sifields_type, "_sigpoll", type);
294
295   /* struct siginfo */
296   siginfo_type = arch_composite_type (gdbarch, NULL, TYPE_CODE_STRUCT);
297   TYPE_NAME (siginfo_type) = xstrdup ("siginfo");
298   append_composite_type_field (siginfo_type, "si_signo", int_type);
299   append_composite_type_field (siginfo_type, "si_errno", int_type);
300   append_composite_type_field (siginfo_type, "si_code", int_type);
301   append_composite_type_field_aligned (siginfo_type,
302                                        "_sifields", sifields_type,
303                                        TYPE_LENGTH (long_type));
304
305   linux_gdbarch_data->siginfo_type = siginfo_type;
306
307   return siginfo_type;
308 }
309
310 /* Return true if the target is running on uClinux instead of normal
311    Linux kernel.  */
312
313 int
314 linux_is_uclinux (void)
315 {
316   CORE_ADDR dummy;
317
318   return (target_auxv_search (&current_target, AT_NULL, &dummy) > 0
319           && target_auxv_search (&current_target, AT_PAGESZ, &dummy) == 0);
320 }
321
322 static int
323 linux_has_shared_address_space (struct gdbarch *gdbarch)
324 {
325   return linux_is_uclinux ();
326 }
327
328 /* This is how we want PTIDs from core files to be printed.  */
329
330 static char *
331 linux_core_pid_to_str (struct gdbarch *gdbarch, ptid_t ptid)
332 {
333   static char buf[80];
334
335   if (ptid_get_lwp (ptid) != 0)
336     {
337       snprintf (buf, sizeof (buf), "LWP %ld", ptid_get_lwp (ptid));
338       return buf;
339     }
340
341   return normal_pid_to_str (ptid);
342 }
343
344 /* Service function for corefiles and info proc.  */
345
346 static void
347 read_mapping (const char *line,
348               ULONGEST *addr, ULONGEST *endaddr,
349               const char **permissions, size_t *permissions_len,
350               ULONGEST *offset,
351               const char **device, size_t *device_len,
352               ULONGEST *inode,
353               const char **filename)
354 {
355   const char *p = line;
356
357   *addr = strtoulst (p, &p, 16);
358   if (*p == '-')
359     p++;
360   *endaddr = strtoulst (p, &p, 16);
361
362   p = skip_spaces_const (p);
363   *permissions = p;
364   while (*p && !isspace (*p))
365     p++;
366   *permissions_len = p - *permissions;
367
368   *offset = strtoulst (p, &p, 16);
369
370   p = skip_spaces_const (p);
371   *device = p;
372   while (*p && !isspace (*p))
373     p++;
374   *device_len = p - *device;
375
376   *inode = strtoulst (p, &p, 10);
377
378   p = skip_spaces_const (p);
379   *filename = p;
380 }
381
382 /* Implement the "info proc" command.  */
383
384 static void
385 linux_info_proc (struct gdbarch *gdbarch, const char *args,
386                  enum info_proc_what what)
387 {
388   /* A long is used for pid instead of an int to avoid a loss of precision
389      compiler warning from the output of strtoul.  */
390   long pid;
391   int cmdline_f = (what == IP_MINIMAL || what == IP_CMDLINE || what == IP_ALL);
392   int cwd_f = (what == IP_MINIMAL || what == IP_CWD || what == IP_ALL);
393   int exe_f = (what == IP_MINIMAL || what == IP_EXE || what == IP_ALL);
394   int mappings_f = (what == IP_MAPPINGS || what == IP_ALL);
395   int status_f = (what == IP_STATUS || what == IP_ALL);
396   int stat_f = (what == IP_STAT || what == IP_ALL);
397   char filename[100];
398   char *data;
399   int target_errno;
400
401   if (args && isdigit (args[0]))
402     {
403       char *tem;
404
405       pid = strtoul (args, &tem, 10);
406       args = tem;
407     }
408   else
409     {
410       if (!target_has_execution)
411         error (_("No current process: you must name one."));
412       if (current_inferior ()->fake_pid_p)
413         error (_("Can't determine the current process's PID: you must name one."));
414
415       pid = current_inferior ()->pid;
416     }
417
418   args = skip_spaces_const (args);
419   if (args && args[0])
420     error (_("Too many parameters: %s"), args);
421
422   printf_filtered (_("process %ld\n"), pid);
423   if (cmdline_f)
424     {
425       xsnprintf (filename, sizeof filename, "/proc/%ld/cmdline", pid);
426       data = target_fileio_read_stralloc (filename);
427       if (data)
428         {
429           struct cleanup *cleanup = make_cleanup (xfree, data);
430           printf_filtered ("cmdline = '%s'\n", data);
431           do_cleanups (cleanup);
432         }
433       else
434         warning (_("unable to open /proc file '%s'"), filename);
435     }
436   if (cwd_f)
437     {
438       xsnprintf (filename, sizeof filename, "/proc/%ld/cwd", pid);
439       data = target_fileio_readlink (filename, &target_errno);
440       if (data)
441         {
442           struct cleanup *cleanup = make_cleanup (xfree, data);
443           printf_filtered ("cwd = '%s'\n", data);
444           do_cleanups (cleanup);
445         }
446       else
447         warning (_("unable to read link '%s'"), filename);
448     }
449   if (exe_f)
450     {
451       xsnprintf (filename, sizeof filename, "/proc/%ld/exe", pid);
452       data = target_fileio_readlink (filename, &target_errno);
453       if (data)
454         {
455           struct cleanup *cleanup = make_cleanup (xfree, data);
456           printf_filtered ("exe = '%s'\n", data);
457           do_cleanups (cleanup);
458         }
459       else
460         warning (_("unable to read link '%s'"), filename);
461     }
462   if (mappings_f)
463     {
464       xsnprintf (filename, sizeof filename, "/proc/%ld/maps", pid);
465       data = target_fileio_read_stralloc (filename);
466       if (data)
467         {
468           struct cleanup *cleanup = make_cleanup (xfree, data);
469           char *line;
470
471           printf_filtered (_("Mapped address spaces:\n\n"));
472           if (gdbarch_addr_bit (gdbarch) == 32)
473             {
474               printf_filtered ("\t%10s %10s %10s %10s %s\n",
475                            "Start Addr",
476                            "  End Addr",
477                            "      Size", "    Offset", "objfile");
478             }
479           else
480             {
481               printf_filtered ("  %18s %18s %10s %10s %s\n",
482                            "Start Addr",
483                            "  End Addr",
484                            "      Size", "    Offset", "objfile");
485             }
486
487           for (line = strtok (data, "\n"); line; line = strtok (NULL, "\n"))
488             {
489               ULONGEST addr, endaddr, offset, inode;
490               const char *permissions, *device, *filename;
491               size_t permissions_len, device_len;
492
493               read_mapping (line, &addr, &endaddr,
494                             &permissions, &permissions_len,
495                             &offset, &device, &device_len,
496                             &inode, &filename);
497
498               if (gdbarch_addr_bit (gdbarch) == 32)
499                 {
500                   printf_filtered ("\t%10s %10s %10s %10s %s\n",
501                                    paddress (gdbarch, addr),
502                                    paddress (gdbarch, endaddr),
503                                    hex_string (endaddr - addr),
504                                    hex_string (offset),
505                                    *filename? filename : "");
506                 }
507               else
508                 {
509                   printf_filtered ("  %18s %18s %10s %10s %s\n",
510                                    paddress (gdbarch, addr),
511                                    paddress (gdbarch, endaddr),
512                                    hex_string (endaddr - addr),
513                                    hex_string (offset),
514                                    *filename? filename : "");
515                 }
516             }
517
518           do_cleanups (cleanup);
519         }
520       else
521         warning (_("unable to open /proc file '%s'"), filename);
522     }
523   if (status_f)
524     {
525       xsnprintf (filename, sizeof filename, "/proc/%ld/status", pid);
526       data = target_fileio_read_stralloc (filename);
527       if (data)
528         {
529           struct cleanup *cleanup = make_cleanup (xfree, data);
530           puts_filtered (data);
531           do_cleanups (cleanup);
532         }
533       else
534         warning (_("unable to open /proc file '%s'"), filename);
535     }
536   if (stat_f)
537     {
538       xsnprintf (filename, sizeof filename, "/proc/%ld/stat", pid);
539       data = target_fileio_read_stralloc (filename);
540       if (data)
541         {
542           struct cleanup *cleanup = make_cleanup (xfree, data);
543           const char *p = data;
544
545           printf_filtered (_("Process: %s\n"),
546                            pulongest (strtoulst (p, &p, 10)));
547
548           p = skip_spaces_const (p);
549           if (*p == '(')
550             {
551               /* ps command also relies on no trailing fields
552                  ever contain ')'.  */
553               const char *ep = strrchr (p, ')');
554               if (ep != NULL)
555                 {
556                   printf_filtered ("Exec file: %.*s\n",
557                                    (int) (ep - p - 1), p + 1);
558                   p = ep + 1;
559                 }
560             }
561
562           p = skip_spaces_const (p);
563           if (*p)
564             printf_filtered (_("State: %c\n"), *p++);
565
566           if (*p)
567             printf_filtered (_("Parent process: %s\n"),
568                              pulongest (strtoulst (p, &p, 10)));
569           if (*p)
570             printf_filtered (_("Process group: %s\n"),
571                              pulongest (strtoulst (p, &p, 10)));
572           if (*p)
573             printf_filtered (_("Session id: %s\n"),
574                              pulongest (strtoulst (p, &p, 10)));
575           if (*p)
576             printf_filtered (_("TTY: %s\n"),
577                              pulongest (strtoulst (p, &p, 10)));
578           if (*p)
579             printf_filtered (_("TTY owner process group: %s\n"),
580                              pulongest (strtoulst (p, &p, 10)));
581
582           if (*p)
583             printf_filtered (_("Flags: %s\n"),
584                              hex_string (strtoulst (p, &p, 10)));
585           if (*p)
586             printf_filtered (_("Minor faults (no memory page): %s\n"),
587                              pulongest (strtoulst (p, &p, 10)));
588           if (*p)
589             printf_filtered (_("Minor faults, children: %s\n"),
590                              pulongest (strtoulst (p, &p, 10)));
591           if (*p)
592             printf_filtered (_("Major faults (memory page faults): %s\n"),
593                              pulongest (strtoulst (p, &p, 10)));
594           if (*p)
595             printf_filtered (_("Major faults, children: %s\n"),
596                              pulongest (strtoulst (p, &p, 10)));
597           if (*p)
598             printf_filtered (_("utime: %s\n"),
599                              pulongest (strtoulst (p, &p, 10)));
600           if (*p)
601             printf_filtered (_("stime: %s\n"),
602                              pulongest (strtoulst (p, &p, 10)));
603           if (*p)
604             printf_filtered (_("utime, children: %s\n"),
605                              pulongest (strtoulst (p, &p, 10)));
606           if (*p)
607             printf_filtered (_("stime, children: %s\n"),
608                              pulongest (strtoulst (p, &p, 10)));
609           if (*p)
610             printf_filtered (_("jiffies remaining in current "
611                                "time slice: %s\n"),
612                              pulongest (strtoulst (p, &p, 10)));
613           if (*p)
614             printf_filtered (_("'nice' value: %s\n"),
615                              pulongest (strtoulst (p, &p, 10)));
616           if (*p)
617             printf_filtered (_("jiffies until next timeout: %s\n"),
618                              pulongest (strtoulst (p, &p, 10)));
619           if (*p)
620             printf_filtered (_("jiffies until next SIGALRM: %s\n"),
621                              pulongest (strtoulst (p, &p, 10)));
622           if (*p)
623             printf_filtered (_("start time (jiffies since "
624                                "system boot): %s\n"),
625                              pulongest (strtoulst (p, &p, 10)));
626           if (*p)
627             printf_filtered (_("Virtual memory size: %s\n"),
628                              pulongest (strtoulst (p, &p, 10)));
629           if (*p)
630             printf_filtered (_("Resident set size: %s\n"),
631                              pulongest (strtoulst (p, &p, 10)));
632           if (*p)
633             printf_filtered (_("rlim: %s\n"),
634                              pulongest (strtoulst (p, &p, 10)));
635           if (*p)
636             printf_filtered (_("Start of text: %s\n"),
637                              hex_string (strtoulst (p, &p, 10)));
638           if (*p)
639             printf_filtered (_("End of text: %s\n"),
640                              hex_string (strtoulst (p, &p, 10)));
641           if (*p)
642             printf_filtered (_("Start of stack: %s\n"),
643                              hex_string (strtoulst (p, &p, 10)));
644 #if 0   /* Don't know how architecture-dependent the rest is...
645            Anyway the signal bitmap info is available from "status".  */
646           if (*p)
647             printf_filtered (_("Kernel stack pointer: %s\n"),
648                              hex_string (strtoulst (p, &p, 10)));
649           if (*p)
650             printf_filtered (_("Kernel instr pointer: %s\n"),
651                              hex_string (strtoulst (p, &p, 10)));
652           if (*p)
653             printf_filtered (_("Pending signals bitmap: %s\n"),
654                              hex_string (strtoulst (p, &p, 10)));
655           if (*p)
656             printf_filtered (_("Blocked signals bitmap: %s\n"),
657                              hex_string (strtoulst (p, &p, 10)));
658           if (*p)
659             printf_filtered (_("Ignored signals bitmap: %s\n"),
660                              hex_string (strtoulst (p, &p, 10)));
661           if (*p)
662             printf_filtered (_("Catched signals bitmap: %s\n"),
663                              hex_string (strtoulst (p, &p, 10)));
664           if (*p)
665             printf_filtered (_("wchan (system call): %s\n"),
666                              hex_string (strtoulst (p, &p, 10)));
667 #endif
668           do_cleanups (cleanup);
669         }
670       else
671         warning (_("unable to open /proc file '%s'"), filename);
672     }
673 }
674
675 /* Implement "info proc mappings" for a corefile.  */
676
677 static void
678 linux_core_info_proc_mappings (struct gdbarch *gdbarch, const char *args)
679 {
680   asection *section;
681   ULONGEST count, page_size;
682   unsigned char *descdata, *filenames, *descend, *contents;
683   size_t note_size;
684   unsigned int addr_size_bits, addr_size;
685   struct cleanup *cleanup;
686   struct gdbarch *core_gdbarch = gdbarch_from_bfd (core_bfd);
687   /* We assume this for reading 64-bit core files.  */
688   gdb_static_assert (sizeof (ULONGEST) >= 8);
689
690   section = bfd_get_section_by_name (core_bfd, ".note.linuxcore.file");
691   if (section == NULL)
692     {
693       warning (_("unable to find mappings in core file"));
694       return;
695     }
696
697   addr_size_bits = gdbarch_addr_bit (core_gdbarch);
698   addr_size = addr_size_bits / 8;
699   note_size = bfd_get_section_size (section);
700
701   if (note_size < 2 * addr_size)
702     error (_("malformed core note - too short for header"));
703
704   contents = xmalloc (note_size);
705   cleanup = make_cleanup (xfree, contents);
706   if (!bfd_get_section_contents (core_bfd, section, contents, 0, note_size))
707     error (_("could not get core note contents"));
708
709   descdata = contents;
710   descend = descdata + note_size;
711
712   if (descdata[note_size - 1] != '\0')
713     error (_("malformed note - does not end with \\0"));
714
715   count = bfd_get (addr_size_bits, core_bfd, descdata);
716   descdata += addr_size;
717
718   page_size = bfd_get (addr_size_bits, core_bfd, descdata);
719   descdata += addr_size;
720
721   if (note_size < 2 * addr_size + count * 3 * addr_size)
722     error (_("malformed note - too short for supplied file count"));
723
724   printf_filtered (_("Mapped address spaces:\n\n"));
725   if (gdbarch_addr_bit (gdbarch) == 32)
726     {
727       printf_filtered ("\t%10s %10s %10s %10s %s\n",
728                        "Start Addr",
729                        "  End Addr",
730                        "      Size", "    Offset", "objfile");
731     }
732   else
733     {
734       printf_filtered ("  %18s %18s %10s %10s %s\n",
735                        "Start Addr",
736                        "  End Addr",
737                        "      Size", "    Offset", "objfile");
738     }
739
740   filenames = descdata + count * 3 * addr_size;
741   while (--count > 0)
742     {
743       ULONGEST start, end, file_ofs;
744
745       if (filenames == descend)
746         error (_("malformed note - filenames end too early"));
747
748       start = bfd_get (addr_size_bits, core_bfd, descdata);
749       descdata += addr_size;
750       end = bfd_get (addr_size_bits, core_bfd, descdata);
751       descdata += addr_size;
752       file_ofs = bfd_get (addr_size_bits, core_bfd, descdata);
753       descdata += addr_size;
754
755       file_ofs *= page_size;
756
757       if (gdbarch_addr_bit (gdbarch) == 32)
758         printf_filtered ("\t%10s %10s %10s %10s %s\n",
759                          paddress (gdbarch, start),
760                          paddress (gdbarch, end),
761                          hex_string (end - start),
762                          hex_string (file_ofs),
763                          filenames);
764       else
765         printf_filtered ("  %18s %18s %10s %10s %s\n",
766                          paddress (gdbarch, start),
767                          paddress (gdbarch, end),
768                          hex_string (end - start),
769                          hex_string (file_ofs),
770                          filenames);
771
772       filenames += 1 + strlen ((char *) filenames);
773     }
774
775   do_cleanups (cleanup);
776 }
777
778 /* Implement "info proc" for a corefile.  */
779
780 static void
781 linux_core_info_proc (struct gdbarch *gdbarch, const char *args,
782                       enum info_proc_what what)
783 {
784   int exe_f = (what == IP_MINIMAL || what == IP_EXE || what == IP_ALL);
785   int mappings_f = (what == IP_MAPPINGS || what == IP_ALL);
786
787   if (exe_f)
788     {
789       const char *exe;
790
791       exe = bfd_core_file_failing_command (core_bfd);
792       if (exe != NULL)
793         printf_filtered ("exe = '%s'\n", exe);
794       else
795         warning (_("unable to find command name in core file"));
796     }
797
798   if (mappings_f)
799     linux_core_info_proc_mappings (gdbarch, args);
800
801   if (!exe_f && !mappings_f)
802     error (_("unable to handle request"));
803 }
804
805 typedef int linux_find_memory_region_ftype (ULONGEST vaddr, ULONGEST size,
806                                             ULONGEST offset, ULONGEST inode,
807                                             int read, int write,
808                                             int exec, int modified,
809                                             const char *filename,
810                                             void *data);
811
812 /* List memory regions in the inferior for a corefile.  */
813
814 static int
815 linux_find_memory_regions_full (struct gdbarch *gdbarch,
816                                 linux_find_memory_region_ftype *func,
817                                 void *obfd)
818 {
819   char mapsfilename[100];
820   char *data;
821
822   /* We need to know the real target PID to access /proc.  */
823   if (current_inferior ()->fake_pid_p)
824     return 1;
825
826   xsnprintf (mapsfilename, sizeof mapsfilename,
827              "/proc/%d/smaps", current_inferior ()->pid);
828   data = target_fileio_read_stralloc (mapsfilename);
829   if (data == NULL)
830     {
831       /* Older Linux kernels did not support /proc/PID/smaps.  */
832       xsnprintf (mapsfilename, sizeof mapsfilename,
833                  "/proc/%d/maps", current_inferior ()->pid);
834       data = target_fileio_read_stralloc (mapsfilename);
835     }
836   if (data)
837     {
838       struct cleanup *cleanup = make_cleanup (xfree, data);
839       char *line;
840
841       line = strtok (data, "\n");
842       while (line)
843         {
844           ULONGEST addr, endaddr, offset, inode;
845           const char *permissions, *device, *filename;
846           size_t permissions_len, device_len;
847           int read, write, exec;
848           int modified = 0, has_anonymous = 0;
849
850           read_mapping (line, &addr, &endaddr, &permissions, &permissions_len,
851                         &offset, &device, &device_len, &inode, &filename);
852
853           /* Decode permissions.  */
854           read = (memchr (permissions, 'r', permissions_len) != 0);
855           write = (memchr (permissions, 'w', permissions_len) != 0);
856           exec = (memchr (permissions, 'x', permissions_len) != 0);
857
858           /* Try to detect if region was modified by parsing smaps counters.  */
859           for (line = strtok (NULL, "\n");
860                line && line[0] >= 'A' && line[0] <= 'Z';
861                line = strtok (NULL, "\n"))
862             {
863               char keyword[64 + 1];
864
865               if (sscanf (line, "%64s", keyword) != 1)
866                 {
867                   warning (_("Error parsing {s,}maps file '%s'"), mapsfilename);
868                   break;
869                 }
870               if (strcmp (keyword, "Anonymous:") == 0)
871                 has_anonymous = 1;
872               if (strcmp (keyword, "Shared_Dirty:") == 0
873                   || strcmp (keyword, "Private_Dirty:") == 0
874                   || strcmp (keyword, "Swap:") == 0
875                   || strcmp (keyword, "Anonymous:") == 0)
876                 {
877                   unsigned long number;
878
879                   if (sscanf (line, "%*s%lu", &number) != 1)
880                     {
881                       warning (_("Error parsing {s,}maps file '%s' number"),
882                                mapsfilename);
883                       break;
884                     }
885                   if (number != 0)
886                     modified = 1;
887                 }
888             }
889
890           /* Older Linux kernels did not support the "Anonymous:" counter.
891              If it is missing, we can't be sure - dump all the pages.  */
892           if (!has_anonymous)
893             modified = 1;
894
895           /* Invoke the callback function to create the corefile segment.  */
896           func (addr, endaddr - addr, offset, inode,
897                 read, write, exec, modified, filename, obfd);
898         }
899
900       do_cleanups (cleanup);
901       return 0;
902     }
903
904   return 1;
905 }
906
907 /* A structure for passing information through
908    linux_find_memory_regions_full.  */
909
910 struct linux_find_memory_regions_data
911 {
912   /* The original callback.  */
913
914   find_memory_region_ftype func;
915
916   /* The original datum.  */
917
918   void *obfd;
919 };
920
921 /* A callback for linux_find_memory_regions that converts between the
922    "full"-style callback and find_memory_region_ftype.  */
923
924 static int
925 linux_find_memory_regions_thunk (ULONGEST vaddr, ULONGEST size,
926                                  ULONGEST offset, ULONGEST inode,
927                                  int read, int write, int exec, int modified,
928                                  const char *filename, void *arg)
929 {
930   struct linux_find_memory_regions_data *data = arg;
931
932   return data->func (vaddr, size, read, write, exec, modified, data->obfd);
933 }
934
935 /* A variant of linux_find_memory_regions_full that is suitable as the
936    gdbarch find_memory_regions method.  */
937
938 static int
939 linux_find_memory_regions (struct gdbarch *gdbarch,
940                            find_memory_region_ftype func, void *obfd)
941 {
942   struct linux_find_memory_regions_data data;
943
944   data.func = func;
945   data.obfd = obfd;
946
947   return linux_find_memory_regions_full (gdbarch,
948                                          linux_find_memory_regions_thunk,
949                                          &data);
950 }
951
952 /* Determine which signal stopped execution.  */
953
954 static int
955 find_signalled_thread (struct thread_info *info, void *data)
956 {
957   if (info->suspend.stop_signal != GDB_SIGNAL_0
958       && ptid_get_pid (info->ptid) == ptid_get_pid (inferior_ptid))
959     return 1;
960
961   return 0;
962 }
963
964 static enum gdb_signal
965 find_stop_signal (void)
966 {
967   struct thread_info *info =
968     iterate_over_threads (find_signalled_thread, NULL);
969
970   if (info)
971     return info->suspend.stop_signal;
972   else
973     return GDB_SIGNAL_0;
974 }
975
976 /* Generate corefile notes for SPU contexts.  */
977
978 static char *
979 linux_spu_make_corefile_notes (bfd *obfd, char *note_data, int *note_size)
980 {
981   static const char *spu_files[] =
982     {
983       "object-id",
984       "mem",
985       "regs",
986       "fpcr",
987       "lslr",
988       "decr",
989       "decr_status",
990       "signal1",
991       "signal1_type",
992       "signal2",
993       "signal2_type",
994       "event_mask",
995       "event_status",
996       "mbox_info",
997       "ibox_info",
998       "wbox_info",
999       "dma_info",
1000       "proxydma_info",
1001    };
1002
1003   enum bfd_endian byte_order = gdbarch_byte_order (target_gdbarch ());
1004   gdb_byte *spu_ids;
1005   LONGEST i, j, size;
1006
1007   /* Determine list of SPU ids.  */
1008   size = target_read_alloc (&current_target, TARGET_OBJECT_SPU,
1009                             NULL, &spu_ids);
1010
1011   /* Generate corefile notes for each SPU file.  */
1012   for (i = 0; i < size; i += 4)
1013     {
1014       int fd = extract_unsigned_integer (spu_ids + i, 4, byte_order);
1015
1016       for (j = 0; j < sizeof (spu_files) / sizeof (spu_files[0]); j++)
1017         {
1018           char annex[32], note_name[32];
1019           gdb_byte *spu_data;
1020           LONGEST spu_len;
1021
1022           xsnprintf (annex, sizeof annex, "%d/%s", fd, spu_files[j]);
1023           spu_len = target_read_alloc (&current_target, TARGET_OBJECT_SPU,
1024                                        annex, &spu_data);
1025           if (spu_len > 0)
1026             {
1027               xsnprintf (note_name, sizeof note_name, "SPU/%s", annex);
1028               note_data = elfcore_write_note (obfd, note_data, note_size,
1029                                               note_name, NT_SPU,
1030                                               spu_data, spu_len);
1031               xfree (spu_data);
1032
1033               if (!note_data)
1034                 {
1035                   xfree (spu_ids);
1036                   return NULL;
1037                 }
1038             }
1039         }
1040     }
1041
1042   if (size > 0)
1043     xfree (spu_ids);
1044
1045   return note_data;
1046 }
1047
1048 /* This is used to pass information from
1049    linux_make_mappings_corefile_notes through
1050    linux_find_memory_regions_full.  */
1051
1052 struct linux_make_mappings_data
1053 {
1054   /* Number of files mapped.  */
1055   ULONGEST file_count;
1056
1057   /* The obstack for the main part of the data.  */
1058   struct obstack *data_obstack;
1059
1060   /* The filename obstack.  */
1061   struct obstack *filename_obstack;
1062
1063   /* The architecture's "long" type.  */
1064   struct type *long_type;
1065 };
1066
1067 static linux_find_memory_region_ftype linux_make_mappings_callback;
1068
1069 /* A callback for linux_find_memory_regions_full that updates the
1070    mappings data for linux_make_mappings_corefile_notes.  */
1071
1072 static int
1073 linux_make_mappings_callback (ULONGEST vaddr, ULONGEST size,
1074                               ULONGEST offset, ULONGEST inode,
1075                               int read, int write, int exec, int modified,
1076                               const char *filename, void *data)
1077 {
1078   struct linux_make_mappings_data *map_data = data;
1079   gdb_byte buf[sizeof (ULONGEST)];
1080
1081   if (*filename == '\0' || inode == 0)
1082     return 0;
1083
1084   ++map_data->file_count;
1085
1086   pack_long (buf, map_data->long_type, vaddr);
1087   obstack_grow (map_data->data_obstack, buf, TYPE_LENGTH (map_data->long_type));
1088   pack_long (buf, map_data->long_type, vaddr + size);
1089   obstack_grow (map_data->data_obstack, buf, TYPE_LENGTH (map_data->long_type));
1090   pack_long (buf, map_data->long_type, offset);
1091   obstack_grow (map_data->data_obstack, buf, TYPE_LENGTH (map_data->long_type));
1092
1093   obstack_grow_str0 (map_data->filename_obstack, filename);
1094
1095   return 0;
1096 }
1097
1098 /* Write the file mapping data to the core file, if possible.  OBFD is
1099    the output BFD.  NOTE_DATA is the current note data, and NOTE_SIZE
1100    is a pointer to the note size.  Returns the new NOTE_DATA and
1101    updates NOTE_SIZE.  */
1102
1103 static char *
1104 linux_make_mappings_corefile_notes (struct gdbarch *gdbarch, bfd *obfd,
1105                                     char *note_data, int *note_size)
1106 {
1107   struct cleanup *cleanup;
1108   struct obstack data_obstack, filename_obstack;
1109   struct linux_make_mappings_data mapping_data;
1110   struct type *long_type
1111     = arch_integer_type (gdbarch, gdbarch_long_bit (gdbarch), 0, "long");
1112   gdb_byte buf[sizeof (ULONGEST)];
1113
1114   obstack_init (&data_obstack);
1115   cleanup = make_cleanup_obstack_free (&data_obstack);
1116   obstack_init (&filename_obstack);
1117   make_cleanup_obstack_free (&filename_obstack);
1118
1119   mapping_data.file_count = 0;
1120   mapping_data.data_obstack = &data_obstack;
1121   mapping_data.filename_obstack = &filename_obstack;
1122   mapping_data.long_type = long_type;
1123
1124   /* Reserve space for the count.  */
1125   obstack_blank (&data_obstack, TYPE_LENGTH (long_type));
1126   /* We always write the page size as 1 since we have no good way to
1127      determine the correct value.  */
1128   pack_long (buf, long_type, 1);
1129   obstack_grow (&data_obstack, buf, TYPE_LENGTH (long_type));
1130
1131   linux_find_memory_regions_full (gdbarch, linux_make_mappings_callback,
1132                                   &mapping_data);
1133
1134   if (mapping_data.file_count != 0)
1135     {
1136       /* Write the count to the obstack.  */
1137       pack_long ((gdb_byte *) obstack_base (&data_obstack),
1138                  long_type, mapping_data.file_count);
1139
1140       /* Copy the filenames to the data obstack.  */
1141       obstack_grow (&data_obstack, obstack_base (&filename_obstack),
1142                     obstack_object_size (&filename_obstack));
1143
1144       note_data = elfcore_write_note (obfd, note_data, note_size,
1145                                       "CORE", NT_FILE,
1146                                       obstack_base (&data_obstack),
1147                                       obstack_object_size (&data_obstack));
1148     }
1149
1150   do_cleanups (cleanup);
1151   return note_data;
1152 }
1153
1154 /* Structure for passing information from
1155    linux_collect_thread_registers via an iterator to
1156    linux_collect_regset_section_cb. */
1157
1158 struct linux_collect_regset_section_cb_data
1159 {
1160   struct gdbarch *gdbarch;
1161   const struct regcache *regcache;
1162   bfd *obfd;
1163   char *note_data;
1164   int *note_size;
1165   unsigned long lwp;
1166   enum gdb_signal stop_signal;
1167   int abort_iteration;
1168 };
1169
1170 /* Callback for iterate_over_regset_sections that records a single
1171    regset in the corefile note section.  */
1172
1173 static void
1174 linux_collect_regset_section_cb (const char *sect_name, int size,
1175                                  const struct regset *regset,
1176                                  const char *human_name, void *cb_data)
1177 {
1178   char *buf;
1179   struct linux_collect_regset_section_cb_data *data = cb_data;
1180
1181   if (data->abort_iteration)
1182     return;
1183
1184   gdb_assert (regset && regset->collect_regset);
1185
1186   buf = xmalloc (size);
1187   regset->collect_regset (regset, data->regcache, -1, buf, size);
1188
1189   /* PRSTATUS still needs to be treated specially.  */
1190   if (strcmp (sect_name, ".reg") == 0)
1191     data->note_data = (char *) elfcore_write_prstatus
1192       (data->obfd, data->note_data, data->note_size, data->lwp,
1193        gdb_signal_to_host (data->stop_signal), buf);
1194   else
1195     data->note_data = (char *) elfcore_write_register_note
1196       (data->obfd, data->note_data, data->note_size,
1197        sect_name, buf, size);
1198   xfree (buf);
1199
1200   if (data->note_data == NULL)
1201     data->abort_iteration = 1;
1202 }
1203
1204 /* Records the thread's register state for the corefile note
1205    section.  */
1206
1207 static char *
1208 linux_collect_thread_registers (const struct regcache *regcache,
1209                                 ptid_t ptid, bfd *obfd,
1210                                 char *note_data, int *note_size,
1211                                 enum gdb_signal stop_signal)
1212 {
1213   struct gdbarch *gdbarch = get_regcache_arch (regcache);
1214   struct linux_collect_regset_section_cb_data data;
1215
1216   data.gdbarch = gdbarch;
1217   data.regcache = regcache;
1218   data.obfd = obfd;
1219   data.note_data = note_data;
1220   data.note_size = note_size;
1221   data.stop_signal = stop_signal;
1222   data.abort_iteration = 0;
1223
1224   /* For remote targets the LWP may not be available, so use the TID.  */
1225   data.lwp = ptid_get_lwp (ptid);
1226   if (!data.lwp)
1227     data.lwp = ptid_get_tid (ptid);
1228
1229   gdbarch_iterate_over_regset_sections (gdbarch,
1230                                         linux_collect_regset_section_cb,
1231                                         &data, regcache);
1232   return data.note_data;
1233 }
1234
1235 /* Fetch the siginfo data for the current thread, if it exists.  If
1236    there is no data, or we could not read it, return NULL.  Otherwise,
1237    return a newly malloc'd buffer holding the data and fill in *SIZE
1238    with the size of the data.  The caller is responsible for freeing
1239    the data.  */
1240
1241 static gdb_byte *
1242 linux_get_siginfo_data (struct gdbarch *gdbarch, LONGEST *size)
1243 {
1244   struct type *siginfo_type;
1245   gdb_byte *buf;
1246   LONGEST bytes_read;
1247   struct cleanup *cleanups;
1248
1249   if (!gdbarch_get_siginfo_type_p (gdbarch))
1250     return NULL;
1251   
1252   siginfo_type = gdbarch_get_siginfo_type (gdbarch);
1253
1254   buf = xmalloc (TYPE_LENGTH (siginfo_type));
1255   cleanups = make_cleanup (xfree, buf);
1256
1257   bytes_read = target_read (&current_target, TARGET_OBJECT_SIGNAL_INFO, NULL,
1258                             buf, 0, TYPE_LENGTH (siginfo_type));
1259   if (bytes_read == TYPE_LENGTH (siginfo_type))
1260     {
1261       discard_cleanups (cleanups);
1262       *size = bytes_read;
1263     }
1264   else
1265     {
1266       do_cleanups (cleanups);
1267       buf = NULL;
1268     }
1269
1270   return buf;
1271 }
1272
1273 struct linux_corefile_thread_data
1274 {
1275   struct gdbarch *gdbarch;
1276   int pid;
1277   bfd *obfd;
1278   char *note_data;
1279   int *note_size;
1280   enum gdb_signal stop_signal;
1281 };
1282
1283 /* Called by gdbthread.c once per thread.  Records the thread's
1284    register state for the corefile note section.  */
1285
1286 static int
1287 linux_corefile_thread_callback (struct thread_info *info, void *data)
1288 {
1289   struct linux_corefile_thread_data *args = data;
1290
1291   /* It can be current thread
1292      which cannot be removed by update_thread_list.  */
1293   if (info->state == THREAD_EXITED)
1294     return 0;
1295
1296   if (ptid_get_pid (info->ptid) == args->pid)
1297     {
1298       struct cleanup *old_chain;
1299       struct regcache *regcache;
1300       gdb_byte *siginfo_data;
1301       LONGEST siginfo_size = 0;
1302
1303       regcache = get_thread_arch_regcache (info->ptid, args->gdbarch);
1304
1305       old_chain = save_inferior_ptid ();
1306       inferior_ptid = info->ptid;
1307       target_fetch_registers (regcache, -1);
1308       siginfo_data = linux_get_siginfo_data (args->gdbarch, &siginfo_size);
1309       do_cleanups (old_chain);
1310
1311       old_chain = make_cleanup (xfree, siginfo_data);
1312
1313       args->note_data = linux_collect_thread_registers
1314         (regcache, info->ptid, args->obfd, args->note_data,
1315          args->note_size, args->stop_signal);
1316
1317       /* Don't return anything if we got no register information above,
1318          such a core file is useless.  */
1319       if (args->note_data != NULL)
1320         if (siginfo_data != NULL)
1321           args->note_data = elfcore_write_note (args->obfd,
1322                                                 args->note_data,
1323                                                 args->note_size,
1324                                                 "CORE", NT_SIGINFO,
1325                                                 siginfo_data, siginfo_size);
1326
1327       do_cleanups (old_chain);
1328     }
1329
1330   return !args->note_data;
1331 }
1332
1333 /* Fill the PRPSINFO structure with information about the process being
1334    debugged.  Returns 1 in case of success, 0 for failures.  Please note that
1335    even if the structure cannot be entirely filled (e.g., GDB was unable to
1336    gather information about the process UID/GID), this function will still
1337    return 1 since some information was already recorded.  It will only return
1338    0 iff nothing can be gathered.  */
1339
1340 static int
1341 linux_fill_prpsinfo (struct elf_internal_linux_prpsinfo *p)
1342 {
1343   /* The filename which we will use to obtain some info about the process.
1344      We will basically use this to store the `/proc/PID/FILENAME' file.  */
1345   char filename[100];
1346   /* The full name of the program which generated the corefile.  */
1347   char *fname;
1348   /* The basename of the executable.  */
1349   const char *basename;
1350   /* The arguments of the program.  */
1351   char *psargs;
1352   char *infargs;
1353   /* The contents of `/proc/PID/stat' and `/proc/PID/status' files.  */
1354   char *proc_stat, *proc_status;
1355   /* Temporary buffer.  */
1356   char *tmpstr;
1357   /* The valid states of a process, according to the Linux kernel.  */
1358   const char valid_states[] = "RSDTZW";
1359   /* The program state.  */
1360   const char *prog_state;
1361   /* The state of the process.  */
1362   char pr_sname;
1363   /* The PID of the program which generated the corefile.  */
1364   pid_t pid;
1365   /* Process flags.  */
1366   unsigned int pr_flag;
1367   /* Process nice value.  */
1368   long pr_nice;
1369   /* The number of fields read by `sscanf'.  */
1370   int n_fields = 0;
1371   /* Cleanups.  */
1372   struct cleanup *c;
1373   int i;
1374
1375   gdb_assert (p != NULL);
1376
1377   /* Obtaining PID and filename.  */
1378   pid = ptid_get_pid (inferior_ptid);
1379   xsnprintf (filename, sizeof (filename), "/proc/%d/cmdline", (int) pid);
1380   fname = target_fileio_read_stralloc (filename);
1381
1382   if (fname == NULL || *fname == '\0')
1383     {
1384       /* No program name was read, so we won't be able to retrieve more
1385          information about the process.  */
1386       xfree (fname);
1387       return 0;
1388     }
1389
1390   c = make_cleanup (xfree, fname);
1391   memset (p, 0, sizeof (*p));
1392
1393   /* Defining the PID.  */
1394   p->pr_pid = pid;
1395
1396   /* Copying the program name.  Only the basename matters.  */
1397   basename = lbasename (fname);
1398   strncpy (p->pr_fname, basename, sizeof (p->pr_fname));
1399   p->pr_fname[sizeof (p->pr_fname) - 1] = '\0';
1400
1401   infargs = get_inferior_args ();
1402
1403   psargs = xstrdup (fname);
1404   if (infargs != NULL)
1405     psargs = reconcat (psargs, psargs, " ", infargs, NULL);
1406
1407   make_cleanup (xfree, psargs);
1408
1409   strncpy (p->pr_psargs, psargs, sizeof (p->pr_psargs));
1410   p->pr_psargs[sizeof (p->pr_psargs) - 1] = '\0';
1411
1412   xsnprintf (filename, sizeof (filename), "/proc/%d/stat", (int) pid);
1413   proc_stat = target_fileio_read_stralloc (filename);
1414   make_cleanup (xfree, proc_stat);
1415
1416   if (proc_stat == NULL || *proc_stat == '\0')
1417     {
1418       /* Despite being unable to read more information about the
1419          process, we return 1 here because at least we have its
1420          command line, PID and arguments.  */
1421       do_cleanups (c);
1422       return 1;
1423     }
1424
1425   /* Ok, we have the stats.  It's time to do a little parsing of the
1426      contents of the buffer, so that we end up reading what we want.
1427
1428      The following parsing mechanism is strongly based on the
1429      information generated by the `fs/proc/array.c' file, present in
1430      the Linux kernel tree.  More details about how the information is
1431      displayed can be obtained by seeing the manpage of proc(5),
1432      specifically under the entry of `/proc/[pid]/stat'.  */
1433
1434   /* Getting rid of the PID, since we already have it.  */
1435   while (isdigit (*proc_stat))
1436     ++proc_stat;
1437
1438   proc_stat = skip_spaces (proc_stat);
1439
1440   /* ps command also relies on no trailing fields ever contain ')'.  */
1441   proc_stat = strrchr (proc_stat, ')');
1442   if (proc_stat == NULL)
1443     {
1444       do_cleanups (c);
1445       return 1;
1446     }
1447   proc_stat++;
1448
1449   proc_stat = skip_spaces (proc_stat);
1450
1451   n_fields = sscanf (proc_stat,
1452                      "%c"               /* Process state.  */
1453                      "%d%d%d"           /* Parent PID, group ID, session ID.  */
1454                      "%*d%*d"           /* tty_nr, tpgid (not used).  */
1455                      "%u"               /* Flags.  */
1456                      "%*s%*s%*s%*s"     /* minflt, cminflt, majflt,
1457                                            cmajflt (not used).  */
1458                      "%*s%*s%*s%*s"     /* utime, stime, cutime,
1459                                            cstime (not used).  */
1460                      "%*s"              /* Priority (not used).  */
1461                      "%ld",             /* Nice.  */
1462                      &pr_sname,
1463                      &p->pr_ppid, &p->pr_pgrp, &p->pr_sid,
1464                      &pr_flag,
1465                      &pr_nice);
1466
1467   if (n_fields != 6)
1468     {
1469       /* Again, we couldn't read the complementary information about
1470          the process state.  However, we already have minimal
1471          information, so we just return 1 here.  */
1472       do_cleanups (c);
1473       return 1;
1474     }
1475
1476   /* Filling the structure fields.  */
1477   prog_state = strchr (valid_states, pr_sname);
1478   if (prog_state != NULL)
1479     p->pr_state = prog_state - valid_states;
1480   else
1481     {
1482       /* Zero means "Running".  */
1483       p->pr_state = 0;
1484     }
1485
1486   p->pr_sname = p->pr_state > 5 ? '.' : pr_sname;
1487   p->pr_zomb = p->pr_sname == 'Z';
1488   p->pr_nice = pr_nice;
1489   p->pr_flag = pr_flag;
1490
1491   /* Finally, obtaining the UID and GID.  For that, we read and parse the
1492      contents of the `/proc/PID/status' file.  */
1493   xsnprintf (filename, sizeof (filename), "/proc/%d/status", (int) pid);
1494   proc_status = target_fileio_read_stralloc (filename);
1495   make_cleanup (xfree, proc_status);
1496
1497   if (proc_status == NULL || *proc_status == '\0')
1498     {
1499       /* Returning 1 since we already have a bunch of information.  */
1500       do_cleanups (c);
1501       return 1;
1502     }
1503
1504   /* Extracting the UID.  */
1505   tmpstr = strstr (proc_status, "Uid:");
1506   if (tmpstr != NULL)
1507     {
1508       /* Advancing the pointer to the beginning of the UID.  */
1509       tmpstr += sizeof ("Uid:");
1510       while (*tmpstr != '\0' && !isdigit (*tmpstr))
1511         ++tmpstr;
1512
1513       if (isdigit (*tmpstr))
1514         p->pr_uid = strtol (tmpstr, &tmpstr, 10);
1515     }
1516
1517   /* Extracting the GID.  */
1518   tmpstr = strstr (proc_status, "Gid:");
1519   if (tmpstr != NULL)
1520     {
1521       /* Advancing the pointer to the beginning of the GID.  */
1522       tmpstr += sizeof ("Gid:");
1523       while (*tmpstr != '\0' && !isdigit (*tmpstr))
1524         ++tmpstr;
1525
1526       if (isdigit (*tmpstr))
1527         p->pr_gid = strtol (tmpstr, &tmpstr, 10);
1528     }
1529
1530   do_cleanups (c);
1531
1532   return 1;
1533 }
1534
1535 /* Build the note section for a corefile, and return it in a malloc
1536    buffer.  */
1537
1538 static char *
1539 linux_make_corefile_notes (struct gdbarch *gdbarch, bfd *obfd, int *note_size)
1540 {
1541   struct linux_corefile_thread_data thread_args;
1542   struct elf_internal_linux_prpsinfo prpsinfo;
1543   char *note_data = NULL;
1544   gdb_byte *auxv;
1545   int auxv_len;
1546   volatile struct gdb_exception e;
1547
1548   if (! gdbarch_iterate_over_regset_sections_p (gdbarch))
1549     return NULL;
1550
1551   if (linux_fill_prpsinfo (&prpsinfo))
1552     {
1553       if (gdbarch_elfcore_write_linux_prpsinfo_p (gdbarch))
1554         {
1555           note_data = gdbarch_elfcore_write_linux_prpsinfo (gdbarch, obfd,
1556                                                             note_data, note_size,
1557                                                             &prpsinfo);
1558         }
1559       else
1560         {
1561           if (gdbarch_ptr_bit (gdbarch) == 64)
1562             note_data = elfcore_write_linux_prpsinfo64 (obfd,
1563                                                         note_data, note_size,
1564                                                         &prpsinfo);
1565           else
1566             note_data = elfcore_write_linux_prpsinfo32 (obfd,
1567                                                         note_data, note_size,
1568                                                         &prpsinfo);
1569         }
1570     }
1571
1572   /* Thread register information.  */
1573   TRY_CATCH (e, RETURN_MASK_ERROR)
1574     {
1575       update_thread_list ();
1576     }
1577   if (e.reason < 0)
1578     exception_print (gdb_stderr, e);
1579   thread_args.gdbarch = gdbarch;
1580   thread_args.pid = ptid_get_pid (inferior_ptid);
1581   thread_args.obfd = obfd;
1582   thread_args.note_data = note_data;
1583   thread_args.note_size = note_size;
1584   thread_args.stop_signal = find_stop_signal ();
1585   iterate_over_threads (linux_corefile_thread_callback, &thread_args);
1586   note_data = thread_args.note_data;
1587   if (!note_data)
1588     return NULL;
1589
1590   /* Auxillary vector.  */
1591   auxv_len = target_read_alloc (&current_target, TARGET_OBJECT_AUXV,
1592                                 NULL, &auxv);
1593   if (auxv_len > 0)
1594     {
1595       note_data = elfcore_write_note (obfd, note_data, note_size,
1596                                       "CORE", NT_AUXV, auxv, auxv_len);
1597       xfree (auxv);
1598
1599       if (!note_data)
1600         return NULL;
1601     }
1602
1603   /* SPU information.  */
1604   note_data = linux_spu_make_corefile_notes (obfd, note_data, note_size);
1605   if (!note_data)
1606     return NULL;
1607
1608   /* File mappings.  */
1609   note_data = linux_make_mappings_corefile_notes (gdbarch, obfd,
1610                                                   note_data, note_size);
1611
1612   return note_data;
1613 }
1614
1615 /* Implementation of `gdbarch_gdb_signal_from_target', as defined in
1616    gdbarch.h.  This function is not static because it is exported to
1617    other -tdep files.  */
1618
1619 enum gdb_signal
1620 linux_gdb_signal_from_target (struct gdbarch *gdbarch, int signal)
1621 {
1622   switch (signal)
1623     {
1624     case 0:
1625       return GDB_SIGNAL_0;
1626
1627     case LINUX_SIGHUP:
1628       return GDB_SIGNAL_HUP;
1629
1630     case LINUX_SIGINT:
1631       return GDB_SIGNAL_INT;
1632
1633     case LINUX_SIGQUIT:
1634       return GDB_SIGNAL_QUIT;
1635
1636     case LINUX_SIGILL:
1637       return GDB_SIGNAL_ILL;
1638
1639     case LINUX_SIGTRAP:
1640       return GDB_SIGNAL_TRAP;
1641
1642     case LINUX_SIGABRT:
1643       return GDB_SIGNAL_ABRT;
1644
1645     case LINUX_SIGBUS:
1646       return GDB_SIGNAL_BUS;
1647
1648     case LINUX_SIGFPE:
1649       return GDB_SIGNAL_FPE;
1650
1651     case LINUX_SIGKILL:
1652       return GDB_SIGNAL_KILL;
1653
1654     case LINUX_SIGUSR1:
1655       return GDB_SIGNAL_USR1;
1656
1657     case LINUX_SIGSEGV:
1658       return GDB_SIGNAL_SEGV;
1659
1660     case LINUX_SIGUSR2:
1661       return GDB_SIGNAL_USR2;
1662
1663     case LINUX_SIGPIPE:
1664       return GDB_SIGNAL_PIPE;
1665
1666     case LINUX_SIGALRM:
1667       return GDB_SIGNAL_ALRM;
1668
1669     case LINUX_SIGTERM:
1670       return GDB_SIGNAL_TERM;
1671
1672     case LINUX_SIGCHLD:
1673       return GDB_SIGNAL_CHLD;
1674
1675     case LINUX_SIGCONT:
1676       return GDB_SIGNAL_CONT;
1677
1678     case LINUX_SIGSTOP:
1679       return GDB_SIGNAL_STOP;
1680
1681     case LINUX_SIGTSTP:
1682       return GDB_SIGNAL_TSTP;
1683
1684     case LINUX_SIGTTIN:
1685       return GDB_SIGNAL_TTIN;
1686
1687     case LINUX_SIGTTOU:
1688       return GDB_SIGNAL_TTOU;
1689
1690     case LINUX_SIGURG:
1691       return GDB_SIGNAL_URG;
1692
1693     case LINUX_SIGXCPU:
1694       return GDB_SIGNAL_XCPU;
1695
1696     case LINUX_SIGXFSZ:
1697       return GDB_SIGNAL_XFSZ;
1698
1699     case LINUX_SIGVTALRM:
1700       return GDB_SIGNAL_VTALRM;
1701
1702     case LINUX_SIGPROF:
1703       return GDB_SIGNAL_PROF;
1704
1705     case LINUX_SIGWINCH:
1706       return GDB_SIGNAL_WINCH;
1707
1708     /* No way to differentiate between SIGIO and SIGPOLL.
1709        Therefore, we just handle the first one.  */
1710     case LINUX_SIGIO:
1711       return GDB_SIGNAL_IO;
1712
1713     case LINUX_SIGPWR:
1714       return GDB_SIGNAL_PWR;
1715
1716     case LINUX_SIGSYS:
1717       return GDB_SIGNAL_SYS;
1718
1719     /* SIGRTMIN and SIGRTMAX are not continuous in <gdb/signals.def>,
1720        therefore we have to handle them here.  */
1721     case LINUX_SIGRTMIN:
1722       return GDB_SIGNAL_REALTIME_32;
1723
1724     case LINUX_SIGRTMAX:
1725       return GDB_SIGNAL_REALTIME_64;
1726     }
1727
1728   if (signal >= LINUX_SIGRTMIN + 1 && signal <= LINUX_SIGRTMAX - 1)
1729     {
1730       int offset = signal - LINUX_SIGRTMIN + 1;
1731
1732       return (enum gdb_signal) ((int) GDB_SIGNAL_REALTIME_33 + offset);
1733     }
1734
1735   return GDB_SIGNAL_UNKNOWN;
1736 }
1737
1738 /* Implementation of `gdbarch_gdb_signal_to_target', as defined in
1739    gdbarch.h.  This function is not static because it is exported to
1740    other -tdep files.  */
1741
1742 int
1743 linux_gdb_signal_to_target (struct gdbarch *gdbarch,
1744                             enum gdb_signal signal)
1745 {
1746   switch (signal)
1747     {
1748     case GDB_SIGNAL_0:
1749       return 0;
1750
1751     case GDB_SIGNAL_HUP:
1752       return LINUX_SIGHUP;
1753
1754     case GDB_SIGNAL_INT:
1755       return LINUX_SIGINT;
1756
1757     case GDB_SIGNAL_QUIT:
1758       return LINUX_SIGQUIT;
1759
1760     case GDB_SIGNAL_ILL:
1761       return LINUX_SIGILL;
1762
1763     case GDB_SIGNAL_TRAP:
1764       return LINUX_SIGTRAP;
1765
1766     case GDB_SIGNAL_ABRT:
1767       return LINUX_SIGABRT;
1768
1769     case GDB_SIGNAL_FPE:
1770       return LINUX_SIGFPE;
1771
1772     case GDB_SIGNAL_KILL:
1773       return LINUX_SIGKILL;
1774
1775     case GDB_SIGNAL_BUS:
1776       return LINUX_SIGBUS;
1777
1778     case GDB_SIGNAL_SEGV:
1779       return LINUX_SIGSEGV;
1780
1781     case GDB_SIGNAL_SYS:
1782       return LINUX_SIGSYS;
1783
1784     case GDB_SIGNAL_PIPE:
1785       return LINUX_SIGPIPE;
1786
1787     case GDB_SIGNAL_ALRM:
1788       return LINUX_SIGALRM;
1789
1790     case GDB_SIGNAL_TERM:
1791       return LINUX_SIGTERM;
1792
1793     case GDB_SIGNAL_URG:
1794       return LINUX_SIGURG;
1795
1796     case GDB_SIGNAL_STOP:
1797       return LINUX_SIGSTOP;
1798
1799     case GDB_SIGNAL_TSTP:
1800       return LINUX_SIGTSTP;
1801
1802     case GDB_SIGNAL_CONT:
1803       return LINUX_SIGCONT;
1804
1805     case GDB_SIGNAL_CHLD:
1806       return LINUX_SIGCHLD;
1807
1808     case GDB_SIGNAL_TTIN:
1809       return LINUX_SIGTTIN;
1810
1811     case GDB_SIGNAL_TTOU:
1812       return LINUX_SIGTTOU;
1813
1814     case GDB_SIGNAL_IO:
1815       return LINUX_SIGIO;
1816
1817     case GDB_SIGNAL_XCPU:
1818       return LINUX_SIGXCPU;
1819
1820     case GDB_SIGNAL_XFSZ:
1821       return LINUX_SIGXFSZ;
1822
1823     case GDB_SIGNAL_VTALRM:
1824       return LINUX_SIGVTALRM;
1825
1826     case GDB_SIGNAL_PROF:
1827       return LINUX_SIGPROF;
1828
1829     case GDB_SIGNAL_WINCH:
1830       return LINUX_SIGWINCH;
1831
1832     case GDB_SIGNAL_USR1:
1833       return LINUX_SIGUSR1;
1834
1835     case GDB_SIGNAL_USR2:
1836       return LINUX_SIGUSR2;
1837
1838     case GDB_SIGNAL_PWR:
1839       return LINUX_SIGPWR;
1840
1841     case GDB_SIGNAL_POLL:
1842       return LINUX_SIGPOLL;
1843
1844     /* GDB_SIGNAL_REALTIME_32 is not continuous in <gdb/signals.def>,
1845        therefore we have to handle it here.  */
1846     case GDB_SIGNAL_REALTIME_32:
1847       return LINUX_SIGRTMIN;
1848
1849     /* Same comment applies to _64.  */
1850     case GDB_SIGNAL_REALTIME_64:
1851       return LINUX_SIGRTMAX;
1852     }
1853
1854   /* GDB_SIGNAL_REALTIME_33 to _64 are continuous.  */
1855   if (signal >= GDB_SIGNAL_REALTIME_33
1856       && signal <= GDB_SIGNAL_REALTIME_63)
1857     {
1858       int offset = signal - GDB_SIGNAL_REALTIME_33;
1859
1860       return LINUX_SIGRTMIN + 1 + offset;
1861     }
1862
1863   return -1;
1864 }
1865
1866 /* Rummage through mappings to find a mapping's size.  */
1867
1868 static int
1869 find_mapping_size (CORE_ADDR vaddr, unsigned long size,
1870                    int read, int write, int exec, int modified,
1871                    void *data)
1872 {
1873   struct mem_range *range = data;
1874
1875   if (vaddr == range->start)
1876     {
1877       range->length = size;
1878       return 1;
1879     }
1880   return 0;
1881 }
1882
1883 /* Helper for linux_vsyscall_range that does the real work of finding
1884    the vsyscall's address range.  */
1885
1886 static int
1887 linux_vsyscall_range_raw (struct gdbarch *gdbarch, struct mem_range *range)
1888 {
1889   if (target_auxv_search (&current_target, AT_SYSINFO_EHDR, &range->start) <= 0)
1890     return 0;
1891
1892   /* This is installed by linux_init_abi below, so should always be
1893      available.  */
1894   gdb_assert (gdbarch_find_memory_regions_p (target_gdbarch ()));
1895
1896   range->length = 0;
1897   gdbarch_find_memory_regions (gdbarch, find_mapping_size, range);
1898   return 1;
1899 }
1900
1901 /* Implementation of the "vsyscall_range" gdbarch hook.  Handles
1902    caching, and defers the real work to linux_vsyscall_range_raw.  */
1903
1904 static int
1905 linux_vsyscall_range (struct gdbarch *gdbarch, struct mem_range *range)
1906 {
1907   struct linux_info *info = get_linux_inferior_data ();
1908
1909   if (info->vsyscall_range_p == 0)
1910     {
1911       if (linux_vsyscall_range_raw (gdbarch, &info->vsyscall_range))
1912         info->vsyscall_range_p = 1;
1913       else
1914         info->vsyscall_range_p = -1;
1915     }
1916
1917   if (info->vsyscall_range_p < 0)
1918     return 0;
1919
1920   *range = info->vsyscall_range;
1921   return 1;
1922 }
1923
1924 /* To be called from the various GDB_OSABI_LINUX handlers for the
1925    various GNU/Linux architectures and machine types.  */
1926
1927 void
1928 linux_init_abi (struct gdbarch_info info, struct gdbarch *gdbarch)
1929 {
1930   set_gdbarch_core_pid_to_str (gdbarch, linux_core_pid_to_str);
1931   set_gdbarch_info_proc (gdbarch, linux_info_proc);
1932   set_gdbarch_core_info_proc (gdbarch, linux_core_info_proc);
1933   set_gdbarch_find_memory_regions (gdbarch, linux_find_memory_regions);
1934   set_gdbarch_make_corefile_notes (gdbarch, linux_make_corefile_notes);
1935   set_gdbarch_has_shared_address_space (gdbarch,
1936                                         linux_has_shared_address_space);
1937   set_gdbarch_gdb_signal_from_target (gdbarch,
1938                                       linux_gdb_signal_from_target);
1939   set_gdbarch_gdb_signal_to_target (gdbarch,
1940                                     linux_gdb_signal_to_target);
1941   set_gdbarch_vsyscall_range (gdbarch, linux_vsyscall_range);
1942 }
1943
1944 /* Provide a prototype to silence -Wmissing-prototypes.  */
1945 extern initialize_file_ftype _initialize_linux_tdep;
1946
1947 void
1948 _initialize_linux_tdep (void)
1949 {
1950   linux_gdbarch_data_handle =
1951     gdbarch_data_register_post_init (init_linux_gdbarch_data);
1952
1953   /* Set a cache per-inferior.  */
1954   linux_inferior_data
1955     = register_inferior_data_with_cleanup (NULL, linux_inferior_data_cleanup);
1956   /* Observers used to invalidate the cache when needed.  */
1957   observer_attach_inferior_exit (invalidate_linux_cache_inf);
1958   observer_attach_inferior_appeared (invalidate_linux_cache_inf);
1959 }