* bfd.c (bfd_get_error, bfd_set_error): New functions.
[external/binutils.git] / bfd / linker.c
1 /* linker.c -- BFD linker routines
2    Copyright (C) 1993, 94 Free Software Foundation, Inc.
3    Written by Steve Chamberlain and Ian Lance Taylor, Cygnus Support
4
5 This file is part of BFD, the Binary File Descriptor library.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
20
21 #include "bfd.h"
22 #include "sysdep.h"
23 #include "libbfd.h"
24 #include "bfdlink.h"
25 #include "genlink.h"
26
27 /*
28 SECTION
29         Linker Functions
30
31 @cindex Linker
32         The linker uses three special entry points in the BFD target
33         vector.  It is not necessary to write special routines for
34         these entry points when creating a new BFD back end, since
35         generic versions are provided.  However, writing them can
36         speed up linking and make it use significantly less runtime
37         memory.
38
39         The first routine creates a hash table used by the other
40         routines.  The second routine adds the symbols from an object
41         file to the hash table.  The third routine takes all the
42         object files and links them together to create the output
43         file.  These routines are designed so that the linker proper
44         does not need to know anything about the symbols in the object
45         files that it is linking.  The linker merely arranges the
46         sections as directed by the linker script and lets BFD handle
47         the details of symbols and relocs.
48
49         The second routine and third routines are passed a pointer to
50         a <<struct bfd_link_info>> structure (defined in
51         <<bfdlink.h>>) which holds information relevant to the link,
52         including the linker hash table (which was created by the
53         first routine) and a set of callback functions to the linker
54         proper.
55
56         The generic linker routines are in <<linker.c>>, and use the
57         header file <<genlink.h>>.  As of this writing, the only back
58         ends which have implemented versions of these routines are
59         a.out (in <<aoutx.h>>) and ECOFF (in <<ecoff.c>>).  The a.out
60         routines are used as examples throughout this section.
61
62 @menu   
63 @* Creating a Linker Hash Table::
64 @* Adding Symbols to the Hash Table::
65 @* Performing the Final Link::
66 @end menu
67
68 INODE
69 Creating a Linker Hash Table, Adding Symbols to the Hash Table, Linker Functions, Linker Functions
70 SUBSECTION
71         Creating a linker hash table
72
73 @cindex _bfd_link_hash_table_create in target vector
74 @cindex target vector (_bfd_link_hash_table_create)
75         The linker routines must create a hash table, which must be
76         derived from <<struct bfd_link_hash_table>> described in
77         <<bfdlink.c>>.  @xref{Hash Tables} for information on how to
78         create a derived hash table.  This entry point is called using
79         the target vector of the linker output file.
80
81         The <<_bfd_link_hash_table_create>> entry point must allocate
82         and initialize an instance of the desired hash table.  If the
83         back end does not require any additional information to be
84         stored with the entries in the hash table, the entry point may
85         simply create a <<struct bfd_link_hash_table>>.  Most likely,
86         however, some additional information will be needed.
87
88         For example, with each entry in the hash table the a.out
89         linker keeps the index the symbol has in the final output file
90         (this index number is used so that when doing a relocateable
91         link the symbol index used in the output file can be quickly
92         filled in when copying over a reloc).  The a.out linker code
93         defines the required structures and functions for a hash table
94         derived from <<struct bfd_link_hash_table>>.  The a.out linker
95         hash table is created by the function
96         <<NAME(aout,link_hash_table_create)>>; it simply allocates
97         space for the hash table, initializes it, and returns a
98         pointer to it.
99
100         When writing the linker routines for a new back end, you will
101         generally not know exactly which fields will be required until
102         you have finished.  You should simply create a new hash table
103         which defines no additional fields, and then simply add fields
104         as they become necessary.
105
106 INODE
107 Adding Symbols to the Hash Table, Performing the Final Link, Creating a Linker Hash Table, Linker Functions
108 SUBSECTION
109         Adding symbols to the hash table
110
111 @cindex _bfd_link_add_symbols in target vector
112 @cindex target vector (_bfd_link_add_symbols)
113         The linker proper will call the <<_bfd_link_add_symbols>>
114         entry point for each object file or archive which is to be
115         linked (typically these are the files named on the command
116         line, but some may also come from the linker script).  The
117         entry point is responsible for examining the file.  For an
118         object file, BFD must add any relevant symbol information to
119         the hash table.  For an archive, BFD must determine which
120         elements of the archive should be used and adding them to the
121         link.
122
123         The a.out version of this entry point is
124         <<NAME(aout,link_add_symbols)>>.
125
126 @menu
127 @* Differing file formats::
128 @* Adding symbols from an object file::
129 @* Adding symbols from an archive::
130 @end menu
131
132 INODE
133 Differing file formats, Adding symbols from an object file, Adding Symbols to the Hash Table, Adding Symbols to the Hash Table
134 SUBSUBSECTION
135         Differing file formats
136
137         Normally all the files involved in a link will be of the same
138         format, but it is also possible to link together different
139         format object files, and the back end must support that.  The
140         <<_bfd_link_add_symbols>> entry point is called via the target
141         vector of the file to be added.  This has an important
142         consequence: the function may not assume that the hash table
143         is the type created by the corresponding
144         <<_bfd_link_hash_table_create>> vector.  All the
145         <<_bfd_link_add_symbols>> function can assume about the hash
146         table is that it is derived from <<struct
147         bfd_link_hash_table>>.
148
149         Sometimes the <<_bfd_link_add_symbols>> function must store
150         some information in the hash table entry to be used by the
151         <<_bfd_final_link>> function.  In such a case the <<creator>>
152         field of the hash table must be checked to make sure that the
153         hash table was created by an object file of the same format.
154
155         The <<_bfd_final_link>> routine must be prepared to handle a
156         hash entry without any extra information added by the
157         <<_bfd_link_add_symbols>> function.  A hash entry without
158         extra information will also occur when the linker script
159         directs the linker to create a symbol.  Note that, regardless
160         of how a hash table entry is added, all the fields will be
161         initialized to some sort of null value by the hash table entry
162         initialization function.
163
164         See <<ecoff_link_add_externals>> for an example of how to
165         check the <<creator>> field before saving information (in this
166         case, the ECOFF external symbol debugging information) in a
167         hash table entry.
168
169 INODE
170 Adding symbols from an object file, Adding symbols from an archive, Differing file formats, Adding Symbols to the Hash Table
171 SUBSUBSECTION
172         Adding symbols from an object file
173
174         When the <<_bfd_link_add_symbols>> routine is passed an object
175         file, it must add all externally visible symbols in that
176         object file to the hash table.  The actual work of adding the
177         symbol to the hash table is normally handled by the function
178         <<_bfd_generic_link_add_one_symbol>>.  The
179         <<_bfd_link_add_symbols>> routine is responsible for reading
180         all the symbols from the object file and passing the correct
181         information to <<_bfd_generic_link_add_one_symbol>>.
182
183         The <<_bfd_link_add_symbols>> routine should not use
184         <<bfd_canonicalize_symtab>> to read the symbols.  The point of
185         providing this routine is to avoid the overhead of converting
186         the symbols into generic <<asymbol>> structures.
187
188 @findex _bfd_generic_link_add_one_symbol
189         <<_bfd_generic_link_add_one_symbol>> handles the details of
190         combining common symbols, warning about multiple definitions,
191         and so forth.  It takes arguments which describe the symbol to
192         add, notably symbol flags, a section, and an offset.  The
193         symbol flags include such things as <<BSF_WEAK>> or
194         <<BSF_INDIRECT>>.  The section is a section in the object
195         file, or something like <<bfd_und_section>> for an undefined
196         symbol or <<bfd_com_section>> for a common symbol.
197
198         If the <<_bfd_final_link>> routine is also going to need to
199         read the symbol information, the <<_bfd_link_add_symbols>>
200         routine should save it somewhere attached to the object file
201         BFD.  However, the information should only be saved if the
202         <<keep_memory>> field of the <<info>> argument is true, so
203         that the <<-no-keep-memory>> linker switch is effective.
204
205         The a.out function which adds symbols from an object file is
206         <<aout_link_add_object_symbols>>, and most of the interesting
207         work is in <<aout_link_add_symbols>>.  The latter saves
208         pointers to the hash tables entries created by
209         <<_bfd_generic_link_add_one_symbol>> indexed by symbol number,
210         so that the <<_bfd_final_link>> routine does not have to call
211         the hash table lookup routine to locate the entry.
212
213 INODE
214 Adding symbols from an archive, , Adding symbols from an object file, Adding Symbols to the Hash Table
215 SUBSUBSECTION
216         Adding symbols from an archive
217
218         When the <<_bfd_link_add_symbols>> routine is passed an
219         archive, it must look through the symbols defined by the
220         archive and decide which elements of the archive should be
221         included in the link.  For each such element it must call the
222         <<add_archive_element>> linker callback, and it must add the
223         symbols from the object file to the linker hash table.
224
225 @findex _bfd_generic_link_add_archive_symbols
226         In most cases the work of looking through the symbols in the
227         archive should be done by the
228         <<_bfd_generic_link_add_archive_symbols>> function.  This
229         function builds a hash table from the archive symbol table and
230         looks through the list of undefined symbols to see which
231         elements should be included.
232         <<_bfd_generic_link_add_archive_symbols>> is passed a function
233         to call to make the final decision about adding an archive
234         element to the link and to do the actual work of adding the
235         symbols to the linker hash table.
236
237         The function passed to
238         <<_bfd_generic_link_add_archive_symbols>> must read the
239         symbols of the archive element and decide whether the archive
240         element should be included in the link.  If the element is to
241         be included, the <<add_archive_element>> linker callback
242         routine must be called with the element as an argument, and
243         the elements symbols must be added to the linker hash table
244         just as though the element had itself been passed to the
245         <<_bfd_link_add_symbols>> function.
246
247         When the a.out <<_bfd_link_add_symbols>> function receives an
248         archive, it calls <<_bfd_generic_link_add_archive_symbols>>
249         passing <<aout_link_check_archive_element>> as the function
250         argument. <<aout_link_check_archive_element>> calls
251         <<aout_link_check_ar_symbols>>.  If the latter decides to add
252         the element (an element is only added if it provides a real,
253         non-common, definition for a previously undefined or common
254         symbol) it calls the <<add_archive_element>> callback and then
255         <<aout_link_check_archive_element>> calls
256         <<aout_link_add_symbols>> to actually add the symbols to the
257         linker hash table.
258
259         The ECOFF back end is unusual in that it does not normally
260         call <<_bfd_generic_link_add_archive_symbols>>, because ECOFF
261         archives already contain a hash table of symbols.  The ECOFF
262         back end searches the archive itself to avoid the overhead of
263         creating a new hash table.
264
265 INODE
266 Performing the Final Link, , Adding Symbols to the Hash Table, Linker Functions
267 SUBSECTION
268         Performing the final link
269
270 @cindex _bfd_link_final_link in target vector
271 @cindex target vector (_bfd_final_link)
272         When all the input files have been processed, the linker calls
273         the <<_bfd_final_link>> entry point of the output BFD.  This
274         routine is responsible for producing the final output file,
275         which has several aspects.  It must relocate the contents of
276         the input sections and copy the data into the output sections.
277         It must build an output symbol table including any local
278         symbols from the input files and the global symbols from the
279         hash table.  When producing relocateable output, it must
280         modify the input relocs and write them into the output file.
281         There may also be object format dependent work to be done.
282
283         The linker will also call the <<write_object_contents>> entry
284         point when the BFD is closed.  The two entry points must work
285         together in order to produce the correct output file.
286
287         The details of how this works are inevitably dependent upon
288         the specific object file format.  The a.out
289         <<_bfd_final_link>> routine is <<NAME(aout,final_link)>>.
290
291 @menu
292 @* Information provided by the linker::
293 @* Relocating the section contents::
294 @* Writing the symbol table::
295 @end menu
296
297 INODE
298 Information provided by the linker, Relocating the section contents, Performing the Final Link, Performing the Final Link
299 SUBSUBSECTION
300         Information provided by the linker
301
302         Before the linker calls the <<_bfd_final_link>> entry point,
303         it sets up some data structures for the function to use.
304
305         The <<input_bfds>> field of the <<bfd_link_info>> structure
306         will point to a list of all the input files included in the
307         link.  These files are linked through the <<link_next>> field
308         of the <<bfd>> structure.
309
310         Each section in the output file will have a list of
311         <<link_order>> structures attached to the <<link_order_head>>
312         field (the <<link_order>> structure is defined in
313         <<bfdlink.h>>).  These structures describe how to create the
314         contents of the output section in terms of the contents of
315         various input sections, fill constants, and, eventually, other
316         types of information.
317
318 INODE
319 Relocating the section contents, Writing the symbol table, Information provided by the linker, Performing the Final Link
320 SUBSUBSECTION
321         Relocating the section contents
322
323         The <<_bfd_final_link>> function should look through the
324         <<link_order>> structures attached to each section of the
325         output file.  Each <<link_order>> structure should either be
326         handled specially, or it should be passed to the function
327         <<_bfd_default_link_order>> which will do the right thing
328         (<<_bfd_default_link_order>> is defined in <<linker.c>>).
329
330         For efficiency, a <<link_order>> of type
331         <<bfd_indirect_link_order>> whose associated section belongs
332         to a BFD of the same format as the output BFD must be handled
333         specially.  This type of <<link_order>> describes part of an
334         output section in terms of a section belonging to one of the
335         input files.  The <<_bfd_final_link>> function should read the
336         contents of the section and any associated relocs, apply the
337         relocs to the section contents, and write out the modified
338         section contents.  If performing a relocateable link, the
339         relocs themselves must also be modified and written out.
340
341 @findex _bfd_relocate_contents
342 @findex _bfd_final_link_relocate
343         The functions <<_bfd_relocate_contents>> and
344         <<_bfd_final_link_relocate>> provide some general support for
345         performing the actual relocations, notably overflow checking.
346         Their arguments include information about the symbol the
347         relocation is against and a <<reloc_howto_type>> argument
348         which describes the relocation to perform.  These functions
349         are defined in <<reloc.c>>.
350
351         The a.out function which handles reading, relocating, and
352         writing section contents is <<aout_link_input_section>>.  The
353         actual relocation is done in <<aout_link_input_section_std>>
354         and <<aout_link_input_section_ext>>.
355
356 INODE
357 Writing the symbol table, , Relocating the section contents, Performing the Final Link
358 SUBSUBSECTION
359         Writing the symbol table
360
361         The <<_bfd_final_link>> function must gather all the symbols
362         in the input files and write them out.  It must also write out
363         all the symbols in the global hash table.  This must be
364         controlled by the <<strip>> and <<discard>> fields of the
365         <<bfd_link_info>> structure.
366
367         The local symbols of the input files will not have been
368         entered into the linker hash table.  The <<_bfd_final_link>>
369         routine must consider each input file and include the symbols
370         in the output file.  It may be convenient to do this when
371         looking through the <<link_order>> structures, or it may be
372         done by stepping through the <<input_bfds>> list.
373
374         The <<_bfd_final_link>> routine must also traverse the global
375         hash table to gather all the externally visible symbols.  It
376         is possible that most of the externally visible symbols may be
377         written out when considering the symbols of each input file,
378         but it is still necessary to traverse the hash table since the
379         linker script may have defined some symbols that are not in
380         any of the input files.  The <<written>> field in the
381         <<bfd_link_hash_entry>> structure may be used to determine
382         which entries in the hash table have not already been written
383         out.
384
385         The <<strip>> field of the <<bfd_link_info>> structure
386         controls which symbols are written out.  The possible values
387         are listed in <<bfdlink.h>>.  If the value is <<strip_some>>,
388         then the <<keep_hash>> field of the <<bfd_link_info>>
389         structure is a hash table of symbols to keep; each symbol
390         should be looked up in this hash table, and only symbols which
391         are present should be included in the output file.
392
393         If the <<strip>> field of the <<bfd_link_info>> structure
394         permits local symbols to be written out, the <<discard>> field
395         is used to further controls which local symbols are included
396         in the output file.  If the value is <<discard_l>>, then all
397         local symbols which begin with a certain prefix are discarded;
398         this prefix is described by the <<lprefix>> and
399         <<lprefix_len>> fields of the <<bfd_link_info>> structure.
400
401         The a.out backend handles symbols by calling
402         <<aout_link_write_symbols>> on each input BFD and then
403         traversing the global hash table with the function
404         <<aout_link_write_other_symbol>>.  It builds a string table
405         while writing out the symbols, which is written to the output
406         file at the end of <<NAME(aout,final_link)>>.
407 */
408
409 static struct bfd_hash_entry *generic_link_hash_newfunc
410   PARAMS ((struct bfd_hash_entry *, struct bfd_hash_table *,
411            const char *));
412 static boolean generic_link_add_object_symbols
413   PARAMS ((bfd *, struct bfd_link_info *));
414 static boolean generic_link_check_archive_element
415   PARAMS ((bfd *, struct bfd_link_info *, boolean *pneeded));
416 static boolean generic_link_add_symbol_list
417   PARAMS ((bfd *, struct bfd_link_info *, bfd_size_type count, asymbol **));
418 static boolean generic_add_output_symbol
419   PARAMS ((bfd *, size_t *psymalloc, asymbol *));
420 static boolean default_fill_link_order
421   PARAMS ((bfd *, struct bfd_link_info *, asection *,
422            struct bfd_link_order *));
423 static boolean default_indirect_link_order
424   PARAMS ((bfd *, struct bfd_link_info *, asection *,
425            struct bfd_link_order *));
426
427 /* The link hash table structure is defined in bfdlink.h.  It provides
428    a base hash table which the backend specific hash tables are built
429    upon.  */
430
431 /* Routine to create an entry in the link hash table.  */
432
433 struct bfd_hash_entry *
434 _bfd_link_hash_newfunc (entry, table, string)
435      struct bfd_hash_entry *entry;
436      struct bfd_hash_table *table;
437      const char *string;
438 {
439   struct bfd_link_hash_entry *ret = (struct bfd_link_hash_entry *) entry;
440
441   /* Allocate the structure if it has not already been allocated by a
442      subclass.  */
443   if (ret == (struct bfd_link_hash_entry *) NULL)
444     ret = ((struct bfd_link_hash_entry *)
445            bfd_hash_allocate (table, sizeof (struct bfd_link_hash_entry)));
446   if (ret == (struct bfd_link_hash_entry *) NULL)
447     {
448       bfd_set_error (bfd_error_no_memory);
449       return NULL;
450     }
451
452   /* Call the allocation method of the superclass.  */
453   ret = ((struct bfd_link_hash_entry *)
454          bfd_hash_newfunc ((struct bfd_hash_entry *) ret, table, string));
455
456   if (ret)
457     {
458       /* Initialize the local fields.  */
459       ret->type = bfd_link_hash_new;
460       ret->written = false;
461       ret->next = NULL;
462     }
463
464   return (struct bfd_hash_entry *) ret;
465 }
466
467 /* Initialize a link hash table.  The BFD argument is the one
468    responsible for creating this table.  */
469
470 boolean
471 _bfd_link_hash_table_init (table, abfd, newfunc)
472      struct bfd_link_hash_table *table;
473      bfd *abfd;
474      struct bfd_hash_entry *(*newfunc) PARAMS ((struct bfd_hash_entry *,
475                                                 struct bfd_hash_table *,
476                                                 const char *));
477 {
478   table->creator = abfd->xvec;
479   table->undefs = NULL;
480   table->undefs_tail = NULL;
481   return bfd_hash_table_init (&table->table, newfunc);
482 }
483
484 /* Look up a symbol in a link hash table.  If follow is true, we
485    follow bfd_link_hash_indirect and bfd_link_hash_warning links to
486    the real symbol.  */
487
488 struct bfd_link_hash_entry *
489 bfd_link_hash_lookup (table, string, create, copy, follow)
490      struct bfd_link_hash_table *table;
491      const char *string;
492      boolean create;
493      boolean copy;
494      boolean follow;
495 {
496   struct bfd_link_hash_entry *ret;
497
498   ret = ((struct bfd_link_hash_entry *)
499          bfd_hash_lookup (&table->table, string, create, copy));
500
501   if (follow && ret != (struct bfd_link_hash_entry *) NULL)
502     {
503       while (ret->type == bfd_link_hash_indirect
504              || ret->type == bfd_link_hash_warning)
505         ret = ret->u.i.link;
506     }
507
508   return ret;
509 }
510
511 /* Traverse a generic link hash table.  The only reason this is not a
512    macro is to do better type checking.  This code presumes that an
513    argument passed as a struct bfd_hash_entry * may be caught as a
514    struct bfd_link_hash_entry * with no explicit cast required on the
515    call.  */
516
517 void 
518 bfd_link_hash_traverse (table, func, info)
519      struct bfd_link_hash_table *table;
520      boolean (*func) PARAMS ((struct bfd_link_hash_entry *, PTR));
521      PTR info;
522 {
523   bfd_hash_traverse (&table->table,
524                      ((boolean (*) PARAMS ((struct bfd_hash_entry *, PTR)))
525                       func),
526                      info);
527 }
528
529 /* Add a symbol to the linker hash table undefs list.  */
530
531 INLINE void
532 bfd_link_add_undef (table, h)
533      struct bfd_link_hash_table *table;
534      struct bfd_link_hash_entry *h;
535 {
536   BFD_ASSERT (h->next == NULL);
537   if (table->undefs_tail != (struct bfd_link_hash_entry *) NULL)
538     table->undefs_tail->next = h;
539   if (table->undefs == (struct bfd_link_hash_entry *) NULL)
540     table->undefs = h;
541   table->undefs_tail = h;
542 }
543 \f
544 /* Routine to create an entry in an generic link hash table.  */
545
546 static struct bfd_hash_entry *
547 generic_link_hash_newfunc (entry, table, string)
548      struct bfd_hash_entry *entry;
549      struct bfd_hash_table *table;
550      const char *string;
551 {
552   struct generic_link_hash_entry *ret =
553     (struct generic_link_hash_entry *) entry;
554
555   /* Allocate the structure if it has not already been allocated by a
556      subclass.  */
557   if (ret == (struct generic_link_hash_entry *) NULL)
558     ret = ((struct generic_link_hash_entry *)
559            bfd_hash_allocate (table, sizeof (struct generic_link_hash_entry)));
560   if (ret == (struct generic_link_hash_entry *) NULL)
561     {
562       bfd_set_error (bfd_error_no_memory);
563       return NULL;
564     }
565
566   /* Call the allocation method of the superclass.  */
567   ret = ((struct generic_link_hash_entry *)
568          _bfd_link_hash_newfunc ((struct bfd_hash_entry *) ret,
569                                  table, string));
570
571   if (ret)
572     {
573       /* Set local fields.  */
574       ret->sym = NULL;
575     }
576
577   return (struct bfd_hash_entry *) ret;
578 }
579
580 /* Create an generic link hash table.  */
581
582 struct bfd_link_hash_table *
583 _bfd_generic_link_hash_table_create (abfd)
584      bfd *abfd;
585 {
586   struct generic_link_hash_table *ret;
587
588   ret = ((struct generic_link_hash_table *)
589          malloc (sizeof (struct generic_link_hash_table)));
590   if (!ret)
591       {
592         bfd_set_error (bfd_error_no_memory);
593         return (struct bfd_link_hash_table *) NULL;
594       }
595   if (! _bfd_link_hash_table_init (&ret->root, abfd,
596                                    generic_link_hash_newfunc))
597     {
598       free (ret);
599       return (struct bfd_link_hash_table *) NULL;
600     }
601   return &ret->root;
602 }
603 \f
604 /* Generic function to add symbols from an object file to the global
605    hash table.  */
606
607 boolean
608 _bfd_generic_link_add_symbols (abfd, info)
609      bfd *abfd;
610      struct bfd_link_info *info;
611 {
612   boolean ret;
613
614   switch (bfd_get_format (abfd))
615     {
616     case bfd_object:
617       ret = generic_link_add_object_symbols (abfd, info);
618       break;
619     case bfd_archive:
620       ret = _bfd_generic_link_add_archive_symbols
621         (abfd, info, generic_link_check_archive_element);
622       break;
623     default:
624       bfd_set_error (bfd_error_wrong_format);
625       ret = false;
626     }
627
628   /* If we might be using the C based alloca function, make sure we
629      have dumped the symbol tables we just allocated.  */
630 #ifndef __GNUC__
631 #ifndef alloca
632   alloca (0);
633 #endif
634 #endif
635
636   return ret;
637 }
638
639 /* Add symbols from an object file to the global hash table.  */
640
641 static boolean
642 generic_link_add_object_symbols (abfd, info)
643      bfd *abfd;
644      struct bfd_link_info *info;
645 {
646   size_t symsize;
647   asymbol **symbols;
648   bfd_size_type symbol_count;
649
650   symsize = get_symtab_upper_bound (abfd);
651   symbols = (asymbol **) alloca (symsize);
652   symbol_count = bfd_canonicalize_symtab (abfd, symbols);
653
654   return generic_link_add_symbol_list (abfd, info, symbol_count, symbols);
655 }
656 \f
657 /* We build a hash table of all symbols defined in an archive.  */
658
659 /* An archive symbol may be defined by multiple archive elements.
660    This linked list is used to hold the elements.  */
661
662 struct archive_list
663 {
664   struct archive_list *next;
665   int indx;
666 };
667
668 /* An entry in an archive hash table.  */
669
670 struct archive_hash_entry
671 {
672   struct bfd_hash_entry root;
673   /* Where the symbol is defined.  */
674   struct archive_list *defs;
675 };
676
677 /* An archive hash table itself.  */
678
679 struct archive_hash_table
680 {
681   struct bfd_hash_table table;
682 };
683
684 static struct bfd_hash_entry *archive_hash_newfunc
685   PARAMS ((struct bfd_hash_entry *, struct bfd_hash_table *, const char *));
686 static boolean archive_hash_table_init
687   PARAMS ((struct archive_hash_table *,
688            struct bfd_hash_entry *(*) (struct bfd_hash_entry *,
689                                        struct bfd_hash_table *,
690                                        const char *)));
691
692 /* Create a new entry for an archive hash table.  */
693
694 static struct bfd_hash_entry *
695 archive_hash_newfunc (entry, table, string)
696      struct bfd_hash_entry *entry;
697      struct bfd_hash_table *table;
698      const char *string;
699 {
700   struct archive_hash_entry *ret = (struct archive_hash_entry *) entry;
701
702   /* Allocate the structure if it has not already been allocated by a
703      subclass.  */
704   if (ret == (struct archive_hash_entry *) NULL)
705     ret = ((struct archive_hash_entry *)
706            bfd_hash_allocate (table, sizeof (struct archive_hash_entry)));
707   if (ret == (struct archive_hash_entry *) NULL)
708     {
709       bfd_set_error (bfd_error_no_memory);
710       return NULL;
711     }
712
713   /* Call the allocation method of the superclass.  */
714   ret = ((struct archive_hash_entry *)
715          bfd_hash_newfunc ((struct bfd_hash_entry *) ret, table, string));
716
717   if (ret)
718     {
719       /* Initialize the local fields.  */
720       ret->defs = (struct archive_list *) NULL;
721     }
722
723   return (struct bfd_hash_entry *) ret;
724 }
725
726 /* Initialize an archive hash table.  */
727
728 static boolean
729 archive_hash_table_init (table, newfunc)
730      struct archive_hash_table *table;
731      struct bfd_hash_entry *(*newfunc) PARAMS ((struct bfd_hash_entry *,
732                                                 struct bfd_hash_table *,
733                                                 const char *));
734 {
735   return bfd_hash_table_init (&table->table, newfunc);
736 }
737
738 /* Look up an entry in an archive hash table.  */
739
740 #define archive_hash_lookup(t, string, create, copy) \
741   ((struct archive_hash_entry *) \
742    bfd_hash_lookup (&(t)->table, (string), (create), (copy)))
743
744 /* Free an archive hash table.  */
745
746 #define archive_hash_table_free(t) bfd_hash_table_free (&(t)->table)
747
748 /* Generic function to add symbols from an archive file to the global
749    hash file.  This function presumes that the archive symbol table
750    has already been read in (this is normally done by the
751    bfd_check_format entry point).  It looks through the undefined and
752    common symbols and searches the archive symbol table for them.  If
753    it finds an entry, it includes the associated object file in the
754    link.
755
756    The old linker looked through the archive symbol table for
757    undefined symbols.  We do it the other way around, looking through
758    undefined symbols for symbols defined in the archive.  The
759    advantage of the newer scheme is that we only have to look through
760    the list of undefined symbols once, whereas the old method had to
761    re-search the symbol table each time a new object file was added.
762
763    The CHECKFN argument is used to see if an object file should be
764    included.  CHECKFN should set *PNEEDED to true if the object file
765    should be included, and must also call the bfd_link_info
766    add_archive_element callback function and handle adding the symbols
767    to the global hash table.  CHECKFN should only return false if some
768    sort of error occurs.
769
770    For some formats, such as a.out, it is possible to look through an
771    object file but not actually include it in the link.  The
772    archive_pass field in a BFD is used to avoid checking the symbols
773    of an object files too many times.  When an object is included in
774    the link, archive_pass is set to -1.  If an object is scanned but
775    not included, archive_pass is set to the pass number.  The pass
776    number is incremented each time a new object file is included.  The
777    pass number is used because when a new object file is included it
778    may create new undefined symbols which cause a previously examined
779    object file to be included.  */
780
781 boolean
782 _bfd_generic_link_add_archive_symbols (abfd, info, checkfn)
783      bfd *abfd;
784      struct bfd_link_info *info;
785      boolean (*checkfn) PARAMS ((bfd *, struct bfd_link_info *,
786                                  boolean *pneeded));
787 {
788   carsym *arsyms;
789   carsym *arsym_end;
790   register carsym *arsym;
791   int pass;
792   struct archive_hash_table arsym_hash;
793   int indx;
794   struct bfd_link_hash_entry **pundef;
795
796   if (! bfd_has_map (abfd))
797     {
798       bfd_set_error (bfd_error_no_symbols);
799       return false;
800     }
801
802   arsyms = bfd_ardata (abfd)->symdefs;
803   arsym_end = arsyms + bfd_ardata (abfd)->symdef_count;
804
805   /* In order to quickly determine whether an symbol is defined in
806      this archive, we build a hash table of the symbols.  */
807   if (! archive_hash_table_init (&arsym_hash, archive_hash_newfunc))
808     return false;
809   for (arsym = arsyms, indx = 0; arsym < arsym_end; arsym++, indx++)
810     {
811       struct archive_hash_entry *arh;
812       struct archive_list *l;
813
814       arh = archive_hash_lookup (&arsym_hash, arsym->name, true, false);
815       if (arh == (struct archive_hash_entry *) NULL)
816         return false;
817       l = (struct archive_list *) alloca (sizeof (struct archive_list));
818       l->next = arh->defs;
819       arh->defs = l;
820       l->indx = indx;
821     }
822
823   pass = 1;
824
825   /* New undefined symbols are added to the end of the list, so we
826      only need to look through it once.  */
827   pundef = &info->hash->undefs;
828   while (*pundef != (struct bfd_link_hash_entry *) NULL)
829     {
830       struct bfd_link_hash_entry *h;
831       struct archive_hash_entry *arh;
832       struct archive_list *l;
833
834       h = *pundef;
835
836       /* When a symbol is defined, it is not necessarily removed from
837          the list.  */
838       if (h->type != bfd_link_hash_undefined
839           && h->type != bfd_link_hash_common)
840         {
841           /* Remove this entry from the list, for general cleanliness
842              and because we are going to look through the list again
843              if we search any more libraries.  We can't remove the
844              entry if it is the tail, because that would lose any
845              entries we add to the list later on.  */
846           if (*pundef != info->hash->undefs_tail)
847             *pundef = (*pundef)->next;
848           else
849             pundef = &(*pundef)->next;
850           continue;
851         }
852
853       /* Look for this symbol in the archive symbol map.  */
854       arh = archive_hash_lookup (&arsym_hash, h->root.string, false, false);
855       if (arh == (struct archive_hash_entry *) NULL)
856         {
857           pundef = &(*pundef)->next;
858           continue;
859         }
860
861       /* Look at all the objects which define this symbol.  */
862       for (l = arh->defs; l != (struct archive_list *) NULL; l = l->next)
863         {
864           bfd *element;
865           boolean needed;
866
867           /* If the symbol has gotten defined along the way, quit.  */
868           if (h->type != bfd_link_hash_undefined
869               && h->type != bfd_link_hash_common)
870             break;
871
872           element = bfd_get_elt_at_index (abfd, l->indx);
873           if (element == (bfd *) NULL)
874             return false;
875
876           /* If we've already included this element, or if we've
877              already checked it on this pass, continue.  */
878           if (element->archive_pass == -1
879               || element->archive_pass == pass)
880             continue;
881
882           /* If we can't figure this element out, just ignore it.  */
883           if (! bfd_check_format (element, bfd_object))
884             {
885               element->archive_pass = -1;
886               continue;
887             }
888
889           /* CHECKFN will see if this element should be included, and
890              go ahead and include it if appropriate.  */
891           if (! (*checkfn) (element, info, &needed))
892             return false;
893
894           if (! needed)
895             element->archive_pass = pass;
896           else
897             {
898               element->archive_pass = -1;
899
900               /* Increment the pass count to show that we may need to
901                  recheck object files which were already checked.  */
902               ++pass;
903             }
904         }
905
906       pundef = &(*pundef)->next;
907     }
908
909   archive_hash_table_free (&arsym_hash);
910
911   return true;
912 }
913 \f
914 /* See if we should include an archive element.  */
915
916 static boolean
917 generic_link_check_archive_element (abfd, info, pneeded)
918      bfd *abfd;
919      struct bfd_link_info *info;
920      boolean *pneeded;
921 {
922   size_t symsize;
923   asymbol **symbols;
924   bfd_size_type symbol_count;
925   asymbol **pp, **ppend;
926
927   *pneeded = false;
928
929   symsize = get_symtab_upper_bound (abfd);
930   symbols = (asymbol **) alloca (symsize);
931   symbol_count = bfd_canonicalize_symtab (abfd, symbols);
932
933   pp = symbols;
934   ppend = symbols + symbol_count;
935   for (; pp < ppend; pp++)
936     {
937       asymbol *p;
938       struct bfd_link_hash_entry *h;
939
940       p = *pp;
941
942       /* We are only interested in globally visible symbols.  */
943       if (! bfd_is_com_section (p->section)
944           && (p->flags & (BSF_GLOBAL | BSF_INDIRECT | BSF_WEAK)) == 0)
945         continue;
946
947       /* We are only interested if we know something about this
948          symbol, and it is undefined or common.  An undefined weak
949          symbol (type bfd_link_hash_weak) is not considered to be a
950          reference when pulling files out of an archive.  See the SVR4
951          ABI, p. 4-27.  */
952       h = bfd_link_hash_lookup (info->hash, bfd_asymbol_name (p), false,
953                                 false, true);
954       if (h == (struct bfd_link_hash_entry *) NULL
955           || (h->type != bfd_link_hash_undefined
956               && h->type != bfd_link_hash_common))
957         continue;
958
959       /* P is a symbol we are looking for.  */
960
961       if (! bfd_is_com_section (p->section))
962         {
963           /* This object file defines this symbol, so pull it in.  */
964           if (! (*info->callbacks->add_archive_element) (info, abfd,
965                                                          bfd_asymbol_name (p)))
966             return false;
967           if (! generic_link_add_symbol_list (abfd, info, symbol_count,
968                                               symbols))
969             return false;
970           *pneeded = true;
971           return true;
972         }
973
974       /* P is a common symbol.  */
975
976       if (h->type == bfd_link_hash_undefined)
977         {
978           bfd *symbfd;
979
980           symbfd = h->u.undef.abfd;
981           if (symbfd == (bfd *) NULL)
982             {
983               /* This symbol was created as undefined from outside
984                  BFD.  We assume that we should link in the object
985                  file.  This is for the -u option in the linker.  */
986               if (! (*info->callbacks->add_archive_element)
987                   (info, abfd, bfd_asymbol_name (p)))
988                 return false;
989               *pneeded = true;
990               return true;
991             }
992
993           /* Turn the symbol into a common symbol but do not link in
994              the object file.  This is how a.out works.  Object
995              formats that require different semantics must implement
996              this function differently.  This symbol is already on the
997              undefs list.  We add the section to a common section
998              attached to symbfd to ensure that it is in a BFD which
999              will be linked in.  */
1000           h->type = bfd_link_hash_common;
1001           h->u.c.size = bfd_asymbol_value (p);
1002           if (p->section == &bfd_com_section)
1003             h->u.c.section = bfd_make_section_old_way (symbfd, "COMMON");
1004           else
1005             h->u.c.section = bfd_make_section_old_way (symbfd,
1006                                                        p->section->name);
1007           h->u.c.section->flags = SEC_ALLOC;
1008         }
1009       else
1010         {
1011           /* Adjust the size of the common symbol if necessary.  This
1012              is how a.out works.  Object formats that require
1013              different semantics must implement this function
1014              differently.  */
1015           if (bfd_asymbol_value (p) > h->u.c.size)
1016             h->u.c.size = bfd_asymbol_value (p);
1017         }
1018     }
1019
1020   /* This archive element is not needed.  */
1021   return true;
1022 }
1023
1024 /* Add the symbol from an object file to the global hash table.  */
1025
1026 static boolean
1027 generic_link_add_symbol_list (abfd, info, symbol_count, symbols)
1028      bfd *abfd;
1029      struct bfd_link_info *info;
1030      bfd_size_type symbol_count;
1031      asymbol **symbols;
1032 {
1033   asymbol **pp, **ppend;
1034
1035   pp = symbols;
1036   ppend = symbols + symbol_count;
1037   for (; pp < ppend; pp++)
1038     {
1039       asymbol *p;
1040
1041       p = *pp;
1042
1043       if ((p->flags & (BSF_INDIRECT
1044                        | BSF_WARNING
1045                        | BSF_GLOBAL
1046                        | BSF_CONSTRUCTOR
1047                        | BSF_WEAK)) != 0
1048           || bfd_get_section (p) == &bfd_und_section
1049           || bfd_is_com_section (bfd_get_section (p))
1050           || bfd_get_section (p) == &bfd_ind_section)
1051         {
1052           const char *name;
1053           const char *string;
1054           struct generic_link_hash_entry *h;
1055
1056           name = bfd_asymbol_name (p);
1057           if ((p->flags & BSF_INDIRECT) != 0
1058               || p->section == &bfd_ind_section)
1059             string = bfd_asymbol_name ((asymbol *) p->value);
1060           else if ((p->flags & BSF_WARNING) != 0)
1061             {
1062               /* The name of P is actually the warning string, and the
1063                  value is actually a pointer to the symbol to warn
1064                  about.  */
1065               string = name;
1066               name = bfd_asymbol_name ((asymbol *) p->value);
1067             }
1068           else
1069             string = NULL;
1070
1071           /* We pass the constructor argument as false, for
1072              compatibility.  As backends are converted they can
1073              arrange to pass the right value (the right value is the
1074              size of a function pointer if gcc uses collect2 for the
1075              object file format, zero if it does not).
1076              FIXME: We pass the bitsize as 32, which is just plain
1077              wrong, but actually doesn't matter very much.  */
1078           if (! (_bfd_generic_link_add_one_symbol
1079                  (info, abfd, name, p->flags, bfd_get_section (p),
1080                   p->value, string, false, 0, 32,
1081                   (struct bfd_link_hash_entry **) &h)))
1082             return false;
1083
1084           /* Save the BFD symbol so that we don't lose any backend
1085              specific information that may be attached to it.  We only
1086              want this one if it gives more information than the
1087              existing one; we don't want to replace a defined symbol
1088              with an undefined one.  This routine may be called with a
1089              hash table other than the generic hash table, so we only
1090              do this if we are certain that the hash table is a
1091              generic one.  */
1092           if (info->hash->creator == abfd->xvec)
1093             {
1094               if (h->sym == (asymbol *) NULL
1095                   || (bfd_get_section (p) != &bfd_und_section
1096                       && (! bfd_is_com_section (bfd_get_section (p))
1097                           || (bfd_get_section (h->sym) == &bfd_und_section))))
1098                 {
1099                   h->sym = p;
1100                   /* BSF_OLD_COMMON is a hack to support COFF reloc
1101                      reading, and it should go away when the COFF
1102                      linker is switched to the new version.  */
1103                   if (bfd_is_com_section (bfd_get_section (p)))
1104                     p->flags |= BSF_OLD_COMMON;
1105                 }
1106             }
1107         }
1108     }
1109
1110   return true;
1111 }
1112 \f
1113 /* We use a state table to deal with adding symbols from an object
1114    file.  The first index into the state table describes the symbol
1115    from the object file.  The second index into the state table is the
1116    type of the symbol in the hash table.  */
1117
1118 /* The symbol from the object file is turned into one of these row
1119    values.  */
1120
1121 enum link_row
1122 {
1123   UNDEF_ROW,            /* Undefined.  */
1124   UNDEFW_ROW,           /* Weak undefined.  */
1125   DEF_ROW,              /* Defined.  */
1126   DEFW_ROW,             /* Weak defined.  */
1127   COMMON_ROW,           /* Common.  */
1128   INDR_ROW,             /* Indirect.  */
1129   WARN_ROW,             /* Warning.  */
1130   SET_ROW               /* Member of set.  */
1131 };
1132
1133 /* The actions to take in the state table.  */
1134
1135 enum link_action
1136 {
1137   FAIL,         /* Abort. */
1138   UND,          /* Mark symbol undefined.  */
1139   WEAK,         /* Mark symbol weak undefined.  */
1140   DEF,          /* Mark symbol defined.  */
1141   COM,          /* Mark symbol common.  */
1142   CREF,         /* Possibly warn about common reference to defined symbol.  */
1143   CDEF,         /* Define existing common symbol.  */
1144   NOACT,        /* No action.  */
1145   BIG,          /* Mark symbol common using largest size.  */
1146   MDEF,         /* Multiple definition error.  */
1147   IND,          /* Make indirect symbol.  */
1148   SET,          /* Add value to set.  */
1149   MWARN,        /* Make warning symbol.  */
1150   WARN,         /* Issue warning.  */
1151   CYCLE,        /* Repeat with symbol pointed to.  */
1152   WARNC         /* Issue warning and then CYCLE.  */
1153 };
1154
1155 /* The state table itself.  The first index is a link_row and the
1156    second index is a bfd_link_hash_type.  */
1157
1158 static const enum link_action link_action[8][7] =
1159 {
1160   /* current\prev    new    undef  weak   def    com    indr   warn  */
1161   /* UNDEF_ROW  */  {UND,   NOACT, NOACT, NOACT, NOACT, CYCLE, WARNC },
1162   /* UNDEFW_ROW */  {WEAK,  WEAK,  NOACT, NOACT, NOACT, CYCLE, WARNC },
1163   /* DEF_ROW    */  {DEF,   DEF,   DEF,   MDEF,  CDEF,  CYCLE, CYCLE },
1164   /* DEFW_ROW   */  {DEF,   DEF,   DEF,   NOACT, NOACT, CYCLE, CYCLE },
1165   /* COMMON_ROW */  {COM,   COM,   COM,   CREF,  BIG,   CYCLE, WARNC },
1166   /* INDR_ROW   */  {IND,   IND,   IND,   MDEF,  MDEF,  MDEF,  WARNC },
1167   /* WARN_ROW   */  {MWARN, WARN,  WARN,  MWARN, MWARN, MWARN, NOACT },
1168   /* SET_ROW    */  {SET,   SET,   SET,   SET,   SET,   CYCLE, WARNC }
1169 };
1170
1171 /* Add a symbol to the global hash table.
1172    ABFD is the BFD the symbol comes from.
1173    NAME is the name of the symbol.
1174    FLAGS is the BSF_* bits associated with the symbol.
1175    SECTION is the section in which the symbol is defined; this may be
1176      bfd_und_section or bfd_com_section.
1177    VALUE is the value of the symbol, relative to the section.
1178    STRING is used for either an indirect symbol, in which case it is
1179      the name of the symbol to indirect to, or a warning symbol, in
1180      which case it is the warning string.
1181    COPY is true if NAME or STRING must be copied into locally
1182      allocated memory if they need to be saved.
1183    CONSTRUCTOR is true if we should automatically collect gcc
1184      constructor or destructor names.
1185    BITSIZE is the number of bits in constructor or set entries.
1186    HASHP, if not NULL, is a place to store the created hash table
1187      entry.  */
1188
1189 boolean
1190 _bfd_generic_link_add_one_symbol (info, abfd, name, flags, section, value,
1191                                   string, copy, constructor, bitsize, hashp)
1192      struct bfd_link_info *info;
1193      bfd *abfd;
1194      const char *name;
1195      flagword flags;
1196      asection *section;
1197      bfd_vma value;
1198      const char *string;
1199      boolean copy;
1200      boolean constructor;
1201      unsigned int bitsize;
1202      struct bfd_link_hash_entry **hashp;
1203 {
1204   enum link_row row;
1205   struct bfd_link_hash_entry *h;
1206   boolean cycle;
1207
1208   if (section == &bfd_ind_section
1209       || (flags & BSF_INDIRECT) != 0)
1210     row = INDR_ROW;
1211   else if ((flags & BSF_WARNING) != 0)
1212     row = WARN_ROW;
1213   else if ((flags & BSF_CONSTRUCTOR) != 0)
1214     row = SET_ROW;
1215   else if (section == &bfd_und_section)
1216     {
1217       if ((flags & BSF_WEAK) != 0)
1218         row = UNDEFW_ROW;
1219       else
1220         row = UNDEF_ROW;
1221     }
1222   else if ((flags & BSF_WEAK) != 0)
1223     row = DEFW_ROW;
1224   else if (bfd_is_com_section (section))
1225     row = COMMON_ROW;
1226   else
1227     row = DEF_ROW;
1228
1229   h = bfd_link_hash_lookup (info->hash, name, true, copy, false);
1230   if (h == (struct bfd_link_hash_entry *) NULL)
1231     {
1232       if (hashp != (struct bfd_link_hash_entry **) NULL)
1233         *hashp = NULL;
1234       return false;
1235     }
1236
1237   if (info->notice_hash != (struct bfd_hash_table *) NULL
1238       && (bfd_hash_lookup (info->notice_hash, name, false, false)
1239           != (struct bfd_hash_entry *) NULL))
1240     {
1241       if (! (*info->callbacks->notice) (info, name, abfd, section, value))
1242         return false;
1243     }
1244
1245   if (hashp != (struct bfd_link_hash_entry **) NULL)
1246     *hashp = h;
1247
1248   do
1249     {
1250       enum link_action action;
1251
1252       cycle = false;
1253       action = link_action[(int) row][(int) h->type];
1254       switch (action)
1255         {
1256         case FAIL:
1257           abort ();
1258         case UND:
1259           h->type = bfd_link_hash_undefined;
1260           h->u.undef.abfd = abfd;
1261           bfd_link_add_undef (info->hash, h);
1262           break;
1263         case WEAK:
1264           h->type = bfd_link_hash_weak;
1265           h->u.undef.abfd = abfd;
1266           break;
1267         case CDEF:
1268           BFD_ASSERT (h->type == bfd_link_hash_common);
1269           if (! ((*info->callbacks->multiple_common)
1270                  (info, name,
1271                   h->u.c.section->owner, bfd_link_hash_common, h->u.c.size,
1272                   abfd, bfd_link_hash_defined, (bfd_vma) 0)))
1273             return false;
1274           /* Fall through.  */
1275         case DEF:
1276           h->type = bfd_link_hash_defined;
1277           h->u.def.section = section;
1278           h->u.def.value = value;
1279
1280           /* If we have been asked to, we act like collect2 and
1281              identify all functions that might be global constructors
1282              and destructors and pass them up in a callback.  We only
1283              do this for certain object file types, since many object
1284              file types can handle this automatically.  */
1285           if (constructor && name[0] == '_')
1286             {
1287               const char *s;
1288
1289               /* A constructor or destructor name starts like this:
1290                    _+GLOBAL_[_.$][ID][_.$]
1291                  where the first [_.$] and the second are the same
1292                  character (we accept any character there, in case a
1293                  new object file format comes along with even worse
1294                  naming restrictions).  */
1295
1296 #define CONS_PREFIX "GLOBAL_"
1297 #define CONS_PREFIX_LEN (sizeof CONS_PREFIX - 1)
1298
1299               s = name + 1;
1300               while (*s == '_')
1301                 ++s;
1302               if (s[0] == 'G'
1303                   && strncmp (s, CONS_PREFIX, CONS_PREFIX_LEN - 1) == 0)
1304                 {
1305                   char c;
1306
1307                   c = s[CONS_PREFIX_LEN + 1];
1308                   if ((c == 'I' || c == 'D')
1309                       && s[CONS_PREFIX_LEN] == s[CONS_PREFIX_LEN + 2])
1310                     {
1311                       if (! ((*info->callbacks->constructor)
1312                              (info,
1313                               c == 'I' ? true : false, bitsize,
1314                               name, abfd, section, value)))
1315                         return false;
1316                     }
1317                 }
1318             }
1319
1320           break;
1321         case COM:
1322           if (h->type == bfd_link_hash_new)
1323             bfd_link_add_undef (info->hash, h);
1324           h->type = bfd_link_hash_common;
1325           h->u.c.size = value;
1326           if (section == &bfd_com_section)
1327             {
1328               h->u.c.section = bfd_make_section_old_way (abfd, "COMMON");
1329               h->u.c.section->flags = SEC_ALLOC;
1330             }
1331           else if (section->owner != abfd)
1332             {
1333               h->u.c.section = bfd_make_section_old_way (abfd, section->name);
1334               h->u.c.section->flags = SEC_ALLOC;
1335             }
1336           else
1337             h->u.c.section = section;
1338           break;
1339         case NOACT:
1340           break;
1341         case BIG:
1342           BFD_ASSERT (h->type == bfd_link_hash_common);
1343           if (! ((*info->callbacks->multiple_common)
1344                  (info, name,
1345                   h->u.c.section->owner, bfd_link_hash_common, h->u.c.size,
1346                   abfd, bfd_link_hash_common, value)))
1347             return false;
1348           if (value > h->u.c.size)
1349             h->u.c.size = value;
1350           break;
1351         case CREF:
1352           BFD_ASSERT (h->type == bfd_link_hash_defined);
1353           if (! ((*info->callbacks->multiple_common)
1354                  (info, name,
1355                   h->u.def.section->owner, bfd_link_hash_defined, (bfd_vma) 0,
1356                   abfd, bfd_link_hash_common, value)))
1357             return false;
1358           break;
1359         case MDEF:
1360           {
1361             asection *msec;
1362             bfd_vma mval;
1363
1364             switch (h->type)
1365               {
1366               case bfd_link_hash_defined:
1367                 msec = h->u.def.section;
1368                 mval = h->u.def.value;
1369                 break;
1370               case bfd_link_hash_common:
1371                 msec = &bfd_com_section;
1372                 mval = h->u.c.size;
1373                 break;
1374               case bfd_link_hash_indirect:
1375                 msec = &bfd_ind_section;
1376                 mval = 0;
1377                 break;
1378               default:
1379                 abort ();
1380               }
1381               
1382             if (! ((*info->callbacks->multiple_definition)
1383                    (info, name, msec->owner, msec, mval, abfd, section,
1384                     value)))
1385               return false;
1386           }
1387           break;
1388         case IND:
1389           {
1390             struct bfd_link_hash_entry *inh;
1391
1392             /* STRING is the name of the symbol we want to indirect
1393                to.  */
1394             inh = bfd_link_hash_lookup (info->hash, string, true, copy,
1395                                         false);
1396             if (inh == (struct bfd_link_hash_entry *) NULL)
1397               return false;
1398             if (inh->type == bfd_link_hash_new)
1399               {
1400                 inh->type = bfd_link_hash_undefined;
1401                 inh->u.undef.abfd = abfd;
1402                 bfd_link_add_undef (info->hash, inh);
1403               }
1404             h->type = bfd_link_hash_indirect;
1405             h->u.i.link = inh;
1406           }
1407           break;
1408         case SET:
1409           if (! (*info->callbacks->add_to_set) (info, h, bitsize, abfd,
1410                                                 section, value))
1411             return false;
1412           break;
1413         case WARN:
1414         case WARNC:
1415           if (h->u.i.warning != NULL)
1416             {
1417               if (! (*info->callbacks->warning) (info, h->u.i.warning))
1418                 return false;
1419               /* Only issue a warning once.  */
1420               h->u.i.warning = NULL;
1421             }
1422           if (action == WARN)
1423             break;
1424           /* Fall through.  */
1425         case CYCLE:
1426           h = h->u.i.link;
1427           cycle = true;
1428           break;
1429         case MWARN:
1430           {
1431             struct bfd_link_hash_entry *sub;
1432
1433             /* STRING is the warning to give.  */
1434             sub = ((struct bfd_link_hash_entry *)
1435                    bfd_hash_allocate (&info->hash->table,
1436                                       sizeof (struct bfd_link_hash_entry)));
1437             if (!sub)
1438               {
1439                 bfd_set_error (bfd_error_no_memory);
1440                 return false;
1441               }
1442             *sub = *h;
1443             h->type = bfd_link_hash_warning;
1444             h->u.i.link = sub;
1445             if (! copy)
1446               h->u.i.warning = string;
1447             else
1448               {
1449                 char *w;
1450
1451                 w = bfd_hash_allocate (&info->hash->table,
1452                                        strlen (string) + 1);
1453                 strcpy (w, string);
1454                 h->u.i.warning = w;
1455               }
1456           }
1457           break;
1458         }
1459     }
1460   while (cycle);
1461
1462   return true;
1463 }
1464 \f
1465 /* Generic final link routine.  */
1466
1467 boolean
1468 _bfd_generic_final_link (abfd, info)
1469      bfd *abfd;
1470      struct bfd_link_info *info;
1471 {
1472   bfd *sub;
1473   asection *o;
1474   struct bfd_link_order *p;
1475   size_t outsymalloc;
1476   struct generic_write_global_symbol_info wginfo;
1477
1478   abfd->outsymbols = (asymbol **) NULL;
1479   abfd->symcount = 0;
1480   outsymalloc = 0;
1481
1482   /* Build the output symbol table.  This also reads in the symbols
1483      for all the input BFDs, keeping them in the outsymbols field.  */
1484   for (sub = info->input_bfds; sub != (bfd *) NULL; sub = sub->link_next)
1485     if (! _bfd_generic_link_output_symbols (abfd, sub, info, &outsymalloc))
1486       return false;
1487
1488   /* Accumulate the global symbols.  */
1489   wginfo.info = info;
1490   wginfo.output_bfd = abfd;
1491   wginfo.psymalloc = &outsymalloc;
1492   _bfd_generic_link_hash_traverse (_bfd_generic_hash_table (info),
1493                                    _bfd_generic_link_write_global_symbol,
1494                                    (PTR) &wginfo);
1495
1496   if (info->relocateable)
1497     {
1498       /* Allocate space for the output relocs for each section.  */
1499       for (o = abfd->sections;
1500            o != (asection *) NULL;
1501            o = o->next)
1502         {
1503           o->reloc_count = 0;
1504           for (p = o->link_order_head;
1505                p != (struct bfd_link_order *) NULL;
1506                p = p->next)
1507             {
1508               if (p->type == bfd_indirect_link_order)
1509                 {
1510                   asection *input_section;
1511                   bfd *input_bfd;
1512                   bfd_size_type relsize;
1513                   arelent **relocs;
1514                   bfd_size_type reloc_count;
1515
1516                   input_section = p->u.indirect.section;
1517                   input_bfd = input_section->owner;
1518                   relsize = bfd_get_reloc_upper_bound (input_bfd,
1519                                                        input_section);
1520                   relocs = (arelent **) malloc ((size_t) relsize);
1521                   if (!relocs)
1522                     {
1523                       bfd_set_error (bfd_error_no_memory);
1524                       return false;
1525                     }
1526                   reloc_count =
1527                     bfd_canonicalize_reloc (input_bfd, input_section,
1528                                             relocs,
1529                                             bfd_get_outsymbols (input_bfd));
1530                   BFD_ASSERT (reloc_count == input_section->reloc_count);
1531                   o->reloc_count += reloc_count;
1532                   free (relocs);
1533                 }
1534             }
1535           if (o->reloc_count > 0)
1536             {
1537               o->orelocation = ((arelent **)
1538                                 bfd_alloc (abfd,
1539                                            (o->reloc_count
1540                                             * sizeof (arelent *))));
1541               if (!o->orelocation)
1542                 {
1543                   bfd_set_error (bfd_error_no_memory);
1544                   return false;
1545                 }
1546               /* Reset the count so that it can be used as an index
1547                  when putting in the output relocs.  */
1548               o->reloc_count = 0;
1549             }
1550         }
1551     }
1552
1553   /* Handle all the link order information for the sections.  */
1554   for (o = abfd->sections;
1555        o != (asection *) NULL;
1556        o = o->next)
1557     {
1558       for (p = o->link_order_head;
1559            p != (struct bfd_link_order *) NULL;
1560            p = p->next)
1561         {
1562           if (! _bfd_default_link_order (abfd, info, o, p))
1563             return false;
1564         }
1565     }
1566
1567   return true;
1568 }
1569
1570 /* Add an output symbol to the output BFD.  */
1571
1572 static boolean
1573 generic_add_output_symbol (output_bfd, psymalloc, sym)
1574      bfd *output_bfd;
1575      size_t *psymalloc;
1576      asymbol *sym;
1577 {
1578   if (output_bfd->symcount >= *psymalloc)
1579     {
1580       asymbol **newsyms;
1581
1582       if (*psymalloc == 0)
1583         *psymalloc = 124;
1584       else
1585         *psymalloc *= 2;
1586       if (output_bfd->outsymbols == (asymbol **) NULL)
1587         newsyms = (asymbol **) malloc (*psymalloc * sizeof (asymbol *));
1588       else
1589         newsyms = (asymbol **) realloc (output_bfd->outsymbols,
1590                                         *psymalloc * sizeof (asymbol *));
1591       if (newsyms == (asymbol **) NULL)
1592         {
1593           bfd_set_error (bfd_error_no_memory);
1594           return false;
1595         }
1596       output_bfd->outsymbols = newsyms;
1597     }
1598
1599   output_bfd->outsymbols[output_bfd->symcount] = sym;
1600   ++output_bfd->symcount;
1601
1602   return true;
1603 }
1604
1605 /* Handle the symbols for an input BFD.  */
1606
1607 boolean
1608 _bfd_generic_link_output_symbols (output_bfd, input_bfd, info, psymalloc)
1609      bfd *output_bfd;
1610      bfd *input_bfd;
1611      struct bfd_link_info *info;
1612      size_t *psymalloc;
1613 {
1614   size_t symsize;
1615   asymbol **sym_ptr;
1616   asymbol **sym_end;
1617
1618   symsize = get_symtab_upper_bound (input_bfd);
1619   input_bfd->outsymbols = (asymbol **) bfd_alloc (input_bfd, symsize);
1620   if (!input_bfd->outsymbols)
1621     {
1622       bfd_set_error (bfd_error_no_memory);
1623       return false;
1624     }
1625   input_bfd->symcount = bfd_canonicalize_symtab (input_bfd,
1626                                                  input_bfd->outsymbols);
1627
1628   /* Create a filename symbol if we are supposed to.  */
1629   if (info->create_object_symbols_section != (asection *) NULL)
1630     {
1631       asection *sec;
1632
1633       for (sec = input_bfd->sections;
1634            sec != (asection *) NULL;
1635            sec = sec->next)
1636         {
1637           if (sec->output_section == info->create_object_symbols_section)
1638             {
1639               asymbol *newsym;
1640
1641               newsym = bfd_make_empty_symbol (input_bfd);
1642               if (!newsym)
1643                 return false;
1644               newsym->name = input_bfd->filename;
1645               newsym->value = 0;
1646               newsym->flags = BSF_LOCAL | BSF_FILE;
1647               newsym->section = sec;
1648
1649               if (! generic_add_output_symbol (output_bfd, psymalloc,
1650                                                newsym))
1651                 return false;
1652
1653               break;
1654             }
1655         }
1656     }
1657
1658   /* Adjust the values of the globally visible symbols, and write out
1659      local symbols.  */
1660   sym_ptr = bfd_get_outsymbols (input_bfd);
1661   sym_end = sym_ptr + bfd_get_symcount (input_bfd);
1662   for (; sym_ptr < sym_end; sym_ptr++)
1663     {
1664       asymbol *sym;
1665       struct generic_link_hash_entry *h;
1666       boolean output;
1667
1668       h = (struct generic_link_hash_entry *) NULL;
1669       sym = *sym_ptr;
1670       if ((sym->flags & (BSF_INDIRECT
1671                          | BSF_WARNING
1672                          | BSF_GLOBAL
1673                          | BSF_CONSTRUCTOR
1674                          | BSF_WEAK)) != 0
1675           || bfd_get_section (sym) == &bfd_und_section
1676           || bfd_is_com_section (bfd_get_section (sym))
1677           || bfd_get_section (sym) == &bfd_ind_section)
1678         {
1679           h = _bfd_generic_link_hash_lookup (_bfd_generic_hash_table (info),
1680                                              bfd_asymbol_name (sym),
1681                                              false, false, true);
1682           if (h != (struct generic_link_hash_entry *) NULL)
1683             {
1684               /* Force all references to this symbol to point to
1685                  the same area in memory.  It is possible that
1686                  this routine will be called with a hash table
1687                  other than a generic hash table, so we double
1688                  check that.  */
1689               if (info->hash->creator == input_bfd->xvec)
1690                 {
1691                   if (h->sym != (asymbol *) NULL)
1692                     *sym_ptr = sym = h->sym;
1693                 }
1694
1695               switch (h->root.type)
1696                 {
1697                 default:
1698                 case bfd_link_hash_new:
1699                   abort ();
1700                 case bfd_link_hash_undefined:
1701                 case bfd_link_hash_weak:
1702                   break;
1703                 case bfd_link_hash_defined:
1704                   sym->value = h->root.u.def.value;
1705                   sym->section = h->root.u.def.section;
1706                   sym->flags |= BSF_GLOBAL;
1707                   break;
1708                 case bfd_link_hash_common:
1709                   sym->value = h->root.u.c.size;
1710                   sym->flags |= BSF_GLOBAL;
1711                   if (! bfd_is_com_section (sym->section))
1712                     {
1713                       BFD_ASSERT (sym->section == &bfd_und_section);
1714                       sym->section = &bfd_com_section;
1715                     }
1716                   /* We do not set the section of the symbol to
1717                      h->root.u.c.section.  That value was saved so
1718                      that we would know where to allocate the symbol
1719                      if it was defined.  In this case the type is
1720                      still bfd_link_hash_common, so we did not define
1721                      it, so we do not want to use that section.  */
1722                   break;
1723                 }
1724             }
1725         }
1726
1727       /* This switch is straight from the old code in
1728          write_file_locals in ldsym.c.  */
1729       if (info->strip == strip_some
1730           && (bfd_hash_lookup (info->keep_hash, bfd_asymbol_name (sym),
1731                                false, false)
1732               == (struct bfd_hash_entry *) NULL))
1733         output = false;
1734       else if ((sym->flags & (BSF_GLOBAL | BSF_WEAK)) != 0)
1735         {
1736           /* If this symbol is marked as occurring now, rather
1737              than at the end, output it now.  This is used for
1738              COFF C_EXT FCN symbols.  FIXME: There must be a
1739              better way.  */
1740           if (bfd_asymbol_bfd (sym) == input_bfd
1741               && (sym->flags & BSF_NOT_AT_END) != 0)
1742             output = true;
1743           else
1744             output = false;
1745         }
1746       else if (sym->section == &bfd_ind_section)
1747         output = false;
1748       else if ((sym->flags & BSF_DEBUGGING) != 0)
1749         {
1750           if (info->strip == strip_none)
1751             output = true;
1752           else
1753             output = false;
1754         }
1755       else if (sym->section == &bfd_und_section
1756                || bfd_is_com_section (sym->section))
1757         output = false;
1758       else if ((sym->flags & BSF_LOCAL) != 0)
1759         {
1760           if ((sym->flags & BSF_WARNING) != 0)
1761             output = false;
1762           else
1763             {
1764               switch (info->discard)
1765                 {
1766                 default:
1767                 case discard_all:
1768                   output = false;
1769                   break;
1770                 case discard_l:
1771                   if (bfd_asymbol_name (sym)[0] == info->lprefix[0]
1772                       && (info->lprefix_len == 1
1773                           || strncmp (bfd_asymbol_name (sym), info->lprefix,
1774                                       info->lprefix_len) == 0))
1775                     output = false;
1776                   else
1777                     output = true;
1778                   break;
1779                 case discard_none:
1780                   output = true;
1781                   break;
1782                 }
1783             }
1784         }
1785       else if ((sym->flags & BSF_CONSTRUCTOR))
1786         {
1787           if (info->strip != strip_all)
1788             output = true;
1789           else
1790             output = false;
1791         }
1792       else
1793         abort ();
1794
1795       if (output)
1796         {
1797           if (! generic_add_output_symbol (output_bfd, psymalloc, sym))
1798             return false;
1799           if (h != (struct generic_link_hash_entry *) NULL)
1800             h->root.written = true;
1801         }
1802     }
1803
1804   return true;
1805 }
1806
1807 /* Write out a global symbol, if it hasn't already been written out.
1808    This is called for each symbol in the hash table.  */
1809
1810 boolean
1811 _bfd_generic_link_write_global_symbol (h, data)
1812      struct generic_link_hash_entry *h;
1813      PTR data;
1814 {
1815   struct generic_write_global_symbol_info *wginfo =
1816     (struct generic_write_global_symbol_info *) data;
1817   asymbol *sym;
1818
1819   if (h->root.written)
1820     return true;
1821
1822   h->root.written = true;
1823
1824   if (wginfo->info->strip == strip_all
1825       || (wginfo->info->strip == strip_some
1826           && bfd_hash_lookup (wginfo->info->keep_hash, h->root.root.string,
1827                               false, false) == NULL))
1828     return true;
1829
1830   if (h->sym != (asymbol *) NULL)
1831     {
1832       sym = h->sym;
1833       BFD_ASSERT (strcmp (bfd_asymbol_name (sym), h->root.root.string) == 0);
1834     }
1835   else
1836     {
1837       sym = bfd_make_empty_symbol (wginfo->output_bfd);
1838       if (!sym)
1839         return false;
1840       sym->name = h->root.root.string;
1841       sym->flags = 0;
1842     }
1843
1844   switch (h->root.type)
1845     {
1846     default:
1847     case bfd_link_hash_new:
1848       abort ();
1849     case bfd_link_hash_undefined:
1850       sym->section = &bfd_und_section;
1851       sym->value = 0;
1852       break;
1853     case bfd_link_hash_weak:
1854       sym->section = &bfd_und_section;
1855       sym->value = 0;
1856       sym->flags |= BSF_WEAK;
1857     case bfd_link_hash_defined:
1858       sym->section = h->root.u.def.section;
1859       sym->value = h->root.u.def.value;
1860       break;
1861     case bfd_link_hash_common:
1862       sym->value = h->root.u.c.size;
1863       if (! bfd_is_com_section (sym->section))
1864         {
1865           BFD_ASSERT (sym->section == &bfd_und_section);
1866           sym->section = &bfd_com_section;
1867         }
1868       /* Do not set the section; see _bfd_generic_link_output_symbols.  */
1869       break;
1870     case bfd_link_hash_indirect:
1871     case bfd_link_hash_warning:
1872       /* FIXME: What should we do here?  */
1873       break;
1874     }
1875
1876   sym->flags |= BSF_GLOBAL;
1877
1878   if (! generic_add_output_symbol (wginfo->output_bfd, wginfo->psymalloc,
1879                                    sym))
1880     {
1881       /* FIXME: No way to return failure.  */
1882       abort ();
1883     }
1884
1885   return true;
1886 }
1887 \f
1888 /* Allocate a new link_order for a section.  */
1889
1890 struct bfd_link_order *
1891 bfd_new_link_order (abfd, section)
1892      bfd *abfd;
1893      asection *section;
1894 {
1895   struct bfd_link_order *new;
1896
1897   new = ((struct bfd_link_order *)
1898          bfd_alloc_by_size_t (abfd, sizeof (struct bfd_link_order)));
1899   if (!new)
1900     {
1901       bfd_set_error (bfd_error_no_memory);
1902       return NULL;
1903     }
1904
1905   new->type = bfd_undefined_link_order;
1906   new->offset = 0;
1907   new->size = 0;
1908   new->next = (struct bfd_link_order *) NULL;
1909
1910   if (section->link_order_tail != (struct bfd_link_order *) NULL)
1911     section->link_order_tail->next = new;
1912   else
1913     section->link_order_head = new;
1914   section->link_order_tail = new;
1915
1916   return new;
1917 }
1918
1919 /* Default link order processing routine.  */
1920
1921 boolean
1922 _bfd_default_link_order (abfd, info, sec, link_order)
1923      bfd *abfd;
1924      struct bfd_link_info *info;
1925      asection *sec;
1926      struct bfd_link_order *link_order;
1927 {
1928   switch (link_order->type)
1929     {
1930     case bfd_undefined_link_order:
1931     default:
1932       abort ();
1933     case bfd_indirect_link_order:
1934       return default_indirect_link_order (abfd, info, sec, link_order);
1935     case bfd_fill_link_order:
1936       return default_fill_link_order (abfd, info, sec, link_order);
1937     }
1938 }
1939
1940 /* Default routine to handle a bfd_fill_link_order.  */
1941
1942 /*ARGSUSED*/
1943 static boolean
1944 default_fill_link_order (abfd, info, sec, link_order)
1945      bfd *abfd;
1946      struct bfd_link_info *info;
1947      asection *sec;
1948      struct bfd_link_order *link_order;
1949 {
1950   size_t size;
1951   char *space;
1952   size_t i;
1953   int fill;
1954
1955   BFD_ASSERT ((sec->flags & SEC_HAS_CONTENTS) != 0);
1956
1957   size = (size_t) link_order->size;
1958   space = (char *) alloca (size);
1959   fill = link_order->u.fill.value;
1960   for (i = 0; i < size; i += 2)
1961     space[i] = fill >> 8;
1962   for (i = 1; i < size; i += 2)
1963     space[i] = fill;
1964   return bfd_set_section_contents (abfd, sec, space,
1965                                    (file_ptr) link_order->offset,
1966                                    link_order->size);
1967 }
1968
1969 /* Default routine to handle a bfd_indirect_link_order.  */
1970
1971 static boolean
1972 default_indirect_link_order (output_bfd, info, output_section, link_order)
1973      bfd *output_bfd;
1974      struct bfd_link_info *info;
1975      asection *output_section;
1976      struct bfd_link_order *link_order;
1977 {
1978   asection *input_section;
1979   bfd *input_bfd;
1980   bfd_byte *contents;
1981
1982   BFD_ASSERT ((output_section->flags & SEC_HAS_CONTENTS) != 0);
1983
1984   if (link_order->size == 0)
1985     return true;
1986
1987   input_section = link_order->u.indirect.section;
1988   input_bfd = input_section->owner;
1989
1990   BFD_ASSERT (input_section->output_section == output_section);
1991   BFD_ASSERT (input_section->output_offset == link_order->offset);
1992   BFD_ASSERT (input_section->_cooked_size == link_order->size);
1993
1994   if (info->relocateable
1995       && input_section->reloc_count > 0
1996       && output_section->orelocation == (arelent **) NULL)
1997     {
1998       /* Space has not been allocated for the output relocations.
1999          This can happen when we are called by a specific backend
2000          because somebody is attempting to link together different
2001          types of object files.  Handling this case correctly is
2002          difficult, and sometimes impossible.  */
2003       abort ();
2004     }
2005
2006   /* Get the canonical symbols.  The generic linker will always have
2007      retrieved them by this point, but we may be being called by a
2008      specific linker when linking different types of object files
2009      together.  */
2010   if (bfd_get_outsymbols (input_bfd) == (asymbol **) NULL)
2011     {
2012       size_t symsize;
2013
2014       symsize = get_symtab_upper_bound (input_bfd);
2015       input_bfd->outsymbols = (asymbol **) bfd_alloc (input_bfd, symsize);
2016       if (!input_bfd->outsymbols)
2017         {
2018           bfd_set_error (bfd_error_no_memory);
2019           return false;
2020         }
2021       input_bfd->symcount = bfd_canonicalize_symtab (input_bfd,
2022                                                      input_bfd->outsymbols);
2023     }
2024
2025   /* Get and relocate the section contents.  */
2026   contents = (bfd_byte *) alloca (bfd_section_size (input_bfd, input_section));
2027   contents = (bfd_get_relocated_section_contents
2028               (output_bfd, info, link_order, contents, info->relocateable,
2029                bfd_get_outsymbols (input_bfd)));
2030   if (!contents)
2031     return false;
2032
2033   /* Output the section contents.  */
2034   if (! bfd_set_section_contents (output_bfd, output_section, (PTR) contents,
2035                                   link_order->offset, link_order->size))
2036     return false;
2037
2038   return true;
2039 }