target_stack -> current_top_target() throughout
[external/binutils.git] / gdb / solib-darwin.c
1 /* Handle Darwin shared libraries for GDB, the GNU Debugger.
2
3    Copyright (C) 2009-2018 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 #include "defs.h"
21
22 #include "symtab.h"
23 #include "bfd.h"
24 #include "symfile.h"
25 #include "objfiles.h"
26 #include "gdbcore.h"
27 #include "target.h"
28 #include "inferior.h"
29 #include "regcache.h"
30 #include "gdbthread.h"
31 #include "gdb_bfd.h"
32
33 #include "solist.h"
34 #include "solib.h"
35 #include "solib-svr4.h"
36
37 #include "bfd-target.h"
38 #include "elf-bfd.h"
39 #include "exec.h"
40 #include "auxv.h"
41 #include "mach-o.h"
42 #include "mach-o/external.h"
43
44 struct gdb_dyld_image_info
45 {
46   /* Base address (which corresponds to the Mach-O header).  */
47   CORE_ADDR mach_header;
48   /* Image file path.  */
49   CORE_ADDR file_path;
50   /* st.m_time of image file.  */
51   unsigned long mtime;
52 };
53
54 /* Content of inferior dyld_all_image_infos structure.
55    See /usr/include/mach-o/dyld_images.h for the documentation.  */
56 struct gdb_dyld_all_image_infos
57 {
58   /* Version (1).  */
59   unsigned int version;
60   /* Number of images.  */
61   unsigned int count;
62   /* Image description.  */
63   CORE_ADDR info;
64   /* Notifier (function called when a library is added or removed).  */
65   CORE_ADDR notifier;
66 };
67
68 /* Current all_image_infos version.  */
69 #define DYLD_VERSION_MIN 1
70 #define DYLD_VERSION_MAX 15
71
72 /* Per PSPACE specific data.  */
73 struct darwin_info
74 {
75   /* Address of structure dyld_all_image_infos in inferior.  */
76   CORE_ADDR all_image_addr;
77
78   /* Gdb copy of dyld_all_info_infos.  */
79   struct gdb_dyld_all_image_infos all_image;
80 };
81
82 /* Per-program-space data key.  */
83 static const struct program_space_data *solib_darwin_pspace_data;
84
85 static void
86 darwin_pspace_data_cleanup (struct program_space *pspace, void *arg)
87 {
88   xfree (arg);
89 }
90
91 /* Get the current darwin data.  If none is found yet, add it now.  This
92    function always returns a valid object.  */
93
94 static struct darwin_info *
95 get_darwin_info (void)
96 {
97   struct darwin_info *info;
98
99   info = (struct darwin_info *) program_space_data (current_program_space,
100                                                     solib_darwin_pspace_data);
101   if (info != NULL)
102     return info;
103
104   info = XCNEW (struct darwin_info);
105   set_program_space_data (current_program_space,
106                           solib_darwin_pspace_data, info);
107   return info;
108 }
109
110 /* Return non-zero if the version in dyld_all_image is known.  */
111
112 static int
113 darwin_dyld_version_ok (const struct darwin_info *info)
114 {
115   return info->all_image.version >= DYLD_VERSION_MIN
116     && info->all_image.version <= DYLD_VERSION_MAX;
117 }
118
119 /* Read dyld_all_image from inferior.  */
120
121 static void
122 darwin_load_image_infos (struct darwin_info *info)
123 {
124   gdb_byte buf[24];
125   enum bfd_endian byte_order = gdbarch_byte_order (target_gdbarch ());
126   struct type *ptr_type = builtin_type (target_gdbarch ())->builtin_data_ptr;
127   int len;
128
129   /* If the structure address is not known, don't continue.  */
130   if (info->all_image_addr == 0)
131     return;
132
133   /* The structure has 4 fields: version (4 bytes), count (4 bytes),
134      info (pointer) and notifier (pointer).  */
135   len = 4 + 4 + 2 * TYPE_LENGTH (ptr_type);
136   gdb_assert (len <= sizeof (buf));
137   memset (&info->all_image, 0, sizeof (info->all_image));
138
139   /* Read structure raw bytes from target.  */
140   if (target_read_memory (info->all_image_addr, buf, len))
141     return;
142
143   /* Extract the fields.  */
144   info->all_image.version = extract_unsigned_integer (buf, 4, byte_order);
145   if (!darwin_dyld_version_ok (info))
146     return;
147
148   info->all_image.count = extract_unsigned_integer (buf + 4, 4, byte_order);
149   info->all_image.info = extract_typed_address (buf + 8, ptr_type);
150   info->all_image.notifier = extract_typed_address
151     (buf + 8 + TYPE_LENGTH (ptr_type), ptr_type);
152 }
153
154 /* Link map info to include in an allocated so_list entry.  */
155
156 struct lm_info_darwin : public lm_info_base
157 {
158   /* The target location of lm.  */
159   CORE_ADDR lm_addr = 0;
160 };
161
162 /* Lookup the value for a specific symbol.  */
163
164 static CORE_ADDR
165 lookup_symbol_from_bfd (bfd *abfd, const char *symname)
166 {
167   long storage_needed;
168   asymbol **symbol_table;
169   unsigned int number_of_symbols;
170   unsigned int i;
171   CORE_ADDR symaddr = 0;
172
173   storage_needed = bfd_get_symtab_upper_bound (abfd);
174
175   if (storage_needed <= 0)
176     return 0;
177
178   symbol_table = (asymbol **) xmalloc (storage_needed);
179   number_of_symbols = bfd_canonicalize_symtab (abfd, symbol_table);
180
181   for (i = 0; i < number_of_symbols; i++)
182     {
183       asymbol *sym = symbol_table[i];
184
185       if (strcmp (sym->name, symname) == 0
186           && (sym->section->flags & (SEC_CODE | SEC_DATA)) != 0)
187         {
188           /* BFD symbols are section relative.  */
189           symaddr = sym->value + sym->section->vma;
190           break;
191         }
192     }
193   xfree (symbol_table);
194
195   return symaddr;
196 }
197
198 /* Return program interpreter string.  */
199
200 static char *
201 find_program_interpreter (void)
202 {
203   char *buf = NULL;
204
205   /* If we have an exec_bfd, get the interpreter from the load commands.  */
206   if (exec_bfd)
207     {
208       bfd_mach_o_load_command *cmd;
209
210       if (bfd_mach_o_lookup_command (exec_bfd,
211                                      BFD_MACH_O_LC_LOAD_DYLINKER, &cmd) == 1)
212         return cmd->command.dylinker.name_str;
213     }
214
215   /* If we didn't find it, read from memory.
216      FIXME: todo.  */
217   return buf;
218 }
219
220 /*  Not used.  I don't see how the main symbol file can be found: the
221     interpreter name is needed and it is known from the executable file.
222     Note that darwin-nat.c implements pid_to_exec_file.  */
223
224 static int
225 open_symbol_file_object (int from_tty)
226 {
227   return 0;
228 }
229
230 /* Build a list of currently loaded shared objects.  See solib-svr4.c.  */
231
232 static struct so_list *
233 darwin_current_sos (void)
234 {
235   struct type *ptr_type = builtin_type (target_gdbarch ())->builtin_data_ptr;
236   enum bfd_endian byte_order = gdbarch_byte_order (target_gdbarch ());
237   int ptr_len = TYPE_LENGTH (ptr_type);
238   unsigned int image_info_size;
239   struct so_list *head = NULL;
240   struct so_list *tail = NULL;
241   int i;
242   struct darwin_info *info = get_darwin_info ();
243
244   /* Be sure image infos are loaded.  */
245   darwin_load_image_infos (info);
246
247   if (!darwin_dyld_version_ok (info))
248     return NULL;
249
250   image_info_size = ptr_len * 3;
251
252   /* Read infos for each solib.
253      The first entry was rumored to be the executable itself, but this is not
254      true when a large number of shared libraries are used (table expanded ?).
255      We now check all entries, but discard executable images.  */
256   for (i = 0; i < info->all_image.count; i++)
257     {
258       CORE_ADDR iinfo = info->all_image.info + i * image_info_size;
259       gdb_byte buf[image_info_size];
260       CORE_ADDR load_addr;
261       CORE_ADDR path_addr;
262       struct mach_o_header_external hdr;
263       unsigned long hdr_val;
264       gdb::unique_xmalloc_ptr<char> file_path;
265       int errcode;
266       struct so_list *newobj;
267       struct cleanup *old_chain;
268
269       /* Read image info from inferior.  */
270       if (target_read_memory (iinfo, buf, image_info_size))
271         break;
272
273       load_addr = extract_typed_address (buf, ptr_type);
274       path_addr = extract_typed_address (buf + ptr_len, ptr_type);
275
276       /* Read Mach-O header from memory.  */
277       if (target_read_memory (load_addr, (gdb_byte *) &hdr, sizeof (hdr) - 4))
278         break;
279       /* Discard wrong magic numbers.  Shouldn't happen.  */
280       hdr_val = extract_unsigned_integer
281         (hdr.magic, sizeof (hdr.magic), byte_order);
282       if (hdr_val != BFD_MACH_O_MH_MAGIC && hdr_val != BFD_MACH_O_MH_MAGIC_64)
283         continue;
284       /* Discard executable.  Should happen only once.  */
285       hdr_val = extract_unsigned_integer
286         (hdr.filetype, sizeof (hdr.filetype), byte_order);
287       if (hdr_val == BFD_MACH_O_MH_EXECUTE)
288         continue;
289
290       target_read_string (path_addr, &file_path,
291                           SO_NAME_MAX_PATH_SIZE - 1, &errcode);
292       if (errcode)
293         break;
294
295       /* Create and fill the new so_list element.  */
296       newobj = XCNEW (struct so_list);
297       old_chain = make_cleanup (xfree, newobj);
298
299       lm_info_darwin *li = new lm_info_darwin;
300       newobj->lm_info = li;
301
302       strncpy (newobj->so_name, file_path.get (), SO_NAME_MAX_PATH_SIZE - 1);
303       newobj->so_name[SO_NAME_MAX_PATH_SIZE - 1] = '\0';
304       strcpy (newobj->so_original_name, newobj->so_name);
305       li->lm_addr = load_addr;
306
307       if (head == NULL)
308         head = newobj;
309       else
310         tail->next = newobj;
311       tail = newobj;
312
313       discard_cleanups (old_chain);
314     }
315
316   return head;
317 }
318
319 /* Check LOAD_ADDR points to a Mach-O executable header.  Return LOAD_ADDR
320    in case of success, 0 in case of failure.  */
321
322 static CORE_ADDR
323 darwin_validate_exec_header (CORE_ADDR load_addr)
324 {
325   enum bfd_endian byte_order = gdbarch_byte_order (target_gdbarch ());
326   struct mach_o_header_external hdr;
327   unsigned long hdr_val;
328
329   /* Read Mach-O header from memory.  */
330   if (target_read_memory (load_addr, (gdb_byte *) &hdr, sizeof (hdr) - 4))
331     return 0;
332
333   /* Discard wrong magic numbers.  Shouldn't happen.  */
334   hdr_val = extract_unsigned_integer
335     (hdr.magic, sizeof (hdr.magic), byte_order);
336   if (hdr_val != BFD_MACH_O_MH_MAGIC && hdr_val != BFD_MACH_O_MH_MAGIC_64)
337     return 0;
338
339   /* Check executable.  */
340   hdr_val = extract_unsigned_integer
341     (hdr.filetype, sizeof (hdr.filetype), byte_order);
342   if (hdr_val == BFD_MACH_O_MH_EXECUTE)
343     return load_addr;
344
345   return 0;
346 }
347
348 /* Get the load address of the executable using dyld list of images.
349    We assume that the dyld info are correct (which is wrong if the target
350    is stopped at the first instruction).  */
351
352 static CORE_ADDR
353 darwin_read_exec_load_addr_from_dyld (struct darwin_info *info)
354 {
355   struct type *ptr_type = builtin_type (target_gdbarch ())->builtin_data_ptr;
356   int ptr_len = TYPE_LENGTH (ptr_type);
357   unsigned int image_info_size = ptr_len * 3;
358   int i;
359
360   /* Read infos for each solib.  One of them should be the executable.  */
361   for (i = 0; i < info->all_image.count; i++)
362     {
363       CORE_ADDR iinfo = info->all_image.info + i * image_info_size;
364       gdb_byte buf[image_info_size];
365       CORE_ADDR load_addr;
366
367       /* Read image info from inferior.  */
368       if (target_read_memory (iinfo, buf, image_info_size))
369         break;
370
371       load_addr = extract_typed_address (buf, ptr_type);
372       if (darwin_validate_exec_header (load_addr) == load_addr)
373         return load_addr;
374     }
375
376   return 0;
377 }
378
379 /* Get the load address of the executable when the PC is at the dyld
380    entry point using parameter passed by the kernel (at SP). */
381
382 static CORE_ADDR
383 darwin_read_exec_load_addr_at_init (struct darwin_info *info)
384 {
385   struct gdbarch *gdbarch = target_gdbarch ();
386   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
387   int addr_size = gdbarch_addr_bit (gdbarch) / 8;
388   ULONGEST load_ptr_addr;
389   ULONGEST load_addr;
390   gdb_byte buf[8];
391
392   /* Get SP.  */
393   if (regcache_cooked_read_unsigned (get_current_regcache (),
394                                      gdbarch_sp_regnum (gdbarch),
395                                      &load_ptr_addr) != REG_VALID)
396     return 0;
397
398   /* Read value at SP (image load address).  */
399   if (target_read_memory (load_ptr_addr, buf, addr_size))
400     return 0;
401
402   load_addr = extract_unsigned_integer (buf, addr_size, byte_order);
403
404   return darwin_validate_exec_header (load_addr);
405 }
406
407 /* Return 1 if PC lies in the dynamic symbol resolution code of the
408    run time loader.  */
409
410 static int
411 darwin_in_dynsym_resolve_code (CORE_ADDR pc)
412 {
413   return 0;
414 }
415
416 /* A wrapper for bfd_mach_o_fat_extract that handles reference
417    counting properly.  This will either return NULL, or return a new
418    reference to a BFD.  */
419
420 static gdb_bfd_ref_ptr
421 gdb_bfd_mach_o_fat_extract (bfd *abfd, bfd_format format,
422                             const bfd_arch_info_type *arch)
423 {
424   bfd *result = bfd_mach_o_fat_extract (abfd, format, arch);
425
426   if (result == NULL)
427     return NULL;
428
429   if (result == abfd)
430     gdb_bfd_ref (result);
431   else
432     gdb_bfd_mark_parent (result, abfd);
433
434   return gdb_bfd_ref_ptr (result);
435 }
436
437 /* Extract dyld_all_image_addr when the process was just created, assuming the
438    current PC is at the entry of the dynamic linker.  */
439
440 static void
441 darwin_solib_get_all_image_info_addr_at_init (struct darwin_info *info)
442 {
443   char *interp_name;
444   CORE_ADDR load_addr = 0;
445
446   /* This method doesn't work with an attached process.  */
447   if (current_inferior ()->attach_flag)
448     return;
449
450   /* Find the program interpreter.  */
451   interp_name = find_program_interpreter ();
452   if (!interp_name)
453     return;
454
455   /* Create a bfd for the interpreter.  */
456   gdb_bfd_ref_ptr dyld_bfd (gdb_bfd_open (interp_name, gnutarget, -1));
457   if (dyld_bfd != NULL)
458     {
459       gdb_bfd_ref_ptr sub
460         (gdb_bfd_mach_o_fat_extract (dyld_bfd.get (), bfd_object,
461                                      gdbarch_bfd_arch_info (target_gdbarch ())));
462       if (sub != NULL)
463         dyld_bfd = sub;
464       else
465         dyld_bfd.release ();
466     }
467   if (dyld_bfd == NULL)
468     return;
469
470   /* We find the dynamic linker's base address by examining
471      the current pc (which should point at the entry point for the
472      dynamic linker) and subtracting the offset of the entry point.  */
473   load_addr = (regcache_read_pc (get_current_regcache ())
474                - bfd_get_start_address (dyld_bfd.get ()));
475
476   /* Now try to set a breakpoint in the dynamic linker.  */
477   info->all_image_addr =
478     lookup_symbol_from_bfd (dyld_bfd.get (), "_dyld_all_image_infos");
479
480   if (info->all_image_addr == 0)
481     return;
482
483   info->all_image_addr += load_addr;
484 }
485
486 /* Extract dyld_all_image_addr reading it from
487    TARGET_OBJECT_DARWIN_DYLD_INFO.  */
488
489 static void
490 darwin_solib_read_all_image_info_addr (struct darwin_info *info)
491 {
492   gdb_byte buf[8];
493   LONGEST len;
494   struct type *ptr_type = builtin_type (target_gdbarch ())->builtin_data_ptr;
495
496   /* Sanity check.  */
497   if (TYPE_LENGTH (ptr_type) > sizeof (buf))
498     return;
499
500   len = target_read (current_top_target (), TARGET_OBJECT_DARWIN_DYLD_INFO,
501                      NULL, buf, 0, TYPE_LENGTH (ptr_type));
502   if (len <= 0)
503     return;
504
505   /* The use of BIG endian is intended, as BUF is a raw stream of bytes.  This
506       makes the support of remote protocol easier.  */
507   info->all_image_addr = extract_unsigned_integer (buf, len, BFD_ENDIAN_BIG);
508 }
509
510 /* Shared library startup support.  See documentation in solib-svr4.c.  */
511
512 static void
513 darwin_solib_create_inferior_hook (int from_tty)
514 {
515   struct darwin_info *info = get_darwin_info ();
516   CORE_ADDR load_addr;
517
518   info->all_image_addr = 0;
519
520   darwin_solib_read_all_image_info_addr (info);
521
522   if (info->all_image_addr == 0)
523     darwin_solib_get_all_image_info_addr_at_init (info);
524
525   if (info->all_image_addr == 0)
526     return;
527
528   darwin_load_image_infos (info);
529
530   if (!darwin_dyld_version_ok (info))
531     {
532       warning (_("unhandled dyld version (%d)"), info->all_image.version);
533       return;
534     }
535
536   /* Add the breakpoint which is hit by dyld when the list of solib is
537      modified.  */
538   create_solib_event_breakpoint (target_gdbarch (), info->all_image.notifier);
539
540   if (info->all_image.count != 0)
541     {
542       /* Possible relocate the main executable (PIE).  */
543       load_addr = darwin_read_exec_load_addr_from_dyld (info);
544     }
545   else
546     {
547       /* Possible issue:
548          Do not break on the notifier if dyld is not initialized (deduced from
549          count == 0).  In that case, dyld hasn't relocated itself and the
550          notifier may point to a wrong address.  */
551
552       load_addr = darwin_read_exec_load_addr_at_init (info);
553     }
554
555   if (load_addr != 0 && symfile_objfile != NULL)
556     {
557       CORE_ADDR vmaddr;
558
559       /* Find the base address of the executable.  */
560       vmaddr = bfd_mach_o_get_base_address (exec_bfd);
561
562       /* Relocate.  */
563       if (vmaddr != load_addr)
564         objfile_rebase (symfile_objfile, load_addr - vmaddr);
565     }
566 }
567
568 static void
569 darwin_clear_solib (void)
570 {
571   struct darwin_info *info = get_darwin_info ();
572
573   info->all_image_addr = 0;
574   info->all_image.version = 0;
575 }
576
577 static void
578 darwin_free_so (struct so_list *so)
579 {
580   lm_info_darwin *li = (lm_info_darwin *) so->lm_info;
581
582   delete li;
583 }
584
585 /* The section table is built from bfd sections using bfd VMAs.
586    Relocate these VMAs according to solib info.  */
587
588 static void
589 darwin_relocate_section_addresses (struct so_list *so,
590                                    struct target_section *sec)
591 {
592   lm_info_darwin *li = (lm_info_darwin *) so->lm_info;
593
594   sec->addr += li->lm_addr;
595   sec->endaddr += li->lm_addr;
596
597   /* Best effort to set addr_high/addr_low.  This is used only by
598      'info sharedlibary'.  */
599   if (so->addr_high == 0)
600     {
601       so->addr_low = sec->addr;
602       so->addr_high = sec->endaddr;
603     }
604   if (sec->endaddr > so->addr_high)
605     so->addr_high = sec->endaddr;
606   if (sec->addr < so->addr_low)
607     so->addr_low = sec->addr;
608 }
609 \f
610 static struct block_symbol
611 darwin_lookup_lib_symbol (struct objfile *objfile,
612                           const char *name,
613                           const domain_enum domain)
614 {
615   return (struct block_symbol) {NULL, NULL};
616 }
617
618 static gdb_bfd_ref_ptr
619 darwin_bfd_open (const char *pathname)
620 {
621   int found_file;
622
623   /* Search for shared library file.  */
624   gdb::unique_xmalloc_ptr<char> found_pathname
625     = solib_find (pathname, &found_file);
626   if (found_pathname == NULL)
627     perror_with_name (pathname);
628
629   /* Open bfd for shared library.  */
630   gdb_bfd_ref_ptr abfd (solib_bfd_fopen (found_pathname.get (), found_file));
631
632   gdb_bfd_ref_ptr res
633     (gdb_bfd_mach_o_fat_extract (abfd.get (), bfd_object,
634                                  gdbarch_bfd_arch_info (target_gdbarch ())));
635   if (res == NULL)
636     error (_("`%s': not a shared-library: %s"),
637            bfd_get_filename (abfd.get ()), bfd_errmsg (bfd_get_error ()));
638
639   /* The current filename for fat-binary BFDs is a name generated
640      by BFD, usually a string containing the name of the architecture.
641      Reset its value to the actual filename.  */
642   xfree (bfd_get_filename (res.get ()));
643   res->filename = xstrdup (pathname);
644
645   return res;
646 }
647
648 struct target_so_ops darwin_so_ops;
649
650 void
651 _initialize_darwin_solib (void)
652 {
653   solib_darwin_pspace_data
654     = register_program_space_data_with_cleanup (NULL,
655                                                 darwin_pspace_data_cleanup);
656
657   darwin_so_ops.relocate_section_addresses = darwin_relocate_section_addresses;
658   darwin_so_ops.free_so = darwin_free_so;
659   darwin_so_ops.clear_solib = darwin_clear_solib;
660   darwin_so_ops.solib_create_inferior_hook = darwin_solib_create_inferior_hook;
661   darwin_so_ops.current_sos = darwin_current_sos;
662   darwin_so_ops.open_symbol_file_object = open_symbol_file_object;
663   darwin_so_ops.in_dynsym_resolve_code = darwin_in_dynsym_resolve_code;
664   darwin_so_ops.lookup_lib_global_symbol = darwin_lookup_lib_symbol;
665   darwin_so_ops.bfd_open = darwin_bfd_open;
666 }