Include gdb_assert.h in common-defs.h
[external/binutils.git] / gdb / machoread.c
1 /* Darwin support for GDB, the GNU debugger.
2    Copyright (C) 2008-2014 Free Software Foundation, Inc.
3
4    Contributed by AdaCore.
5
6    This file is part of GDB.
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
20
21 #include "defs.h"
22 #include "symtab.h"
23 #include "gdbtypes.h"
24 #include "bfd.h"
25 #include "symfile.h"
26 #include "objfiles.h"
27 #include "buildsym.h"
28 #include "gdbcmd.h"
29 #include "gdbcore.h"
30 #include "mach-o.h"
31 #include "aout/stab_gnu.h"
32 #include "vec.h"
33 #include "psympriv.h"
34 #include "complaints.h"
35 #include "gdb_bfd.h"
36
37 #include <string.h>
38
39 /* If non-zero displays debugging message.  */
40 static unsigned int mach_o_debug_level = 0;
41
42 /* Dwarf debugging information are never in the final executable.  They stay
43    in object files and the executable contains the list of object files read
44    during the link.
45    Each time an oso (other source) is found in the executable, the reader
46    creates such a structure.  They are read after the processing of the
47    executable.  */
48
49 typedef struct oso_el
50 {
51   /* Object file name.  Can also be a member name.  */
52   const char *name;
53
54   /* Associated time stamp.  */
55   unsigned long mtime;
56
57   /* Stab symbols range for this OSO.  */
58   asymbol **oso_sym;
59   asymbol **end_sym;
60
61   /* Number of interesting stabs in the range.  */
62   unsigned int nbr_syms;
63 }
64 oso_el;
65
66 /* Vector of object files to be read after the executable.  */
67 DEF_VEC_O (oso_el);
68
69 static void
70 macho_new_init (struct objfile *objfile)
71 {
72 }
73
74 static void
75 macho_symfile_init (struct objfile *objfile)
76 {
77   objfile->flags |= OBJF_REORDERED;
78 }
79
80 /*  Add a new OSO to the vector of OSO to load.  */
81
82 static void
83 macho_register_oso (VEC (oso_el) **oso_vector_ptr,
84                     struct objfile *objfile,
85                     asymbol **oso_sym, asymbol **end_sym,
86                     unsigned int nbr_syms)
87 {
88   oso_el el;
89
90   el.name = (*oso_sym)->name;
91   el.mtime = (*oso_sym)->value;
92   el.oso_sym = oso_sym;
93   el.end_sym = end_sym;
94   el.nbr_syms = nbr_syms;
95   VEC_safe_push (oso_el, *oso_vector_ptr, &el);
96 }
97
98 /* Add symbol SYM to the minimal symbol table of OBJFILE.  */
99
100 static void
101 macho_symtab_add_minsym (struct objfile *objfile, const asymbol *sym)
102 {
103   if (sym->name == NULL || *sym->name == '\0')
104     {
105       /* Skip names that don't exist (shouldn't happen), or names
106          that are null strings (may happen).  */
107       return;
108     }
109
110   if (sym->flags & (BSF_GLOBAL | BSF_LOCAL | BSF_WEAK))
111     {
112       CORE_ADDR symaddr;
113       enum minimal_symbol_type ms_type;
114
115       /* Bfd symbols are section relative.  */
116       symaddr = sym->value + sym->section->vma;
117
118       if (sym->section == bfd_abs_section_ptr)
119         ms_type = mst_abs;
120       else if (sym->section->flags & SEC_CODE)
121         {
122           if (sym->flags & (BSF_GLOBAL | BSF_WEAK))
123             ms_type = mst_text;
124           else
125             ms_type = mst_file_text;
126         }
127       else if (sym->section->flags & SEC_ALLOC)
128         {
129           if (sym->flags & (BSF_GLOBAL | BSF_WEAK))
130             {
131               if (sym->section->flags & SEC_LOAD)
132                 ms_type = mst_data;
133               else
134                 ms_type = mst_bss;
135             }
136           else if (sym->flags & BSF_LOCAL)
137             {
138               /* Not a special stabs-in-elf symbol, do regular
139                  symbol processing.  */
140               if (sym->section->flags & SEC_LOAD)
141                 ms_type = mst_file_data;
142               else
143                 ms_type = mst_file_bss;
144             }
145           else
146             ms_type = mst_unknown;
147         }
148       else
149         return; /* Skip this symbol.  */
150
151       prim_record_minimal_symbol_and_info
152         (sym->name, symaddr, ms_type,
153          gdb_bfd_section_index (objfile->obfd, sym->section),
154          objfile);
155     }
156 }
157
158 /* Build the minimal symbol table from SYMBOL_TABLE of length
159    NUMBER_OF_SYMBOLS for OBJFILE.  Registers OSO filenames found.  */
160
161 static void
162 macho_symtab_read (struct objfile *objfile,
163                    long number_of_symbols, asymbol **symbol_table,
164                    VEC (oso_el) **oso_vector_ptr)
165 {
166   long i;
167   const asymbol *dir_so = NULL;
168   const asymbol *file_so = NULL;
169   asymbol **oso_file = NULL;
170   unsigned int nbr_syms = 0;
171
172   /* Current state while reading stabs.  */
173   enum
174   {
175     /* Not within an SO part.  Only non-debugging symbols should be present,
176        and will be added to the minimal symbols table.  */
177     S_NO_SO,
178
179     /* First SO read.  Introduce an SO section, and may be followed by a second
180        SO.  The SO section should contain onl debugging symbols.  */
181     S_FIRST_SO,
182
183     /* Second non-null SO found, just after the first one.  Means that the first
184        is in fact a directory name.  */
185     S_SECOND_SO,
186
187     /* Non-null OSO found.  Debugging info are DWARF in this OSO file.  */
188     S_DWARF_FILE,
189
190     S_STAB_FILE
191   } state = S_NO_SO;
192
193   for (i = 0; i < number_of_symbols; i++)
194     {
195       const asymbol *sym = symbol_table[i];
196       bfd_mach_o_asymbol *mach_o_sym = (bfd_mach_o_asymbol *)sym;
197
198       switch (state)
199         {
200         case S_NO_SO:
201           if (mach_o_sym->n_type == N_SO)
202             {
203               /* Start of object stab.  */
204               if (sym->name == NULL || sym->name[0] == 0)
205                 {
206                   /* Unexpected empty N_SO.  */
207                   complaint (&symfile_complaints,
208                              _("Unexpected empty N_SO stab"));
209                 }
210               else
211                 {
212                   file_so = sym;
213                   dir_so = NULL;
214                   state = S_FIRST_SO;
215                 }
216             }
217           else if (sym->flags & BSF_DEBUGGING)
218             {
219               if (mach_o_sym->n_type == N_OPT)
220                 {
221                   /* No complaint for OPT.  */
222                   break;
223                 }
224
225               /* Debugging symbols are not expected here.  */
226               complaint (&symfile_complaints,
227                          _("%s: Unexpected debug stab outside SO markers"),
228                          objfile_name (objfile));
229             }
230           else
231             {
232               /* Non-debugging symbols go to the minimal symbol table.  */
233               macho_symtab_add_minsym (objfile, sym);
234             }
235           break;
236
237         case S_FIRST_SO:
238         case S_SECOND_SO:
239           if (mach_o_sym->n_type == N_SO)
240             {
241               if (sym->name == NULL || sym->name[0] == 0)
242                 {
243                   /* Unexpected empty N_SO.  */
244                   complaint (&symfile_complaints, _("Empty SO section"));
245                   state = S_NO_SO;
246                 }
247               else if (state == S_FIRST_SO)
248                 {
249                   /* Second SO stab for the file name.  */
250                   dir_so = file_so;
251                   file_so = sym;
252                   state = S_SECOND_SO;
253                 }
254               else
255                 complaint (&symfile_complaints, _("Three SO in a raw"));
256             }
257           else if (mach_o_sym->n_type == N_OSO)
258             {
259               if (sym->name == NULL || sym->name[0] == 0)
260                 {
261                   /* Empty OSO.  Means that this file was compiled with
262                      stabs.  */
263                   state = S_STAB_FILE;
264                   warning (_("stabs debugging not supported for %s"),
265                            file_so->name);
266                 }
267               else
268                 {
269                   /* Non-empty OSO for a Dwarf file.  */
270                   oso_file = symbol_table + i;
271                   nbr_syms = 0;
272                   state = S_DWARF_FILE;
273                 }
274             }
275           else
276             complaint (&symfile_complaints,
277                        _("Unexpected stab after SO"));
278           break;
279
280         case S_STAB_FILE:
281         case S_DWARF_FILE:
282           if (mach_o_sym->n_type == N_SO)
283             {
284               if (sym->name == NULL || sym->name[0] == 0)
285                 {
286                   /* End of file.  */
287                   if (state == S_DWARF_FILE)
288                     macho_register_oso (oso_vector_ptr, objfile,
289                                         oso_file, symbol_table + i,
290                                         nbr_syms);
291                   state = S_NO_SO;
292                 }
293               else
294                 {
295                   complaint (&symfile_complaints, _("Missing nul SO"));
296                   file_so = sym;
297                   dir_so = NULL;
298                   state = S_FIRST_SO;
299                 }
300             }
301           else if (sym->flags & BSF_DEBUGGING)
302             {
303               if (state == S_STAB_FILE)
304                 {
305                   /* FIXME: to be implemented.  */
306                 }
307               else
308                 {
309                   switch (mach_o_sym->n_type)
310                     {
311                     case N_FUN:
312                       if (sym->name == NULL || sym->name[0] == 0)
313                         break;
314                       /* Fall through.  */
315                     case N_STSYM:
316                       /* Interesting symbol.  */
317                       nbr_syms++;
318                       break;
319                     case N_ENSYM:
320                     case N_BNSYM:
321                     case N_GSYM:
322                       break;
323                     default:
324                       complaint (&symfile_complaints,
325                                  _("unhandled stab for dwarf OSO file"));
326                       break;
327                     }
328                 }
329             }
330           else
331             complaint (&symfile_complaints,
332                        _("non-debugging symbol within SO"));
333           break;
334         }
335     }
336
337   if (state != S_NO_SO)
338     complaint (&symfile_complaints, _("missing nul SO"));
339 }
340
341 /* If NAME describes an archive member (ie: ARCHIVE '(' MEMBER ')'),
342    returns the length of the archive name.
343    Returns -1 otherwise.  */
344
345 static int
346 get_archive_prefix_len (const char *name)
347 {
348   char *lparen;
349   int name_len = strlen (name);
350
351   if (name_len == 0 || name[name_len - 1] != ')')
352     return -1;
353
354   lparen = strrchr (name, '(');
355   if (lparen == NULL || lparen == name)
356     return -1;
357   return lparen - name;
358 }
359
360 /* Compare function to qsort OSOs, so that members of a library are
361    gathered.  */
362
363 static int
364 oso_el_compare_name (const void *vl, const void *vr)
365 {
366   const oso_el *l = (const oso_el *)vl;
367   const oso_el *r = (const oso_el *)vr;
368
369   return strcmp (l->name, r->name);
370 }
371
372 /* Hash table entry structure for the stabs symbols in the main object file.
373    This is used to speed up lookup for symbols in the OSO.  */
374
375 struct macho_sym_hash_entry
376 {
377   struct bfd_hash_entry base;
378   const asymbol *sym;
379 };
380
381 /* Routine to create an entry in the hash table.  */
382
383 static struct bfd_hash_entry *
384 macho_sym_hash_newfunc (struct bfd_hash_entry *entry,
385                         struct bfd_hash_table *table,
386                         const char *string)
387 {
388   struct macho_sym_hash_entry *ret = (struct macho_sym_hash_entry *) entry;
389
390   /* Allocate the structure if it has not already been allocated by a
391      subclass.  */
392   if (ret == NULL)
393     ret = (struct macho_sym_hash_entry *) bfd_hash_allocate (table,
394                                                              sizeof (* ret));
395   if (ret == NULL)
396     return NULL;
397
398   /* Call the allocation method of the superclass.  */
399   ret = (struct macho_sym_hash_entry *)
400          bfd_hash_newfunc ((struct bfd_hash_entry *) ret, table, string);
401
402   if (ret)
403     {
404       /* Initialize the local fields.  */
405       ret->sym = NULL;
406     }
407
408   return (struct bfd_hash_entry *) ret;
409 }
410
411 /* Get the value of SYM from the minimal symtab of MAIN_OBJFILE.  This is used
412    to get the value of global and common symbols.  */
413
414 static CORE_ADDR
415 macho_resolve_oso_sym_with_minsym (struct objfile *main_objfile, asymbol *sym)
416 {
417   /* For common symbol and global symbols, use the min symtab.  */
418   struct bound_minimal_symbol msym;
419   const char *name = sym->name;
420
421   if (name[0] == bfd_get_symbol_leading_char (main_objfile->obfd))
422     ++name;
423   msym = lookup_minimal_symbol (name, NULL, main_objfile);
424   if (msym.minsym == NULL)
425     {
426       warning (_("can't find symbol '%s' in minsymtab"), name);
427       return 0;
428     }
429   else
430     return BMSYMBOL_VALUE_ADDRESS (msym);
431 }
432
433 /* Add oso file OSO/ABFD as a symbol file.  */
434
435 static void
436 macho_add_oso_symfile (oso_el *oso, bfd *abfd, const char *name,
437                        struct objfile *main_objfile, int symfile_flags)
438 {
439   int storage;
440   int i;
441   asymbol **symbol_table;
442   asymbol **symp;
443   struct bfd_hash_table table;
444   int nbr_sections;
445   struct cleanup *cleanup;
446
447   /* Per section flag to mark which section have been rebased.  */
448   unsigned char *sections_rebased;
449
450   if (mach_o_debug_level > 0)
451     printf_unfiltered
452       (_("Loading debugging symbols from oso: %s\n"), oso->name);
453
454   if (!bfd_check_format (abfd, bfd_object))
455     {
456       warning (_("`%s': can't read symbols: %s."), oso->name,
457                bfd_errmsg (bfd_get_error ()));
458       gdb_bfd_unref (abfd);
459       return;
460     }
461
462   if (abfd->my_archive == NULL && oso->mtime != bfd_get_mtime (abfd))
463     {
464       warning (_("`%s': file time stamp mismatch."), oso->name);
465       gdb_bfd_unref (abfd);
466       return;
467     }
468
469   if (!bfd_hash_table_init_n (&table, macho_sym_hash_newfunc,
470                               sizeof (struct macho_sym_hash_entry),
471                               oso->nbr_syms))
472     {
473       warning (_("`%s': can't create hash table"), oso->name);
474       gdb_bfd_unref (abfd);
475       return;
476     }
477
478   bfd_set_cacheable (abfd, 1);
479
480   /* Read symbols table.  */
481   storage = bfd_get_symtab_upper_bound (abfd);
482   symbol_table = (asymbol **) xmalloc (storage);
483   bfd_canonicalize_symtab (abfd, symbol_table);
484
485   /* Init section flags.  */
486   nbr_sections = bfd_count_sections (abfd);
487   sections_rebased = (unsigned char *) alloca (nbr_sections);
488   for (i = 0; i < nbr_sections; i++)
489     sections_rebased[i] = 0;
490
491   /* Put symbols for the OSO file in the hash table.  */
492   for (symp = oso->oso_sym; symp != oso->end_sym; symp++)
493     {
494       const asymbol *sym = *symp;
495       bfd_mach_o_asymbol *mach_o_sym = (bfd_mach_o_asymbol *)sym;
496
497       switch (mach_o_sym->n_type)
498         {
499         case N_ENSYM:
500         case N_BNSYM:
501         case N_GSYM:
502           sym = NULL;
503           break;
504         case N_FUN:
505           if (sym->name == NULL || sym->name[0] == 0)
506             sym = NULL;
507           break;
508         case N_STSYM:
509           break;
510         default:
511           sym = NULL;
512           break;
513         }
514       if (sym != NULL)
515         {
516           struct macho_sym_hash_entry *ent;
517
518           ent = (struct macho_sym_hash_entry *)
519             bfd_hash_lookup (&table, sym->name, TRUE, FALSE);
520           if (ent->sym != NULL)
521             complaint (&symfile_complaints,
522                        _("Duplicated symbol %s in symbol table"), sym->name);
523           else
524             {
525               if (mach_o_debug_level > 4)
526                 {
527                   struct gdbarch *arch = get_objfile_arch (main_objfile);
528                   printf_unfiltered
529                     (_("Adding symbol %s (addr: %s)\n"),
530                      sym->name, paddress (arch, sym->value));
531                 }
532               ent->sym = sym;
533             }
534         }
535     }
536
537   /* Relocate symbols of the OSO.  */
538   for (i = 0; symbol_table[i]; i++)
539     {
540       asymbol *sym = symbol_table[i];
541       bfd_mach_o_asymbol *mach_o_sym = (bfd_mach_o_asymbol *)sym;
542
543       if (mach_o_sym->n_type & BFD_MACH_O_N_STAB)
544         continue;
545       if ((mach_o_sym->n_type & BFD_MACH_O_N_TYPE) == BFD_MACH_O_N_UNDF
546            && sym->value != 0)
547         {
548           /* For common symbol use the min symtab and modify the OSO
549              symbol table.  */
550           CORE_ADDR res;
551
552           res = macho_resolve_oso_sym_with_minsym (main_objfile, sym);
553           if (res != 0)
554             {
555               sym->section = bfd_com_section_ptr;
556               sym->value = res;
557             }
558         }
559       else if ((mach_o_sym->n_type & BFD_MACH_O_N_TYPE) == BFD_MACH_O_N_SECT)
560         {
561           /* Normal symbol.  */
562           asection *sec = sym->section;
563           bfd_mach_o_section *msec;
564           unsigned int sec_type;
565
566           /* Skip buggy ones.  */
567           if (sec == NULL || sections_rebased[sec->index] != 0)
568             continue;
569
570           /* Only consider regular, non-debugging sections.  */
571           msec = bfd_mach_o_get_mach_o_section (sec);
572           sec_type = msec->flags & BFD_MACH_O_SECTION_TYPE_MASK;
573           if ((sec_type == BFD_MACH_O_S_REGULAR
574                || sec_type == BFD_MACH_O_S_ZEROFILL)
575               && (msec->flags & BFD_MACH_O_S_ATTR_DEBUG) == 0)
576             {
577               CORE_ADDR addr = 0;
578
579               if ((mach_o_sym->n_type & BFD_MACH_O_N_EXT) != 0)
580                 {
581                   /* Use the min symtab for global symbols.  */
582                   addr = macho_resolve_oso_sym_with_minsym (main_objfile, sym);
583                 }
584               else
585                 {
586                   struct macho_sym_hash_entry *ent;
587
588                   ent = (struct macho_sym_hash_entry *)
589                     bfd_hash_lookup (&table, sym->name, FALSE, FALSE);
590                   if (ent != NULL)
591                     addr = bfd_asymbol_value (ent->sym);
592                 }
593
594               /* Adjust the section.  */
595               if (addr != 0)
596                 {
597                   CORE_ADDR res = addr - sym->value;
598
599                   if (mach_o_debug_level > 3)
600                     {
601                       struct gdbarch *arch = get_objfile_arch (main_objfile);
602                       printf_unfiltered
603                         (_("resolve sect %s with %s (set to %s)\n"),
604                          sec->name, sym->name,
605                          paddress (arch, res));
606                     }
607                   bfd_set_section_vma (abfd, sec, res);
608                   sections_rebased[sec->index] = 1;
609                 }
610             }
611           else
612             {
613               /* Mark the section as never rebased.  */
614               sections_rebased[sec->index] = 2;
615             }
616         }
617     }
618
619   bfd_hash_table_free (&table);
620
621   /* We need to clear SYMFILE_MAINLINE to avoid interractive question
622      from symfile.c:symbol_file_add_with_addrs_or_offsets.  */
623   cleanup = make_cleanup_bfd_unref (abfd);
624   symbol_file_add_from_bfd
625     (abfd, name, symfile_flags & ~(SYMFILE_MAINLINE | SYMFILE_VERBOSE), NULL,
626      main_objfile->flags & (OBJF_REORDERED | OBJF_SHARED
627                             | OBJF_READNOW | OBJF_USERLOADED),
628      main_objfile);
629   do_cleanups (cleanup);
630 }
631
632 /* Read symbols from the vector of oso files.
633
634    Note that this function sorts OSO_VECTOR_PTR.  */
635
636 static void
637 macho_symfile_read_all_oso (VEC (oso_el) **oso_vector_ptr,
638                             struct objfile *main_objfile,
639                             int symfile_flags)
640 {
641   int ix;
642   VEC (oso_el) *vec = *oso_vector_ptr;
643   oso_el *oso;
644   struct cleanup *cleanup = make_cleanup (null_cleanup, NULL);
645
646   /* Sort oso by name so that files from libraries are gathered.  */
647   qsort (VEC_address (oso_el, vec), VEC_length (oso_el, vec),
648          sizeof (oso_el), oso_el_compare_name);
649
650   for (ix = 0; VEC_iterate (oso_el, vec, ix, oso);)
651     {
652       int pfx_len;
653
654       /* Check if this is a library name.  */
655       pfx_len = get_archive_prefix_len (oso->name);
656       if (pfx_len > 0)
657         {
658           bfd *archive_bfd;
659           bfd *member_bfd;
660           char *archive_name = XNEWVEC (char, pfx_len + 1);
661           int last_ix;
662           oso_el *oso2;
663           int ix2;
664
665           memcpy (archive_name, oso->name, pfx_len);
666           archive_name[pfx_len] = '\0';
667
668           make_cleanup (xfree, archive_name);
669
670           /* Compute number of oso for this archive.  */
671           for (last_ix = ix;
672                VEC_iterate (oso_el, vec, last_ix, oso2); last_ix++)
673             {
674               if (strncmp (oso2->name, archive_name, pfx_len) != 0)
675                 break;
676             }
677
678           /* Open the archive and check the format.  */
679           archive_bfd = gdb_bfd_open (archive_name, gnutarget, -1);
680           if (archive_bfd == NULL)
681             {
682               warning (_("Could not open OSO archive file \"%s\""),
683                        archive_name);
684               ix = last_ix;
685               continue;
686             }
687           if (!bfd_check_format (archive_bfd, bfd_archive))
688             {
689               warning (_("OSO archive file \"%s\" not an archive."),
690                        archive_name);
691               gdb_bfd_unref (archive_bfd);
692               ix = last_ix;
693               continue;
694             }
695
696           member_bfd = gdb_bfd_openr_next_archived_file (archive_bfd, NULL);
697
698           if (member_bfd == NULL)
699             {
700               warning (_("Could not read archive members out of "
701                          "OSO archive \"%s\""), archive_name);
702               gdb_bfd_unref (archive_bfd);
703               ix = last_ix;
704               continue;
705             }
706
707           /* Load all oso in this library.  */
708           while (member_bfd != NULL)
709             {
710               bfd *prev;
711               const char *member_name = member_bfd->filename;
712               int member_len = strlen (member_name);
713
714               /* If this member is referenced, add it as a symfile.  */
715               for (ix2 = ix; ix2 < last_ix; ix2++)
716                 {
717                   oso2 = VEC_index (oso_el, vec, ix2);
718
719                   if (oso2->name
720                       && strlen (oso2->name) == pfx_len + member_len + 2
721                       && !memcmp (member_name, oso2->name + pfx_len + 1,
722                                   member_len))
723                     {
724                       macho_add_oso_symfile (oso2, member_bfd,
725                                              bfd_get_filename (member_bfd),
726                                              main_objfile, symfile_flags);
727                       oso2->name = NULL;
728                       break;
729                     }
730                 }
731
732               prev = member_bfd;
733               member_bfd = gdb_bfd_openr_next_archived_file (archive_bfd,
734                                                              member_bfd);
735
736               /* Free previous member if not referenced by an oso.  */
737               if (ix2 >= last_ix)
738                 gdb_bfd_unref (prev);
739             }
740           for (ix2 = ix; ix2 < last_ix; ix2++)
741             {
742               oso_el *oso2 = VEC_index (oso_el, vec, ix2);
743
744               if (oso2->name != NULL)
745                 warning (_("Could not find specified archive member "
746                            "for OSO name \"%s\""), oso->name);
747             }
748           ix = last_ix;
749         }
750       else
751         {
752           bfd *abfd;
753
754           abfd = gdb_bfd_open (oso->name, gnutarget, -1);
755           if (!abfd)
756             warning (_("`%s': can't open to read symbols: %s."), oso->name,
757                      bfd_errmsg (bfd_get_error ()));
758           else
759             macho_add_oso_symfile (oso, abfd, oso->name, main_objfile,
760                                    symfile_flags);
761
762           ix++;
763         }
764     }
765
766   do_cleanups (cleanup);
767 }
768
769 /* DSYM (debug symbols) files contain the debug info of an executable.
770    This is a separate file created by dsymutil(1) and is similar to debug
771    link feature on ELF.
772    DSYM files are located in a subdirectory.  Append DSYM_SUFFIX to the
773    executable name and the executable base name to get the DSYM file name.  */
774 #define DSYM_SUFFIX ".dSYM/Contents/Resources/DWARF/"
775
776 /* Check if a dsym file exists for OBJFILE.  If so, returns a bfd for it
777    and return *FILENAMEP with its original xmalloc-ated filename.
778    Return NULL if no valid dsym file is found (FILENAMEP is not used in
779    such case).  */
780
781 static bfd *
782 macho_check_dsym (struct objfile *objfile, char **filenamep)
783 {
784   size_t name_len = strlen (objfile_name (objfile));
785   size_t dsym_len = strlen (DSYM_SUFFIX);
786   const char *base_name = lbasename (objfile_name (objfile));
787   size_t base_len = strlen (base_name);
788   char *dsym_filename = alloca (name_len + dsym_len + base_len + 1);
789   bfd *dsym_bfd;
790   bfd_mach_o_load_command *main_uuid;
791   bfd_mach_o_load_command *dsym_uuid;
792
793   strcpy (dsym_filename, objfile_name (objfile));
794   strcpy (dsym_filename + name_len, DSYM_SUFFIX);
795   strcpy (dsym_filename + name_len + dsym_len, base_name);
796
797   if (access (dsym_filename, R_OK) != 0)
798     return NULL;
799
800   if (bfd_mach_o_lookup_command (objfile->obfd,
801                                  BFD_MACH_O_LC_UUID, &main_uuid) == 0)
802     {
803       warning (_("can't find UUID in %s"), objfile_name (objfile));
804       return NULL;
805     }
806   dsym_bfd = gdb_bfd_openr (dsym_filename, gnutarget);
807   if (dsym_bfd == NULL)
808     {
809       warning (_("can't open dsym file %s"), dsym_filename);
810       return NULL;
811     }
812
813   if (!bfd_check_format (dsym_bfd, bfd_object))
814     {
815       gdb_bfd_unref (dsym_bfd);
816       warning (_("bad dsym file format: %s"), bfd_errmsg (bfd_get_error ()));
817       return NULL;
818     }
819
820   if (bfd_mach_o_lookup_command (dsym_bfd,
821                                  BFD_MACH_O_LC_UUID, &dsym_uuid) == 0)
822     {
823       warning (_("can't find UUID in %s"), dsym_filename);
824       gdb_bfd_unref (dsym_bfd);
825       return NULL;
826     }
827   if (memcmp (dsym_uuid->command.uuid.uuid, main_uuid->command.uuid.uuid,
828               sizeof (main_uuid->command.uuid.uuid)))
829     {
830       warning (_("dsym file UUID doesn't match the one in %s"),
831                objfile_name (objfile));
832       gdb_bfd_unref (dsym_bfd);
833       return NULL;
834     }
835   *filenamep = xstrdup (dsym_filename);
836   return dsym_bfd;
837 }
838
839 static void
840 macho_symfile_read (struct objfile *objfile, int symfile_flags)
841 {
842   bfd *abfd = objfile->obfd;
843   CORE_ADDR offset;
844   long storage_needed;
845   bfd *dsym_bfd;
846   VEC (oso_el) *oso_vector = NULL;
847   struct cleanup *old_chain = make_cleanup (VEC_cleanup (oso_el), &oso_vector);
848
849   /* Get symbols from the symbol table only if the file is an executable.
850      The symbol table of object files is not relocated and is expected to
851      be in the executable.  */
852   if (bfd_get_file_flags (abfd) & (EXEC_P | DYNAMIC))
853     {
854       char *dsym_filename;
855
856       /* Process the normal symbol table first.  */
857       storage_needed = bfd_get_symtab_upper_bound (objfile->obfd);
858       if (storage_needed < 0)
859         error (_("Can't read symbols from %s: %s"),
860                bfd_get_filename (objfile->obfd),
861                bfd_errmsg (bfd_get_error ()));
862
863       if (storage_needed > 0)
864         {
865           asymbol **symbol_table;
866           long symcount;
867
868           symbol_table = (asymbol **) xmalloc (storage_needed);
869           make_cleanup (xfree, symbol_table);
870
871           init_minimal_symbol_collection ();
872           make_cleanup_discard_minimal_symbols ();
873
874           symcount = bfd_canonicalize_symtab (objfile->obfd, symbol_table);
875
876           if (symcount < 0)
877             error (_("Can't read symbols from %s: %s"),
878                    bfd_get_filename (objfile->obfd),
879                    bfd_errmsg (bfd_get_error ()));
880
881           macho_symtab_read (objfile, symcount, symbol_table, &oso_vector);
882
883           install_minimal_symbols (objfile);
884         }
885
886       /* Try to read .eh_frame / .debug_frame.  */
887       /* First, locate these sections.  We ignore the result status
888          as it only checks for debug info.  */
889       dwarf2_has_info (objfile, NULL);
890       dwarf2_build_frame_info (objfile);
891
892       /* Check for DSYM file.  */
893       dsym_bfd = macho_check_dsym (objfile, &dsym_filename);
894       if (dsym_bfd != NULL)
895         {
896           int ix;
897           oso_el *oso;
898           struct bfd_section *asect, *dsect;
899
900           make_cleanup (xfree, dsym_filename);
901
902           if (mach_o_debug_level > 0)
903             printf_unfiltered (_("dsym file found\n"));
904
905           /* Set dsym section size.  */
906           for (asect = objfile->obfd->sections, dsect = dsym_bfd->sections;
907                asect && dsect;
908                asect = asect->next, dsect = dsect->next)
909             {
910               if (strcmp (asect->name, dsect->name) != 0)
911                 break;
912               bfd_set_section_size (dsym_bfd, dsect,
913                                     bfd_get_section_size (asect));
914             }
915
916           /* Add the dsym file as a separate file.  */
917           make_cleanup_bfd_unref (dsym_bfd);
918           symbol_file_add_separate (dsym_bfd, dsym_filename, symfile_flags,
919                                     objfile);
920
921           /* Don't try to read dwarf2 from main file or shared libraries.  */
922           do_cleanups (old_chain);
923           return;
924         }
925     }
926
927   if (dwarf2_has_info (objfile, NULL))
928     {
929       /* DWARF 2 sections */
930       dwarf2_build_psymtabs (objfile);
931     }
932
933   /* Then the oso.  */
934   if (oso_vector != NULL)
935     macho_symfile_read_all_oso (&oso_vector, objfile, symfile_flags);
936
937   do_cleanups (old_chain);
938 }
939
940 static bfd_byte *
941 macho_symfile_relocate (struct objfile *objfile, asection *sectp,
942                         bfd_byte *buf)
943 {
944   bfd *abfd = objfile->obfd;
945
946   /* We're only interested in sections with relocation
947      information.  */
948   if ((sectp->flags & SEC_RELOC) == 0)
949     return NULL;
950
951   if (mach_o_debug_level > 0)
952     printf_unfiltered (_("Relocate section '%s' of %s\n"),
953                        sectp->name, objfile_name (objfile));
954
955   return bfd_simple_get_relocated_section_contents (abfd, sectp, buf, NULL);
956 }
957
958 static void
959 macho_symfile_finish (struct objfile *objfile)
960 {
961 }
962
963 static void
964 macho_symfile_offsets (struct objfile *objfile,
965                        const struct section_addr_info *addrs)
966 {
967   unsigned int i;
968   unsigned int num_sections;
969   struct obj_section *osect;
970
971   /* Allocate section_offsets.  */
972   objfile->num_sections = bfd_count_sections (objfile->obfd);
973   objfile->section_offsets = (struct section_offsets *)
974     obstack_alloc (&objfile->objfile_obstack,
975                    SIZEOF_N_SECTION_OFFSETS (objfile->num_sections));
976   memset (objfile->section_offsets, 0,
977           SIZEOF_N_SECTION_OFFSETS (objfile->num_sections));
978
979   /* This code is run when we first add the objfile with
980      symfile_add_with_addrs_or_offsets, when "addrs" not "offsets" are
981      passed in.  The place in symfile.c where the addrs are applied
982      depends on the addrs having section names.  But in the dyld code
983      we build an anonymous array of addrs, so that code is a no-op.
984      Because of that, we have to apply the addrs to the sections here.
985      N.B. if an objfile slides after we've already created it, then it
986      goes through objfile_relocate.  */
987
988   for (i = 0; i < addrs->num_sections; i++)
989     {
990       ALL_OBJFILE_OSECTIONS (objfile, osect)
991         {
992           const char *bfd_sect_name = osect->the_bfd_section->name;
993
994           if (strcmp (bfd_sect_name, addrs->other[i].name) == 0)
995             {
996               obj_section_offset (osect) = addrs->other[i].addr;
997               break;
998             }
999         }
1000     }
1001
1002   objfile->sect_index_text = 0;
1003
1004   ALL_OBJFILE_OSECTIONS (objfile, osect)
1005     {
1006       const char *bfd_sect_name = osect->the_bfd_section->name;
1007       int sect_index = osect - objfile->sections;;
1008
1009       if (strncmp (bfd_sect_name, "LC_SEGMENT.", 11) == 0)
1010         bfd_sect_name += 11;
1011       if (strcmp (bfd_sect_name, "__TEXT") == 0
1012           || strcmp (bfd_sect_name, "__TEXT.__text") == 0)
1013         objfile->sect_index_text = sect_index;
1014     }
1015 }
1016
1017 static const struct sym_fns macho_sym_fns = {
1018   macho_new_init,               /* init anything gbl to entire symtab */
1019   macho_symfile_init,           /* read initial info, setup for sym_read() */
1020   macho_symfile_read,           /* read a symbol file into symtab */
1021   NULL,                         /* sym_read_psymbols */
1022   macho_symfile_finish,         /* finished with file, cleanup */
1023   macho_symfile_offsets,        /* xlate external to internal form */
1024   default_symfile_segments,     /* Get segment information from a file.  */
1025   NULL,
1026   macho_symfile_relocate,       /* Relocate a debug section.  */
1027   NULL,                         /* sym_get_probes */
1028   &psym_functions
1029 };
1030
1031 /* -Wmissing-prototypes */
1032 extern initialize_file_ftype _initialize_machoread;
1033
1034 void
1035 _initialize_machoread (void)
1036 {
1037   add_symtab_fns (bfd_target_mach_o_flavour, &macho_sym_fns);
1038
1039   add_setshow_zuinteger_cmd ("mach-o", class_obscure,
1040                              &mach_o_debug_level,
1041                              _("Set if printing Mach-O symbols processing."),
1042                              _("Show if printing Mach-O symbols processing."),
1043                              NULL, NULL, NULL,
1044                              &setdebuglist, &showdebuglist);
1045 }