Split size in regset section iterators
[external/binutils.git] / gdb / linux-tdep.c
1 /* Target-dependent code for GNU/Linux, architecture independent.
2
3    Copyright (C) 2009-2018 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 "observable.h"
36 #include "objfiles.h"
37 #include "infcall.h"
38 #include "gdbcmd.h"
39 #include "gdb_regex.h"
40 #include "common/enum-flags.h"
41 #include "common/gdb_optional.h"
42
43 #include <ctype.h>
44
45 /* This enum represents the values that the user can choose when
46    informing the Linux kernel about which memory mappings will be
47    dumped in a corefile.  They are described in the file
48    Documentation/filesystems/proc.txt, inside the Linux kernel
49    tree.  */
50
51 enum filter_flag
52   {
53     COREFILTER_ANON_PRIVATE = 1 << 0,
54     COREFILTER_ANON_SHARED = 1 << 1,
55     COREFILTER_MAPPED_PRIVATE = 1 << 2,
56     COREFILTER_MAPPED_SHARED = 1 << 3,
57     COREFILTER_ELF_HEADERS = 1 << 4,
58     COREFILTER_HUGETLB_PRIVATE = 1 << 5,
59     COREFILTER_HUGETLB_SHARED = 1 << 6,
60   };
61 DEF_ENUM_FLAGS_TYPE (enum filter_flag, filter_flags);
62
63 /* This struct is used to map flags found in the "VmFlags:" field (in
64    the /proc/<PID>/smaps file).  */
65
66 struct smaps_vmflags
67   {
68     /* Zero if this structure has not been initialized yet.  It
69        probably means that the Linux kernel being used does not emit
70        the "VmFlags:" field on "/proc/PID/smaps".  */
71
72     unsigned int initialized_p : 1;
73
74     /* Memory mapped I/O area (VM_IO, "io").  */
75
76     unsigned int io_page : 1;
77
78     /* Area uses huge TLB pages (VM_HUGETLB, "ht").  */
79
80     unsigned int uses_huge_tlb : 1;
81
82     /* Do not include this memory region on the coredump (VM_DONTDUMP, "dd").  */
83
84     unsigned int exclude_coredump : 1;
85
86     /* Is this a MAP_SHARED mapping (VM_SHARED, "sh").  */
87
88     unsigned int shared_mapping : 1;
89   };
90
91 /* Whether to take the /proc/PID/coredump_filter into account when
92    generating a corefile.  */
93
94 static int use_coredump_filter = 1;
95
96 /* Whether the value of smaps_vmflags->exclude_coredump should be
97    ignored, including mappings marked with the VM_DONTDUMP flag in
98    the dump.  */
99 static int dump_excluded_mappings = 0;
100
101 /* This enum represents the signals' numbers on a generic architecture
102    running the Linux kernel.  The definition of "generic" comes from
103    the file <include/uapi/asm-generic/signal.h>, from the Linux kernel
104    tree, which is the "de facto" implementation of signal numbers to
105    be used by new architecture ports.
106
107    For those architectures which have differences between the generic
108    standard (e.g., Alpha), we define the different signals (and *only*
109    those) in the specific target-dependent file (e.g.,
110    alpha-linux-tdep.c, for Alpha).  Please refer to the architecture's
111    tdep file for more information.
112
113    ARM deserves a special mention here.  On the file
114    <arch/arm/include/uapi/asm/signal.h>, it defines only one different
115    (and ARM-only) signal, which is SIGSWI, with the same number as
116    SIGRTMIN.  This signal is used only for a very specific target,
117    called ArthurOS (from RISCOS).  Therefore, we do not handle it on
118    the ARM-tdep file, and we can safely use the generic signal handler
119    here for ARM targets.
120
121    As stated above, this enum is derived from
122    <include/uapi/asm-generic/signal.h>, from the Linux kernel
123    tree.  */
124
125 enum
126   {
127     LINUX_SIGHUP = 1,
128     LINUX_SIGINT = 2,
129     LINUX_SIGQUIT = 3,
130     LINUX_SIGILL = 4,
131     LINUX_SIGTRAP = 5,
132     LINUX_SIGABRT = 6,
133     LINUX_SIGIOT = 6,
134     LINUX_SIGBUS = 7,
135     LINUX_SIGFPE = 8,
136     LINUX_SIGKILL = 9,
137     LINUX_SIGUSR1 = 10,
138     LINUX_SIGSEGV = 11,
139     LINUX_SIGUSR2 = 12,
140     LINUX_SIGPIPE = 13,
141     LINUX_SIGALRM = 14,
142     LINUX_SIGTERM = 15,
143     LINUX_SIGSTKFLT = 16,
144     LINUX_SIGCHLD = 17,
145     LINUX_SIGCONT = 18,
146     LINUX_SIGSTOP = 19,
147     LINUX_SIGTSTP = 20,
148     LINUX_SIGTTIN = 21,
149     LINUX_SIGTTOU = 22,
150     LINUX_SIGURG = 23,
151     LINUX_SIGXCPU = 24,
152     LINUX_SIGXFSZ = 25,
153     LINUX_SIGVTALRM = 26,
154     LINUX_SIGPROF = 27,
155     LINUX_SIGWINCH = 28,
156     LINUX_SIGIO = 29,
157     LINUX_SIGPOLL = LINUX_SIGIO,
158     LINUX_SIGPWR = 30,
159     LINUX_SIGSYS = 31,
160     LINUX_SIGUNUSED = 31,
161
162     LINUX_SIGRTMIN = 32,
163     LINUX_SIGRTMAX = 64,
164   };
165
166 static struct gdbarch_data *linux_gdbarch_data_handle;
167
168 struct linux_gdbarch_data
169   {
170     struct type *siginfo_type;
171   };
172
173 static void *
174 init_linux_gdbarch_data (struct gdbarch *gdbarch)
175 {
176   return GDBARCH_OBSTACK_ZALLOC (gdbarch, struct linux_gdbarch_data);
177 }
178
179 static struct linux_gdbarch_data *
180 get_linux_gdbarch_data (struct gdbarch *gdbarch)
181 {
182   return ((struct linux_gdbarch_data *)
183           gdbarch_data (gdbarch, linux_gdbarch_data_handle));
184 }
185
186 /* Per-inferior data key.  */
187 static const struct inferior_data *linux_inferior_data;
188
189 /* Linux-specific cached data.  This is used by GDB for caching
190    purposes for each inferior.  This helps reduce the overhead of
191    transfering data from a remote target to the local host.  */
192 struct linux_info
193 {
194   /* Cache of the inferior's vsyscall/vDSO mapping range.  Only valid
195      if VSYSCALL_RANGE_P is positive.  This is cached because getting
196      at this info requires an auxv lookup (which is itself cached),
197      and looking through the inferior's mappings (which change
198      throughout execution and therefore cannot be cached).  */
199   struct mem_range vsyscall_range;
200
201   /* Zero if we haven't tried looking up the vsyscall's range before
202      yet.  Positive if we tried looking it up, and found it.  Negative
203      if we tried looking it up but failed.  */
204   int vsyscall_range_p;
205 };
206
207 /* Frees whatever allocated space there is to be freed and sets INF's
208    linux cache data pointer to NULL.  */
209
210 static void
211 invalidate_linux_cache_inf (struct inferior *inf)
212 {
213   struct linux_info *info;
214
215   info = (struct linux_info *) inferior_data (inf, linux_inferior_data);
216   if (info != NULL)
217     {
218       xfree (info);
219       set_inferior_data (inf, linux_inferior_data, NULL);
220     }
221 }
222
223 /* Handles the cleanup of the linux cache for inferior INF.  ARG is
224    ignored.  Callback for the inferior_appeared and inferior_exit
225    events.  */
226
227 static void
228 linux_inferior_data_cleanup (struct inferior *inf, void *arg)
229 {
230   invalidate_linux_cache_inf (inf);
231 }
232
233 /* Fetch the linux cache info for INF.  This function always returns a
234    valid INFO pointer.  */
235
236 static struct linux_info *
237 get_linux_inferior_data (void)
238 {
239   struct linux_info *info;
240   struct inferior *inf = current_inferior ();
241
242   info = (struct linux_info *) inferior_data (inf, linux_inferior_data);
243   if (info == NULL)
244     {
245       info = XCNEW (struct linux_info);
246       set_inferior_data (inf, linux_inferior_data, info);
247     }
248
249   return info;
250 }
251
252 /* See linux-tdep.h.  */
253
254 struct type *
255 linux_get_siginfo_type_with_fields (struct gdbarch *gdbarch,
256                                     linux_siginfo_extra_fields extra_fields)
257 {
258   struct linux_gdbarch_data *linux_gdbarch_data;
259   struct type *int_type, *uint_type, *long_type, *void_ptr_type, *short_type;
260   struct type *uid_type, *pid_type;
261   struct type *sigval_type, *clock_type;
262   struct type *siginfo_type, *sifields_type;
263   struct type *type;
264
265   linux_gdbarch_data = get_linux_gdbarch_data (gdbarch);
266   if (linux_gdbarch_data->siginfo_type != NULL)
267     return linux_gdbarch_data->siginfo_type;
268
269   int_type = arch_integer_type (gdbarch, gdbarch_int_bit (gdbarch),
270                                 0, "int");
271   uint_type = arch_integer_type (gdbarch, gdbarch_int_bit (gdbarch),
272                                  1, "unsigned int");
273   long_type = arch_integer_type (gdbarch, gdbarch_long_bit (gdbarch),
274                                  0, "long");
275   short_type = arch_integer_type (gdbarch, gdbarch_long_bit (gdbarch),
276                                  0, "short");
277   void_ptr_type = lookup_pointer_type (builtin_type (gdbarch)->builtin_void);
278
279   /* sival_t */
280   sigval_type = arch_composite_type (gdbarch, NULL, TYPE_CODE_UNION);
281   TYPE_NAME (sigval_type) = xstrdup ("sigval_t");
282   append_composite_type_field (sigval_type, "sival_int", int_type);
283   append_composite_type_field (sigval_type, "sival_ptr", void_ptr_type);
284
285   /* __pid_t */
286   pid_type = arch_type (gdbarch, TYPE_CODE_TYPEDEF,
287                         TYPE_LENGTH (int_type) * TARGET_CHAR_BIT, "__pid_t");
288   TYPE_TARGET_TYPE (pid_type) = int_type;
289   TYPE_TARGET_STUB (pid_type) = 1;
290
291   /* __uid_t */
292   uid_type = arch_type (gdbarch, TYPE_CODE_TYPEDEF,
293                         TYPE_LENGTH (uint_type) * TARGET_CHAR_BIT, "__uid_t");
294   TYPE_TARGET_TYPE (uid_type) = uint_type;
295   TYPE_TARGET_STUB (uid_type) = 1;
296
297   /* __clock_t */
298   clock_type = arch_type (gdbarch, TYPE_CODE_TYPEDEF,
299                           TYPE_LENGTH (long_type) * TARGET_CHAR_BIT,
300                           "__clock_t");
301   TYPE_TARGET_TYPE (clock_type) = long_type;
302   TYPE_TARGET_STUB (clock_type) = 1;
303
304   /* _sifields */
305   sifields_type = arch_composite_type (gdbarch, NULL, TYPE_CODE_UNION);
306
307   {
308     const int si_max_size = 128;
309     int si_pad_size;
310     int size_of_int = gdbarch_int_bit (gdbarch) / HOST_CHAR_BIT;
311
312     /* _pad */
313     if (gdbarch_ptr_bit (gdbarch) == 64)
314       si_pad_size = (si_max_size / size_of_int) - 4;
315     else
316       si_pad_size = (si_max_size / size_of_int) - 3;
317     append_composite_type_field (sifields_type, "_pad",
318                                  init_vector_type (int_type, si_pad_size));
319   }
320
321   /* _kill */
322   type = arch_composite_type (gdbarch, NULL, TYPE_CODE_STRUCT);
323   append_composite_type_field (type, "si_pid", pid_type);
324   append_composite_type_field (type, "si_uid", uid_type);
325   append_composite_type_field (sifields_type, "_kill", type);
326
327   /* _timer */
328   type = arch_composite_type (gdbarch, NULL, TYPE_CODE_STRUCT);
329   append_composite_type_field (type, "si_tid", int_type);
330   append_composite_type_field (type, "si_overrun", int_type);
331   append_composite_type_field (type, "si_sigval", sigval_type);
332   append_composite_type_field (sifields_type, "_timer", type);
333
334   /* _rt */
335   type = arch_composite_type (gdbarch, NULL, TYPE_CODE_STRUCT);
336   append_composite_type_field (type, "si_pid", pid_type);
337   append_composite_type_field (type, "si_uid", uid_type);
338   append_composite_type_field (type, "si_sigval", sigval_type);
339   append_composite_type_field (sifields_type, "_rt", type);
340
341   /* _sigchld */
342   type = arch_composite_type (gdbarch, NULL, TYPE_CODE_STRUCT);
343   append_composite_type_field (type, "si_pid", pid_type);
344   append_composite_type_field (type, "si_uid", uid_type);
345   append_composite_type_field (type, "si_status", int_type);
346   append_composite_type_field (type, "si_utime", clock_type);
347   append_composite_type_field (type, "si_stime", clock_type);
348   append_composite_type_field (sifields_type, "_sigchld", type);
349
350   /* _sigfault */
351   type = arch_composite_type (gdbarch, NULL, TYPE_CODE_STRUCT);
352   append_composite_type_field (type, "si_addr", void_ptr_type);
353
354   /* Additional bound fields for _sigfault in case they were requested.  */
355   if ((extra_fields & LINUX_SIGINFO_FIELD_ADDR_BND) != 0)
356     {
357       struct type *sigfault_bnd_fields;
358
359       append_composite_type_field (type, "_addr_lsb", short_type);
360       sigfault_bnd_fields = arch_composite_type (gdbarch, NULL, TYPE_CODE_STRUCT);
361       append_composite_type_field (sigfault_bnd_fields, "_lower", void_ptr_type);
362       append_composite_type_field (sigfault_bnd_fields, "_upper", void_ptr_type);
363       append_composite_type_field (type, "_addr_bnd", sigfault_bnd_fields);
364     }
365   append_composite_type_field (sifields_type, "_sigfault", type);
366
367   /* _sigpoll */
368   type = arch_composite_type (gdbarch, NULL, TYPE_CODE_STRUCT);
369   append_composite_type_field (type, "si_band", long_type);
370   append_composite_type_field (type, "si_fd", int_type);
371   append_composite_type_field (sifields_type, "_sigpoll", type);
372
373   /* struct siginfo */
374   siginfo_type = arch_composite_type (gdbarch, NULL, TYPE_CODE_STRUCT);
375   TYPE_NAME (siginfo_type) = xstrdup ("siginfo");
376   append_composite_type_field (siginfo_type, "si_signo", int_type);
377   append_composite_type_field (siginfo_type, "si_errno", int_type);
378   append_composite_type_field (siginfo_type, "si_code", int_type);
379   append_composite_type_field_aligned (siginfo_type,
380                                        "_sifields", sifields_type,
381                                        TYPE_LENGTH (long_type));
382
383   linux_gdbarch_data->siginfo_type = siginfo_type;
384
385   return siginfo_type;
386 }
387
388 /* This function is suitable for architectures that don't
389    extend/override the standard siginfo structure.  */
390
391 static struct type *
392 linux_get_siginfo_type (struct gdbarch *gdbarch)
393 {
394   return linux_get_siginfo_type_with_fields (gdbarch, 0);
395 }
396
397 /* Return true if the target is running on uClinux instead of normal
398    Linux kernel.  */
399
400 int
401 linux_is_uclinux (void)
402 {
403   CORE_ADDR dummy;
404
405   return (target_auxv_search (current_top_target (), AT_NULL, &dummy) > 0
406           && target_auxv_search (current_top_target (), AT_PAGESZ, &dummy) == 0);
407 }
408
409 static int
410 linux_has_shared_address_space (struct gdbarch *gdbarch)
411 {
412   return linux_is_uclinux ();
413 }
414
415 /* This is how we want PTIDs from core files to be printed.  */
416
417 static const char *
418 linux_core_pid_to_str (struct gdbarch *gdbarch, ptid_t ptid)
419 {
420   static char buf[80];
421
422   if (ptid.lwp () != 0)
423     {
424       snprintf (buf, sizeof (buf), "LWP %ld", ptid.lwp ());
425       return buf;
426     }
427
428   return normal_pid_to_str (ptid);
429 }
430
431 /* Service function for corefiles and info proc.  */
432
433 static void
434 read_mapping (const char *line,
435               ULONGEST *addr, ULONGEST *endaddr,
436               const char **permissions, size_t *permissions_len,
437               ULONGEST *offset,
438               const char **device, size_t *device_len,
439               ULONGEST *inode,
440               const char **filename)
441 {
442   const char *p = line;
443
444   *addr = strtoulst (p, &p, 16);
445   if (*p == '-')
446     p++;
447   *endaddr = strtoulst (p, &p, 16);
448
449   p = skip_spaces (p);
450   *permissions = p;
451   while (*p && !isspace (*p))
452     p++;
453   *permissions_len = p - *permissions;
454
455   *offset = strtoulst (p, &p, 16);
456
457   p = skip_spaces (p);
458   *device = p;
459   while (*p && !isspace (*p))
460     p++;
461   *device_len = p - *device;
462
463   *inode = strtoulst (p, &p, 10);
464
465   p = skip_spaces (p);
466   *filename = p;
467 }
468
469 /* Helper function to decode the "VmFlags" field in /proc/PID/smaps.
470
471    This function was based on the documentation found on
472    <Documentation/filesystems/proc.txt>, on the Linux kernel.
473
474    Linux kernels before commit
475    834f82e2aa9a8ede94b17b656329f850c1471514 (3.10) do not have this
476    field on smaps.  */
477
478 static void
479 decode_vmflags (char *p, struct smaps_vmflags *v)
480 {
481   char *saveptr = NULL;
482   const char *s;
483
484   v->initialized_p = 1;
485   p = skip_to_space (p);
486   p = skip_spaces (p);
487
488   for (s = strtok_r (p, " ", &saveptr);
489        s != NULL;
490        s = strtok_r (NULL, " ", &saveptr))
491     {
492       if (strcmp (s, "io") == 0)
493         v->io_page = 1;
494       else if (strcmp (s, "ht") == 0)
495         v->uses_huge_tlb = 1;
496       else if (strcmp (s, "dd") == 0)
497         v->exclude_coredump = 1;
498       else if (strcmp (s, "sh") == 0)
499         v->shared_mapping = 1;
500     }
501 }
502
503 /* Regexes used by mapping_is_anonymous_p.  Put in a structure because
504    they're initialized lazily.  */
505
506 struct mapping_regexes
507 {
508   /* Matches "/dev/zero" filenames (with or without the "(deleted)"
509      string in the end).  We know for sure, based on the Linux kernel
510      code, that memory mappings whose associated filename is
511      "/dev/zero" are guaranteed to be MAP_ANONYMOUS.  */
512   compiled_regex dev_zero
513     {"^/dev/zero\\( (deleted)\\)\\?$", REG_NOSUB,
514      _("Could not compile regex to match /dev/zero filename")};
515
516   /* Matches "/SYSV%08x" filenames (with or without the "(deleted)"
517      string in the end).  These filenames refer to shared memory
518      (shmem), and memory mappings associated with them are
519      MAP_ANONYMOUS as well.  */
520   compiled_regex shmem_file
521     {"^/\\?SYSV[0-9a-fA-F]\\{8\\}\\( (deleted)\\)\\?$", REG_NOSUB,
522      _("Could not compile regex to match shmem filenames")};
523
524   /* A heuristic we use to try to mimic the Linux kernel's 'n_link ==
525      0' code, which is responsible to decide if it is dealing with a
526      'MAP_SHARED | MAP_ANONYMOUS' mapping.  In other words, if
527      FILE_DELETED matches, it does not necessarily mean that we are
528      dealing with an anonymous shared mapping.  However, there is no
529      easy way to detect this currently, so this is the best
530      approximation we have.
531
532      As a result, GDB will dump readonly pages of deleted executables
533      when using the default value of coredump_filter (0x33), while the
534      Linux kernel will not dump those pages.  But we can live with
535      that.  */
536   compiled_regex file_deleted
537     {" (deleted)$", REG_NOSUB,
538      _("Could not compile regex to match '<file> (deleted)'")};
539 };
540
541 /* Return 1 if the memory mapping is anonymous, 0 otherwise.
542
543    FILENAME is the name of the file present in the first line of the
544    memory mapping, in the "/proc/PID/smaps" output.  For example, if
545    the first line is:
546
547    7fd0ca877000-7fd0d0da0000 r--p 00000000 fd:02 2100770   /path/to/file
548
549    Then FILENAME will be "/path/to/file".  */
550
551 static int
552 mapping_is_anonymous_p (const char *filename)
553 {
554   static gdb::optional<mapping_regexes> regexes;
555   static int init_regex_p = 0;
556
557   if (!init_regex_p)
558     {
559       /* Let's be pessimistic and assume there will be an error while
560          compiling the regex'es.  */
561       init_regex_p = -1;
562
563       regexes.emplace ();
564
565       /* If we reached this point, then everything succeeded.  */
566       init_regex_p = 1;
567     }
568
569   if (init_regex_p == -1)
570     {
571       const char deleted[] = " (deleted)";
572       size_t del_len = sizeof (deleted) - 1;
573       size_t filename_len = strlen (filename);
574
575       /* There was an error while compiling the regex'es above.  In
576          order to try to give some reliable information to the caller,
577          we just try to find the string " (deleted)" in the filename.
578          If we managed to find it, then we assume the mapping is
579          anonymous.  */
580       return (filename_len >= del_len
581               && strcmp (filename + filename_len - del_len, deleted) == 0);
582     }
583
584   if (*filename == '\0'
585       || regexes->dev_zero.exec (filename, 0, NULL, 0) == 0
586       || regexes->shmem_file.exec (filename, 0, NULL, 0) == 0
587       || regexes->file_deleted.exec (filename, 0, NULL, 0) == 0)
588     return 1;
589
590   return 0;
591 }
592
593 /* Return 0 if the memory mapping (which is related to FILTERFLAGS, V,
594    MAYBE_PRIVATE_P, and MAPPING_ANONYMOUS_P) should not be dumped, or
595    greater than 0 if it should.
596
597    In a nutshell, this is the logic that we follow in order to decide
598    if a mapping should be dumped or not.
599
600    - If the mapping is associated to a file whose name ends with
601      " (deleted)", or if the file is "/dev/zero", or if it is
602      "/SYSV%08x" (shared memory), or if there is no file associated
603      with it, or if the AnonHugePages: or the Anonymous: fields in the
604      /proc/PID/smaps have contents, then GDB considers this mapping to
605      be anonymous.  Otherwise, GDB considers this mapping to be a
606      file-backed mapping (because there will be a file associated with
607      it).
608  
609      It is worth mentioning that, from all those checks described
610      above, the most fragile is the one to see if the file name ends
611      with " (deleted)".  This does not necessarily mean that the
612      mapping is anonymous, because the deleted file associated with
613      the mapping may have been a hard link to another file, for
614      example.  The Linux kernel checks to see if "i_nlink == 0", but
615      GDB cannot easily (and normally) do this check (iff running as
616      root, it could find the mapping in /proc/PID/map_files/ and
617      determine whether there still are other hard links to the
618      inode/file).  Therefore, we made a compromise here, and we assume
619      that if the file name ends with " (deleted)", then the mapping is
620      indeed anonymous.  FWIW, this is something the Linux kernel could
621      do better: expose this information in a more direct way.
622  
623    - If we see the flag "sh" in the "VmFlags:" field (in
624      /proc/PID/smaps), then certainly the memory mapping is shared
625      (VM_SHARED).  If we have access to the VmFlags, and we don't see
626      the "sh" there, then certainly the mapping is private.  However,
627      Linux kernels before commit
628      834f82e2aa9a8ede94b17b656329f850c1471514 (3.10) do not have the
629      "VmFlags:" field; in that case, we use another heuristic: if we
630      see 'p' in the permission flags, then we assume that the mapping
631      is private, even though the presence of the 's' flag there would
632      mean VM_MAYSHARE, which means the mapping could still be private.
633      This should work OK enough, however.  */
634
635 static int
636 dump_mapping_p (filter_flags filterflags, const struct smaps_vmflags *v,
637                 int maybe_private_p, int mapping_anon_p, int mapping_file_p,
638                 const char *filename)
639 {
640   /* Initially, we trust in what we received from our caller.  This
641      value may not be very precise (i.e., it was probably gathered
642      from the permission line in the /proc/PID/smaps list, which
643      actually refers to VM_MAYSHARE, and not VM_SHARED), but it is
644      what we have until we take a look at the "VmFlags:" field
645      (assuming that the version of the Linux kernel being used
646      supports it, of course).  */
647   int private_p = maybe_private_p;
648
649   /* We always dump vDSO and vsyscall mappings, because it's likely that
650      there'll be no file to read the contents from at core load time.
651      The kernel does the same.  */
652   if (strcmp ("[vdso]", filename) == 0
653       || strcmp ("[vsyscall]", filename) == 0)
654     return 1;
655
656   if (v->initialized_p)
657     {
658       /* We never dump I/O mappings.  */
659       if (v->io_page)
660         return 0;
661
662       /* Check if we should exclude this mapping.  */
663       if (!dump_excluded_mappings && v->exclude_coredump)
664         return 0;
665
666       /* Update our notion of whether this mapping is shared or
667          private based on a trustworthy value.  */
668       private_p = !v->shared_mapping;
669
670       /* HugeTLB checking.  */
671       if (v->uses_huge_tlb)
672         {
673           if ((private_p && (filterflags & COREFILTER_HUGETLB_PRIVATE))
674               || (!private_p && (filterflags & COREFILTER_HUGETLB_SHARED)))
675             return 1;
676
677           return 0;
678         }
679     }
680
681   if (private_p)
682     {
683       if (mapping_anon_p && mapping_file_p)
684         {
685           /* This is a special situation.  It can happen when we see a
686              mapping that is file-backed, but that contains anonymous
687              pages.  */
688           return ((filterflags & COREFILTER_ANON_PRIVATE) != 0
689                   || (filterflags & COREFILTER_MAPPED_PRIVATE) != 0);
690         }
691       else if (mapping_anon_p)
692         return (filterflags & COREFILTER_ANON_PRIVATE) != 0;
693       else
694         return (filterflags & COREFILTER_MAPPED_PRIVATE) != 0;
695     }
696   else
697     {
698       if (mapping_anon_p && mapping_file_p)
699         {
700           /* This is a special situation.  It can happen when we see a
701              mapping that is file-backed, but that contains anonymous
702              pages.  */
703           return ((filterflags & COREFILTER_ANON_SHARED) != 0
704                   || (filterflags & COREFILTER_MAPPED_SHARED) != 0);
705         }
706       else if (mapping_anon_p)
707         return (filterflags & COREFILTER_ANON_SHARED) != 0;
708       else
709         return (filterflags & COREFILTER_MAPPED_SHARED) != 0;
710     }
711 }
712
713 /* Implement the "info proc" command.  */
714
715 static void
716 linux_info_proc (struct gdbarch *gdbarch, const char *args,
717                  enum info_proc_what what)
718 {
719   /* A long is used for pid instead of an int to avoid a loss of precision
720      compiler warning from the output of strtoul.  */
721   long pid;
722   int cmdline_f = (what == IP_MINIMAL || what == IP_CMDLINE || what == IP_ALL);
723   int cwd_f = (what == IP_MINIMAL || what == IP_CWD || what == IP_ALL);
724   int exe_f = (what == IP_MINIMAL || what == IP_EXE || what == IP_ALL);
725   int mappings_f = (what == IP_MAPPINGS || what == IP_ALL);
726   int status_f = (what == IP_STATUS || what == IP_ALL);
727   int stat_f = (what == IP_STAT || what == IP_ALL);
728   char filename[100];
729   int target_errno;
730
731   if (args && isdigit (args[0]))
732     {
733       char *tem;
734
735       pid = strtoul (args, &tem, 10);
736       args = tem;
737     }
738   else
739     {
740       if (!target_has_execution)
741         error (_("No current process: you must name one."));
742       if (current_inferior ()->fake_pid_p)
743         error (_("Can't determine the current process's PID: you must name one."));
744
745       pid = current_inferior ()->pid;
746     }
747
748   args = skip_spaces (args);
749   if (args && args[0])
750     error (_("Too many parameters: %s"), args);
751
752   printf_filtered (_("process %ld\n"), pid);
753   if (cmdline_f)
754     {
755       xsnprintf (filename, sizeof filename, "/proc/%ld/cmdline", pid);
756       gdb_byte *buffer;
757       ssize_t len = target_fileio_read_alloc (NULL, filename, &buffer);
758
759       if (len > 0)
760         {
761           gdb::unique_xmalloc_ptr<char> cmdline ((char *) buffer);
762           ssize_t pos;
763
764           for (pos = 0; pos < len - 1; pos++)
765             {
766               if (buffer[pos] == '\0')
767                 buffer[pos] = ' ';
768             }
769           buffer[len - 1] = '\0';
770           printf_filtered ("cmdline = '%s'\n", buffer);
771         }
772       else
773         warning (_("unable to open /proc file '%s'"), filename);
774     }
775   if (cwd_f)
776     {
777       xsnprintf (filename, sizeof filename, "/proc/%ld/cwd", pid);
778       gdb::optional<std::string> contents
779         = target_fileio_readlink (NULL, filename, &target_errno);
780       if (contents.has_value ())
781         printf_filtered ("cwd = '%s'\n", contents->c_str ());
782       else
783         warning (_("unable to read link '%s'"), filename);
784     }
785   if (exe_f)
786     {
787       xsnprintf (filename, sizeof filename, "/proc/%ld/exe", pid);
788       gdb::optional<std::string> contents
789         = target_fileio_readlink (NULL, filename, &target_errno);
790       if (contents.has_value ())
791         printf_filtered ("exe = '%s'\n", contents->c_str ());
792       else
793         warning (_("unable to read link '%s'"), filename);
794     }
795   if (mappings_f)
796     {
797       xsnprintf (filename, sizeof filename, "/proc/%ld/maps", pid);
798       gdb::unique_xmalloc_ptr<char> map
799         = target_fileio_read_stralloc (NULL, filename);
800       if (map != NULL)
801         {
802           char *line;
803
804           printf_filtered (_("Mapped address spaces:\n\n"));
805           if (gdbarch_addr_bit (gdbarch) == 32)
806             {
807               printf_filtered ("\t%10s %10s %10s %10s %s\n",
808                            "Start Addr",
809                            "  End Addr",
810                            "      Size", "    Offset", "objfile");
811             }
812           else
813             {
814               printf_filtered ("  %18s %18s %10s %10s %s\n",
815                            "Start Addr",
816                            "  End Addr",
817                            "      Size", "    Offset", "objfile");
818             }
819
820           for (line = strtok (map.get (), "\n");
821                line;
822                line = strtok (NULL, "\n"))
823             {
824               ULONGEST addr, endaddr, offset, inode;
825               const char *permissions, *device, *filename;
826               size_t permissions_len, device_len;
827
828               read_mapping (line, &addr, &endaddr,
829                             &permissions, &permissions_len,
830                             &offset, &device, &device_len,
831                             &inode, &filename);
832
833               if (gdbarch_addr_bit (gdbarch) == 32)
834                 {
835                   printf_filtered ("\t%10s %10s %10s %10s %s\n",
836                                    paddress (gdbarch, addr),
837                                    paddress (gdbarch, endaddr),
838                                    hex_string (endaddr - addr),
839                                    hex_string (offset),
840                                    *filename? filename : "");
841                 }
842               else
843                 {
844                   printf_filtered ("  %18s %18s %10s %10s %s\n",
845                                    paddress (gdbarch, addr),
846                                    paddress (gdbarch, endaddr),
847                                    hex_string (endaddr - addr),
848                                    hex_string (offset),
849                                    *filename? filename : "");
850                 }
851             }
852         }
853       else
854         warning (_("unable to open /proc file '%s'"), filename);
855     }
856   if (status_f)
857     {
858       xsnprintf (filename, sizeof filename, "/proc/%ld/status", pid);
859       gdb::unique_xmalloc_ptr<char> status
860         = target_fileio_read_stralloc (NULL, filename);
861       if (status)
862         puts_filtered (status.get ());
863       else
864         warning (_("unable to open /proc file '%s'"), filename);
865     }
866   if (stat_f)
867     {
868       xsnprintf (filename, sizeof filename, "/proc/%ld/stat", pid);
869       gdb::unique_xmalloc_ptr<char> statstr
870         = target_fileio_read_stralloc (NULL, filename);
871       if (statstr)
872         {
873           const char *p = statstr.get ();
874
875           printf_filtered (_("Process: %s\n"),
876                            pulongest (strtoulst (p, &p, 10)));
877
878           p = skip_spaces (p);
879           if (*p == '(')
880             {
881               /* ps command also relies on no trailing fields
882                  ever contain ')'.  */
883               const char *ep = strrchr (p, ')');
884               if (ep != NULL)
885                 {
886                   printf_filtered ("Exec file: %.*s\n",
887                                    (int) (ep - p - 1), p + 1);
888                   p = ep + 1;
889                 }
890             }
891
892           p = skip_spaces (p);
893           if (*p)
894             printf_filtered (_("State: %c\n"), *p++);
895
896           if (*p)
897             printf_filtered (_("Parent process: %s\n"),
898                              pulongest (strtoulst (p, &p, 10)));
899           if (*p)
900             printf_filtered (_("Process group: %s\n"),
901                              pulongest (strtoulst (p, &p, 10)));
902           if (*p)
903             printf_filtered (_("Session id: %s\n"),
904                              pulongest (strtoulst (p, &p, 10)));
905           if (*p)
906             printf_filtered (_("TTY: %s\n"),
907                              pulongest (strtoulst (p, &p, 10)));
908           if (*p)
909             printf_filtered (_("TTY owner process group: %s\n"),
910                              pulongest (strtoulst (p, &p, 10)));
911
912           if (*p)
913             printf_filtered (_("Flags: %s\n"),
914                              hex_string (strtoulst (p, &p, 10)));
915           if (*p)
916             printf_filtered (_("Minor faults (no memory page): %s\n"),
917                              pulongest (strtoulst (p, &p, 10)));
918           if (*p)
919             printf_filtered (_("Minor faults, children: %s\n"),
920                              pulongest (strtoulst (p, &p, 10)));
921           if (*p)
922             printf_filtered (_("Major faults (memory page faults): %s\n"),
923                              pulongest (strtoulst (p, &p, 10)));
924           if (*p)
925             printf_filtered (_("Major faults, children: %s\n"),
926                              pulongest (strtoulst (p, &p, 10)));
927           if (*p)
928             printf_filtered (_("utime: %s\n"),
929                              pulongest (strtoulst (p, &p, 10)));
930           if (*p)
931             printf_filtered (_("stime: %s\n"),
932                              pulongest (strtoulst (p, &p, 10)));
933           if (*p)
934             printf_filtered (_("utime, children: %s\n"),
935                              pulongest (strtoulst (p, &p, 10)));
936           if (*p)
937             printf_filtered (_("stime, children: %s\n"),
938                              pulongest (strtoulst (p, &p, 10)));
939           if (*p)
940             printf_filtered (_("jiffies remaining in current "
941                                "time slice: %s\n"),
942                              pulongest (strtoulst (p, &p, 10)));
943           if (*p)
944             printf_filtered (_("'nice' value: %s\n"),
945                              pulongest (strtoulst (p, &p, 10)));
946           if (*p)
947             printf_filtered (_("jiffies until next timeout: %s\n"),
948                              pulongest (strtoulst (p, &p, 10)));
949           if (*p)
950             printf_filtered (_("jiffies until next SIGALRM: %s\n"),
951                              pulongest (strtoulst (p, &p, 10)));
952           if (*p)
953             printf_filtered (_("start time (jiffies since "
954                                "system boot): %s\n"),
955                              pulongest (strtoulst (p, &p, 10)));
956           if (*p)
957             printf_filtered (_("Virtual memory size: %s\n"),
958                              pulongest (strtoulst (p, &p, 10)));
959           if (*p)
960             printf_filtered (_("Resident set size: %s\n"),
961                              pulongest (strtoulst (p, &p, 10)));
962           if (*p)
963             printf_filtered (_("rlim: %s\n"),
964                              pulongest (strtoulst (p, &p, 10)));
965           if (*p)
966             printf_filtered (_("Start of text: %s\n"),
967                              hex_string (strtoulst (p, &p, 10)));
968           if (*p)
969             printf_filtered (_("End of text: %s\n"),
970                              hex_string (strtoulst (p, &p, 10)));
971           if (*p)
972             printf_filtered (_("Start of stack: %s\n"),
973                              hex_string (strtoulst (p, &p, 10)));
974 #if 0   /* Don't know how architecture-dependent the rest is...
975            Anyway the signal bitmap info is available from "status".  */
976           if (*p)
977             printf_filtered (_("Kernel stack pointer: %s\n"),
978                              hex_string (strtoulst (p, &p, 10)));
979           if (*p)
980             printf_filtered (_("Kernel instr pointer: %s\n"),
981                              hex_string (strtoulst (p, &p, 10)));
982           if (*p)
983             printf_filtered (_("Pending signals bitmap: %s\n"),
984                              hex_string (strtoulst (p, &p, 10)));
985           if (*p)
986             printf_filtered (_("Blocked signals bitmap: %s\n"),
987                              hex_string (strtoulst (p, &p, 10)));
988           if (*p)
989             printf_filtered (_("Ignored signals bitmap: %s\n"),
990                              hex_string (strtoulst (p, &p, 10)));
991           if (*p)
992             printf_filtered (_("Catched signals bitmap: %s\n"),
993                              hex_string (strtoulst (p, &p, 10)));
994           if (*p)
995             printf_filtered (_("wchan (system call): %s\n"),
996                              hex_string (strtoulst (p, &p, 10)));
997 #endif
998         }
999       else
1000         warning (_("unable to open /proc file '%s'"), filename);
1001     }
1002 }
1003
1004 /* Implement "info proc mappings" for a corefile.  */
1005
1006 static void
1007 linux_core_info_proc_mappings (struct gdbarch *gdbarch, const char *args)
1008 {
1009   asection *section;
1010   ULONGEST count, page_size;
1011   unsigned char *descdata, *filenames, *descend;
1012   size_t note_size;
1013   unsigned int addr_size_bits, addr_size;
1014   struct gdbarch *core_gdbarch = gdbarch_from_bfd (core_bfd);
1015   /* We assume this for reading 64-bit core files.  */
1016   gdb_static_assert (sizeof (ULONGEST) >= 8);
1017
1018   section = bfd_get_section_by_name (core_bfd, ".note.linuxcore.file");
1019   if (section == NULL)
1020     {
1021       warning (_("unable to find mappings in core file"));
1022       return;
1023     }
1024
1025   addr_size_bits = gdbarch_addr_bit (core_gdbarch);
1026   addr_size = addr_size_bits / 8;
1027   note_size = bfd_get_section_size (section);
1028
1029   if (note_size < 2 * addr_size)
1030     error (_("malformed core note - too short for header"));
1031
1032   gdb::def_vector<unsigned char> contents (note_size);
1033   if (!bfd_get_section_contents (core_bfd, section, contents.data (),
1034                                  0, note_size))
1035     error (_("could not get core note contents"));
1036
1037   descdata = contents.data ();
1038   descend = descdata + note_size;
1039
1040   if (descdata[note_size - 1] != '\0')
1041     error (_("malformed note - does not end with \\0"));
1042
1043   count = bfd_get (addr_size_bits, core_bfd, descdata);
1044   descdata += addr_size;
1045
1046   page_size = bfd_get (addr_size_bits, core_bfd, descdata);
1047   descdata += addr_size;
1048
1049   if (note_size < 2 * addr_size + count * 3 * addr_size)
1050     error (_("malformed note - too short for supplied file count"));
1051
1052   printf_filtered (_("Mapped address spaces:\n\n"));
1053   if (gdbarch_addr_bit (gdbarch) == 32)
1054     {
1055       printf_filtered ("\t%10s %10s %10s %10s %s\n",
1056                        "Start Addr",
1057                        "  End Addr",
1058                        "      Size", "    Offset", "objfile");
1059     }
1060   else
1061     {
1062       printf_filtered ("  %18s %18s %10s %10s %s\n",
1063                        "Start Addr",
1064                        "  End Addr",
1065                        "      Size", "    Offset", "objfile");
1066     }
1067
1068   filenames = descdata + count * 3 * addr_size;
1069   while (--count > 0)
1070     {
1071       ULONGEST start, end, file_ofs;
1072
1073       if (filenames == descend)
1074         error (_("malformed note - filenames end too early"));
1075
1076       start = bfd_get (addr_size_bits, core_bfd, descdata);
1077       descdata += addr_size;
1078       end = bfd_get (addr_size_bits, core_bfd, descdata);
1079       descdata += addr_size;
1080       file_ofs = bfd_get (addr_size_bits, core_bfd, descdata);
1081       descdata += addr_size;
1082
1083       file_ofs *= page_size;
1084
1085       if (gdbarch_addr_bit (gdbarch) == 32)
1086         printf_filtered ("\t%10s %10s %10s %10s %s\n",
1087                          paddress (gdbarch, start),
1088                          paddress (gdbarch, end),
1089                          hex_string (end - start),
1090                          hex_string (file_ofs),
1091                          filenames);
1092       else
1093         printf_filtered ("  %18s %18s %10s %10s %s\n",
1094                          paddress (gdbarch, start),
1095                          paddress (gdbarch, end),
1096                          hex_string (end - start),
1097                          hex_string (file_ofs),
1098                          filenames);
1099
1100       filenames += 1 + strlen ((char *) filenames);
1101     }
1102 }
1103
1104 /* Implement "info proc" for a corefile.  */
1105
1106 static void
1107 linux_core_info_proc (struct gdbarch *gdbarch, const char *args,
1108                       enum info_proc_what what)
1109 {
1110   int exe_f = (what == IP_MINIMAL || what == IP_EXE || what == IP_ALL);
1111   int mappings_f = (what == IP_MAPPINGS || what == IP_ALL);
1112
1113   if (exe_f)
1114     {
1115       const char *exe;
1116
1117       exe = bfd_core_file_failing_command (core_bfd);
1118       if (exe != NULL)
1119         printf_filtered ("exe = '%s'\n", exe);
1120       else
1121         warning (_("unable to find command name in core file"));
1122     }
1123
1124   if (mappings_f)
1125     linux_core_info_proc_mappings (gdbarch, args);
1126
1127   if (!exe_f && !mappings_f)
1128     error (_("unable to handle request"));
1129 }
1130
1131 /* Read siginfo data from the core, if possible.  Returns -1 on
1132    failure.  Otherwise, returns the number of bytes read.  READBUF,
1133    OFFSET, and LEN are all as specified by the to_xfer_partial
1134    interface.  */
1135
1136 static LONGEST
1137 linux_core_xfer_siginfo (struct gdbarch *gdbarch, gdb_byte *readbuf,
1138                          ULONGEST offset, ULONGEST len)
1139 {
1140   thread_section_name section_name (".note.linuxcore.siginfo", inferior_ptid);
1141   asection *section = bfd_get_section_by_name (core_bfd, section_name.c_str ());
1142   if (section == NULL)
1143     return -1;
1144
1145   if (!bfd_get_section_contents (core_bfd, section, readbuf, offset, len))
1146     return -1;
1147
1148   return len;
1149 }
1150
1151 typedef int linux_find_memory_region_ftype (ULONGEST vaddr, ULONGEST size,
1152                                             ULONGEST offset, ULONGEST inode,
1153                                             int read, int write,
1154                                             int exec, int modified,
1155                                             const char *filename,
1156                                             void *data);
1157
1158 /* List memory regions in the inferior for a corefile.  */
1159
1160 static int
1161 linux_find_memory_regions_full (struct gdbarch *gdbarch,
1162                                 linux_find_memory_region_ftype *func,
1163                                 void *obfd)
1164 {
1165   char mapsfilename[100];
1166   char coredumpfilter_name[100];
1167   pid_t pid;
1168   /* Default dump behavior of coredump_filter (0x33), according to
1169      Documentation/filesystems/proc.txt from the Linux kernel
1170      tree.  */
1171   filter_flags filterflags = (COREFILTER_ANON_PRIVATE
1172                               | COREFILTER_ANON_SHARED
1173                               | COREFILTER_ELF_HEADERS
1174                               | COREFILTER_HUGETLB_PRIVATE);
1175
1176   /* We need to know the real target PID to access /proc.  */
1177   if (current_inferior ()->fake_pid_p)
1178     return 1;
1179
1180   pid = current_inferior ()->pid;
1181
1182   if (use_coredump_filter)
1183     {
1184       xsnprintf (coredumpfilter_name, sizeof (coredumpfilter_name),
1185                  "/proc/%d/coredump_filter", pid);
1186       gdb::unique_xmalloc_ptr<char> coredumpfilterdata
1187         = target_fileio_read_stralloc (NULL, coredumpfilter_name);
1188       if (coredumpfilterdata != NULL)
1189         {
1190           unsigned int flags;
1191
1192           sscanf (coredumpfilterdata.get (), "%x", &flags);
1193           filterflags = (enum filter_flag) flags;
1194         }
1195     }
1196
1197   xsnprintf (mapsfilename, sizeof mapsfilename, "/proc/%d/smaps", pid);
1198   gdb::unique_xmalloc_ptr<char> data
1199     = target_fileio_read_stralloc (NULL, mapsfilename);
1200   if (data == NULL)
1201     {
1202       /* Older Linux kernels did not support /proc/PID/smaps.  */
1203       xsnprintf (mapsfilename, sizeof mapsfilename, "/proc/%d/maps", pid);
1204       data = target_fileio_read_stralloc (NULL, mapsfilename);
1205     }
1206
1207   if (data != NULL)
1208     {
1209       char *line, *t;
1210
1211       line = strtok_r (data.get (), "\n", &t);
1212       while (line != NULL)
1213         {
1214           ULONGEST addr, endaddr, offset, inode;
1215           const char *permissions, *device, *filename;
1216           struct smaps_vmflags v;
1217           size_t permissions_len, device_len;
1218           int read, write, exec, priv;
1219           int has_anonymous = 0;
1220           int should_dump_p = 0;
1221           int mapping_anon_p;
1222           int mapping_file_p;
1223
1224           memset (&v, 0, sizeof (v));
1225           read_mapping (line, &addr, &endaddr, &permissions, &permissions_len,
1226                         &offset, &device, &device_len, &inode, &filename);
1227           mapping_anon_p = mapping_is_anonymous_p (filename);
1228           /* If the mapping is not anonymous, then we can consider it
1229              to be file-backed.  These two states (anonymous or
1230              file-backed) seem to be exclusive, but they can actually
1231              coexist.  For example, if a file-backed mapping has
1232              "Anonymous:" pages (see more below), then the Linux
1233              kernel will dump this mapping when the user specified
1234              that she only wants anonymous mappings in the corefile
1235              (*even* when she explicitly disabled the dumping of
1236              file-backed mappings).  */
1237           mapping_file_p = !mapping_anon_p;
1238
1239           /* Decode permissions.  */
1240           read = (memchr (permissions, 'r', permissions_len) != 0);
1241           write = (memchr (permissions, 'w', permissions_len) != 0);
1242           exec = (memchr (permissions, 'x', permissions_len) != 0);
1243           /* 'private' here actually means VM_MAYSHARE, and not
1244              VM_SHARED.  In order to know if a mapping is really
1245              private or not, we must check the flag "sh" in the
1246              VmFlags field.  This is done by decode_vmflags.  However,
1247              if we are using a Linux kernel released before the commit
1248              834f82e2aa9a8ede94b17b656329f850c1471514 (3.10), we will
1249              not have the VmFlags there.  In this case, there is
1250              really no way to know if we are dealing with VM_SHARED,
1251              so we just assume that VM_MAYSHARE is enough.  */
1252           priv = memchr (permissions, 'p', permissions_len) != 0;
1253
1254           /* Try to detect if region should be dumped by parsing smaps
1255              counters.  */
1256           for (line = strtok_r (NULL, "\n", &t);
1257                line != NULL && line[0] >= 'A' && line[0] <= 'Z';
1258                line = strtok_r (NULL, "\n", &t))
1259             {
1260               char keyword[64 + 1];
1261
1262               if (sscanf (line, "%64s", keyword) != 1)
1263                 {
1264                   warning (_("Error parsing {s,}maps file '%s'"), mapsfilename);
1265                   break;
1266                 }
1267
1268               if (strcmp (keyword, "Anonymous:") == 0)
1269                 {
1270                   /* Older Linux kernels did not support the
1271                      "Anonymous:" counter.  Check it here.  */
1272                   has_anonymous = 1;
1273                 }
1274               else if (strcmp (keyword, "VmFlags:") == 0)
1275                 decode_vmflags (line, &v);
1276
1277               if (strcmp (keyword, "AnonHugePages:") == 0
1278                   || strcmp (keyword, "Anonymous:") == 0)
1279                 {
1280                   unsigned long number;
1281
1282                   if (sscanf (line, "%*s%lu", &number) != 1)
1283                     {
1284                       warning (_("Error parsing {s,}maps file '%s' number"),
1285                                mapsfilename);
1286                       break;
1287                     }
1288                   if (number > 0)
1289                     {
1290                       /* Even if we are dealing with a file-backed
1291                          mapping, if it contains anonymous pages we
1292                          consider it to be *also* an anonymous
1293                          mapping, because this is what the Linux
1294                          kernel does:
1295
1296                          // Dump segments that have been written to.
1297                          if (vma->anon_vma && FILTER(ANON_PRIVATE))
1298                                 goto whole;
1299
1300                          Note that if the mapping is already marked as
1301                          file-backed (i.e., mapping_file_p is
1302                          non-zero), then this is a special case, and
1303                          this mapping will be dumped either when the
1304                          user wants to dump file-backed *or* anonymous
1305                          mappings.  */
1306                       mapping_anon_p = 1;
1307                     }
1308                 }
1309             }
1310
1311           if (has_anonymous)
1312             should_dump_p = dump_mapping_p (filterflags, &v, priv,
1313                                             mapping_anon_p, mapping_file_p,
1314                                             filename);
1315           else
1316             {
1317               /* Older Linux kernels did not support the "Anonymous:" counter.
1318                  If it is missing, we can't be sure - dump all the pages.  */
1319               should_dump_p = 1;
1320             }
1321
1322           /* Invoke the callback function to create the corefile segment.  */
1323           if (should_dump_p)
1324             func (addr, endaddr - addr, offset, inode,
1325                   read, write, exec, 1, /* MODIFIED is true because we
1326                                            want to dump the mapping.  */
1327                   filename, obfd);
1328         }
1329
1330       return 0;
1331     }
1332
1333   return 1;
1334 }
1335
1336 /* A structure for passing information through
1337    linux_find_memory_regions_full.  */
1338
1339 struct linux_find_memory_regions_data
1340 {
1341   /* The original callback.  */
1342
1343   find_memory_region_ftype func;
1344
1345   /* The original datum.  */
1346
1347   void *obfd;
1348 };
1349
1350 /* A callback for linux_find_memory_regions that converts between the
1351    "full"-style callback and find_memory_region_ftype.  */
1352
1353 static int
1354 linux_find_memory_regions_thunk (ULONGEST vaddr, ULONGEST size,
1355                                  ULONGEST offset, ULONGEST inode,
1356                                  int read, int write, int exec, int modified,
1357                                  const char *filename, void *arg)
1358 {
1359   struct linux_find_memory_regions_data *data
1360     = (struct linux_find_memory_regions_data *) arg;
1361
1362   return data->func (vaddr, size, read, write, exec, modified, data->obfd);
1363 }
1364
1365 /* A variant of linux_find_memory_regions_full that is suitable as the
1366    gdbarch find_memory_regions method.  */
1367
1368 static int
1369 linux_find_memory_regions (struct gdbarch *gdbarch,
1370                            find_memory_region_ftype func, void *obfd)
1371 {
1372   struct linux_find_memory_regions_data data;
1373
1374   data.func = func;
1375   data.obfd = obfd;
1376
1377   return linux_find_memory_regions_full (gdbarch,
1378                                          linux_find_memory_regions_thunk,
1379                                          &data);
1380 }
1381
1382 /* Determine which signal stopped execution.  */
1383
1384 static int
1385 find_signalled_thread (struct thread_info *info, void *data)
1386 {
1387   if (info->suspend.stop_signal != GDB_SIGNAL_0
1388       && info->ptid.pid () == inferior_ptid.pid ())
1389     return 1;
1390
1391   return 0;
1392 }
1393
1394 /* Generate corefile notes for SPU contexts.  */
1395
1396 static char *
1397 linux_spu_make_corefile_notes (bfd *obfd, char *note_data, int *note_size)
1398 {
1399   static const char *spu_files[] =
1400     {
1401       "object-id",
1402       "mem",
1403       "regs",
1404       "fpcr",
1405       "lslr",
1406       "decr",
1407       "decr_status",
1408       "signal1",
1409       "signal1_type",
1410       "signal2",
1411       "signal2_type",
1412       "event_mask",
1413       "event_status",
1414       "mbox_info",
1415       "ibox_info",
1416       "wbox_info",
1417       "dma_info",
1418       "proxydma_info",
1419    };
1420
1421   enum bfd_endian byte_order = gdbarch_byte_order (target_gdbarch ());
1422
1423   /* Determine list of SPU ids.  */
1424   gdb::optional<gdb::byte_vector>
1425     spu_ids = target_read_alloc (current_top_target (),
1426                                  TARGET_OBJECT_SPU, NULL);
1427
1428   if (!spu_ids)
1429     return note_data;
1430
1431   /* Generate corefile notes for each SPU file.  */
1432   for (size_t i = 0; i < spu_ids->size (); i += 4)
1433     {
1434       int fd = extract_unsigned_integer (spu_ids->data () + i, 4, byte_order);
1435
1436       for (size_t j = 0; j < sizeof (spu_files) / sizeof (spu_files[0]); j++)
1437         {
1438           char annex[32], note_name[32];
1439
1440           xsnprintf (annex, sizeof annex, "%d/%s", fd, spu_files[j]);
1441           gdb::optional<gdb::byte_vector> spu_data
1442             = target_read_alloc (current_top_target (), TARGET_OBJECT_SPU, annex);
1443
1444           if (spu_data && !spu_data->empty ())
1445             {
1446               xsnprintf (note_name, sizeof note_name, "SPU/%s", annex);
1447               note_data = elfcore_write_note (obfd, note_data, note_size,
1448                                               note_name, NT_SPU,
1449                                               spu_data->data (),
1450                                               spu_data->size ());
1451
1452               if (!note_data)
1453                 return nullptr;
1454             }
1455         }
1456     }
1457
1458   return note_data;
1459 }
1460
1461 /* This is used to pass information from
1462    linux_make_mappings_corefile_notes through
1463    linux_find_memory_regions_full.  */
1464
1465 struct linux_make_mappings_data
1466 {
1467   /* Number of files mapped.  */
1468   ULONGEST file_count;
1469
1470   /* The obstack for the main part of the data.  */
1471   struct obstack *data_obstack;
1472
1473   /* The filename obstack.  */
1474   struct obstack *filename_obstack;
1475
1476   /* The architecture's "long" type.  */
1477   struct type *long_type;
1478 };
1479
1480 static linux_find_memory_region_ftype linux_make_mappings_callback;
1481
1482 /* A callback for linux_find_memory_regions_full that updates the
1483    mappings data for linux_make_mappings_corefile_notes.  */
1484
1485 static int
1486 linux_make_mappings_callback (ULONGEST vaddr, ULONGEST size,
1487                               ULONGEST offset, ULONGEST inode,
1488                               int read, int write, int exec, int modified,
1489                               const char *filename, void *data)
1490 {
1491   struct linux_make_mappings_data *map_data
1492     = (struct linux_make_mappings_data *) data;
1493   gdb_byte buf[sizeof (ULONGEST)];
1494
1495   if (*filename == '\0' || inode == 0)
1496     return 0;
1497
1498   ++map_data->file_count;
1499
1500   pack_long (buf, map_data->long_type, vaddr);
1501   obstack_grow (map_data->data_obstack, buf, TYPE_LENGTH (map_data->long_type));
1502   pack_long (buf, map_data->long_type, vaddr + size);
1503   obstack_grow (map_data->data_obstack, buf, TYPE_LENGTH (map_data->long_type));
1504   pack_long (buf, map_data->long_type, offset);
1505   obstack_grow (map_data->data_obstack, buf, TYPE_LENGTH (map_data->long_type));
1506
1507   obstack_grow_str0 (map_data->filename_obstack, filename);
1508
1509   return 0;
1510 }
1511
1512 /* Write the file mapping data to the core file, if possible.  OBFD is
1513    the output BFD.  NOTE_DATA is the current note data, and NOTE_SIZE
1514    is a pointer to the note size.  Returns the new NOTE_DATA and
1515    updates NOTE_SIZE.  */
1516
1517 static char *
1518 linux_make_mappings_corefile_notes (struct gdbarch *gdbarch, bfd *obfd,
1519                                     char *note_data, int *note_size)
1520 {
1521   struct linux_make_mappings_data mapping_data;
1522   struct type *long_type
1523     = arch_integer_type (gdbarch, gdbarch_long_bit (gdbarch), 0, "long");
1524   gdb_byte buf[sizeof (ULONGEST)];
1525
1526   auto_obstack data_obstack, filename_obstack;
1527
1528   mapping_data.file_count = 0;
1529   mapping_data.data_obstack = &data_obstack;
1530   mapping_data.filename_obstack = &filename_obstack;
1531   mapping_data.long_type = long_type;
1532
1533   /* Reserve space for the count.  */
1534   obstack_blank (&data_obstack, TYPE_LENGTH (long_type));
1535   /* We always write the page size as 1 since we have no good way to
1536      determine the correct value.  */
1537   pack_long (buf, long_type, 1);
1538   obstack_grow (&data_obstack, buf, TYPE_LENGTH (long_type));
1539
1540   linux_find_memory_regions_full (gdbarch, linux_make_mappings_callback,
1541                                   &mapping_data);
1542
1543   if (mapping_data.file_count != 0)
1544     {
1545       /* Write the count to the obstack.  */
1546       pack_long ((gdb_byte *) obstack_base (&data_obstack),
1547                  long_type, mapping_data.file_count);
1548
1549       /* Copy the filenames to the data obstack.  */
1550       obstack_grow (&data_obstack, obstack_base (&filename_obstack),
1551                     obstack_object_size (&filename_obstack));
1552
1553       note_data = elfcore_write_note (obfd, note_data, note_size,
1554                                       "CORE", NT_FILE,
1555                                       obstack_base (&data_obstack),
1556                                       obstack_object_size (&data_obstack));
1557     }
1558
1559   return note_data;
1560 }
1561
1562 /* Structure for passing information from
1563    linux_collect_thread_registers via an iterator to
1564    linux_collect_regset_section_cb. */
1565
1566 struct linux_collect_regset_section_cb_data
1567 {
1568   struct gdbarch *gdbarch;
1569   const struct regcache *regcache;
1570   bfd *obfd;
1571   char *note_data;
1572   int *note_size;
1573   unsigned long lwp;
1574   enum gdb_signal stop_signal;
1575   int abort_iteration;
1576 };
1577
1578 /* Callback for iterate_over_regset_sections that records a single
1579    regset in the corefile note section.  */
1580
1581 static void
1582 linux_collect_regset_section_cb (const char *sect_name, int supply_size,
1583                                  int collect_size, const struct regset *regset,
1584                                  const char *human_name, void *cb_data)
1585 {
1586   char *buf;
1587   struct linux_collect_regset_section_cb_data *data
1588     = (struct linux_collect_regset_section_cb_data *) cb_data;
1589   bool variable_size_section = (regset != NULL
1590                                 && regset->flags & REGSET_VARIABLE_SIZE);
1591
1592   if (!variable_size_section)
1593     gdb_assert (supply_size == collect_size);
1594
1595   if (data->abort_iteration)
1596     return;
1597
1598   gdb_assert (regset && regset->collect_regset);
1599
1600   buf = (char *) xmalloc (collect_size);
1601   regset->collect_regset (regset, data->regcache, -1, buf, collect_size);
1602
1603   /* PRSTATUS still needs to be treated specially.  */
1604   if (strcmp (sect_name, ".reg") == 0)
1605     data->note_data = (char *) elfcore_write_prstatus
1606       (data->obfd, data->note_data, data->note_size, data->lwp,
1607        gdb_signal_to_host (data->stop_signal), buf);
1608   else
1609     data->note_data = (char *) elfcore_write_register_note
1610       (data->obfd, data->note_data, data->note_size,
1611        sect_name, buf, collect_size);
1612   xfree (buf);
1613
1614   if (data->note_data == NULL)
1615     data->abort_iteration = 1;
1616 }
1617
1618 /* Records the thread's register state for the corefile note
1619    section.  */
1620
1621 static char *
1622 linux_collect_thread_registers (const struct regcache *regcache,
1623                                 ptid_t ptid, bfd *obfd,
1624                                 char *note_data, int *note_size,
1625                                 enum gdb_signal stop_signal)
1626 {
1627   struct gdbarch *gdbarch = regcache->arch ();
1628   struct linux_collect_regset_section_cb_data data;
1629
1630   data.gdbarch = gdbarch;
1631   data.regcache = regcache;
1632   data.obfd = obfd;
1633   data.note_data = note_data;
1634   data.note_size = note_size;
1635   data.stop_signal = stop_signal;
1636   data.abort_iteration = 0;
1637
1638   /* For remote targets the LWP may not be available, so use the TID.  */
1639   data.lwp = ptid.lwp ();
1640   if (!data.lwp)
1641     data.lwp = ptid.tid ();
1642
1643   gdbarch_iterate_over_regset_sections (gdbarch,
1644                                         linux_collect_regset_section_cb,
1645                                         &data, regcache);
1646   return data.note_data;
1647 }
1648
1649 /* Fetch the siginfo data for the specified thread, if it exists.  If
1650    there is no data, or we could not read it, return an empty
1651    buffer.  */
1652
1653 static gdb::byte_vector
1654 linux_get_siginfo_data (thread_info *thread, struct gdbarch *gdbarch)
1655 {
1656   struct type *siginfo_type;
1657   LONGEST bytes_read;
1658
1659   if (!gdbarch_get_siginfo_type_p (gdbarch))
1660     return gdb::byte_vector ();
1661
1662   scoped_restore save_inferior_ptid = make_scoped_restore (&inferior_ptid);
1663   inferior_ptid = thread->ptid;
1664
1665   siginfo_type = gdbarch_get_siginfo_type (gdbarch);
1666
1667   gdb::byte_vector buf (TYPE_LENGTH (siginfo_type));
1668
1669   bytes_read = target_read (current_top_target (), TARGET_OBJECT_SIGNAL_INFO, NULL,
1670                             buf.data (), 0, TYPE_LENGTH (siginfo_type));
1671   if (bytes_read != TYPE_LENGTH (siginfo_type))
1672     buf.clear ();
1673
1674   return buf;
1675 }
1676
1677 struct linux_corefile_thread_data
1678 {
1679   struct gdbarch *gdbarch;
1680   bfd *obfd;
1681   char *note_data;
1682   int *note_size;
1683   enum gdb_signal stop_signal;
1684 };
1685
1686 /* Records the thread's register state for the corefile note
1687    section.  */
1688
1689 static void
1690 linux_corefile_thread (struct thread_info *info,
1691                        struct linux_corefile_thread_data *args)
1692 {
1693   struct regcache *regcache;
1694
1695   regcache = get_thread_arch_regcache (info->ptid, args->gdbarch);
1696
1697   target_fetch_registers (regcache, -1);
1698   gdb::byte_vector siginfo_data = linux_get_siginfo_data (info, args->gdbarch);
1699
1700   args->note_data = linux_collect_thread_registers
1701     (regcache, info->ptid, args->obfd, args->note_data,
1702      args->note_size, args->stop_signal);
1703
1704   /* Don't return anything if we got no register information above,
1705      such a core file is useless.  */
1706   if (args->note_data != NULL)
1707     if (!siginfo_data.empty ())
1708       args->note_data = elfcore_write_note (args->obfd,
1709                                             args->note_data,
1710                                             args->note_size,
1711                                             "CORE", NT_SIGINFO,
1712                                             siginfo_data.data (),
1713                                             siginfo_data.size ());
1714 }
1715
1716 /* Fill the PRPSINFO structure with information about the process being
1717    debugged.  Returns 1 in case of success, 0 for failures.  Please note that
1718    even if the structure cannot be entirely filled (e.g., GDB was unable to
1719    gather information about the process UID/GID), this function will still
1720    return 1 since some information was already recorded.  It will only return
1721    0 iff nothing can be gathered.  */
1722
1723 static int
1724 linux_fill_prpsinfo (struct elf_internal_linux_prpsinfo *p)
1725 {
1726   /* The filename which we will use to obtain some info about the process.
1727      We will basically use this to store the `/proc/PID/FILENAME' file.  */
1728   char filename[100];
1729   /* The basename of the executable.  */
1730   const char *basename;
1731   char *infargs;
1732   /* Temporary buffer.  */
1733   char *tmpstr;
1734   /* The valid states of a process, according to the Linux kernel.  */
1735   const char valid_states[] = "RSDTZW";
1736   /* The program state.  */
1737   const char *prog_state;
1738   /* The state of the process.  */
1739   char pr_sname;
1740   /* The PID of the program which generated the corefile.  */
1741   pid_t pid;
1742   /* Process flags.  */
1743   unsigned int pr_flag;
1744   /* Process nice value.  */
1745   long pr_nice;
1746   /* The number of fields read by `sscanf'.  */
1747   int n_fields = 0;
1748
1749   gdb_assert (p != NULL);
1750
1751   /* Obtaining PID and filename.  */
1752   pid = inferior_ptid.pid ();
1753   xsnprintf (filename, sizeof (filename), "/proc/%d/cmdline", (int) pid);
1754   /* The full name of the program which generated the corefile.  */
1755   gdb::unique_xmalloc_ptr<char> fname
1756     = target_fileio_read_stralloc (NULL, filename);
1757
1758   if (fname == NULL || fname.get ()[0] == '\0')
1759     {
1760       /* No program name was read, so we won't be able to retrieve more
1761          information about the process.  */
1762       return 0;
1763     }
1764
1765   memset (p, 0, sizeof (*p));
1766
1767   /* Defining the PID.  */
1768   p->pr_pid = pid;
1769
1770   /* Copying the program name.  Only the basename matters.  */
1771   basename = lbasename (fname.get ());
1772   strncpy (p->pr_fname, basename, sizeof (p->pr_fname));
1773   p->pr_fname[sizeof (p->pr_fname) - 1] = '\0';
1774
1775   infargs = get_inferior_args ();
1776
1777   /* The arguments of the program.  */
1778   std::string psargs = fname.get ();
1779   if (infargs != NULL)
1780     psargs = psargs + " " + infargs;
1781
1782   strncpy (p->pr_psargs, psargs.c_str (), sizeof (p->pr_psargs));
1783   p->pr_psargs[sizeof (p->pr_psargs) - 1] = '\0';
1784
1785   xsnprintf (filename, sizeof (filename), "/proc/%d/stat", (int) pid);
1786   /* The contents of `/proc/PID/stat'.  */
1787   gdb::unique_xmalloc_ptr<char> proc_stat_contents
1788     = target_fileio_read_stralloc (NULL, filename);
1789   char *proc_stat = proc_stat_contents.get ();
1790
1791   if (proc_stat == NULL || *proc_stat == '\0')
1792     {
1793       /* Despite being unable to read more information about the
1794          process, we return 1 here because at least we have its
1795          command line, PID and arguments.  */
1796       return 1;
1797     }
1798
1799   /* Ok, we have the stats.  It's time to do a little parsing of the
1800      contents of the buffer, so that we end up reading what we want.
1801
1802      The following parsing mechanism is strongly based on the
1803      information generated by the `fs/proc/array.c' file, present in
1804      the Linux kernel tree.  More details about how the information is
1805      displayed can be obtained by seeing the manpage of proc(5),
1806      specifically under the entry of `/proc/[pid]/stat'.  */
1807
1808   /* Getting rid of the PID, since we already have it.  */
1809   while (isdigit (*proc_stat))
1810     ++proc_stat;
1811
1812   proc_stat = skip_spaces (proc_stat);
1813
1814   /* ps command also relies on no trailing fields ever contain ')'.  */
1815   proc_stat = strrchr (proc_stat, ')');
1816   if (proc_stat == NULL)
1817     return 1;
1818   proc_stat++;
1819
1820   proc_stat = skip_spaces (proc_stat);
1821
1822   n_fields = sscanf (proc_stat,
1823                      "%c"               /* Process state.  */
1824                      "%d%d%d"           /* Parent PID, group ID, session ID.  */
1825                      "%*d%*d"           /* tty_nr, tpgid (not used).  */
1826                      "%u"               /* Flags.  */
1827                      "%*s%*s%*s%*s"     /* minflt, cminflt, majflt,
1828                                            cmajflt (not used).  */
1829                      "%*s%*s%*s%*s"     /* utime, stime, cutime,
1830                                            cstime (not used).  */
1831                      "%*s"              /* Priority (not used).  */
1832                      "%ld",             /* Nice.  */
1833                      &pr_sname,
1834                      &p->pr_ppid, &p->pr_pgrp, &p->pr_sid,
1835                      &pr_flag,
1836                      &pr_nice);
1837
1838   if (n_fields != 6)
1839     {
1840       /* Again, we couldn't read the complementary information about
1841          the process state.  However, we already have minimal
1842          information, so we just return 1 here.  */
1843       return 1;
1844     }
1845
1846   /* Filling the structure fields.  */
1847   prog_state = strchr (valid_states, pr_sname);
1848   if (prog_state != NULL)
1849     p->pr_state = prog_state - valid_states;
1850   else
1851     {
1852       /* Zero means "Running".  */
1853       p->pr_state = 0;
1854     }
1855
1856   p->pr_sname = p->pr_state > 5 ? '.' : pr_sname;
1857   p->pr_zomb = p->pr_sname == 'Z';
1858   p->pr_nice = pr_nice;
1859   p->pr_flag = pr_flag;
1860
1861   /* Finally, obtaining the UID and GID.  For that, we read and parse the
1862      contents of the `/proc/PID/status' file.  */
1863   xsnprintf (filename, sizeof (filename), "/proc/%d/status", (int) pid);
1864   /* The contents of `/proc/PID/status'.  */
1865   gdb::unique_xmalloc_ptr<char> proc_status_contents
1866     = target_fileio_read_stralloc (NULL, filename);
1867   char *proc_status = proc_status_contents.get ();
1868
1869   if (proc_status == NULL || *proc_status == '\0')
1870     {
1871       /* Returning 1 since we already have a bunch of information.  */
1872       return 1;
1873     }
1874
1875   /* Extracting the UID.  */
1876   tmpstr = strstr (proc_status, "Uid:");
1877   if (tmpstr != NULL)
1878     {
1879       /* Advancing the pointer to the beginning of the UID.  */
1880       tmpstr += sizeof ("Uid:");
1881       while (*tmpstr != '\0' && !isdigit (*tmpstr))
1882         ++tmpstr;
1883
1884       if (isdigit (*tmpstr))
1885         p->pr_uid = strtol (tmpstr, &tmpstr, 10);
1886     }
1887
1888   /* Extracting the GID.  */
1889   tmpstr = strstr (proc_status, "Gid:");
1890   if (tmpstr != NULL)
1891     {
1892       /* Advancing the pointer to the beginning of the GID.  */
1893       tmpstr += sizeof ("Gid:");
1894       while (*tmpstr != '\0' && !isdigit (*tmpstr))
1895         ++tmpstr;
1896
1897       if (isdigit (*tmpstr))
1898         p->pr_gid = strtol (tmpstr, &tmpstr, 10);
1899     }
1900
1901   return 1;
1902 }
1903
1904 /* Build the note section for a corefile, and return it in a malloc
1905    buffer.  */
1906
1907 static char *
1908 linux_make_corefile_notes (struct gdbarch *gdbarch, bfd *obfd, int *note_size)
1909 {
1910   struct linux_corefile_thread_data thread_args;
1911   struct elf_internal_linux_prpsinfo prpsinfo;
1912   char *note_data = NULL;
1913   struct thread_info *curr_thr, *signalled_thr, *thr;
1914
1915   if (! gdbarch_iterate_over_regset_sections_p (gdbarch))
1916     return NULL;
1917
1918   if (linux_fill_prpsinfo (&prpsinfo))
1919     {
1920       if (gdbarch_ptr_bit (gdbarch) == 64)
1921         note_data = elfcore_write_linux_prpsinfo64 (obfd,
1922                                                     note_data, note_size,
1923                                                     &prpsinfo);
1924       else
1925         note_data = elfcore_write_linux_prpsinfo32 (obfd,
1926                                                     note_data, note_size,
1927                                                     &prpsinfo);
1928     }
1929
1930   /* Thread register information.  */
1931   TRY
1932     {
1933       update_thread_list ();
1934     }
1935   CATCH (e, RETURN_MASK_ERROR)
1936     {
1937       exception_print (gdb_stderr, e);
1938     }
1939   END_CATCH
1940
1941   /* Like the kernel, prefer dumping the signalled thread first.
1942      "First thread" is what tools use to infer the signalled thread.
1943      In case there's more than one signalled thread, prefer the
1944      current thread, if it is signalled.  */
1945   curr_thr = inferior_thread ();
1946   if (curr_thr->suspend.stop_signal != GDB_SIGNAL_0)
1947     signalled_thr = curr_thr;
1948   else
1949     {
1950       signalled_thr = iterate_over_threads (find_signalled_thread, NULL);
1951       if (signalled_thr == NULL)
1952         signalled_thr = curr_thr;
1953     }
1954
1955   thread_args.gdbarch = gdbarch;
1956   thread_args.obfd = obfd;
1957   thread_args.note_data = note_data;
1958   thread_args.note_size = note_size;
1959   thread_args.stop_signal = signalled_thr->suspend.stop_signal;
1960
1961   linux_corefile_thread (signalled_thr, &thread_args);
1962   ALL_NON_EXITED_THREADS (thr)
1963     {
1964       if (thr == signalled_thr)
1965         continue;
1966       if (thr->ptid.pid () != inferior_ptid.pid ())
1967         continue;
1968
1969       linux_corefile_thread (thr, &thread_args);
1970     }
1971
1972   note_data = thread_args.note_data;
1973   if (!note_data)
1974     return NULL;
1975
1976   /* Auxillary vector.  */
1977   gdb::optional<gdb::byte_vector> auxv =
1978     target_read_alloc (current_top_target (), TARGET_OBJECT_AUXV, NULL);
1979   if (auxv && !auxv->empty ())
1980     {
1981       note_data = elfcore_write_note (obfd, note_data, note_size,
1982                                       "CORE", NT_AUXV, auxv->data (),
1983                                       auxv->size ());
1984
1985       if (!note_data)
1986         return NULL;
1987     }
1988
1989   /* SPU information.  */
1990   note_data = linux_spu_make_corefile_notes (obfd, note_data, note_size);
1991   if (!note_data)
1992     return NULL;
1993
1994   /* File mappings.  */
1995   note_data = linux_make_mappings_corefile_notes (gdbarch, obfd,
1996                                                   note_data, note_size);
1997
1998   return note_data;
1999 }
2000
2001 /* Implementation of `gdbarch_gdb_signal_from_target', as defined in
2002    gdbarch.h.  This function is not static because it is exported to
2003    other -tdep files.  */
2004
2005 enum gdb_signal
2006 linux_gdb_signal_from_target (struct gdbarch *gdbarch, int signal)
2007 {
2008   switch (signal)
2009     {
2010     case 0:
2011       return GDB_SIGNAL_0;
2012
2013     case LINUX_SIGHUP:
2014       return GDB_SIGNAL_HUP;
2015
2016     case LINUX_SIGINT:
2017       return GDB_SIGNAL_INT;
2018
2019     case LINUX_SIGQUIT:
2020       return GDB_SIGNAL_QUIT;
2021
2022     case LINUX_SIGILL:
2023       return GDB_SIGNAL_ILL;
2024
2025     case LINUX_SIGTRAP:
2026       return GDB_SIGNAL_TRAP;
2027
2028     case LINUX_SIGABRT:
2029       return GDB_SIGNAL_ABRT;
2030
2031     case LINUX_SIGBUS:
2032       return GDB_SIGNAL_BUS;
2033
2034     case LINUX_SIGFPE:
2035       return GDB_SIGNAL_FPE;
2036
2037     case LINUX_SIGKILL:
2038       return GDB_SIGNAL_KILL;
2039
2040     case LINUX_SIGUSR1:
2041       return GDB_SIGNAL_USR1;
2042
2043     case LINUX_SIGSEGV:
2044       return GDB_SIGNAL_SEGV;
2045
2046     case LINUX_SIGUSR2:
2047       return GDB_SIGNAL_USR2;
2048
2049     case LINUX_SIGPIPE:
2050       return GDB_SIGNAL_PIPE;
2051
2052     case LINUX_SIGALRM:
2053       return GDB_SIGNAL_ALRM;
2054
2055     case LINUX_SIGTERM:
2056       return GDB_SIGNAL_TERM;
2057
2058     case LINUX_SIGCHLD:
2059       return GDB_SIGNAL_CHLD;
2060
2061     case LINUX_SIGCONT:
2062       return GDB_SIGNAL_CONT;
2063
2064     case LINUX_SIGSTOP:
2065       return GDB_SIGNAL_STOP;
2066
2067     case LINUX_SIGTSTP:
2068       return GDB_SIGNAL_TSTP;
2069
2070     case LINUX_SIGTTIN:
2071       return GDB_SIGNAL_TTIN;
2072
2073     case LINUX_SIGTTOU:
2074       return GDB_SIGNAL_TTOU;
2075
2076     case LINUX_SIGURG:
2077       return GDB_SIGNAL_URG;
2078
2079     case LINUX_SIGXCPU:
2080       return GDB_SIGNAL_XCPU;
2081
2082     case LINUX_SIGXFSZ:
2083       return GDB_SIGNAL_XFSZ;
2084
2085     case LINUX_SIGVTALRM:
2086       return GDB_SIGNAL_VTALRM;
2087
2088     case LINUX_SIGPROF:
2089       return GDB_SIGNAL_PROF;
2090
2091     case LINUX_SIGWINCH:
2092       return GDB_SIGNAL_WINCH;
2093
2094     /* No way to differentiate between SIGIO and SIGPOLL.
2095        Therefore, we just handle the first one.  */
2096     case LINUX_SIGIO:
2097       return GDB_SIGNAL_IO;
2098
2099     case LINUX_SIGPWR:
2100       return GDB_SIGNAL_PWR;
2101
2102     case LINUX_SIGSYS:
2103       return GDB_SIGNAL_SYS;
2104
2105     /* SIGRTMIN and SIGRTMAX are not continuous in <gdb/signals.def>,
2106        therefore we have to handle them here.  */
2107     case LINUX_SIGRTMIN:
2108       return GDB_SIGNAL_REALTIME_32;
2109
2110     case LINUX_SIGRTMAX:
2111       return GDB_SIGNAL_REALTIME_64;
2112     }
2113
2114   if (signal >= LINUX_SIGRTMIN + 1 && signal <= LINUX_SIGRTMAX - 1)
2115     {
2116       int offset = signal - LINUX_SIGRTMIN + 1;
2117
2118       return (enum gdb_signal) ((int) GDB_SIGNAL_REALTIME_33 + offset);
2119     }
2120
2121   return GDB_SIGNAL_UNKNOWN;
2122 }
2123
2124 /* Implementation of `gdbarch_gdb_signal_to_target', as defined in
2125    gdbarch.h.  This function is not static because it is exported to
2126    other -tdep files.  */
2127
2128 int
2129 linux_gdb_signal_to_target (struct gdbarch *gdbarch,
2130                             enum gdb_signal signal)
2131 {
2132   switch (signal)
2133     {
2134     case GDB_SIGNAL_0:
2135       return 0;
2136
2137     case GDB_SIGNAL_HUP:
2138       return LINUX_SIGHUP;
2139
2140     case GDB_SIGNAL_INT:
2141       return LINUX_SIGINT;
2142
2143     case GDB_SIGNAL_QUIT:
2144       return LINUX_SIGQUIT;
2145
2146     case GDB_SIGNAL_ILL:
2147       return LINUX_SIGILL;
2148
2149     case GDB_SIGNAL_TRAP:
2150       return LINUX_SIGTRAP;
2151
2152     case GDB_SIGNAL_ABRT:
2153       return LINUX_SIGABRT;
2154
2155     case GDB_SIGNAL_FPE:
2156       return LINUX_SIGFPE;
2157
2158     case GDB_SIGNAL_KILL:
2159       return LINUX_SIGKILL;
2160
2161     case GDB_SIGNAL_BUS:
2162       return LINUX_SIGBUS;
2163
2164     case GDB_SIGNAL_SEGV:
2165       return LINUX_SIGSEGV;
2166
2167     case GDB_SIGNAL_SYS:
2168       return LINUX_SIGSYS;
2169
2170     case GDB_SIGNAL_PIPE:
2171       return LINUX_SIGPIPE;
2172
2173     case GDB_SIGNAL_ALRM:
2174       return LINUX_SIGALRM;
2175
2176     case GDB_SIGNAL_TERM:
2177       return LINUX_SIGTERM;
2178
2179     case GDB_SIGNAL_URG:
2180       return LINUX_SIGURG;
2181
2182     case GDB_SIGNAL_STOP:
2183       return LINUX_SIGSTOP;
2184
2185     case GDB_SIGNAL_TSTP:
2186       return LINUX_SIGTSTP;
2187
2188     case GDB_SIGNAL_CONT:
2189       return LINUX_SIGCONT;
2190
2191     case GDB_SIGNAL_CHLD:
2192       return LINUX_SIGCHLD;
2193
2194     case GDB_SIGNAL_TTIN:
2195       return LINUX_SIGTTIN;
2196
2197     case GDB_SIGNAL_TTOU:
2198       return LINUX_SIGTTOU;
2199
2200     case GDB_SIGNAL_IO:
2201       return LINUX_SIGIO;
2202
2203     case GDB_SIGNAL_XCPU:
2204       return LINUX_SIGXCPU;
2205
2206     case GDB_SIGNAL_XFSZ:
2207       return LINUX_SIGXFSZ;
2208
2209     case GDB_SIGNAL_VTALRM:
2210       return LINUX_SIGVTALRM;
2211
2212     case GDB_SIGNAL_PROF:
2213       return LINUX_SIGPROF;
2214
2215     case GDB_SIGNAL_WINCH:
2216       return LINUX_SIGWINCH;
2217
2218     case GDB_SIGNAL_USR1:
2219       return LINUX_SIGUSR1;
2220
2221     case GDB_SIGNAL_USR2:
2222       return LINUX_SIGUSR2;
2223
2224     case GDB_SIGNAL_PWR:
2225       return LINUX_SIGPWR;
2226
2227     case GDB_SIGNAL_POLL:
2228       return LINUX_SIGPOLL;
2229
2230     /* GDB_SIGNAL_REALTIME_32 is not continuous in <gdb/signals.def>,
2231        therefore we have to handle it here.  */
2232     case GDB_SIGNAL_REALTIME_32:
2233       return LINUX_SIGRTMIN;
2234
2235     /* Same comment applies to _64.  */
2236     case GDB_SIGNAL_REALTIME_64:
2237       return LINUX_SIGRTMAX;
2238     }
2239
2240   /* GDB_SIGNAL_REALTIME_33 to _64 are continuous.  */
2241   if (signal >= GDB_SIGNAL_REALTIME_33
2242       && signal <= GDB_SIGNAL_REALTIME_63)
2243     {
2244       int offset = signal - GDB_SIGNAL_REALTIME_33;
2245
2246       return LINUX_SIGRTMIN + 1 + offset;
2247     }
2248
2249   return -1;
2250 }
2251
2252 /* Helper for linux_vsyscall_range that does the real work of finding
2253    the vsyscall's address range.  */
2254
2255 static int
2256 linux_vsyscall_range_raw (struct gdbarch *gdbarch, struct mem_range *range)
2257 {
2258   char filename[100];
2259   long pid;
2260
2261   if (target_auxv_search (current_top_target (), AT_SYSINFO_EHDR, &range->start) <= 0)
2262     return 0;
2263
2264   /* It doesn't make sense to access the host's /proc when debugging a
2265      core file.  Instead, look for the PT_LOAD segment that matches
2266      the vDSO.  */
2267   if (!target_has_execution)
2268     {
2269       Elf_Internal_Phdr *phdrs;
2270       long phdrs_size;
2271       int num_phdrs, i;
2272
2273       phdrs_size = bfd_get_elf_phdr_upper_bound (core_bfd);
2274       if (phdrs_size == -1)
2275         return 0;
2276
2277       phdrs = (Elf_Internal_Phdr *) alloca (phdrs_size);
2278       num_phdrs = bfd_get_elf_phdrs (core_bfd, phdrs);
2279       if (num_phdrs == -1)
2280         return 0;
2281
2282       for (i = 0; i < num_phdrs; i++)
2283         if (phdrs[i].p_type == PT_LOAD
2284             && phdrs[i].p_vaddr == range->start)
2285           {
2286             range->length = phdrs[i].p_memsz;
2287             return 1;
2288           }
2289
2290       return 0;
2291     }
2292
2293   /* We need to know the real target PID to access /proc.  */
2294   if (current_inferior ()->fake_pid_p)
2295     return 0;
2296
2297   pid = current_inferior ()->pid;
2298
2299   /* Note that reading /proc/PID/task/PID/maps (1) is much faster than
2300      reading /proc/PID/maps (2).  The later identifies thread stacks
2301      in the output, which requires scanning every thread in the thread
2302      group to check whether a VMA is actually a thread's stack.  With
2303      Linux 4.4 on an Intel i7-4810MQ @ 2.80GHz, with an inferior with
2304      a few thousand threads, (1) takes a few miliseconds, while (2)
2305      takes several seconds.  Also note that "smaps", what we read for
2306      determining core dump mappings, is even slower than "maps".  */
2307   xsnprintf (filename, sizeof filename, "/proc/%ld/task/%ld/maps", pid, pid);
2308   gdb::unique_xmalloc_ptr<char> data
2309     = target_fileio_read_stralloc (NULL, filename);
2310   if (data != NULL)
2311     {
2312       char *line;
2313       char *saveptr = NULL;
2314
2315       for (line = strtok_r (data.get (), "\n", &saveptr);
2316            line != NULL;
2317            line = strtok_r (NULL, "\n", &saveptr))
2318         {
2319           ULONGEST addr, endaddr;
2320           const char *p = line;
2321
2322           addr = strtoulst (p, &p, 16);
2323           if (addr == range->start)
2324             {
2325               if (*p == '-')
2326                 p++;
2327               endaddr = strtoulst (p, &p, 16);
2328               range->length = endaddr - addr;
2329               return 1;
2330             }
2331         }
2332     }
2333   else
2334     warning (_("unable to open /proc file '%s'"), filename);
2335
2336   return 0;
2337 }
2338
2339 /* Implementation of the "vsyscall_range" gdbarch hook.  Handles
2340    caching, and defers the real work to linux_vsyscall_range_raw.  */
2341
2342 static int
2343 linux_vsyscall_range (struct gdbarch *gdbarch, struct mem_range *range)
2344 {
2345   struct linux_info *info = get_linux_inferior_data ();
2346
2347   if (info->vsyscall_range_p == 0)
2348     {
2349       if (linux_vsyscall_range_raw (gdbarch, &info->vsyscall_range))
2350         info->vsyscall_range_p = 1;
2351       else
2352         info->vsyscall_range_p = -1;
2353     }
2354
2355   if (info->vsyscall_range_p < 0)
2356     return 0;
2357
2358   *range = info->vsyscall_range;
2359   return 1;
2360 }
2361
2362 /* Symbols for linux_infcall_mmap's ARG_FLAGS; their Linux MAP_* system
2363    definitions would be dependent on compilation host.  */
2364 #define GDB_MMAP_MAP_PRIVATE    0x02            /* Changes are private.  */
2365 #define GDB_MMAP_MAP_ANONYMOUS  0x20            /* Don't use a file.  */
2366
2367 /* See gdbarch.sh 'infcall_mmap'.  */
2368
2369 static CORE_ADDR
2370 linux_infcall_mmap (CORE_ADDR size, unsigned prot)
2371 {
2372   struct objfile *objf;
2373   /* Do there still exist any Linux systems without "mmap64"?
2374      "mmap" uses 64-bit off_t on x86_64 and 32-bit off_t on i386 and x32.  */
2375   struct value *mmap_val = find_function_in_inferior ("mmap64", &objf);
2376   struct value *addr_val;
2377   struct gdbarch *gdbarch = get_objfile_arch (objf);
2378   CORE_ADDR retval;
2379   enum
2380     {
2381       ARG_ADDR, ARG_LENGTH, ARG_PROT, ARG_FLAGS, ARG_FD, ARG_OFFSET, ARG_LAST
2382     };
2383   struct value *arg[ARG_LAST];
2384
2385   arg[ARG_ADDR] = value_from_pointer (builtin_type (gdbarch)->builtin_data_ptr,
2386                                       0);
2387   /* Assuming sizeof (unsigned long) == sizeof (size_t).  */
2388   arg[ARG_LENGTH] = value_from_ulongest
2389                     (builtin_type (gdbarch)->builtin_unsigned_long, size);
2390   gdb_assert ((prot & ~(GDB_MMAP_PROT_READ | GDB_MMAP_PROT_WRITE
2391                         | GDB_MMAP_PROT_EXEC))
2392               == 0);
2393   arg[ARG_PROT] = value_from_longest (builtin_type (gdbarch)->builtin_int, prot);
2394   arg[ARG_FLAGS] = value_from_longest (builtin_type (gdbarch)->builtin_int,
2395                                        GDB_MMAP_MAP_PRIVATE
2396                                        | GDB_MMAP_MAP_ANONYMOUS);
2397   arg[ARG_FD] = value_from_longest (builtin_type (gdbarch)->builtin_int, -1);
2398   arg[ARG_OFFSET] = value_from_longest (builtin_type (gdbarch)->builtin_int64,
2399                                         0);
2400   addr_val = call_function_by_hand (mmap_val, NULL, ARG_LAST, arg);
2401   retval = value_as_address (addr_val);
2402   if (retval == (CORE_ADDR) -1)
2403     error (_("Failed inferior mmap call for %s bytes, errno is changed."),
2404            pulongest (size));
2405   return retval;
2406 }
2407
2408 /* See gdbarch.sh 'infcall_munmap'.  */
2409
2410 static void
2411 linux_infcall_munmap (CORE_ADDR addr, CORE_ADDR size)
2412 {
2413   struct objfile *objf;
2414   struct value *munmap_val = find_function_in_inferior ("munmap", &objf);
2415   struct value *retval_val;
2416   struct gdbarch *gdbarch = get_objfile_arch (objf);
2417   LONGEST retval;
2418   enum
2419     {
2420       ARG_ADDR, ARG_LENGTH, ARG_LAST
2421     };
2422   struct value *arg[ARG_LAST];
2423
2424   arg[ARG_ADDR] = value_from_pointer (builtin_type (gdbarch)->builtin_data_ptr,
2425                                       addr);
2426   /* Assuming sizeof (unsigned long) == sizeof (size_t).  */
2427   arg[ARG_LENGTH] = value_from_ulongest
2428                     (builtin_type (gdbarch)->builtin_unsigned_long, size);
2429   retval_val = call_function_by_hand (munmap_val, NULL, ARG_LAST, arg);
2430   retval = value_as_long (retval_val);
2431   if (retval != 0)
2432     warning (_("Failed inferior munmap call at %s for %s bytes, "
2433                "errno is changed."),
2434              hex_string (addr), pulongest (size));
2435 }
2436
2437 /* See linux-tdep.h.  */
2438
2439 CORE_ADDR
2440 linux_displaced_step_location (struct gdbarch *gdbarch)
2441 {
2442   CORE_ADDR addr;
2443   int bp_len;
2444
2445   /* Determine entry point from target auxiliary vector.  This avoids
2446      the need for symbols.  Also, when debugging a stand-alone SPU
2447      executable, entry_point_address () will point to an SPU
2448      local-store address and is thus not usable as displaced stepping
2449      location.  The auxiliary vector gets us the PowerPC-side entry
2450      point address instead.  */
2451   if (target_auxv_search (current_top_target (), AT_ENTRY, &addr) <= 0)
2452     throw_error (NOT_SUPPORTED_ERROR,
2453                  _("Cannot find AT_ENTRY auxiliary vector entry."));
2454
2455   /* Make certain that the address points at real code, and not a
2456      function descriptor.  */
2457   addr = gdbarch_convert_from_func_ptr_addr (gdbarch, addr,
2458                                              current_top_target ());
2459
2460   /* Inferior calls also use the entry point as a breakpoint location.
2461      We don't want displaced stepping to interfere with those
2462      breakpoints, so leave space.  */
2463   gdbarch_breakpoint_from_pc (gdbarch, &addr, &bp_len);
2464   addr += bp_len * 2;
2465
2466   return addr;
2467 }
2468
2469 /* Display whether the gcore command is using the
2470    /proc/PID/coredump_filter file.  */
2471
2472 static void
2473 show_use_coredump_filter (struct ui_file *file, int from_tty,
2474                           struct cmd_list_element *c, const char *value)
2475 {
2476   fprintf_filtered (file, _("Use of /proc/PID/coredump_filter file to generate"
2477                             " corefiles is %s.\n"), value);
2478 }
2479
2480 /* Display whether the gcore command is dumping mappings marked with
2481    the VM_DONTDUMP flag.  */
2482
2483 static void
2484 show_dump_excluded_mappings (struct ui_file *file, int from_tty,
2485                              struct cmd_list_element *c, const char *value)
2486 {
2487   fprintf_filtered (file, _("Dumping of mappings marked with the VM_DONTDUMP"
2488                             " flag is %s.\n"), value);
2489 }
2490
2491 /* To be called from the various GDB_OSABI_LINUX handlers for the
2492    various GNU/Linux architectures and machine types.  */
2493
2494 void
2495 linux_init_abi (struct gdbarch_info info, struct gdbarch *gdbarch)
2496 {
2497   set_gdbarch_core_pid_to_str (gdbarch, linux_core_pid_to_str);
2498   set_gdbarch_info_proc (gdbarch, linux_info_proc);
2499   set_gdbarch_core_info_proc (gdbarch, linux_core_info_proc);
2500   set_gdbarch_core_xfer_siginfo (gdbarch, linux_core_xfer_siginfo);
2501   set_gdbarch_find_memory_regions (gdbarch, linux_find_memory_regions);
2502   set_gdbarch_make_corefile_notes (gdbarch, linux_make_corefile_notes);
2503   set_gdbarch_has_shared_address_space (gdbarch,
2504                                         linux_has_shared_address_space);
2505   set_gdbarch_gdb_signal_from_target (gdbarch,
2506                                       linux_gdb_signal_from_target);
2507   set_gdbarch_gdb_signal_to_target (gdbarch,
2508                                     linux_gdb_signal_to_target);
2509   set_gdbarch_vsyscall_range (gdbarch, linux_vsyscall_range);
2510   set_gdbarch_infcall_mmap (gdbarch, linux_infcall_mmap);
2511   set_gdbarch_infcall_munmap (gdbarch, linux_infcall_munmap);
2512   set_gdbarch_get_siginfo_type (gdbarch, linux_get_siginfo_type);
2513 }
2514
2515 void
2516 _initialize_linux_tdep (void)
2517 {
2518   linux_gdbarch_data_handle =
2519     gdbarch_data_register_post_init (init_linux_gdbarch_data);
2520
2521   /* Set a cache per-inferior.  */
2522   linux_inferior_data
2523     = register_inferior_data_with_cleanup (NULL, linux_inferior_data_cleanup);
2524   /* Observers used to invalidate the cache when needed.  */
2525   gdb::observers::inferior_exit.attach (invalidate_linux_cache_inf);
2526   gdb::observers::inferior_appeared.attach (invalidate_linux_cache_inf);
2527
2528   add_setshow_boolean_cmd ("use-coredump-filter", class_files,
2529                            &use_coredump_filter, _("\
2530 Set whether gcore should consider /proc/PID/coredump_filter."),
2531                            _("\
2532 Show whether gcore should consider /proc/PID/coredump_filter."),
2533                            _("\
2534 Use this command to set whether gcore should consider the contents\n\
2535 of /proc/PID/coredump_filter when generating the corefile.  For more information\n\
2536 about this file, refer to the manpage of core(5)."),
2537                            NULL, show_use_coredump_filter,
2538                            &setlist, &showlist);
2539
2540   add_setshow_boolean_cmd ("dump-excluded-mappings", class_files,
2541                            &dump_excluded_mappings, _("\
2542 Set whether gcore should dump mappings marked with the VM_DONTDUMP flag."),
2543                            _("\
2544 Show whether gcore should dump mappings marked with the VM_DONTDUMP flag."),
2545                            _("\
2546 Use this command to set whether gcore should dump mappings marked with the\n\
2547 VM_DONTDUMP flag (\"dd\" in /proc/PID/smaps) when generating the corefile.  For\n\
2548 more information about this file, refer to the manpage of proc(5) and core(5)."),
2549                            NULL, show_dump_excluded_mappings,
2550                            &setlist, &showlist);
2551 }