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