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