run copyright.sh for 2011.
[external/binutils.git] / gdb / objfiles.c
1 /* GDB routines for manipulating objfiles.
2
3    Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001,
4    2002, 2003, 2004, 2007, 2008, 2009, 2010, 2011
5    Free Software Foundation, Inc.
6
7    Contributed by Cygnus Support, using pieces from other GDB modules.
8
9    This file is part of GDB.
10
11    This program is free software; you can redistribute it and/or modify
12    it under the terms of the GNU General Public License as published by
13    the Free Software Foundation; either version 3 of the License, or
14    (at your option) any later version.
15
16    This program is distributed in the hope that it will be useful,
17    but WITHOUT ANY WARRANTY; without even the implied warranty of
18    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19    GNU General Public License for more details.
20
21    You should have received a copy of the GNU General Public License
22    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
23
24 /* This file contains support routines for creating, manipulating, and
25    destroying objfile structures. */
26
27 #include "defs.h"
28 #include "bfd.h"                /* Binary File Description */
29 #include "symtab.h"
30 #include "symfile.h"
31 #include "objfiles.h"
32 #include "gdb-stabs.h"
33 #include "target.h"
34 #include "bcache.h"
35 #include "mdebugread.h"
36 #include "expression.h"
37 #include "parser-defs.h"
38
39 #include "gdb_assert.h"
40 #include <sys/types.h>
41 #include "gdb_stat.h"
42 #include <fcntl.h>
43 #include "gdb_obstack.h"
44 #include "gdb_string.h"
45 #include "hashtab.h"
46
47 #include "breakpoint.h"
48 #include "block.h"
49 #include "dictionary.h"
50 #include "source.h"
51 #include "addrmap.h"
52 #include "arch-utils.h"
53 #include "exec.h"
54 #include "observer.h"
55 #include "complaints.h"
56 #include "psymtab.h"
57 #include "solist.h"
58
59 /* Prototypes for local functions */
60
61 static void objfile_alloc_data (struct objfile *objfile);
62 static void objfile_free_data (struct objfile *objfile);
63
64 /* Externally visible variables that are owned by this module.
65    See declarations in objfile.h for more info. */
66
67 struct objfile *current_objfile;        /* For symbol file being read in */
68 struct objfile *rt_common_objfile;      /* For runtime common symbols */
69
70 struct objfile_pspace_info
71 {
72   int objfiles_changed_p;
73   struct obj_section **sections;
74   int num_sections;
75 };
76
77 /* Per-program-space data key.  */
78 static const struct program_space_data *objfiles_pspace_data;
79
80 static void
81 objfiles_pspace_data_cleanup (struct program_space *pspace, void *arg)
82 {
83   struct objfile_pspace_info *info;
84
85   info = program_space_data (pspace, objfiles_pspace_data);
86   if (info != NULL)
87     {
88       xfree (info->sections);
89       xfree (info);
90     }
91 }
92
93 /* Get the current svr4 data.  If none is found yet, add it now.  This
94    function always returns a valid object.  */
95
96 static struct objfile_pspace_info *
97 get_objfile_pspace_data (struct program_space *pspace)
98 {
99   struct objfile_pspace_info *info;
100
101   info = program_space_data (pspace, objfiles_pspace_data);
102   if (info == NULL)
103     {
104       info = XZALLOC (struct objfile_pspace_info);
105       set_program_space_data (pspace, objfiles_pspace_data, info);
106     }
107
108   return info;
109 }
110
111 /* Records whether any objfiles appeared or disappeared since we last updated
112    address to obj section map.  */
113
114 /* Locate all mappable sections of a BFD file. 
115    objfile_p_char is a char * to get it through
116    bfd_map_over_sections; we cast it back to its proper type.  */
117
118 /* Called via bfd_map_over_sections to build up the section table that
119    the objfile references.  The objfile contains pointers to the start
120    of the table (objfile->sections) and to the first location after
121    the end of the table (objfile->sections_end). */
122
123 static void
124 add_to_objfile_sections (struct bfd *abfd, struct bfd_section *asect,
125                          void *objfile_p_char)
126 {
127   struct objfile *objfile = (struct objfile *) objfile_p_char;
128   struct obj_section section;
129   flagword aflag;
130
131   aflag = bfd_get_section_flags (abfd, asect);
132
133   if (!(aflag & SEC_ALLOC))
134     return;
135
136   if (0 == bfd_section_size (abfd, asect))
137     return;
138   section.objfile = objfile;
139   section.the_bfd_section = asect;
140   section.ovly_mapped = 0;
141   obstack_grow (&objfile->objfile_obstack, (char *) &section, sizeof (section));
142   objfile->sections_end
143     = (struct obj_section *) (((size_t) objfile->sections_end) + 1);
144 }
145
146 /* Builds a section table for OBJFILE.
147    Returns 0 if OK, 1 on error (in which case bfd_error contains the
148    error).
149
150    Note that while we are building the table, which goes into the
151    psymbol obstack, we hijack the sections_end pointer to instead hold
152    a count of the number of sections.  When bfd_map_over_sections
153    returns, this count is used to compute the pointer to the end of
154    the sections table, which then overwrites the count.
155
156    Also note that the OFFSET and OVLY_MAPPED in each table entry
157    are initialized to zero.
158
159    Also note that if anything else writes to the psymbol obstack while
160    we are building the table, we're pretty much hosed. */
161
162 int
163 build_objfile_section_table (struct objfile *objfile)
164 {
165   /* objfile->sections can be already set when reading a mapped symbol
166      file.  I believe that we do need to rebuild the section table in
167      this case (we rebuild other things derived from the bfd), but we
168      can't free the old one (it's in the objfile_obstack).  So we just
169      waste some memory.  */
170
171   objfile->sections_end = 0;
172   bfd_map_over_sections (objfile->obfd,
173                          add_to_objfile_sections, (void *) objfile);
174   objfile->sections = obstack_finish (&objfile->objfile_obstack);
175   objfile->sections_end = objfile->sections + (size_t) objfile->sections_end;
176   return (0);
177 }
178
179 /* Given a pointer to an initialized bfd (ABFD) and some flag bits
180    allocate a new objfile struct, fill it in as best we can, link it
181    into the list of all known objfiles, and return a pointer to the
182    new objfile struct.
183
184    The FLAGS word contains various bits (OBJF_*) that can be taken as
185    requests for specific operations.  Other bits like OBJF_SHARED are
186    simply copied through to the new objfile flags member. */
187
188 /* NOTE: carlton/2003-02-04: This function is called with args NULL, 0
189    by jv-lang.c, to create an artificial objfile used to hold
190    information about dynamically-loaded Java classes.  Unfortunately,
191    that branch of this function doesn't get tested very frequently, so
192    it's prone to breakage.  (E.g. at one time the name was set to NULL
193    in that situation, which broke a loop over all names in the dynamic
194    library loader.)  If you change this function, please try to leave
195    things in a consistent state even if abfd is NULL.  */
196
197 struct objfile *
198 allocate_objfile (bfd *abfd, int flags)
199 {
200   struct objfile *objfile;
201
202   objfile = (struct objfile *) xzalloc (sizeof (struct objfile));
203   objfile->psymbol_cache = psymbol_bcache_init ();
204   objfile->macro_cache = bcache_xmalloc (NULL, NULL);
205   objfile->filename_cache = bcache_xmalloc (NULL, NULL);
206   /* We could use obstack_specify_allocation here instead, but
207      gdb_obstack.h specifies the alloc/dealloc functions.  */
208   obstack_init (&objfile->objfile_obstack);
209   terminate_minimal_symbol_table (objfile);
210
211   objfile_alloc_data (objfile);
212
213   /* Update the per-objfile information that comes from the bfd, ensuring
214      that any data that is reference is saved in the per-objfile data
215      region. */
216
217   objfile->obfd = gdb_bfd_ref (abfd);
218   if (abfd != NULL)
219     {
220       /* Look up the gdbarch associated with the BFD.  */
221       objfile->gdbarch = gdbarch_from_bfd (abfd);
222
223       objfile->name = xstrdup (bfd_get_filename (abfd));
224       objfile->mtime = bfd_get_mtime (abfd);
225
226       /* Build section table.  */
227
228       if (build_objfile_section_table (objfile))
229         {
230           error (_("Can't find the file sections in `%s': %s"),
231                  objfile->name, bfd_errmsg (bfd_get_error ()));
232         }
233     }
234   else
235     {
236       objfile->name = xstrdup ("<<anonymous objfile>>");
237     }
238
239   objfile->pspace = current_program_space;
240
241   /* Initialize the section indexes for this objfile, so that we can
242      later detect if they are used w/o being properly assigned to. */
243
244   objfile->sect_index_text = -1;
245   objfile->sect_index_data = -1;
246   objfile->sect_index_bss = -1;
247   objfile->sect_index_rodata = -1;
248
249   /* We don't yet have a C++-specific namespace symtab.  */
250
251   objfile->cp_namespace_symtab = NULL;
252
253   /* Add this file onto the tail of the linked list of other such files. */
254
255   objfile->next = NULL;
256   if (object_files == NULL)
257     object_files = objfile;
258   else
259     {
260       struct objfile *last_one;
261
262       for (last_one = object_files;
263            last_one->next;
264            last_one = last_one->next);
265       last_one->next = objfile;
266     }
267
268   /* Save passed in flag bits. */
269   objfile->flags |= flags;
270
271   /* Rebuild section map next time we need it.  */
272   get_objfile_pspace_data (objfile->pspace)->objfiles_changed_p = 1;
273
274   return objfile;
275 }
276
277 /* Retrieve the gdbarch associated with OBJFILE.  */
278 struct gdbarch *
279 get_objfile_arch (struct objfile *objfile)
280 {
281   return objfile->gdbarch;
282 }
283
284 /* Initialize entry point information for this objfile. */
285
286 void
287 init_entry_point_info (struct objfile *objfile)
288 {
289   /* Save startup file's range of PC addresses to help blockframe.c
290      decide where the bottom of the stack is.  */
291
292   if (bfd_get_file_flags (objfile->obfd) & EXEC_P)
293     {
294       /* Executable file -- record its entry point so we'll recognize
295          the startup file because it contains the entry point.  */
296       objfile->ei.entry_point = bfd_get_start_address (objfile->obfd);
297       objfile->ei.entry_point_p = 1;
298     }
299   else if (bfd_get_file_flags (objfile->obfd) & DYNAMIC
300            && bfd_get_start_address (objfile->obfd) != 0)
301     {
302       /* Some shared libraries may have entry points set and be
303          runnable.  There's no clear way to indicate this, so just check
304          for values other than zero.  */
305       objfile->ei.entry_point = bfd_get_start_address (objfile->obfd);    
306       objfile->ei.entry_point_p = 1;
307     }
308   else
309     {
310       /* Examination of non-executable.o files.  Short-circuit this stuff.  */
311       objfile->ei.entry_point_p = 0;
312     }
313 }
314
315 /* If there is a valid and known entry point, function fills *ENTRY_P with it
316    and returns non-zero; otherwise it returns zero.  */
317
318 int
319 entry_point_address_query (CORE_ADDR *entry_p)
320 {
321   struct gdbarch *gdbarch;
322   CORE_ADDR entry_point;
323
324   if (symfile_objfile == NULL || !symfile_objfile->ei.entry_point_p)
325     return 0;
326
327   gdbarch = get_objfile_arch (symfile_objfile);
328
329   entry_point = symfile_objfile->ei.entry_point;
330
331   /* Make certain that the address points at real code, and not a
332      function descriptor.  */
333   entry_point = gdbarch_convert_from_func_ptr_addr (gdbarch, entry_point,
334                                                     &current_target);
335
336   /* Remove any ISA markers, so that this matches entries in the
337      symbol table.  */
338   entry_point = gdbarch_addr_bits_remove (gdbarch, entry_point);
339
340   *entry_p = entry_point;
341   return 1;
342 }
343
344 /* Get current entry point address.  Call error if it is not known.  */
345
346 CORE_ADDR
347 entry_point_address (void)
348 {
349   CORE_ADDR retval;
350
351   if (!entry_point_address_query (&retval))
352     error (_("Entry point address is not known."));
353
354   return retval;
355 }
356
357 /* Create the terminating entry of OBJFILE's minimal symbol table.
358    If OBJFILE->msymbols is zero, allocate a single entry from
359    OBJFILE->objfile_obstack; otherwise, just initialize
360    OBJFILE->msymbols[OBJFILE->minimal_symbol_count].  */
361 void
362 terminate_minimal_symbol_table (struct objfile *objfile)
363 {
364   if (! objfile->msymbols)
365     objfile->msymbols = ((struct minimal_symbol *)
366                          obstack_alloc (&objfile->objfile_obstack,
367                                         sizeof (objfile->msymbols[0])));
368
369   {
370     struct minimal_symbol *m
371       = &objfile->msymbols[objfile->minimal_symbol_count];
372
373     memset (m, 0, sizeof (*m));
374     /* Don't rely on these enumeration values being 0's.  */
375     MSYMBOL_TYPE (m) = mst_unknown;
376     SYMBOL_SET_LANGUAGE (m, language_unknown);
377   }
378 }
379
380 /* Iterator on PARENT and every separate debug objfile of PARENT.
381    The usage pattern is:
382      for (objfile = parent;
383           objfile;
384           objfile = objfile_separate_debug_iterate (parent, objfile))
385        ...
386 */
387
388 struct objfile *
389 objfile_separate_debug_iterate (const struct objfile *parent,
390                                 const struct objfile *objfile)
391 {
392   struct objfile *res;
393
394   /* If any, return the first child.  */
395   res = objfile->separate_debug_objfile;
396   if (res)
397     return res;
398
399   /* Common case where there is no separate debug objfile.  */
400   if (objfile == parent)
401     return NULL;
402
403   /* Return the brother if any.  Note that we don't iterate on brothers of
404      the parents.  */
405   res = objfile->separate_debug_objfile_link;
406   if (res)
407     return res;
408
409   for (res = objfile->separate_debug_objfile_backlink;
410        res != parent;
411        res = res->separate_debug_objfile_backlink)
412     {
413       gdb_assert (res != NULL);
414       if (res->separate_debug_objfile_link)
415         return res->separate_debug_objfile_link;
416     }
417   return NULL;
418 }
419
420 /* Put one object file before a specified on in the global list.
421    This can be used to make sure an object file is destroyed before
422    another when using ALL_OBJFILES_SAFE to free all objfiles. */
423 void
424 put_objfile_before (struct objfile *objfile, struct objfile *before_this)
425 {
426   struct objfile **objp;
427
428   unlink_objfile (objfile);
429   
430   for (objp = &object_files; *objp != NULL; objp = &((*objp)->next))
431     {
432       if (*objp == before_this)
433         {
434           objfile->next = *objp;
435           *objp = objfile;
436           return;
437         }
438     }
439   
440   internal_error (__FILE__, __LINE__,
441                   _("put_objfile_before: before objfile not in list"));
442 }
443
444 /* Put OBJFILE at the front of the list.  */
445
446 void
447 objfile_to_front (struct objfile *objfile)
448 {
449   struct objfile **objp;
450   for (objp = &object_files; *objp != NULL; objp = &((*objp)->next))
451     {
452       if (*objp == objfile)
453         {
454           /* Unhook it from where it is.  */
455           *objp = objfile->next;
456           /* Put it in the front.  */
457           objfile->next = object_files;
458           object_files = objfile;
459           break;
460         }
461     }
462 }
463
464 /* Unlink OBJFILE from the list of known objfiles, if it is found in the
465    list.
466
467    It is not a bug, or error, to call this function if OBJFILE is not known
468    to be in the current list.  This is done in the case of mapped objfiles,
469    for example, just to ensure that the mapped objfile doesn't appear twice
470    in the list.  Since the list is threaded, linking in a mapped objfile
471    twice would create a circular list.
472
473    If OBJFILE turns out to be in the list, we zap it's NEXT pointer after
474    unlinking it, just to ensure that we have completely severed any linkages
475    between the OBJFILE and the list. */
476
477 void
478 unlink_objfile (struct objfile *objfile)
479 {
480   struct objfile **objpp;
481
482   for (objpp = &object_files; *objpp != NULL; objpp = &((*objpp)->next))
483     {
484       if (*objpp == objfile)
485         {
486           *objpp = (*objpp)->next;
487           objfile->next = NULL;
488           return;
489         }
490     }
491
492   internal_error (__FILE__, __LINE__,
493                   _("unlink_objfile: objfile already unlinked"));
494 }
495
496 /* Add OBJFILE as a separate debug objfile of PARENT.  */
497
498 void
499 add_separate_debug_objfile (struct objfile *objfile, struct objfile *parent)
500 {
501   gdb_assert (objfile && parent);
502
503   /* Must not be already in a list.  */
504   gdb_assert (objfile->separate_debug_objfile_backlink == NULL);
505   gdb_assert (objfile->separate_debug_objfile_link == NULL);
506
507   objfile->separate_debug_objfile_backlink = parent;
508   objfile->separate_debug_objfile_link = parent->separate_debug_objfile;
509   parent->separate_debug_objfile = objfile;
510
511   /* Put the separate debug object before the normal one, this is so that
512      usage of the ALL_OBJFILES_SAFE macro will stay safe. */
513   put_objfile_before (objfile, parent);
514 }
515
516 /* Free all separate debug objfile of OBJFILE, but don't free OBJFILE
517    itself.  */
518
519 void
520 free_objfile_separate_debug (struct objfile *objfile)
521 {
522   struct objfile *child;
523
524   for (child = objfile->separate_debug_objfile; child;)
525     {
526       struct objfile *next_child = child->separate_debug_objfile_link;
527       free_objfile (child);
528       child = next_child;
529     }
530 }
531
532 /* Destroy an objfile and all the symtabs and psymtabs under it.  Note
533    that as much as possible is allocated on the objfile_obstack 
534    so that the memory can be efficiently freed.
535
536    Things which we do NOT free because they are not in malloc'd memory
537    or not in memory specific to the objfile include:
538
539    objfile -> sf
540
541    FIXME:  If the objfile is using reusable symbol information (via mmalloc),
542    then we need to take into account the fact that more than one process
543    may be using the symbol information at the same time (when mmalloc is
544    extended to support cooperative locking).  When more than one process
545    is using the mapped symbol info, we need to be more careful about when
546    we free objects in the reusable area. */
547
548 void
549 free_objfile (struct objfile *objfile)
550 {
551   /* Free all separate debug objfiles.  */
552   free_objfile_separate_debug (objfile);
553
554   if (objfile->separate_debug_objfile_backlink)
555     {
556       /* We freed the separate debug file, make sure the base objfile
557          doesn't reference it.  */
558       struct objfile *child;
559
560       child = objfile->separate_debug_objfile_backlink->separate_debug_objfile;
561
562       if (child == objfile)
563         {
564           /* OBJFILE is the first child.  */
565           objfile->separate_debug_objfile_backlink->separate_debug_objfile =
566             objfile->separate_debug_objfile_link;
567         }
568       else
569         {
570           /* Find OBJFILE in the list.  */
571           while (1)
572             {
573               if (child->separate_debug_objfile_link == objfile)
574                 {
575                   child->separate_debug_objfile_link =
576                     objfile->separate_debug_objfile_link;
577                   break;
578                 }
579               child = child->separate_debug_objfile_link;
580               gdb_assert (child);
581             }
582         }
583     }
584   
585   /* Remove any references to this objfile in the global value
586      lists.  */
587   preserve_values (objfile);
588
589   /* First do any symbol file specific actions required when we are
590      finished with a particular symbol file.  Note that if the objfile
591      is using reusable symbol information (via mmalloc) then each of
592      these routines is responsible for doing the correct thing, either
593      freeing things which are valid only during this particular gdb
594      execution, or leaving them to be reused during the next one. */
595
596   if (objfile->sf != NULL)
597     {
598       (*objfile->sf->sym_finish) (objfile);
599     }
600
601   /* Discard any data modules have associated with the objfile.  */
602   objfile_free_data (objfile);
603
604   gdb_bfd_unref (objfile->obfd);
605
606   /* Remove it from the chain of all objfiles. */
607
608   unlink_objfile (objfile);
609
610   if (objfile == symfile_objfile)
611     symfile_objfile = NULL;
612
613   if (objfile == rt_common_objfile)
614     rt_common_objfile = NULL;
615
616   /* Before the symbol table code was redone to make it easier to
617      selectively load and remove information particular to a specific
618      linkage unit, gdb used to do these things whenever the monolithic
619      symbol table was blown away.  How much still needs to be done
620      is unknown, but we play it safe for now and keep each action until
621      it is shown to be no longer needed. */
622
623   /* Not all our callers call clear_symtab_users (objfile_purge_solibs,
624      for example), so we need to call this here.  */
625   clear_pc_function_cache ();
626
627   /* Clear globals which might have pointed into a removed objfile.
628      FIXME: It's not clear which of these are supposed to persist
629      between expressions and which ought to be reset each time.  */
630   expression_context_block = NULL;
631   innermost_block = NULL;
632
633   /* Check to see if the current_source_symtab belongs to this objfile,
634      and if so, call clear_current_source_symtab_and_line. */
635
636   {
637     struct symtab_and_line cursal = get_current_source_symtab_and_line ();
638     struct symtab *s;
639
640     ALL_OBJFILE_SYMTABS (objfile, s)
641       {
642         if (s == cursal.symtab)
643           clear_current_source_symtab_and_line ();
644       }
645   }
646
647   /* The last thing we do is free the objfile struct itself. */
648
649   xfree (objfile->name);
650   if (objfile->global_psymbols.list)
651     xfree (objfile->global_psymbols.list);
652   if (objfile->static_psymbols.list)
653     xfree (objfile->static_psymbols.list);
654   /* Free the obstacks for non-reusable objfiles */
655   psymbol_bcache_free (objfile->psymbol_cache);
656   bcache_xfree (objfile->macro_cache);
657   bcache_xfree (objfile->filename_cache);
658   if (objfile->demangled_names_hash)
659     htab_delete (objfile->demangled_names_hash);
660   obstack_free (&objfile->objfile_obstack, 0);
661
662   /* Rebuild section map next time we need it.  */
663   get_objfile_pspace_data (objfile->pspace)->objfiles_changed_p = 1;
664
665   xfree (objfile);
666 }
667
668 static void
669 do_free_objfile_cleanup (void *obj)
670 {
671   free_objfile (obj);
672 }
673
674 struct cleanup *
675 make_cleanup_free_objfile (struct objfile *obj)
676 {
677   return make_cleanup (do_free_objfile_cleanup, obj);
678 }
679
680 /* Free all the object files at once and clean up their users.  */
681
682 void
683 free_all_objfiles (void)
684 {
685   struct objfile *objfile, *temp;
686   struct so_list *so;
687
688   /* Any objfile referencewould become stale.  */
689   for (so = master_so_list (); so; so = so->next)
690     gdb_assert (so->objfile == NULL);
691
692   ALL_OBJFILES_SAFE (objfile, temp)
693   {
694     free_objfile (objfile);
695   }
696   clear_symtab_users (0);
697 }
698 \f
699 /* A helper function for objfile_relocate1 that relocates a single
700    symbol.  */
701
702 static void
703 relocate_one_symbol (struct symbol *sym, struct objfile *objfile,
704                      struct section_offsets *delta)
705 {
706   fixup_symbol_section (sym, objfile);
707
708   /* The RS6000 code from which this was taken skipped
709      any symbols in STRUCT_DOMAIN or UNDEF_DOMAIN.
710      But I'm leaving out that test, on the theory that
711      they can't possibly pass the tests below.  */
712   if ((SYMBOL_CLASS (sym) == LOC_LABEL
713        || SYMBOL_CLASS (sym) == LOC_STATIC)
714       && SYMBOL_SECTION (sym) >= 0)
715     {
716       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (delta, SYMBOL_SECTION (sym));
717     }
718 }
719
720 /* Relocate OBJFILE to NEW_OFFSETS.  There should be OBJFILE->NUM_SECTIONS
721    entries in new_offsets.  SEPARATE_DEBUG_OBJFILE is not touched here.
722    Return non-zero iff any change happened.  */
723
724 static int
725 objfile_relocate1 (struct objfile *objfile, 
726                    struct section_offsets *new_offsets)
727 {
728   struct obj_section *s;
729   struct section_offsets *delta =
730     ((struct section_offsets *) 
731      alloca (SIZEOF_N_SECTION_OFFSETS (objfile->num_sections)));
732
733   int i;
734   int something_changed = 0;
735
736   for (i = 0; i < objfile->num_sections; ++i)
737     {
738       delta->offsets[i] =
739         ANOFFSET (new_offsets, i) - ANOFFSET (objfile->section_offsets, i);
740       if (ANOFFSET (delta, i) != 0)
741         something_changed = 1;
742     }
743   if (!something_changed)
744     return 0;
745
746   /* OK, get all the symtabs.  */
747   {
748     struct symtab *s;
749
750     ALL_OBJFILE_SYMTABS (objfile, s)
751     {
752       struct linetable *l;
753       struct blockvector *bv;
754       int i;
755
756       /* First the line table.  */
757       l = LINETABLE (s);
758       if (l)
759         {
760           for (i = 0; i < l->nitems; ++i)
761             l->item[i].pc += ANOFFSET (delta, s->block_line_section);
762         }
763
764       /* Don't relocate a shared blockvector more than once.  */
765       if (!s->primary)
766         continue;
767
768       bv = BLOCKVECTOR (s);
769       if (BLOCKVECTOR_MAP (bv))
770         addrmap_relocate (BLOCKVECTOR_MAP (bv),
771                           ANOFFSET (delta, s->block_line_section));
772
773       for (i = 0; i < BLOCKVECTOR_NBLOCKS (bv); ++i)
774         {
775           struct block *b;
776           struct symbol *sym;
777           struct dict_iterator iter;
778
779           b = BLOCKVECTOR_BLOCK (bv, i);
780           BLOCK_START (b) += ANOFFSET (delta, s->block_line_section);
781           BLOCK_END (b) += ANOFFSET (delta, s->block_line_section);
782
783           ALL_BLOCK_SYMBOLS (b, iter, sym)
784             {
785               relocate_one_symbol (sym, objfile, delta);
786             }
787         }
788     }
789   }
790
791   /* Relocate isolated symbols.  */
792   {
793     struct symbol *iter;
794
795     for (iter = objfile->template_symbols; iter; iter = iter->hash_next)
796       relocate_one_symbol (iter, objfile, delta);
797   }
798
799   if (objfile->psymtabs_addrmap)
800     addrmap_relocate (objfile->psymtabs_addrmap,
801                       ANOFFSET (delta, SECT_OFF_TEXT (objfile)));
802
803   if (objfile->sf)
804     objfile->sf->qf->relocate (objfile, new_offsets, delta);
805
806   {
807     struct minimal_symbol *msym;
808
809     ALL_OBJFILE_MSYMBOLS (objfile, msym)
810       if (SYMBOL_SECTION (msym) >= 0)
811       SYMBOL_VALUE_ADDRESS (msym) += ANOFFSET (delta, SYMBOL_SECTION (msym));
812   }
813   /* Relocating different sections by different amounts may cause the symbols
814      to be out of order.  */
815   msymbols_sort (objfile);
816
817   if (objfile->ei.entry_point_p)
818     {
819       /* Relocate ei.entry_point with its section offset, use SECT_OFF_TEXT
820          only as a fallback.  */
821       struct obj_section *s;
822       s = find_pc_section (objfile->ei.entry_point);
823       if (s)
824         objfile->ei.entry_point += ANOFFSET (delta, s->the_bfd_section->index);
825       else
826         objfile->ei.entry_point += ANOFFSET (delta, SECT_OFF_TEXT (objfile));
827     }
828
829   {
830     int i;
831
832     for (i = 0; i < objfile->num_sections; ++i)
833       (objfile->section_offsets)->offsets[i] = ANOFFSET (new_offsets, i);
834   }
835
836   /* Rebuild section map next time we need it.  */
837   get_objfile_pspace_data (objfile->pspace)->objfiles_changed_p = 1;
838
839   /* Update the table in exec_ops, used to read memory.  */
840   ALL_OBJFILE_OSECTIONS (objfile, s)
841     {
842       int idx = s->the_bfd_section->index;
843
844       exec_set_section_address (bfd_get_filename (objfile->obfd), idx,
845                                 obj_section_addr (s));
846     }
847
848   /* Data changed.  */
849   return 1;
850 }
851
852 /* Relocate OBJFILE to NEW_OFFSETS.  There should be OBJFILE->NUM_SECTIONS
853    entries in new_offsets.  Process also OBJFILE's SEPARATE_DEBUG_OBJFILEs.
854
855    The number and ordering of sections does differ between the two objfiles.
856    Only their names match.  Also the file offsets will differ (objfile being
857    possibly prelinked but separate_debug_objfile is probably not prelinked) but
858    the in-memory absolute address as specified by NEW_OFFSETS must match both
859    files.  */
860
861 void
862 objfile_relocate (struct objfile *objfile, struct section_offsets *new_offsets)
863 {
864   struct objfile *debug_objfile;
865   int changed = 0;
866
867   changed |= objfile_relocate1 (objfile, new_offsets);
868
869   for (debug_objfile = objfile->separate_debug_objfile;
870        debug_objfile;
871        debug_objfile = objfile_separate_debug_iterate (objfile, debug_objfile))
872     {
873       struct section_addr_info *objfile_addrs;
874       struct section_offsets *new_debug_offsets;
875       struct cleanup *my_cleanups;
876
877       objfile_addrs = build_section_addr_info_from_objfile (objfile);
878       my_cleanups = make_cleanup (xfree, objfile_addrs);
879
880       /* Here OBJFILE_ADDRS contain the correct absolute addresses, the
881          relative ones must be already created according to debug_objfile.  */
882
883       addr_info_make_relative (objfile_addrs, debug_objfile->obfd);
884
885       gdb_assert (debug_objfile->num_sections
886                   == bfd_count_sections (debug_objfile->obfd));
887       new_debug_offsets = 
888         xmalloc (SIZEOF_N_SECTION_OFFSETS (debug_objfile->num_sections));
889       make_cleanup (xfree, new_debug_offsets);
890       relative_addr_info_to_section_offsets (new_debug_offsets,
891                                              debug_objfile->num_sections,
892                                              objfile_addrs);
893
894       changed |= objfile_relocate1 (debug_objfile, new_debug_offsets);
895
896       do_cleanups (my_cleanups);
897     }
898
899   /* Relocate breakpoints as necessary, after things are relocated. */
900   if (changed)
901     breakpoint_re_set ();
902 }
903 \f
904 /* Return non-zero if OBJFILE has partial symbols.  */
905
906 int
907 objfile_has_partial_symbols (struct objfile *objfile)
908 {
909   return objfile->sf ? objfile->sf->qf->has_symbols (objfile) : 0;
910 }
911
912 /* Return non-zero if OBJFILE has full symbols.  */
913
914 int
915 objfile_has_full_symbols (struct objfile *objfile)
916 {
917   return objfile->symtabs != NULL;
918 }
919
920 /* Return non-zero if OBJFILE has full or partial symbols, either directly
921    or through a separate debug file.  */
922
923 int
924 objfile_has_symbols (struct objfile *objfile)
925 {
926   struct objfile *o;
927
928   for (o = objfile; o; o = objfile_separate_debug_iterate (objfile, o))
929     if (objfile_has_partial_symbols (o) || objfile_has_full_symbols (o))
930       return 1;
931   return 0;
932 }
933
934
935 /* Many places in gdb want to test just to see if we have any partial
936    symbols available.  This function returns zero if none are currently
937    available, nonzero otherwise. */
938
939 int
940 have_partial_symbols (void)
941 {
942   struct objfile *ofp;
943
944   ALL_OBJFILES (ofp)
945   {
946     if (objfile_has_partial_symbols (ofp))
947       return 1;
948   }
949   return 0;
950 }
951
952 /* Many places in gdb want to test just to see if we have any full
953    symbols available.  This function returns zero if none are currently
954    available, nonzero otherwise. */
955
956 int
957 have_full_symbols (void)
958 {
959   struct objfile *ofp;
960
961   ALL_OBJFILES (ofp)
962   {
963     if (objfile_has_full_symbols (ofp))
964       return 1;
965   }
966   return 0;
967 }
968
969
970 /* This operations deletes all objfile entries that represent solibs that
971    weren't explicitly loaded by the user, via e.g., the add-symbol-file
972    command.
973  */
974 void
975 objfile_purge_solibs (void)
976 {
977   struct objfile *objf;
978   struct objfile *temp;
979
980   ALL_OBJFILES_SAFE (objf, temp)
981   {
982     /* We assume that the solib package has been purged already, or will
983        be soon.
984      */
985     if (!(objf->flags & OBJF_USERLOADED) && (objf->flags & OBJF_SHARED))
986       free_objfile (objf);
987   }
988 }
989
990
991 /* Many places in gdb want to test just to see if we have any minimal
992    symbols available.  This function returns zero if none are currently
993    available, nonzero otherwise. */
994
995 int
996 have_minimal_symbols (void)
997 {
998   struct objfile *ofp;
999
1000   ALL_OBJFILES (ofp)
1001   {
1002     if (ofp->minimal_symbol_count > 0)
1003       {
1004         return 1;
1005       }
1006   }
1007   return 0;
1008 }
1009
1010 /* Qsort comparison function.  */
1011
1012 static int
1013 qsort_cmp (const void *a, const void *b)
1014 {
1015   const struct obj_section *sect1 = *(const struct obj_section **) a;
1016   const struct obj_section *sect2 = *(const struct obj_section **) b;
1017   const CORE_ADDR sect1_addr = obj_section_addr (sect1);
1018   const CORE_ADDR sect2_addr = obj_section_addr (sect2);
1019
1020   if (sect1_addr < sect2_addr)
1021     return -1;
1022   else if (sect1_addr > sect2_addr)
1023     return 1;
1024   else
1025     {
1026       /* Sections are at the same address.  This could happen if
1027          A) we have an objfile and a separate debuginfo.
1028          B) we are confused, and have added sections without proper relocation,
1029          or something like that. */
1030
1031       const struct objfile *const objfile1 = sect1->objfile;
1032       const struct objfile *const objfile2 = sect2->objfile;
1033
1034       if (objfile1->separate_debug_objfile == objfile2
1035           || objfile2->separate_debug_objfile == objfile1)
1036         {
1037           /* Case A.  The ordering doesn't matter: separate debuginfo files
1038              will be filtered out later.  */
1039
1040           return 0;
1041         }
1042
1043       /* Case B.  Maintain stable sort order, so bugs in GDB are easier to
1044          triage.  This section could be slow (since we iterate over all
1045          objfiles in each call to qsort_cmp), but this shouldn't happen
1046          very often (GDB is already in a confused state; one hopes this
1047          doesn't happen at all).  If you discover that significant time is
1048          spent in the loops below, do 'set complaints 100' and examine the
1049          resulting complaints.  */
1050
1051       if (objfile1 == objfile2)
1052         {
1053           /* Both sections came from the same objfile.  We are really confused.
1054              Sort on sequence order of sections within the objfile.  */
1055
1056           const struct obj_section *osect;
1057
1058           ALL_OBJFILE_OSECTIONS (objfile1, osect)
1059             if (osect == sect1)
1060               return -1;
1061             else if (osect == sect2)
1062               return 1;
1063
1064           /* We should have found one of the sections before getting here.  */
1065           gdb_assert_not_reached ("section not found");
1066         }
1067       else
1068         {
1069           /* Sort on sequence number of the objfile in the chain.  */
1070
1071           const struct objfile *objfile;
1072
1073           ALL_OBJFILES (objfile)
1074             if (objfile == objfile1)
1075               return -1;
1076             else if (objfile == objfile2)
1077               return 1;
1078
1079           /* We should have found one of the objfiles before getting here.  */
1080           gdb_assert_not_reached ("objfile not found");
1081         }
1082     }
1083
1084   /* Unreachable.  */
1085   gdb_assert_not_reached ("unexpected code path");
1086   return 0;
1087 }
1088
1089 /* Select "better" obj_section to keep.  We prefer the one that came from
1090    the real object, rather than the one from separate debuginfo.
1091    Most of the time the two sections are exactly identical, but with
1092    prelinking the .rel.dyn section in the real object may have different
1093    size.  */
1094
1095 static struct obj_section *
1096 preferred_obj_section (struct obj_section *a, struct obj_section *b)
1097 {
1098   gdb_assert (obj_section_addr (a) == obj_section_addr (b));
1099   gdb_assert ((a->objfile->separate_debug_objfile == b->objfile)
1100               || (b->objfile->separate_debug_objfile == a->objfile));
1101   gdb_assert ((a->objfile->separate_debug_objfile_backlink == b->objfile)
1102               || (b->objfile->separate_debug_objfile_backlink == a->objfile));
1103
1104   if (a->objfile->separate_debug_objfile != NULL)
1105     return a;
1106   return b;
1107 }
1108
1109 /* Return 1 if SECTION should be inserted into the section map.
1110    We want to insert only non-overlay and non-TLS section.  */
1111
1112 static int
1113 insert_section_p (const struct bfd *abfd,
1114                   const struct bfd_section *section)
1115 {
1116   const bfd_vma lma = bfd_section_lma (abfd, section);
1117
1118   if (lma != 0 && lma != bfd_section_vma (abfd, section)
1119       && (bfd_get_file_flags (abfd) & BFD_IN_MEMORY) == 0)
1120     /* This is an overlay section.  IN_MEMORY check is needed to avoid
1121        discarding sections from the "system supplied DSO" (aka vdso)
1122        on some Linux systems (e.g. Fedora 11).  */
1123     return 0;
1124   if ((bfd_get_section_flags (abfd, section) & SEC_THREAD_LOCAL) != 0)
1125     /* This is a TLS section.  */
1126     return 0;
1127
1128   return 1;
1129 }
1130
1131 /* Filter out overlapping sections where one section came from the real
1132    objfile, and the other from a separate debuginfo file.
1133    Return the size of table after redundant sections have been eliminated.  */
1134
1135 static int
1136 filter_debuginfo_sections (struct obj_section **map, int map_size)
1137 {
1138   int i, j;
1139
1140   for (i = 0, j = 0; i < map_size - 1; i++)
1141     {
1142       struct obj_section *const sect1 = map[i];
1143       struct obj_section *const sect2 = map[i + 1];
1144       const struct objfile *const objfile1 = sect1->objfile;
1145       const struct objfile *const objfile2 = sect2->objfile;
1146       const CORE_ADDR sect1_addr = obj_section_addr (sect1);
1147       const CORE_ADDR sect2_addr = obj_section_addr (sect2);
1148
1149       if (sect1_addr == sect2_addr
1150           && (objfile1->separate_debug_objfile == objfile2
1151               || objfile2->separate_debug_objfile == objfile1))
1152         {
1153           map[j++] = preferred_obj_section (sect1, sect2);
1154           ++i;
1155         }
1156       else
1157         map[j++] = sect1;
1158     }
1159
1160   if (i < map_size)
1161     {
1162       gdb_assert (i == map_size - 1);
1163       map[j++] = map[i];
1164     }
1165
1166   /* The map should not have shrunk to less than half the original size.  */
1167   gdb_assert (map_size / 2 <= j);
1168
1169   return j;
1170 }
1171
1172 /* Filter out overlapping sections, issuing a warning if any are found.
1173    Overlapping sections could really be overlay sections which we didn't
1174    classify as such in insert_section_p, or we could be dealing with a
1175    corrupt binary.  */
1176
1177 static int
1178 filter_overlapping_sections (struct obj_section **map, int map_size)
1179 {
1180   int i, j;
1181
1182   for (i = 0, j = 0; i < map_size - 1; )
1183     {
1184       int k;
1185
1186       map[j++] = map[i];
1187       for (k = i + 1; k < map_size; k++)
1188         {
1189           struct obj_section *const sect1 = map[i];
1190           struct obj_section *const sect2 = map[k];
1191           const CORE_ADDR sect1_addr = obj_section_addr (sect1);
1192           const CORE_ADDR sect2_addr = obj_section_addr (sect2);
1193           const CORE_ADDR sect1_endaddr = obj_section_endaddr (sect1);
1194
1195           gdb_assert (sect1_addr <= sect2_addr);
1196
1197           if (sect1_endaddr <= sect2_addr)
1198             break;
1199           else
1200             {
1201               /* We have an overlap.  Report it.  */
1202
1203               struct objfile *const objf1 = sect1->objfile;
1204               struct objfile *const objf2 = sect2->objfile;
1205
1206               const struct bfd *const abfd1 = objf1->obfd;
1207               const struct bfd *const abfd2 = objf2->obfd;
1208
1209               const struct bfd_section *const bfds1 = sect1->the_bfd_section;
1210               const struct bfd_section *const bfds2 = sect2->the_bfd_section;
1211
1212               const CORE_ADDR sect2_endaddr = obj_section_endaddr (sect2);
1213
1214               struct gdbarch *const gdbarch = get_objfile_arch (objf1);
1215
1216               complaint (&symfile_complaints,
1217                          _("unexpected overlap between:\n"
1218                            " (A) section `%s' from `%s' [%s, %s)\n"
1219                            " (B) section `%s' from `%s' [%s, %s).\n"
1220                            "Will ignore section B"),
1221                          bfd_section_name (abfd1, bfds1), objf1->name,
1222                          paddress (gdbarch, sect1_addr),
1223                          paddress (gdbarch, sect1_endaddr),
1224                          bfd_section_name (abfd2, bfds2), objf2->name,
1225                          paddress (gdbarch, sect2_addr),
1226                          paddress (gdbarch, sect2_endaddr));
1227             }
1228         }
1229       i = k;
1230     }
1231
1232   if (i < map_size)
1233     {
1234       gdb_assert (i == map_size - 1);
1235       map[j++] = map[i];
1236     }
1237
1238   return j;
1239 }
1240
1241
1242 /* Update PMAP, PMAP_SIZE with sections from all objfiles, excluding any
1243    TLS, overlay and overlapping sections.  */
1244
1245 static void
1246 update_section_map (struct program_space *pspace,
1247                     struct obj_section ***pmap, int *pmap_size)
1248 {
1249   int alloc_size, map_size, i;
1250   struct obj_section *s, **map;
1251   struct objfile *objfile;
1252
1253   gdb_assert (get_objfile_pspace_data (pspace)->objfiles_changed_p != 0);
1254
1255   map = *pmap;
1256   xfree (map);
1257
1258   alloc_size = 0;
1259   ALL_PSPACE_OBJFILES (pspace, objfile)
1260     ALL_OBJFILE_OSECTIONS (objfile, s)
1261       if (insert_section_p (objfile->obfd, s->the_bfd_section))
1262         alloc_size += 1;
1263
1264   /* This happens on detach/attach (e.g. in gdb.base/attach.exp).  */
1265   if (alloc_size == 0)
1266     {
1267       *pmap = NULL;
1268       *pmap_size = 0;
1269       return;
1270     }
1271
1272   map = xmalloc (alloc_size * sizeof (*map));
1273
1274   i = 0;
1275   ALL_PSPACE_OBJFILES (pspace, objfile)
1276     ALL_OBJFILE_OSECTIONS (objfile, s)
1277       if (insert_section_p (objfile->obfd, s->the_bfd_section))
1278         map[i++] = s;
1279
1280   qsort (map, alloc_size, sizeof (*map), qsort_cmp);
1281   map_size = filter_debuginfo_sections(map, alloc_size);
1282   map_size = filter_overlapping_sections(map, map_size);
1283
1284   if (map_size < alloc_size)
1285     /* Some sections were eliminated.  Trim excess space.  */
1286     map = xrealloc (map, map_size * sizeof (*map));
1287   else
1288     gdb_assert (alloc_size == map_size);
1289
1290   *pmap = map;
1291   *pmap_size = map_size;
1292 }
1293
1294 /* Bsearch comparison function. */
1295
1296 static int
1297 bsearch_cmp (const void *key, const void *elt)
1298 {
1299   const CORE_ADDR pc = *(CORE_ADDR *) key;
1300   const struct obj_section *section = *(const struct obj_section **) elt;
1301
1302   if (pc < obj_section_addr (section))
1303     return -1;
1304   if (pc < obj_section_endaddr (section))
1305     return 0;
1306   return 1;
1307 }
1308
1309 /* Returns a section whose range includes PC or NULL if none found.   */
1310
1311 struct obj_section *
1312 find_pc_section (CORE_ADDR pc)
1313 {
1314   struct objfile_pspace_info *pspace_info;
1315   struct obj_section *s, **sp;
1316
1317   /* Check for mapped overlay section first.  */
1318   s = find_pc_mapped_section (pc);
1319   if (s)
1320     return s;
1321
1322   pspace_info = get_objfile_pspace_data (current_program_space);
1323   if (pspace_info->objfiles_changed_p != 0)
1324     {
1325       update_section_map (current_program_space,
1326                           &pspace_info->sections,
1327                           &pspace_info->num_sections);
1328
1329       /* Don't need updates to section map until objfiles are added,
1330          removed or relocated.  */
1331       pspace_info->objfiles_changed_p = 0;
1332     }
1333
1334   /* The C standard (ISO/IEC 9899:TC2) requires the BASE argument to
1335      bsearch be non-NULL.  */
1336   if (pspace_info->sections == NULL)
1337     {
1338       gdb_assert (pspace_info->num_sections == 0);
1339       return NULL;
1340     }
1341
1342   sp = (struct obj_section **) bsearch (&pc,
1343                                         pspace_info->sections,
1344                                         pspace_info->num_sections,
1345                                         sizeof (*pspace_info->sections),
1346                                         bsearch_cmp);
1347   if (sp != NULL)
1348     return *sp;
1349   return NULL;
1350 }
1351
1352
1353 /* In SVR4, we recognize a trampoline by it's section name. 
1354    That is, if the pc is in a section named ".plt" then we are in
1355    a trampoline.  */
1356
1357 int
1358 in_plt_section (CORE_ADDR pc, char *name)
1359 {
1360   struct obj_section *s;
1361   int retval = 0;
1362
1363   s = find_pc_section (pc);
1364
1365   retval = (s != NULL
1366             && s->the_bfd_section->name != NULL
1367             && strcmp (s->the_bfd_section->name, ".plt") == 0);
1368   return (retval);
1369 }
1370 \f
1371
1372 /* Keep a registry of per-objfile data-pointers required by other GDB
1373    modules.  */
1374
1375 struct objfile_data
1376 {
1377   unsigned index;
1378   void (*save) (struct objfile *, void *);
1379   void (*free) (struct objfile *, void *);
1380 };
1381
1382 struct objfile_data_registration
1383 {
1384   struct objfile_data *data;
1385   struct objfile_data_registration *next;
1386 };
1387   
1388 struct objfile_data_registry
1389 {
1390   struct objfile_data_registration *registrations;
1391   unsigned num_registrations;
1392 };
1393
1394 static struct objfile_data_registry objfile_data_registry = { NULL, 0 };
1395
1396 const struct objfile_data *
1397 register_objfile_data_with_cleanup (void (*save) (struct objfile *, void *),
1398                                     void (*free) (struct objfile *, void *))
1399 {
1400   struct objfile_data_registration **curr;
1401
1402   /* Append new registration.  */
1403   for (curr = &objfile_data_registry.registrations;
1404        *curr != NULL; curr = &(*curr)->next);
1405
1406   *curr = XMALLOC (struct objfile_data_registration);
1407   (*curr)->next = NULL;
1408   (*curr)->data = XMALLOC (struct objfile_data);
1409   (*curr)->data->index = objfile_data_registry.num_registrations++;
1410   (*curr)->data->save = save;
1411   (*curr)->data->free = free;
1412
1413   return (*curr)->data;
1414 }
1415
1416 const struct objfile_data *
1417 register_objfile_data (void)
1418 {
1419   return register_objfile_data_with_cleanup (NULL, NULL);
1420 }
1421
1422 static void
1423 objfile_alloc_data (struct objfile *objfile)
1424 {
1425   gdb_assert (objfile->data == NULL);
1426   objfile->num_data = objfile_data_registry.num_registrations;
1427   objfile->data = XCALLOC (objfile->num_data, void *);
1428 }
1429
1430 static void
1431 objfile_free_data (struct objfile *objfile)
1432 {
1433   gdb_assert (objfile->data != NULL);
1434   clear_objfile_data (objfile);
1435   xfree (objfile->data);
1436   objfile->data = NULL;
1437 }
1438
1439 void
1440 clear_objfile_data (struct objfile *objfile)
1441 {
1442   struct objfile_data_registration *registration;
1443   int i;
1444
1445   gdb_assert (objfile->data != NULL);
1446
1447   /* Process all the save handlers.  */
1448
1449   for (registration = objfile_data_registry.registrations, i = 0;
1450        i < objfile->num_data;
1451        registration = registration->next, i++)
1452     if (objfile->data[i] != NULL && registration->data->save != NULL)
1453       registration->data->save (objfile, objfile->data[i]);
1454
1455   /* Now process all the free handlers.  */
1456
1457   for (registration = objfile_data_registry.registrations, i = 0;
1458        i < objfile->num_data;
1459        registration = registration->next, i++)
1460     if (objfile->data[i] != NULL && registration->data->free != NULL)
1461       registration->data->free (objfile, objfile->data[i]);
1462
1463   memset (objfile->data, 0, objfile->num_data * sizeof (void *));
1464 }
1465
1466 void
1467 set_objfile_data (struct objfile *objfile, const struct objfile_data *data,
1468                   void *value)
1469 {
1470   gdb_assert (data->index < objfile->num_data);
1471   objfile->data[data->index] = value;
1472 }
1473
1474 void *
1475 objfile_data (struct objfile *objfile, const struct objfile_data *data)
1476 {
1477   gdb_assert (data->index < objfile->num_data);
1478   return objfile->data[data->index];
1479 }
1480
1481 /* Set objfiles_changed_p so section map will be rebuilt next time it
1482    is used.  Called by reread_symbols.  */
1483
1484 void
1485 objfiles_changed (void)
1486 {
1487   /* Rebuild section map next time we need it.  */
1488   get_objfile_pspace_data (current_program_space)->objfiles_changed_p = 1;
1489 }
1490
1491 /* Close ABFD, and warn if that fails.  */
1492
1493 int
1494 gdb_bfd_close_or_warn (struct bfd *abfd)
1495 {
1496   int ret;
1497   char *name = bfd_get_filename (abfd);
1498
1499   ret = bfd_close (abfd);
1500
1501   if (!ret)
1502     warning (_("cannot close \"%s\": %s"),
1503              name, bfd_errmsg (bfd_get_error ()));
1504
1505   return ret;
1506 }
1507
1508 /* Add reference to ABFD.  Returns ABFD.  */
1509 struct bfd *
1510 gdb_bfd_ref (struct bfd *abfd)
1511 {
1512   int *p_refcount;
1513
1514   if (abfd == NULL)
1515     return NULL;
1516
1517   p_refcount = bfd_usrdata (abfd);
1518
1519   if (p_refcount != NULL)
1520     {
1521       *p_refcount += 1;
1522       return abfd;
1523     }
1524
1525   p_refcount = xmalloc (sizeof (*p_refcount));
1526   *p_refcount = 1;
1527   bfd_usrdata (abfd) = p_refcount;
1528
1529   return abfd;
1530 }
1531
1532 /* Unreference and possibly close ABFD.  */
1533 void
1534 gdb_bfd_unref (struct bfd *abfd)
1535 {
1536   int *p_refcount;
1537   char *name;
1538
1539   if (abfd == NULL)
1540     return;
1541
1542   p_refcount = bfd_usrdata (abfd);
1543
1544   /* Valid range for p_refcount: a pointer to int counter, which has a
1545      value of 1 (single owner) or 2 (shared).  */
1546   gdb_assert (*p_refcount == 1 || *p_refcount == 2);
1547
1548   *p_refcount -= 1;
1549   if (*p_refcount > 0)
1550     return;
1551
1552   xfree (p_refcount);
1553   bfd_usrdata (abfd) = NULL;  /* Paranoia.  */
1554
1555   name = bfd_get_filename (abfd);
1556   gdb_bfd_close_or_warn (abfd);
1557   xfree (name);
1558 }
1559
1560 /* Provide a prototype to silence -Wmissing-prototypes.  */
1561 extern initialize_file_ftype _initialize_objfiles;
1562
1563 void
1564 _initialize_objfiles (void)
1565 {
1566   objfiles_pspace_data
1567     = register_program_space_data_with_cleanup (objfiles_pspace_data_cleanup);
1568 }