target_stack -> current_top_target() throughout
[external/binutils.git] / gdb / auxv.c
1 /* Auxiliary vector support for GDB, the GNU debugger.
2
3    Copyright (C) 2004-2018 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 #include "defs.h"
21 #include "target.h"
22 #include "gdbtypes.h"
23 #include "command.h"
24 #include "inferior.h"
25 #include "valprint.h"
26 #include "gdbcore.h"
27 #include "observable.h"
28 #include "filestuff.h"
29 #include "objfiles.h"
30
31 #include "auxv.h"
32 #include "elf/common.h"
33
34 #include <unistd.h>
35 #include <fcntl.h>
36
37
38 /* Implement the to_xfer_partial target_ops method.  This function
39    handles access via /proc/PID/auxv, which is a common method for
40    native targets.  */
41
42 static enum target_xfer_status
43 procfs_xfer_auxv (gdb_byte *readbuf,
44                   const gdb_byte *writebuf,
45                   ULONGEST offset,
46                   ULONGEST len,
47                   ULONGEST *xfered_len)
48 {
49   char *pathname;
50   int fd;
51   ssize_t l;
52
53   pathname = xstrprintf ("/proc/%d/auxv", ptid_get_pid (inferior_ptid));
54   fd = gdb_open_cloexec (pathname, writebuf != NULL ? O_WRONLY : O_RDONLY, 0);
55   xfree (pathname);
56   if (fd < 0)
57     return TARGET_XFER_E_IO;
58
59   if (offset != (ULONGEST) 0
60       && lseek (fd, (off_t) offset, SEEK_SET) != (off_t) offset)
61     l = -1;
62   else if (readbuf != NULL)
63     l = read (fd, readbuf, (size_t) len);
64   else
65     l = write (fd, writebuf, (size_t) len);
66
67   (void) close (fd);
68
69   if (l < 0)
70     return TARGET_XFER_E_IO;
71   else if (l == 0)
72     return TARGET_XFER_EOF;
73   else
74     {
75       *xfered_len = (ULONGEST) l;
76       return TARGET_XFER_OK;
77     }
78 }
79
80 /* This function handles access via ld.so's symbol `_dl_auxv'.  */
81
82 static enum target_xfer_status
83 ld_so_xfer_auxv (gdb_byte *readbuf,
84                  const gdb_byte *writebuf,
85                  ULONGEST offset,
86                  ULONGEST len, ULONGEST *xfered_len)
87 {
88   struct bound_minimal_symbol msym;
89   CORE_ADDR data_address, pointer_address;
90   struct type *ptr_type = builtin_type (target_gdbarch ())->builtin_data_ptr;
91   size_t ptr_size = TYPE_LENGTH (ptr_type);
92   size_t auxv_pair_size = 2 * ptr_size;
93   gdb_byte *ptr_buf = (gdb_byte *) alloca (ptr_size);
94   LONGEST retval;
95   size_t block;
96
97   msym = lookup_minimal_symbol ("_dl_auxv", NULL, NULL);
98   if (msym.minsym == NULL)
99     return TARGET_XFER_E_IO;
100
101   if (MSYMBOL_SIZE (msym.minsym) != ptr_size)
102     return TARGET_XFER_E_IO;
103
104   /* POINTER_ADDRESS is a location where the `_dl_auxv' variable
105      resides.  DATA_ADDRESS is the inferior value present in
106      `_dl_auxv', therefore the real inferior AUXV address.  */
107
108   pointer_address = BMSYMBOL_VALUE_ADDRESS (msym);
109
110   /* The location of the _dl_auxv symbol may no longer be correct if
111      ld.so runs at a different address than the one present in the
112      file.  This is very common case - for unprelinked ld.so or with a
113      PIE executable.  PIE executable forces random address even for
114      libraries already being prelinked to some address.  PIE
115      executables themselves are never prelinked even on prelinked
116      systems.  Prelinking of a PIE executable would block their
117      purpose of randomizing load of everything including the
118      executable.
119
120      If the memory read fails, return -1 to fallback on another
121      mechanism for retrieving the AUXV.
122
123      In most cases of a PIE running under valgrind there is no way to
124      find out the base addresses of any of ld.so, executable or AUXV
125      as everything is randomized and /proc information is not relevant
126      for the virtual executable running under valgrind.  We think that
127      we might need a valgrind extension to make it work.  This is PR
128      11440.  */
129
130   if (target_read_memory (pointer_address, ptr_buf, ptr_size) != 0)
131     return TARGET_XFER_E_IO;
132
133   data_address = extract_typed_address (ptr_buf, ptr_type);
134
135   /* Possibly still not initialized such as during an inferior
136      startup.  */
137   if (data_address == 0)
138     return TARGET_XFER_E_IO;
139
140   data_address += offset;
141
142   if (writebuf != NULL)
143     {
144       if (target_write_memory (data_address, writebuf, len) == 0)
145         {
146           *xfered_len = (ULONGEST) len;
147           return TARGET_XFER_OK;
148         }
149       else
150         return TARGET_XFER_E_IO;
151     }
152
153   /* Stop if trying to read past the existing AUXV block.  The final
154      AT_NULL was already returned before.  */
155
156   if (offset >= auxv_pair_size)
157     {
158       if (target_read_memory (data_address - auxv_pair_size, ptr_buf,
159                               ptr_size) != 0)
160         return TARGET_XFER_E_IO;
161
162       if (extract_typed_address (ptr_buf, ptr_type) == AT_NULL)
163         return TARGET_XFER_EOF;
164     }
165
166   retval = 0;
167   block = 0x400;
168   gdb_assert (block % auxv_pair_size == 0);
169
170   while (len > 0)
171     {
172       if (block > len)
173         block = len;
174
175       /* Reading sizes smaller than AUXV_PAIR_SIZE is not supported.
176          Tails unaligned to AUXV_PAIR_SIZE will not be read during a
177          call (they should be completed during next read with
178          new/extended buffer).  */
179
180       block &= -auxv_pair_size;
181       if (block == 0)
182         break;
183
184       if (target_read_memory (data_address, readbuf, block) != 0)
185         {
186           if (block <= auxv_pair_size)
187             break;
188
189           block = auxv_pair_size;
190           continue;
191         }
192
193       data_address += block;
194       len -= block;
195
196       /* Check terminal AT_NULL.  This function is being called
197          indefinitely being extended its READBUF until it returns EOF
198          (0).  */
199
200       while (block >= auxv_pair_size)
201         {
202           retval += auxv_pair_size;
203
204           if (extract_typed_address (readbuf, ptr_type) == AT_NULL)
205             {
206               *xfered_len = (ULONGEST) retval;
207               return TARGET_XFER_OK;
208             }
209
210           readbuf += auxv_pair_size;
211           block -= auxv_pair_size;
212         }
213     }
214
215   *xfered_len = (ULONGEST) retval;
216   return TARGET_XFER_OK;
217 }
218
219 /* Implement the to_xfer_partial target_ops method for
220    TARGET_OBJECT_AUXV.  It handles access to AUXV.  */
221
222 enum target_xfer_status
223 memory_xfer_auxv (struct target_ops *ops,
224                   enum target_object object,
225                   const char *annex,
226                   gdb_byte *readbuf,
227                   const gdb_byte *writebuf,
228                   ULONGEST offset,
229                   ULONGEST len, ULONGEST *xfered_len)
230 {
231   gdb_assert (object == TARGET_OBJECT_AUXV);
232   gdb_assert (readbuf || writebuf);
233
234    /* ld_so_xfer_auxv is the only function safe for virtual
235       executables being executed by valgrind's memcheck.  Using
236       ld_so_xfer_auxv during inferior startup is problematic, because
237       ld.so symbol tables have not yet been relocated.  So GDB uses
238       this function only when attaching to a process.
239       */
240
241   if (current_inferior ()->attach_flag != 0)
242     {
243       enum target_xfer_status ret;
244
245       ret = ld_so_xfer_auxv (readbuf, writebuf, offset, len, xfered_len);
246       if (ret != TARGET_XFER_E_IO)
247         return ret;
248     }
249
250   return procfs_xfer_auxv (readbuf, writebuf, offset, len, xfered_len);
251 }
252
253 /* Read one auxv entry from *READPTR, not reading locations >= ENDPTR.
254    Return 0 if *READPTR is already at the end of the buffer.
255    Return -1 if there is insufficient buffer for a whole entry.
256    Return 1 if an entry was read into *TYPEP and *VALP.  */
257 int
258 default_auxv_parse (struct target_ops *ops, gdb_byte **readptr,
259                    gdb_byte *endptr, CORE_ADDR *typep, CORE_ADDR *valp)
260 {
261   const int sizeof_auxv_field = gdbarch_ptr_bit (target_gdbarch ())
262                                 / TARGET_CHAR_BIT;
263   const enum bfd_endian byte_order = gdbarch_byte_order (target_gdbarch ());
264   gdb_byte *ptr = *readptr;
265
266   if (endptr == ptr)
267     return 0;
268
269   if (endptr - ptr < sizeof_auxv_field * 2)
270     return -1;
271
272   *typep = extract_unsigned_integer (ptr, sizeof_auxv_field, byte_order);
273   ptr += sizeof_auxv_field;
274   *valp = extract_unsigned_integer (ptr, sizeof_auxv_field, byte_order);
275   ptr += sizeof_auxv_field;
276
277   *readptr = ptr;
278   return 1;
279 }
280
281 /* Read one auxv entry from *READPTR, not reading locations >= ENDPTR.
282    Return 0 if *READPTR is already at the end of the buffer.
283    Return -1 if there is insufficient buffer for a whole entry.
284    Return 1 if an entry was read into *TYPEP and *VALP.  */
285 int
286 target_auxv_parse (gdb_byte **readptr,
287                    gdb_byte *endptr, CORE_ADDR *typep, CORE_ADDR *valp)
288 {
289   struct gdbarch *gdbarch = target_gdbarch();
290
291   if (gdbarch_auxv_parse_p (gdbarch))
292     return gdbarch_auxv_parse (gdbarch, readptr, endptr, typep, valp);
293
294   return current_top_target ()->auxv_parse (readptr, endptr, typep, valp);
295 }
296
297
298 /* Per-inferior data key for auxv.  */
299 static const struct inferior_data *auxv_inferior_data;
300
301 /*  Auxiliary Vector information structure.  This is used by GDB
302     for caching purposes for each inferior.  This helps reduce the
303     overhead of transfering data from a remote target to the local host.  */
304 struct auxv_info
305 {
306   gdb::optional<gdb::byte_vector> data;
307 };
308
309 /* Handles the cleanup of the auxv cache for inferior INF.  ARG is ignored.
310    Frees whatever allocated space there is to be freed and sets INF's auxv cache
311    data pointer to NULL.
312
313    This function is called when the following events occur: inferior_appeared,
314    inferior_exit and executable_changed.  */
315
316 static void
317 auxv_inferior_data_cleanup (struct inferior *inf, void *arg)
318 {
319   struct auxv_info *info;
320
321   info = (struct auxv_info *) inferior_data (inf, auxv_inferior_data);
322   if (info != NULL)
323     {
324       delete info;
325       set_inferior_data (inf, auxv_inferior_data, NULL);
326     }
327 }
328
329 /* Invalidate INF's auxv cache.  */
330
331 static void
332 invalidate_auxv_cache_inf (struct inferior *inf)
333 {
334   auxv_inferior_data_cleanup (inf, NULL);
335 }
336
337 /* Invalidate current inferior's auxv cache.  */
338
339 static void
340 invalidate_auxv_cache (void)
341 {
342   invalidate_auxv_cache_inf (current_inferior ());
343 }
344
345 /* Fetch the auxv object from inferior INF.  If auxv is cached already,
346    return a pointer to the cache.  If not, fetch the auxv object from the
347    target and cache it.  This function always returns a valid INFO pointer.  */
348
349 static struct auxv_info *
350 get_auxv_inferior_data (struct target_ops *ops)
351 {
352   struct auxv_info *info;
353   struct inferior *inf = current_inferior ();
354
355   info = (struct auxv_info *) inferior_data (inf, auxv_inferior_data);
356   if (info == NULL)
357     {
358       info = new auxv_info;
359       info->data = target_read_alloc (ops, TARGET_OBJECT_AUXV, NULL);
360       set_inferior_data (inf, auxv_inferior_data, info);
361     }
362
363   return info;
364 }
365
366 /* Extract the auxiliary vector entry with a_type matching MATCH.
367    Return zero if no such entry was found, or -1 if there was
368    an error getting the information.  On success, return 1 after
369    storing the entry's value field in *VALP.  */
370 int
371 target_auxv_search (struct target_ops *ops, CORE_ADDR match, CORE_ADDR *valp)
372 {
373   CORE_ADDR type, val;
374   auxv_info *info = get_auxv_inferior_data (ops);
375
376   if (!info->data)
377     return -1;
378
379   gdb_byte *data = info->data->data ();
380   gdb_byte *ptr = data;
381   size_t len = info->data->size ();
382
383   while (1)
384     switch (target_auxv_parse (&ptr, data + len, &type, &val))
385       {
386       case 1:                   /* Here's an entry, check it.  */
387         if (type == match)
388           {
389             *valp = val;
390             return 1;
391           }
392         break;
393       case 0:                   /* End of the vector.  */
394         return 0;
395       default:                  /* Bogosity.  */
396         return -1;
397       }
398
399   /*NOTREACHED*/
400 }
401
402
403 /* Print the description of a single AUXV entry on the specified file.  */
404
405 void
406 fprint_auxv_entry (struct ui_file *file, const char *name,
407                    const char *description, enum auxv_format format,
408                    CORE_ADDR type, CORE_ADDR val)
409 {
410   fprintf_filtered (file, ("%-4s %-20s %-30s "),
411                     plongest (type), name, description);
412   switch (format)
413     {
414     case AUXV_FORMAT_DEC:
415       fprintf_filtered (file, ("%s\n"), plongest (val));
416       break;
417     case AUXV_FORMAT_HEX:
418       fprintf_filtered (file, ("%s\n"), paddress (target_gdbarch (), val));
419       break;
420     case AUXV_FORMAT_STR:
421       {
422         struct value_print_options opts;
423
424         get_user_print_options (&opts);
425         if (opts.addressprint)
426           fprintf_filtered (file, ("%s "), paddress (target_gdbarch (), val));
427         val_print_string (builtin_type (target_gdbarch ())->builtin_char,
428                           NULL, val, -1, file, &opts);
429         fprintf_filtered (file, ("\n"));
430       }
431       break;
432     }
433 }
434
435 /* The default implementation of gdbarch_print_auxv_entry.  */
436
437 void
438 default_print_auxv_entry (struct gdbarch *gdbarch, struct ui_file *file,
439                           CORE_ADDR type, CORE_ADDR val)
440 {
441   const char *name = "???";
442   const char *description = "";
443   enum auxv_format format = AUXV_FORMAT_HEX;
444
445   switch (type)
446     {
447 #define TAG(tag, text, kind) \
448       case tag: name = #tag; description = text; format = kind; break
449       TAG (AT_NULL, _("End of vector"), AUXV_FORMAT_HEX);
450       TAG (AT_IGNORE, _("Entry should be ignored"), AUXV_FORMAT_HEX);
451       TAG (AT_EXECFD, _("File descriptor of program"), AUXV_FORMAT_DEC);
452       TAG (AT_PHDR, _("Program headers for program"), AUXV_FORMAT_HEX);
453       TAG (AT_PHENT, _("Size of program header entry"), AUXV_FORMAT_DEC);
454       TAG (AT_PHNUM, _("Number of program headers"), AUXV_FORMAT_DEC);
455       TAG (AT_PAGESZ, _("System page size"), AUXV_FORMAT_DEC);
456       TAG (AT_BASE, _("Base address of interpreter"), AUXV_FORMAT_HEX);
457       TAG (AT_FLAGS, _("Flags"), AUXV_FORMAT_HEX);
458       TAG (AT_ENTRY, _("Entry point of program"), AUXV_FORMAT_HEX);
459       TAG (AT_NOTELF, _("Program is not ELF"), AUXV_FORMAT_DEC);
460       TAG (AT_UID, _("Real user ID"), AUXV_FORMAT_DEC);
461       TAG (AT_EUID, _("Effective user ID"), AUXV_FORMAT_DEC);
462       TAG (AT_GID, _("Real group ID"), AUXV_FORMAT_DEC);
463       TAG (AT_EGID, _("Effective group ID"), AUXV_FORMAT_DEC);
464       TAG (AT_CLKTCK, _("Frequency of times()"), AUXV_FORMAT_DEC);
465       TAG (AT_PLATFORM, _("String identifying platform"), AUXV_FORMAT_STR);
466       TAG (AT_HWCAP, _("Machine-dependent CPU capability hints"),
467            AUXV_FORMAT_HEX);
468       TAG (AT_FPUCW, _("Used FPU control word"), AUXV_FORMAT_DEC);
469       TAG (AT_DCACHEBSIZE, _("Data cache block size"), AUXV_FORMAT_DEC);
470       TAG (AT_ICACHEBSIZE, _("Instruction cache block size"), AUXV_FORMAT_DEC);
471       TAG (AT_UCACHEBSIZE, _("Unified cache block size"), AUXV_FORMAT_DEC);
472       TAG (AT_IGNOREPPC, _("Entry should be ignored"), AUXV_FORMAT_DEC);
473       TAG (AT_BASE_PLATFORM, _("String identifying base platform"),
474            AUXV_FORMAT_STR);
475       TAG (AT_RANDOM, _("Address of 16 random bytes"), AUXV_FORMAT_HEX);
476       TAG (AT_HWCAP2, _("Extension of AT_HWCAP"), AUXV_FORMAT_HEX);
477       TAG (AT_EXECFN, _("File name of executable"), AUXV_FORMAT_STR);
478       TAG (AT_SECURE, _("Boolean, was exec setuid-like?"), AUXV_FORMAT_DEC);
479       TAG (AT_SYSINFO, _("Special system info/entry points"), AUXV_FORMAT_HEX);
480       TAG (AT_SYSINFO_EHDR, _("System-supplied DSO's ELF header"),
481            AUXV_FORMAT_HEX);
482       TAG (AT_L1I_CACHESHAPE, _("L1 Instruction cache information"),
483            AUXV_FORMAT_HEX);
484       TAG (AT_L1D_CACHESHAPE, _("L1 Data cache information"), AUXV_FORMAT_HEX);
485       TAG (AT_L2_CACHESHAPE, _("L2 cache information"), AUXV_FORMAT_HEX);
486       TAG (AT_L3_CACHESHAPE, _("L3 cache information"), AUXV_FORMAT_HEX);
487       TAG (AT_SUN_UID, _("Effective user ID"), AUXV_FORMAT_DEC);
488       TAG (AT_SUN_RUID, _("Real user ID"), AUXV_FORMAT_DEC);
489       TAG (AT_SUN_GID, _("Effective group ID"), AUXV_FORMAT_DEC);
490       TAG (AT_SUN_RGID, _("Real group ID"), AUXV_FORMAT_DEC);
491       TAG (AT_SUN_LDELF, _("Dynamic linker's ELF header"), AUXV_FORMAT_HEX);
492       TAG (AT_SUN_LDSHDR, _("Dynamic linker's section headers"),
493            AUXV_FORMAT_HEX);
494       TAG (AT_SUN_LDNAME, _("String giving name of dynamic linker"),
495            AUXV_FORMAT_STR);
496       TAG (AT_SUN_LPAGESZ, _("Large pagesize"), AUXV_FORMAT_DEC);
497       TAG (AT_SUN_PLATFORM, _("Platform name string"), AUXV_FORMAT_STR);
498       TAG (AT_SUN_HWCAP, _("Machine-dependent CPU capability hints"),
499            AUXV_FORMAT_HEX);
500       TAG (AT_SUN_IFLUSH, _("Should flush icache?"), AUXV_FORMAT_DEC);
501       TAG (AT_SUN_CPU, _("CPU name string"), AUXV_FORMAT_STR);
502       TAG (AT_SUN_EMUL_ENTRY, _("COFF entry point address"), AUXV_FORMAT_HEX);
503       TAG (AT_SUN_EMUL_EXECFD, _("COFF executable file descriptor"),
504            AUXV_FORMAT_DEC);
505       TAG (AT_SUN_EXECNAME,
506            _("Canonicalized file name given to execve"), AUXV_FORMAT_STR);
507       TAG (AT_SUN_MMU, _("String for name of MMU module"), AUXV_FORMAT_STR);
508       TAG (AT_SUN_LDDATA, _("Dynamic linker's data segment address"),
509            AUXV_FORMAT_HEX);
510       TAG (AT_SUN_AUXFLAGS,
511            _("AF_SUN_ flags passed from the kernel"), AUXV_FORMAT_HEX);
512     }
513
514   fprint_auxv_entry (file, name, description, format, type, val);
515 }
516
517 /* Print the contents of the target's AUXV on the specified file.  */
518
519 int
520 fprint_target_auxv (struct ui_file *file, struct target_ops *ops)
521 {
522   struct gdbarch *gdbarch = target_gdbarch ();
523   CORE_ADDR type, val;
524   int ents = 0;
525   auxv_info *info = get_auxv_inferior_data (ops);
526
527   if (!info->data)
528     return -1;
529
530   gdb_byte *data = info->data->data ();
531   gdb_byte *ptr = data;
532   size_t len = info->data->size ();
533
534   while (target_auxv_parse (&ptr, data + len, &type, &val) > 0)
535     {
536       gdbarch_print_auxv_entry (gdbarch, file, type, val);
537       ++ents;
538       if (type == AT_NULL)
539         break;
540     }
541
542   return ents;
543 }
544
545 static void
546 info_auxv_command (const char *cmd, int from_tty)
547 {
548   if (! target_has_stack)
549     error (_("The program has no auxiliary information now."));
550   else
551     {
552       int ents = fprint_target_auxv (gdb_stdout, current_top_target ());
553
554       if (ents < 0)
555         error (_("No auxiliary vector found, or failed reading it."));
556       else if (ents == 0)
557         error (_("Auxiliary vector is empty."));
558     }
559 }
560
561 void
562 _initialize_auxv (void)
563 {
564   add_info ("auxv", info_auxv_command,
565             _("Display the inferior's auxiliary vector.\n\
566 This is information provided by the operating system at program startup."));
567
568   /* Set an auxv cache per-inferior.  */
569   auxv_inferior_data
570     = register_inferior_data_with_cleanup (NULL, auxv_inferior_data_cleanup);
571
572   /* Observers used to invalidate the auxv cache when needed.  */
573   gdb::observers::inferior_exit.attach (invalidate_auxv_cache_inf);
574   gdb::observers::inferior_appeared.attach (invalidate_auxv_cache_inf);
575   gdb::observers::executable_changed.attach (invalidate_auxv_cache);
576 }