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