* xcofflink.c (_bfd_xcoff_bfd_link_add_symbols): Do the regular
[external/binutils.git] / bfd / xcofflink.c
1 /* POWER/PowerPC XCOFF linker support.
2    Copyright 1995, 1996 Free Software Foundation, Inc.
3    Written by Ian Lance Taylor <ian@cygnus.com>, 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
20
21 #include "bfd.h"
22 #include "sysdep.h"
23 #include "bfdlink.h"
24 #include "libbfd.h"
25 #include "coff/internal.h"
26 #include "libcoff.h"
27
28 /* This file holds the XCOFF linker code.  */
29
30 #define STRING_SIZE_SIZE (4)
31
32 /* In order to support linking different object file formats into an
33    XCOFF format, we need to be able to determine whether a particular
34    bfd_target is an XCOFF vector.  FIXME: We need to rethink this
35    whole approach.  */
36 #define XCOFF_XVECP(xv) \
37   (strcmp ((xv)->name, "aixcoff-rs6000") == 0 \
38    || strcmp ((xv)->name, "xcoff-powermac") == 0)
39
40 /* Get the XCOFF hash table entries for a BFD.  */
41 #define obj_xcoff_sym_hashes(bfd) \
42   ((struct xcoff_link_hash_entry **) obj_coff_sym_hashes (bfd))
43
44 /* XCOFF relocation types.  These probably belong in a header file
45    somewhere.  The relocations are described in the function
46    _bfd_ppc_xcoff_relocate_section in this file.  */
47
48 #define R_POS   (0x00)
49 #define R_NEG   (0x01)
50 #define R_REL   (0x02)
51 #define R_TOC   (0x03)
52 #define R_RTB   (0x04)
53 #define R_GL    (0x05)
54 #define R_TCL   (0x06)
55 #define R_BA    (0x08)
56 #define R_BR    (0x0a)
57 #define R_RL    (0x0c)
58 #define R_RLA   (0x0d)
59 #define R_REF   (0x0f)
60 #define R_TRL   (0x12)
61 #define R_TRLA  (0x13)
62 #define R_RRTBI (0x14)
63 #define R_RRTBA (0x15)
64 #define R_CAI   (0x16)
65 #define R_CREL  (0x17)
66 #define R_RBA   (0x18)
67 #define R_RBAC  (0x19)
68 #define R_RBR   (0x1a)
69 #define R_RBRC  (0x1b)
70
71 /* The first word of global linkage code.  This must be modified by
72    filling in the correct TOC offset.  */
73
74 #define XCOFF_GLINK_FIRST (0x81820000)  /* lwz r12,0(r2) */
75
76 /* The remaining words of global linkage code.  */
77
78 static unsigned long xcoff_glink_code[] =
79 {
80   0x90410014,   /* stw r2,20(r1) */
81   0x800c0000,   /* lwz r0,0(r12) */
82   0x804c0004,   /* lwz r2,4(r12) */
83   0x7c0903a6,   /* mtctr r0 */
84   0x4e800420,   /* bctr */
85   0x0,          /* start of traceback table */
86   0x000c8000,   /* traceback table */
87   0x0           /* traceback table */
88 };
89
90 #define XCOFF_GLINK_SIZE \
91   (((sizeof xcoff_glink_code / sizeof xcoff_glink_code[0]) * 4) + 4)
92
93 /* We reuse the SEC_ROM flag as a mark flag for garbage collection.
94    This flag will only be used on input sections.  */
95
96 #define SEC_MARK (SEC_ROM)
97
98 /* The ldhdr structure.  This appears at the start of the .loader
99    section.  */
100
101 struct internal_ldhdr
102 {
103   /* The version number: currently always 1.  */
104   unsigned long l_version;
105   /* The number of symbol table entries.  */
106   bfd_size_type l_nsyms;
107   /* The number of relocation table entries.  */
108   bfd_size_type l_nreloc;
109   /* The length of the import file string table.  */
110   bfd_size_type l_istlen;
111   /* The number of import files.  */
112   bfd_size_type l_nimpid;
113   /* The offset from the start of the .loader section to the first
114      entry in the import file table.  */
115   bfd_size_type l_impoff;
116   /* The length of the string table.  */
117   bfd_size_type l_stlen;
118   /* The offset from the start of the .loader section to the first
119      entry in the string table.  */
120   bfd_size_type l_stoff;
121 };
122
123 struct external_ldhdr
124 {
125   bfd_byte l_version[4];
126   bfd_byte l_nsyms[4];
127   bfd_byte l_nreloc[4];
128   bfd_byte l_istlen[4];
129   bfd_byte l_nimpid[4];
130   bfd_byte l_impoff[4];
131   bfd_byte l_stlen[4];
132   bfd_byte l_stoff[4];
133 };
134
135 #define LDHDRSZ (8 * 4)
136
137 /* The ldsym structure.  This is used to represent a symbol in the
138    .loader section.  */
139
140 struct internal_ldsym
141 {
142   union
143     {
144       /* The symbol name if <= SYMNMLEN characters.  */
145       char _l_name[SYMNMLEN];
146       struct
147         {
148           /* Zero if the symbol name is more than SYMNMLEN characters.  */
149           long _l_zeroes;
150           /* The offset in the string table if the symbol name is more
151              than SYMNMLEN characters.  */
152           long _l_offset;
153         } _l_l;
154     } _l;
155   /* The symbol value.  */
156   bfd_vma l_value;
157   /* The symbol section number.  */
158   short l_scnum;
159   /* The symbol type and flags.  */
160   char l_smtype;
161   /* The symbol storage class.  */
162   char l_smclas;
163   /* The import file ID.  */
164   bfd_size_type l_ifile;
165   /* Offset to the parameter type check string.  */
166   bfd_size_type l_parm;
167 };
168
169 struct external_ldsym
170 {
171   union
172     {
173       bfd_byte _l_name[SYMNMLEN];
174       struct
175         {
176           bfd_byte _l_zeroes[4];
177           bfd_byte _l_offset[4];
178         } _l_l;
179     } _l;
180   bfd_byte l_value[4];
181   bfd_byte l_scnum[2];
182   bfd_byte l_smtype[1];
183   bfd_byte l_smclas[1];
184   bfd_byte l_ifile[4];
185   bfd_byte l_parm[4];
186 };
187
188 #define LDSYMSZ (8 + 3 * 4 + 2 + 2)
189
190 /* These flags are for the l_smtype field (the lower three bits are an
191    XTY_* value).  */
192
193 /* Imported symbol.  */
194 #define L_IMPORT (0x40)
195 /* Entry point.  */
196 #define L_ENTRY (0x20)
197 /* Exported symbol.  */
198 #define L_EXPORT (0x10)
199
200 /* The ldrel structure.  This is used to represent a reloc in the
201    .loader section.  */
202
203 struct internal_ldrel
204 {
205   /* The reloc address.  */
206   bfd_vma l_vaddr;
207   /* The symbol table index in the .loader section symbol table.  */
208   bfd_size_type l_symndx;
209   /* The relocation type and size.  */
210   short l_rtype;
211   /* The section number this relocation applies to.  */
212   short l_rsecnm;
213 };
214
215 struct external_ldrel
216 {
217   bfd_byte l_vaddr[4];
218   bfd_byte l_symndx[4];
219   bfd_byte l_rtype[2];
220   bfd_byte l_rsecnm[2];
221 };
222
223 #define LDRELSZ (2 * 4 + 2 * 2)
224
225 /* The list of import files.  */
226
227 struct xcoff_import_file
228 {
229   /* The next entry in the list.  */
230   struct xcoff_import_file *next;
231   /* The path.  */
232   const char *path;
233   /* The file name.  */
234   const char *file;
235   /* The member name.  */
236   const char *member;
237 };
238
239 /* An entry in the XCOFF linker hash table.  */
240
241 struct xcoff_link_hash_entry
242 {
243   struct bfd_link_hash_entry root;
244
245   /* Symbol index in output file.  Set to -1 initially.  Set to -2 if
246      there is a reloc against this symbol.  */
247   long indx;
248
249   /* If we have created a TOC entry for this symbol, this is the .tc
250      section which holds it.  */
251   asection *toc_section;
252
253   union
254     {
255       /* If we have created a TOC entry (the XCOFF_SET_TOC flag is
256          set), this is the offset in toc_section.  */
257       bfd_vma toc_offset;
258       /* If the TOC entry comes from an input file, this is set to the
259          symbol index of the C_HIDEXT XMC_TC or XMC_TD symbol.  */
260       long toc_indx;
261     } u;
262
263   /* If this symbol is a function entry point which is called, this
264      field holds a pointer to the function descriptor.  If this symbol
265      is a function descriptor, this field holds a pointer to the
266      function entry point.  */
267   struct xcoff_link_hash_entry *descriptor;
268
269   /* The .loader symbol table entry, if there is one.  */
270   struct internal_ldsym *ldsym;
271
272   /* The .loader symbol table index.  */
273   long ldindx;
274
275   /* Some linker flags.  */
276   unsigned short flags;
277   /* Symbol is referenced by a regular object.  */
278 #define XCOFF_REF_REGULAR (01)
279   /* Symbol is defined by a regular object.  */
280 #define XCOFF_DEF_REGULAR (02)
281   /* Symbol is defined by a dynamic object.  */
282 #define XCOFF_DEF_DYNAMIC (04)
283   /* Symbol is used in a reloc being copied into the .loader section.  */
284 #define XCOFF_LDREL (010)
285   /* Symbol is the entry point.  */
286 #define XCOFF_ENTRY (020)
287   /* Symbol is called; this is, it appears in a R_BR reloc.  */
288 #define XCOFF_CALLED (040)
289   /* Symbol needs the TOC entry filled in.  */
290 #define XCOFF_SET_TOC (0100)
291   /* Symbol is explicitly imported.  */
292 #define XCOFF_IMPORT (0200)
293   /* Symbol is explicitly exported.  */
294 #define XCOFF_EXPORT (0400)
295   /* Symbol has been processed by xcoff_build_ldsyms.  */
296 #define XCOFF_BUILT_LDSYM (01000)
297   /* Symbol is mentioned by a section which was not garbage collected.  */
298 #define XCOFF_MARK (02000)
299   /* Symbol size is recorded in size_list list from hash table.  */
300 #define XCOFF_HAS_SIZE (04000)
301   /* Symbol is a function descriptor.  */
302 #define XCOFF_DESCRIPTOR (010000)
303
304   /* The storage mapping class.  */
305   unsigned char smclas;
306 };
307
308 /* The XCOFF linker hash table.  */
309
310 struct xcoff_link_hash_table
311 {
312   struct bfd_link_hash_table root;
313
314   /* The .debug string hash table.  We need to compute this while
315      reading the input files, so that we know how large the .debug
316      section will be before we assign section positions.  */
317   struct bfd_strtab_hash *debug_strtab;
318
319   /* The .debug section we will use for the final output.  */
320   asection *debug_section;
321
322   /* The .loader section we will use for the final output.  */
323   asection *loader_section;
324
325   /* A count of non TOC relative relocs which will need to be
326      allocated in the .loader section.  */
327   size_t ldrel_count;
328
329   /* The .loader section header.  */
330   struct internal_ldhdr ldhdr;
331
332   /* The .gl section we use to hold global linkage code.  */
333   asection *linkage_section;
334
335   /* The .tc section we use to hold toc entries we build for global
336      linkage code.  */
337   asection *toc_section;
338
339   /* The .ds section we use to hold function descriptors which we
340      create for exported symbols.  */
341   asection *descriptor_section;
342
343   /* The list of import files.  */
344   struct xcoff_import_file *imports;
345
346   /* Required alignment of sections within the output file.  */
347   unsigned long file_align;
348
349   /* Whether the .text section must be read-only.  */
350   boolean textro;
351
352   /* Whether garbage collection was done.  */
353   boolean gc;
354
355   /* A linked list of symbols for which we have size information.  */
356   struct xcoff_link_size_list
357     {
358       struct xcoff_link_size_list *next;
359       struct xcoff_link_hash_entry *h;
360       bfd_size_type size;
361     } *size_list;
362
363   /* Magic sections: _text, _etext, _data, _edata, _end, end.  */
364   asection *special_sections[6];
365 };
366
367 /* Information we keep for each section in the output file during the
368    final link phase.  */
369
370 struct xcoff_link_section_info
371 {
372   /* The relocs to be output.  */
373   struct internal_reloc *relocs;
374   /* For each reloc against a global symbol whose index was not known
375      when the reloc was handled, the global hash table entry.  */
376   struct xcoff_link_hash_entry **rel_hashes;
377   /* If there is a TOC relative reloc against a global symbol, and the
378      index of the TOC symbol is not known when the reloc was handled,
379      an entry is added to this linked list.  This is not an array,
380      like rel_hashes, because this case is quite uncommon.  */
381   struct xcoff_toc_rel_hash
382     {
383       struct xcoff_toc_rel_hash *next;
384       struct xcoff_link_hash_entry *h;
385       struct internal_reloc *rel;
386     } *toc_rel_hashes;
387 };
388
389 /* Information that we pass around while doing the final link step.  */
390
391 struct xcoff_final_link_info
392 {
393   /* General link information.  */
394   struct bfd_link_info *info;
395   /* Output BFD.  */
396   bfd *output_bfd;
397   /* Hash table for long symbol names.  */
398   struct bfd_strtab_hash *strtab;
399   /* Array of information kept for each output section, indexed by the
400      target_index field.  */
401   struct xcoff_link_section_info *section_info;
402   /* Symbol index of last C_FILE symbol (-1 if none).  */
403   long last_file_index;
404   /* Contents of last C_FILE symbol.  */
405   struct internal_syment last_file;
406   /* Symbol index of TOC symbol.  */
407   long toc_symindx;
408   /* Start of .loader symbols.  */
409   struct external_ldsym *ldsym;
410   /* Next .loader reloc to swap out.  */
411   struct external_ldrel *ldrel;
412   /* File position of start of line numbers.  */
413   file_ptr line_filepos;
414   /* Buffer large enough to hold swapped symbols of any input file.  */
415   struct internal_syment *internal_syms;
416   /* Buffer large enough to hold output indices of symbols of any
417      input file.  */
418   long *sym_indices;
419   /* Buffer large enough to hold output symbols for any input file.  */
420   bfd_byte *outsyms;
421   /* Buffer large enough to hold external line numbers for any input
422      section.  */
423   bfd_byte *linenos;
424   /* Buffer large enough to hold any input section.  */
425   bfd_byte *contents;
426   /* Buffer large enough to hold external relocs of any input section.  */
427   bfd_byte *external_relocs;
428 };
429
430 static void xcoff_swap_ldhdr_in
431   PARAMS ((bfd *, const struct external_ldhdr *, struct internal_ldhdr *));
432 static void xcoff_swap_ldhdr_out
433   PARAMS ((bfd *, const struct internal_ldhdr *, struct external_ldhdr *));
434 static void xcoff_swap_ldsym_in
435   PARAMS ((bfd *, const struct external_ldsym *, struct internal_ldsym *));
436 static void xcoff_swap_ldsym_out
437   PARAMS ((bfd *, const struct internal_ldsym *, struct external_ldsym *));
438 static void xcoff_swap_ldrel_in
439   PARAMS ((bfd *, const struct external_ldrel *, struct internal_ldrel *));
440 static void xcoff_swap_ldrel_out
441   PARAMS ((bfd *, const struct internal_ldrel *, struct external_ldrel *));
442 static struct bfd_hash_entry *xcoff_link_hash_newfunc
443   PARAMS ((struct bfd_hash_entry *, struct bfd_hash_table *, const char *));
444 static struct internal_reloc *xcoff_read_internal_relocs
445   PARAMS ((bfd *, asection *, boolean, bfd_byte *, boolean,
446            struct internal_reloc *));
447 static boolean xcoff_link_add_object_symbols
448   PARAMS ((bfd *, struct bfd_link_info *));
449 static boolean xcoff_link_check_archive_element
450   PARAMS ((bfd *, struct bfd_link_info *, boolean *));
451 static boolean xcoff_link_check_ar_symbols
452   PARAMS ((bfd *, struct bfd_link_info *, boolean *));
453 static boolean xcoff_link_check_dynamic_ar_symbols
454   PARAMS ((bfd *, struct bfd_link_info *, boolean *));
455 static bfd_size_type xcoff_find_reloc
456   PARAMS ((struct internal_reloc *, bfd_size_type, bfd_vma));
457 static boolean xcoff_link_add_symbols PARAMS ((bfd *, struct bfd_link_info *));
458 static boolean xcoff_link_add_dynamic_symbols
459   PARAMS ((bfd *, struct bfd_link_info *));
460 static boolean xcoff_mark PARAMS ((struct bfd_link_info *, asection *));
461 static void xcoff_sweep PARAMS ((struct bfd_link_info *));
462 static boolean xcoff_build_ldsyms
463   PARAMS ((struct xcoff_link_hash_entry *, PTR));
464 static boolean xcoff_link_input_bfd
465   PARAMS ((struct xcoff_final_link_info *, bfd *));
466 static boolean xcoff_write_global_symbol
467   PARAMS ((struct xcoff_link_hash_entry *, PTR));
468 static boolean xcoff_reloc_link_order
469   PARAMS ((bfd *, struct xcoff_final_link_info *, asection *,
470            struct bfd_link_order *));
471 static int xcoff_sort_relocs PARAMS ((const PTR, const PTR));
472 \f
473 /* Routines to swap information in the XCOFF .loader section.  If we
474    ever need to write an XCOFF loader, this stuff will need to be
475    moved to another file shared by the linker (which XCOFF calls the
476    ``binder'') and the loader.  */
477
478 /* Swap in the ldhdr structure.  */
479
480 static void
481 xcoff_swap_ldhdr_in (abfd, src, dst)
482      bfd *abfd;
483      const struct external_ldhdr *src;
484      struct internal_ldhdr *dst;
485 {
486   dst->l_version = bfd_get_32 (abfd, src->l_version);
487   dst->l_nsyms = bfd_get_32 (abfd, src->l_nsyms);
488   dst->l_nreloc = bfd_get_32 (abfd, src->l_nreloc);
489   dst->l_istlen = bfd_get_32 (abfd, src->l_istlen);
490   dst->l_nimpid = bfd_get_32 (abfd, src->l_nimpid);
491   dst->l_impoff = bfd_get_32 (abfd, src->l_impoff);
492   dst->l_stlen = bfd_get_32 (abfd, src->l_stlen);
493   dst->l_stoff = bfd_get_32 (abfd, src->l_stoff);
494 }
495
496 /* Swap out the ldhdr structure.  */
497
498 static void
499 xcoff_swap_ldhdr_out (abfd, src, dst)
500      bfd *abfd;
501      const struct internal_ldhdr *src;
502      struct external_ldhdr *dst;
503 {
504   bfd_put_32 (abfd, src->l_version, dst->l_version);
505   bfd_put_32 (abfd, src->l_nsyms, dst->l_nsyms);
506   bfd_put_32 (abfd, src->l_nreloc, dst->l_nreloc);
507   bfd_put_32 (abfd, src->l_istlen, dst->l_istlen);
508   bfd_put_32 (abfd, src->l_nimpid, dst->l_nimpid);
509   bfd_put_32 (abfd, src->l_impoff, dst->l_impoff);
510   bfd_put_32 (abfd, src->l_stlen, dst->l_stlen);
511   bfd_put_32 (abfd, src->l_stoff, dst->l_stoff);
512 }
513
514 /* Swap in the ldsym structure.  */
515
516 static void
517 xcoff_swap_ldsym_in (abfd, src, dst)
518      bfd *abfd;
519      const struct external_ldsym *src;
520      struct internal_ldsym *dst;
521 {
522   if (bfd_get_32 (abfd, src->_l._l_l._l_zeroes) != 0)
523     memcpy (dst->_l._l_name, src->_l._l_name, SYMNMLEN);
524   else
525     {
526       dst->_l._l_l._l_zeroes = 0;
527       dst->_l._l_l._l_offset = bfd_get_32 (abfd, src->_l._l_l._l_offset);
528     }
529   dst->l_value = bfd_get_32 (abfd, src->l_value);
530   dst->l_scnum = bfd_get_16 (abfd, src->l_scnum);
531   dst->l_smtype = bfd_get_8 (abfd, src->l_smtype);
532   dst->l_smclas = bfd_get_8 (abfd, src->l_smclas);
533   dst->l_ifile = bfd_get_32 (abfd, src->l_ifile);
534   dst->l_parm = bfd_get_32 (abfd, src->l_parm);
535 }
536
537 /* Swap out the ldsym structure.  */
538
539 static void
540 xcoff_swap_ldsym_out (abfd, src, dst)
541      bfd *abfd;
542      const struct internal_ldsym *src;
543      struct external_ldsym *dst;
544 {
545   if (src->_l._l_l._l_zeroes != 0)
546     memcpy (dst->_l._l_name, src->_l._l_name, SYMNMLEN);
547   else
548     {
549       bfd_put_32 (abfd, 0, dst->_l._l_l._l_zeroes);
550       bfd_put_32 (abfd, src->_l._l_l._l_offset, dst->_l._l_l._l_offset);
551     }
552   bfd_put_32 (abfd, src->l_value, dst->l_value);
553   bfd_put_16 (abfd, src->l_scnum, dst->l_scnum);
554   bfd_put_8 (abfd, src->l_smtype, dst->l_smtype);
555   bfd_put_8 (abfd, src->l_smclas, dst->l_smclas);
556   bfd_put_32 (abfd, src->l_ifile, dst->l_ifile);
557   bfd_put_32 (abfd, src->l_parm, dst->l_parm);
558 }
559
560 /* Swap in the ldrel structure.  */
561
562 static void
563 xcoff_swap_ldrel_in (abfd, src, dst)
564      bfd *abfd;
565      const struct external_ldrel *src;
566      struct internal_ldrel *dst;
567 {
568   dst->l_vaddr = bfd_get_32 (abfd, src->l_vaddr);
569   dst->l_symndx = bfd_get_32 (abfd, src->l_symndx);
570   dst->l_rtype = bfd_get_16 (abfd, src->l_rtype);
571   dst->l_rsecnm = bfd_get_16 (abfd, src->l_rsecnm);
572 }
573
574 /* Swap out the ldrel structure.  */
575
576 static void
577 xcoff_swap_ldrel_out (abfd, src, dst)
578      bfd *abfd;
579      const struct internal_ldrel *src;
580      struct external_ldrel *dst;
581 {
582   bfd_put_32 (abfd, src->l_vaddr, dst->l_vaddr);
583   bfd_put_32 (abfd, src->l_symndx, dst->l_symndx);
584   bfd_put_16 (abfd, src->l_rtype, dst->l_rtype);
585   bfd_put_16 (abfd, src->l_rsecnm, dst->l_rsecnm);
586 }
587 \f
588 /* Routines to read XCOFF dynamic information.  This don't really
589    belong here, but we already have the ldsym manipulation routines
590    here.  */
591
592 /* Read the contents of a section.  */
593
594 static boolean
595 xcoff_get_section_contents (abfd, sec)
596      bfd *abfd;
597      asection *sec;
598 {
599   if (coff_section_data (abfd, sec) == NULL)
600     {
601       sec->used_by_bfd = bfd_zalloc (abfd,
602                                      sizeof (struct coff_section_tdata));
603       if (sec->used_by_bfd == NULL)
604         return false;
605     }
606
607   if (coff_section_data (abfd, sec)->contents == NULL)
608     {
609       coff_section_data (abfd, sec)->contents = bfd_malloc (sec->_raw_size);
610       if (coff_section_data (abfd, sec)->contents == NULL)
611         return false;
612
613       if (! bfd_get_section_contents (abfd, sec,
614                                       coff_section_data (abfd, sec)->contents,
615                                       (file_ptr) 0, sec->_raw_size))
616         return false;
617     }
618
619   return true;
620 }
621
622 /* Get the size required to hold the dynamic symbols.  */
623
624 long
625 _bfd_xcoff_get_dynamic_symtab_upper_bound (abfd)
626      bfd *abfd;
627 {
628   asection *lsec;
629   bfd_byte *contents;
630   struct internal_ldhdr ldhdr;
631
632   if ((abfd->flags & DYNAMIC) == 0)
633     {
634       bfd_set_error (bfd_error_invalid_operation);
635       return -1;
636     }
637
638   lsec = bfd_get_section_by_name (abfd, ".loader");
639   if (lsec == NULL)
640     {
641       bfd_set_error (bfd_error_no_symbols);
642       return -1;
643     }
644
645   if (! xcoff_get_section_contents (abfd, lsec))
646     return -1;
647   contents = coff_section_data (abfd, lsec)->contents;
648
649   xcoff_swap_ldhdr_in (abfd, (struct external_ldhdr *) contents, &ldhdr);
650
651   return (ldhdr.l_nsyms + 1) * sizeof (asymbol *);
652 }
653
654 /* Get the dynamic symbols.  */
655
656 long
657 _bfd_xcoff_canonicalize_dynamic_symtab (abfd, psyms)
658      bfd *abfd;
659      asymbol **psyms;
660 {
661   asection *lsec;
662   bfd_byte *contents;
663   struct internal_ldhdr ldhdr;
664   const char *strings;
665   struct external_ldsym *elsym, *elsymend;
666   coff_symbol_type *symbuf;
667
668   if ((abfd->flags & DYNAMIC) == 0)
669     {
670       bfd_set_error (bfd_error_invalid_operation);
671       return -1;
672     }
673
674   lsec = bfd_get_section_by_name (abfd, ".loader");
675   if (lsec == NULL)
676     {
677       bfd_set_error (bfd_error_no_symbols);
678       return -1;
679     }
680
681   if (! xcoff_get_section_contents (abfd, lsec))
682     return -1;
683   contents = coff_section_data (abfd, lsec)->contents;
684
685   coff_section_data (abfd, lsec)->keep_contents = true;
686
687   xcoff_swap_ldhdr_in (abfd, (struct external_ldhdr *) contents, &ldhdr);
688
689   strings = (char *) contents + ldhdr.l_stoff;
690
691   symbuf = ((coff_symbol_type *)
692             bfd_zalloc (abfd, ldhdr.l_nsyms * sizeof (coff_symbol_type)));
693   if (symbuf == NULL)
694     return -1;
695
696   elsym = (struct external_ldsym *) (contents + LDHDRSZ);
697   elsymend = elsym + ldhdr.l_nsyms;
698   for (; elsym < elsymend; elsym++, symbuf++, psyms++)
699     {
700       struct internal_ldsym ldsym;
701
702       xcoff_swap_ldsym_in (abfd, elsym, &ldsym);
703
704       symbuf->symbol.the_bfd = abfd;
705
706       if (ldsym._l._l_l._l_zeroes == 0)
707         symbuf->symbol.name = strings + ldsym._l._l_l._l_offset;
708       else
709         {
710           int i;
711
712           for (i = 0; i < SYMNMLEN; i++)
713             if (ldsym._l._l_name[i] == '\0')
714               break;
715           if (i < SYMNMLEN)
716             symbuf->symbol.name = elsym->_l._l_name;
717           else
718             {
719               char *c;
720
721               c = bfd_alloc (abfd, SYMNMLEN + 1);
722               if (c == NULL)
723                 return -1;
724               memcpy (c, ldsym._l._l_name, SYMNMLEN);
725               c[SYMNMLEN] = '\0';
726               symbuf->symbol.name = c;
727             }
728         }
729
730       if (ldsym.l_smclas == XMC_XO)
731         symbuf->symbol.section = bfd_abs_section_ptr;
732       else
733         symbuf->symbol.section = coff_section_from_bfd_index (abfd,
734                                                               ldsym.l_scnum);
735       symbuf->symbol.value = ldsym.l_value - symbuf->symbol.section->vma;
736
737       symbuf->symbol.flags = BSF_NO_FLAGS;
738       if ((ldsym.l_smtype & L_EXPORT) != 0)
739         symbuf->symbol.flags |= BSF_GLOBAL;
740
741       /* FIXME: We have no way to record the other information stored
742          with the loader symbol.  */
743
744       *psyms = (asymbol *) symbuf;
745     }
746
747   *psyms = NULL;
748
749   return ldhdr.l_nsyms;
750 }
751
752 /* Get the size required to hold the dynamic relocs.  */
753
754 long
755 _bfd_xcoff_get_dynamic_reloc_upper_bound (abfd)
756      bfd *abfd;
757 {
758   asection *lsec;
759   bfd_byte *contents;
760   struct internal_ldhdr ldhdr;
761
762   if ((abfd->flags & DYNAMIC) == 0)
763     {
764       bfd_set_error (bfd_error_invalid_operation);
765       return -1;
766     }
767
768   lsec = bfd_get_section_by_name (abfd, ".loader");
769   if (lsec == NULL)
770     {
771       bfd_set_error (bfd_error_no_symbols);
772       return -1;
773     }
774
775   if (! xcoff_get_section_contents (abfd, lsec))
776     return -1;
777   contents = coff_section_data (abfd, lsec)->contents;
778
779   xcoff_swap_ldhdr_in (abfd, (struct external_ldhdr *) contents, &ldhdr);
780
781   return (ldhdr.l_nreloc + 1) * sizeof (arelent *);
782 }
783
784 /* The typical dynamic reloc.  */
785
786 static reloc_howto_type xcoff_dynamic_reloc =
787   HOWTO (0,                     /* type */                                 
788          0,                     /* rightshift */                           
789          2,                     /* size (0 = byte, 1 = short, 2 = long) */ 
790          32,                    /* bitsize */                   
791          false,                 /* pc_relative */                          
792          0,                     /* bitpos */                               
793          complain_overflow_bitfield, /* complain_on_overflow */
794          0,                     /* special_function */                     
795          "R_POS",               /* name */                                 
796          true,                  /* partial_inplace */                      
797          0xffffffff,            /* src_mask */                             
798          0xffffffff,            /* dst_mask */                             
799          false);                /* pcrel_offset */
800
801 /* Get the dynamic relocs.  */
802
803 long
804 _bfd_xcoff_canonicalize_dynamic_reloc (abfd, prelocs, syms)
805      bfd *abfd;
806      arelent **prelocs;
807      asymbol **syms;
808 {
809   asection *lsec;
810   bfd_byte *contents;
811   struct internal_ldhdr ldhdr;
812   arelent *relbuf;
813   struct external_ldrel *elrel, *elrelend;
814
815   if ((abfd->flags & DYNAMIC) == 0)
816     {
817       bfd_set_error (bfd_error_invalid_operation);
818       return -1;
819     }
820
821   lsec = bfd_get_section_by_name (abfd, ".loader");
822   if (lsec == NULL)
823     {
824       bfd_set_error (bfd_error_no_symbols);
825       return -1;
826     }
827
828   if (! xcoff_get_section_contents (abfd, lsec))
829     return -1;
830   contents = coff_section_data (abfd, lsec)->contents;
831
832   xcoff_swap_ldhdr_in (abfd, (struct external_ldhdr *) contents, &ldhdr);
833
834   relbuf = (arelent *) bfd_alloc (abfd, ldhdr.l_nreloc * sizeof (arelent));
835   if (relbuf == NULL)
836     return -1;
837
838   elrel = ((struct external_ldrel *)
839            (contents + LDHDRSZ + ldhdr.l_nsyms * LDSYMSZ));
840   elrelend = elrel + ldhdr.l_nreloc;
841   for (; elrel < elrelend; elrel++, relbuf++, prelocs++)
842     {
843       struct internal_ldrel ldrel;
844
845       xcoff_swap_ldrel_in (abfd, elrel, &ldrel);
846
847       if (ldrel.l_symndx >= 3)
848         relbuf->sym_ptr_ptr = syms + (ldrel.l_symndx - 3);
849       else
850         {
851           const char *name;
852           asection *sec;
853
854           switch (ldrel.l_symndx)
855             {
856             case 0:
857               name = ".text";
858               break;
859             case 1:
860               name = ".data";
861               break;
862             case 2:
863               name = ".bss";
864               break;
865             default:
866               abort ();
867               break;
868             }
869
870           sec = bfd_get_section_by_name (abfd, name);
871           if (sec == NULL)
872             {
873               bfd_set_error (bfd_error_bad_value);
874               return -1;
875             }
876
877           relbuf->sym_ptr_ptr = sec->symbol_ptr_ptr;
878         }
879
880       relbuf->address = ldrel.l_vaddr;
881       relbuf->addend = 0;
882
883       /* Most dynamic relocs have the same type.  FIXME: This is only
884          correct if ldrel.l_rtype == 0.  In other cases, we should use
885          a different howto.  */
886       relbuf->howto = &xcoff_dynamic_reloc;
887
888       /* FIXME: We have no way to record the l_rsecnm field.  */
889
890       *prelocs = relbuf;
891     }
892
893   *prelocs = NULL;
894
895   return ldhdr.l_nreloc;
896 }
897 \f
898 /* Routine to create an entry in an XCOFF link hash table.  */
899
900 static struct bfd_hash_entry *
901 xcoff_link_hash_newfunc (entry, table, string)
902      struct bfd_hash_entry *entry;
903      struct bfd_hash_table *table;
904      const char *string;
905 {
906   struct xcoff_link_hash_entry *ret = (struct xcoff_link_hash_entry *) entry;
907
908   /* Allocate the structure if it has not already been allocated by a
909      subclass.  */
910   if (ret == (struct xcoff_link_hash_entry *) NULL)
911     ret = ((struct xcoff_link_hash_entry *)
912            bfd_hash_allocate (table, sizeof (struct xcoff_link_hash_entry)));
913   if (ret == (struct xcoff_link_hash_entry *) NULL)
914     return (struct bfd_hash_entry *) ret;
915
916   /* Call the allocation method of the superclass.  */
917   ret = ((struct xcoff_link_hash_entry *)
918          _bfd_link_hash_newfunc ((struct bfd_hash_entry *) ret,
919                                  table, string));
920   if (ret != NULL)
921     {
922       /* Set local fields.  */
923       ret->indx = -1;
924       ret->toc_section = NULL;
925       ret->u.toc_indx = -1;
926       ret->descriptor = NULL;
927       ret->ldsym = NULL;
928       ret->ldindx = -1;
929       ret->flags = 0;
930       ret->smclas = XMC_UA;
931     }
932
933   return (struct bfd_hash_entry *) ret;
934 }
935
936 /* Create a XCOFF link hash table.  */
937
938 struct bfd_link_hash_table *
939 _bfd_xcoff_bfd_link_hash_table_create (abfd)
940      bfd *abfd;
941 {
942   struct xcoff_link_hash_table *ret;
943
944   ret = ((struct xcoff_link_hash_table *)
945          bfd_alloc (abfd, sizeof (struct xcoff_link_hash_table)));
946   if (ret == (struct xcoff_link_hash_table *) NULL)
947     return (struct bfd_link_hash_table *) NULL;
948   if (! _bfd_link_hash_table_init (&ret->root, abfd, xcoff_link_hash_newfunc))
949     {
950       bfd_release (abfd, ret);
951       return (struct bfd_link_hash_table *) NULL;
952     }
953
954   ret->debug_strtab = _bfd_xcoff_stringtab_init ();
955   ret->debug_section = NULL;
956   ret->loader_section = NULL;
957   ret->ldrel_count = 0;
958   memset (&ret->ldhdr, 0, sizeof (struct internal_ldhdr));
959   ret->linkage_section = NULL;
960   ret->toc_section = NULL;
961   ret->descriptor_section = NULL;
962   ret->imports = NULL;
963   ret->file_align = 0;
964   ret->textro = false;
965   ret->gc = false;
966   memset (ret->special_sections, 0, sizeof ret->special_sections);
967
968   /* The linker will always generate a full a.out header.  We need to
969      record that fact now, before the sizeof_headers routine could be
970      called.  */
971   xcoff_data (abfd)->full_aouthdr = true;
972
973   return &ret->root;
974 }
975
976 /* Look up an entry in an XCOFF link hash table.  */
977
978 #define xcoff_link_hash_lookup(table, string, create, copy, follow) \
979   ((struct xcoff_link_hash_entry *) \
980    bfd_link_hash_lookup (&(table)->root, (string), (create), (copy),\
981                          (follow)))
982
983 /* Traverse an XCOFF link hash table.  */
984
985 #define xcoff_link_hash_traverse(table, func, info)                     \
986   (bfd_link_hash_traverse                                               \
987    (&(table)->root,                                                     \
988     (boolean (*) PARAMS ((struct bfd_link_hash_entry *, PTR))) (func),  \
989     (info)))
990
991 /* Get the XCOFF link hash table from the info structure.  This is
992    just a cast.  */
993
994 #define xcoff_hash_table(p) ((struct xcoff_link_hash_table *) ((p)->hash))
995 \f
996 /* Read internal relocs for an XCOFF csect.  This is a wrapper around
997    _bfd_coff_read_internal_relocs which tries to take advantage of any
998    relocs which may have been cached for the enclosing section.  */
999
1000 static struct internal_reloc *
1001 xcoff_read_internal_relocs (abfd, sec, cache, external_relocs,
1002                             require_internal, internal_relocs)
1003      bfd *abfd;
1004      asection *sec;
1005      boolean cache;
1006      bfd_byte *external_relocs;
1007      boolean require_internal;
1008      struct internal_reloc *internal_relocs;
1009 {
1010   if (coff_section_data (abfd, sec) != NULL
1011       && coff_section_data (abfd, sec)->relocs == NULL
1012       && xcoff_section_data (abfd, sec) != NULL)
1013     {
1014       asection *enclosing;
1015
1016       enclosing = xcoff_section_data (abfd, sec)->enclosing;
1017
1018       if (enclosing != NULL
1019           && (coff_section_data (abfd, enclosing) == NULL
1020               || coff_section_data (abfd, enclosing)->relocs == NULL)
1021           && cache
1022           && enclosing->reloc_count > 0)
1023         {
1024           if (_bfd_coff_read_internal_relocs (abfd, enclosing, true,
1025                                               external_relocs, false,
1026                                               (struct internal_reloc *) NULL)
1027               == NULL)
1028             return NULL;
1029         }
1030
1031       if (enclosing != NULL
1032           && coff_section_data (abfd, enclosing) != NULL
1033           && coff_section_data (abfd, enclosing)->relocs != NULL)
1034         {
1035           size_t off;
1036
1037           off = ((sec->rel_filepos - enclosing->rel_filepos)
1038                  / bfd_coff_relsz (abfd));
1039           if (! require_internal)
1040             return coff_section_data (abfd, enclosing)->relocs + off;
1041           memcpy (internal_relocs,
1042                   coff_section_data (abfd, enclosing)->relocs + off,
1043                   sec->reloc_count * sizeof (struct internal_reloc));
1044           return internal_relocs;
1045         }
1046     }
1047
1048   return _bfd_coff_read_internal_relocs (abfd, sec, cache, external_relocs,
1049                                          require_internal, internal_relocs);
1050 }
1051 \f
1052 /* Given an XCOFF BFD, add symbols to the global hash table as
1053    appropriate.  */
1054
1055 boolean
1056 _bfd_xcoff_bfd_link_add_symbols (abfd, info)
1057      bfd *abfd;
1058      struct bfd_link_info *info;
1059 {
1060   switch (bfd_get_format (abfd))
1061     {
1062     case bfd_object:
1063       return xcoff_link_add_object_symbols (abfd, info);
1064
1065     case bfd_archive:
1066       /* If the archive has a map, do the usual search.  We then need
1067          to check the archive for stripped dynamic objects, because
1068          they will not appear in the archive map even though they
1069          should, perhaps, be included.  If the archive has no map, we
1070          just consider each object file in turn, since that apparently
1071          is what the AIX native linker does.  */
1072       if (bfd_has_map (abfd))
1073         {
1074           if (! (_bfd_generic_link_add_archive_symbols
1075                  (abfd, info, xcoff_link_check_archive_element)))
1076             return false;
1077         }
1078
1079       {
1080         bfd *member;
1081
1082         member = bfd_openr_next_archived_file (abfd, (bfd *) NULL);
1083         while (member != NULL)
1084           {
1085             if (bfd_check_format (member, bfd_object)
1086                 && (! bfd_has_map (abfd)
1087                     || ((member->flags & DYNAMIC) != 0
1088                         && (member->flags & HAS_SYMS) == 0)))
1089               {
1090                 boolean needed;
1091
1092                 if (! xcoff_link_check_archive_element (member, info, &needed))
1093                   return false;
1094                 if (needed)
1095                   member->archive_pass = -1;
1096               }
1097             member = bfd_openr_next_archived_file (abfd, member);
1098           }
1099       }
1100
1101       return true;
1102
1103     default:
1104       bfd_set_error (bfd_error_wrong_format);
1105       return false;
1106     }
1107 }
1108
1109 /* Add symbols from an XCOFF object file.  */
1110
1111 static boolean
1112 xcoff_link_add_object_symbols (abfd, info)
1113      bfd *abfd;
1114      struct bfd_link_info *info;
1115 {
1116   if (! _bfd_coff_get_external_symbols (abfd))
1117     return false;
1118   if (! xcoff_link_add_symbols (abfd, info))
1119     return false;
1120   if (! info->keep_memory)
1121     {
1122       if (! _bfd_coff_free_symbols (abfd))
1123         return false;
1124     }
1125   return true;
1126 }
1127
1128 /* Check a single archive element to see if we need to include it in
1129    the link.  *PNEEDED is set according to whether this element is
1130    needed in the link or not.  This is called via
1131    _bfd_generic_link_add_archive_symbols.  */
1132
1133 static boolean
1134 xcoff_link_check_archive_element (abfd, info, pneeded)
1135      bfd *abfd;
1136      struct bfd_link_info *info;
1137      boolean *pneeded;
1138 {
1139   if (! _bfd_coff_get_external_symbols (abfd))
1140     return false;
1141
1142   if (! xcoff_link_check_ar_symbols (abfd, info, pneeded))
1143     return false;
1144
1145   if (*pneeded)
1146     {
1147       if (! xcoff_link_add_symbols (abfd, info))
1148         return false;
1149     }
1150
1151   if (! info->keep_memory || ! *pneeded)
1152     {
1153       if (! _bfd_coff_free_symbols (abfd))
1154         return false;
1155     }
1156
1157   return true;
1158 }
1159
1160 /* Look through the symbols to see if this object file should be
1161    included in the link.  */
1162
1163 static boolean
1164 xcoff_link_check_ar_symbols (abfd, info, pneeded)
1165      bfd *abfd;
1166      struct bfd_link_info *info;
1167      boolean *pneeded;
1168 {
1169   bfd_size_type symesz;
1170   bfd_byte *esym;
1171   bfd_byte *esym_end;
1172
1173   *pneeded = false;
1174
1175   if ((abfd->flags & DYNAMIC) != 0
1176       && ! info->static_link
1177       && info->hash->creator == abfd->xvec)
1178     return xcoff_link_check_dynamic_ar_symbols (abfd, info, pneeded);
1179
1180   symesz = bfd_coff_symesz (abfd);
1181   esym = (bfd_byte *) obj_coff_external_syms (abfd);
1182   esym_end = esym + obj_raw_syment_count (abfd) * symesz;
1183   while (esym < esym_end)
1184     {
1185       struct internal_syment sym;
1186
1187       bfd_coff_swap_sym_in (abfd, (PTR) esym, (PTR) &sym);
1188
1189       if (sym.n_sclass == C_EXT && sym.n_scnum != N_UNDEF)
1190         {
1191           const char *name;
1192           char buf[SYMNMLEN + 1];
1193           struct bfd_link_hash_entry *h;
1194
1195           /* This symbol is externally visible, and is defined by this
1196              object file.  */
1197
1198           name = _bfd_coff_internal_syment_name (abfd, &sym, buf);
1199           if (name == NULL)
1200             return false;
1201           h = bfd_link_hash_lookup (info->hash, name, false, false, true);
1202
1203           /* We are only interested in symbols that are currently
1204              undefined.  If a symbol is currently known to be common,
1205              XCOFF linkers do not bring in an object file which
1206              defines it.  We also don't bring in symbols to satisfy
1207              undefined references in shared objects.  */
1208           if (h != (struct bfd_link_hash_entry *) NULL
1209               && h->type == bfd_link_hash_undefined
1210               && (info->hash->creator != abfd->xvec
1211                   || (((struct xcoff_link_hash_entry *) h)->flags
1212                       & XCOFF_DEF_DYNAMIC) == 0))
1213             {
1214               if (! (*info->callbacks->add_archive_element) (info, abfd, name))
1215                 return false;
1216               *pneeded = true;
1217               return true;
1218             }
1219         }
1220
1221       esym += (sym.n_numaux + 1) * symesz;
1222     }
1223
1224   /* We do not need this object file.  */
1225   return true;
1226 }
1227
1228 /* Look through the loader symbols to see if this dynamic object
1229    should be included in the link.  The native linker uses the loader
1230    symbols, not the normal symbol table, so we do too.  */
1231
1232 static boolean
1233 xcoff_link_check_dynamic_ar_symbols (abfd, info, pneeded)
1234      bfd *abfd;
1235      struct bfd_link_info *info;
1236      boolean *pneeded;
1237 {
1238   asection *lsec;
1239   bfd_byte *buf;
1240   struct internal_ldhdr ldhdr;
1241   const char *strings;
1242   struct external_ldsym *elsym, *elsymend;
1243
1244   *pneeded = false;
1245
1246   lsec = bfd_get_section_by_name (abfd, ".loader");
1247   if (lsec == NULL)
1248     {
1249       /* There are no symbols, so don't try to include it.  */
1250       return true;
1251     }
1252
1253   if (! xcoff_get_section_contents (abfd, lsec))
1254     return false;
1255   buf = coff_section_data (abfd, lsec)->contents;
1256
1257   xcoff_swap_ldhdr_in (abfd, (struct external_ldhdr *) buf, &ldhdr);
1258
1259   strings = (char *) buf + ldhdr.l_stoff;
1260
1261   elsym = (struct external_ldsym *) (buf + LDHDRSZ);
1262   elsymend = elsym + ldhdr.l_nsyms;
1263   for (; elsym < elsymend; elsym++)
1264     {
1265       struct internal_ldsym ldsym;
1266       char nambuf[SYMNMLEN + 1];
1267       const char *name;
1268       struct bfd_link_hash_entry *h;
1269
1270       xcoff_swap_ldsym_in (abfd, elsym, &ldsym);
1271
1272       /* We are only interested in exported symbols.  */
1273       if ((ldsym.l_smtype & L_EXPORT) == 0)
1274         continue;
1275
1276       if (ldsym._l._l_l._l_zeroes == 0)
1277         name = strings + ldsym._l._l_l._l_offset;
1278       else
1279         {
1280           memcpy (nambuf, ldsym._l._l_name, SYMNMLEN);
1281           nambuf[SYMNMLEN] = '\0';
1282           name = nambuf;
1283         }
1284
1285       h = bfd_link_hash_lookup (info->hash, name, false, false, true);
1286
1287       /* We are only interested in symbols that are currently
1288          undefined.  At this point we know that we are using an XCOFF
1289          hash table.  */
1290       if (h != NULL
1291           && h->type == bfd_link_hash_undefined
1292           && (((struct xcoff_link_hash_entry *) h)->flags
1293               & XCOFF_DEF_DYNAMIC) == 0)
1294         {
1295           if (! (*info->callbacks->add_archive_element) (info, abfd, name))
1296             return false;
1297           *pneeded = true;
1298           return true;
1299         }
1300     }
1301
1302   /* We do not need this shared object.  */
1303
1304   if (buf != NULL && ! coff_section_data (abfd, lsec)->keep_contents)
1305     {
1306       free (coff_section_data (abfd, lsec)->contents);
1307       coff_section_data (abfd, lsec)->contents = NULL;
1308     }
1309
1310   return true;
1311 }
1312
1313 /* Returns the index of reloc in RELOCS with the least address greater
1314    than or equal to ADDRESS.  The relocs are sorted by address.  */
1315
1316 static bfd_size_type
1317 xcoff_find_reloc (relocs, count, address)
1318      struct internal_reloc *relocs;
1319      bfd_size_type count;
1320      bfd_vma address;
1321 {
1322   bfd_size_type min, max, this;
1323
1324   if (count < 2)
1325     {
1326       if (count == 1 && relocs[0].r_vaddr < address)
1327         return 1;
1328       else
1329         return 0;
1330     }
1331
1332   min = 0;
1333   max = count;
1334
1335   /* Do a binary search over (min,max].  */
1336   while (min + 1 < max)
1337     {
1338       bfd_vma raddr;
1339
1340       this = (max + min) / 2;
1341       raddr = relocs[this].r_vaddr;
1342       if (raddr > address)
1343         max = this;
1344       else if (raddr < address)
1345         min = this;
1346       else
1347         {
1348           min = this;
1349           break;
1350         }
1351     }
1352
1353   if (relocs[min].r_vaddr < address)
1354     return min + 1;
1355
1356   while (min > 0
1357          && relocs[min - 1].r_vaddr == address)
1358     --min;
1359
1360   return min;
1361 }
1362
1363 /* Add all the symbols from an object file to the hash table.
1364
1365    XCOFF is a weird format.  A normal XCOFF .o files will have three
1366    COFF sections--.text, .data, and .bss--but each COFF section will
1367    contain many csects.  These csects are described in the symbol
1368    table.  From the linker's point of view, each csect must be
1369    considered a section in its own right.  For example, a TOC entry is
1370    handled as a small XMC_TC csect.  The linker must be able to merge
1371    different TOC entries together, which means that it must be able to
1372    extract the XMC_TC csects from the .data section of the input .o
1373    file.
1374
1375    From the point of view of our linker, this is, of course, a hideous
1376    nightmare.  We cope by actually creating sections for each csect,
1377    and discarding the original sections.  We then have to handle the
1378    relocation entries carefully, since the only way to tell which
1379    csect they belong to is to examine the address.  */
1380
1381 static boolean
1382 xcoff_link_add_symbols (abfd, info)
1383      bfd *abfd;
1384      struct bfd_link_info *info;
1385 {
1386   unsigned int n_tmask;
1387   unsigned int n_btshft;
1388   boolean default_copy;
1389   bfd_size_type symcount;
1390   struct xcoff_link_hash_entry **sym_hash;
1391   asection **csect_cache;
1392   bfd_size_type linesz;
1393   asection *o;
1394   asection *last_real;
1395   boolean keep_syms;
1396   asection *csect;
1397   unsigned int csect_index;
1398   asection *first_csect;
1399   bfd_size_type symesz;
1400   bfd_byte *esym;
1401   bfd_byte *esym_end;
1402   struct reloc_info_struct
1403     {
1404       struct internal_reloc *relocs;
1405       asection **csects;
1406       bfd_byte *linenos;
1407     } *reloc_info = NULL;
1408
1409   if ((abfd->flags & DYNAMIC) != 0
1410       && ! info->static_link)
1411     {
1412       if (! xcoff_link_add_dynamic_symbols (abfd, info))
1413         return false;
1414     }
1415
1416   if (info->hash->creator == abfd->xvec)
1417     {
1418       /* We need to build a .loader section, so we do it here.  This
1419          won't work if we're producing an XCOFF output file with no
1420          XCOFF input files.  FIXME.  */
1421       if (xcoff_hash_table (info)->loader_section == NULL)
1422         {
1423           asection *lsec;
1424
1425           lsec = bfd_make_section_anyway (abfd, ".loader");
1426           if (lsec == NULL)
1427             goto error_return;
1428           xcoff_hash_table (info)->loader_section = lsec;
1429           lsec->flags |= SEC_HAS_CONTENTS | SEC_IN_MEMORY;
1430         }
1431       /* Likewise for the linkage section.  */
1432       if (xcoff_hash_table (info)->linkage_section == NULL)
1433         {
1434           asection *lsec;
1435
1436           lsec = bfd_make_section_anyway (abfd, ".gl");
1437           if (lsec == NULL)
1438             goto error_return;
1439           xcoff_hash_table (info)->linkage_section = lsec;
1440           lsec->flags |= (SEC_ALLOC | SEC_LOAD | SEC_HAS_CONTENTS
1441                           | SEC_IN_MEMORY);
1442           lsec->alignment_power = 2;
1443         }
1444       /* Likewise for the TOC section.  */
1445       if (xcoff_hash_table (info)->toc_section == NULL)
1446         {
1447           asection *tsec;
1448
1449           tsec = bfd_make_section_anyway (abfd, ".tc");
1450           if (tsec == NULL)
1451             goto error_return;
1452           xcoff_hash_table (info)->toc_section = tsec;
1453           tsec->flags |= (SEC_ALLOC | SEC_LOAD | SEC_HAS_CONTENTS
1454                           | SEC_IN_MEMORY);
1455           tsec->alignment_power = 2;
1456         }
1457       /* Likewise for the descriptor section.  */
1458       if (xcoff_hash_table (info)->descriptor_section == NULL)
1459         {
1460           asection *dsec;
1461
1462           dsec = bfd_make_section_anyway (abfd, ".ds");
1463           if (dsec == NULL)
1464             goto error_return;
1465           xcoff_hash_table (info)->descriptor_section = dsec;
1466           dsec->flags |= (SEC_ALLOC | SEC_LOAD | SEC_HAS_CONTENTS
1467                           | SEC_IN_MEMORY);
1468           dsec->alignment_power = 2;
1469         }
1470       /* Likewise for the .debug section.  */
1471       if (xcoff_hash_table (info)->debug_section == NULL)
1472         {
1473           asection *dsec;
1474
1475           dsec = bfd_make_section_anyway (abfd, ".debug");
1476           if (dsec == NULL)
1477             goto error_return;
1478           xcoff_hash_table (info)->debug_section = dsec;
1479           dsec->flags |= SEC_HAS_CONTENTS | SEC_IN_MEMORY;
1480         }
1481     }
1482
1483   if ((abfd->flags & DYNAMIC) != 0
1484       && ! info->static_link)
1485     return true;
1486
1487   n_tmask = coff_data (abfd)->local_n_tmask;
1488   n_btshft = coff_data (abfd)->local_n_btshft;
1489
1490   /* Define macros so that ISFCN, et. al., macros work correctly.  */
1491 #define N_TMASK n_tmask
1492 #define N_BTSHFT n_btshft
1493
1494   if (info->keep_memory)
1495     default_copy = false;
1496   else
1497     default_copy = true;
1498
1499   symcount = obj_raw_syment_count (abfd);
1500
1501   /* We keep a list of the linker hash table entries that correspond
1502      to each external symbol.  */
1503   sym_hash = ((struct xcoff_link_hash_entry **)
1504               bfd_alloc (abfd,
1505                          (symcount
1506                           * sizeof (struct xcoff_link_hash_entry *))));
1507   if (sym_hash == NULL && symcount != 0)
1508     goto error_return;
1509   coff_data (abfd)->sym_hashes = (struct coff_link_hash_entry **) sym_hash;
1510   memset (sym_hash, 0,
1511           (size_t) symcount * sizeof (struct xcoff_link_hash_entry *));
1512
1513   /* Because of the weird stuff we are doing with XCOFF csects, we can
1514      not easily determine which section a symbol is in, so we store
1515      the information in the tdata for the input file.  */
1516   csect_cache = ((asection **)
1517                  bfd_alloc (abfd, symcount * sizeof (asection *)));
1518   if (csect_cache == NULL && symcount != 0)
1519     goto error_return;
1520   xcoff_data (abfd)->csects = csect_cache;
1521   memset (csect_cache, 0, (size_t) symcount * sizeof (asection *));
1522
1523   /* While splitting sections into csects, we need to assign the
1524      relocs correctly.  The relocs and the csects must both be in
1525      order by VMA within a given section, so we handle this by
1526      scanning along the relocs as we process the csects.  We index
1527      into reloc_info using the section target_index.  */
1528   reloc_info = ((struct reloc_info_struct *)
1529                 bfd_malloc ((abfd->section_count + 1)
1530                             * sizeof (struct reloc_info_struct)));
1531   if (reloc_info == NULL)
1532     goto error_return;
1533   memset ((PTR) reloc_info, 0,
1534           (abfd->section_count + 1) * sizeof (struct reloc_info_struct));
1535
1536   /* Read in the relocs and line numbers for each section.  */
1537   linesz = bfd_coff_linesz (abfd);
1538   last_real = NULL;
1539   for (o = abfd->sections; o != NULL; o = o->next)
1540     {
1541       last_real = o;
1542       if ((o->flags & SEC_RELOC) != 0)
1543         {
1544           reloc_info[o->target_index].relocs =
1545             xcoff_read_internal_relocs (abfd, o, true, (bfd_byte *) NULL,
1546                                         false, (struct internal_reloc *) NULL);
1547           reloc_info[o->target_index].csects =
1548             (asection **) bfd_malloc (o->reloc_count * sizeof (asection *));
1549           if (reloc_info[o->target_index].csects == NULL)
1550             goto error_return;
1551           memset (reloc_info[o->target_index].csects, 0,
1552                   o->reloc_count * sizeof (asection *));
1553         }
1554
1555       if ((info->strip == strip_none || info->strip == strip_some)
1556           && o->lineno_count > 0)
1557         {
1558           bfd_byte *linenos;
1559
1560           linenos = (bfd_byte *) bfd_malloc (o->lineno_count * linesz);
1561           if (linenos == NULL)
1562             goto error_return;
1563           reloc_info[o->target_index].linenos = linenos;
1564           if (bfd_seek (abfd, o->line_filepos, SEEK_SET) != 0
1565               || (bfd_read (linenos, linesz, o->lineno_count, abfd)
1566                   != linesz * o->lineno_count))
1567             goto error_return;
1568         }
1569     }
1570
1571   /* Don't let the linker relocation routines discard the symbols.  */
1572   keep_syms = obj_coff_keep_syms (abfd);
1573   obj_coff_keep_syms (abfd) = true;
1574
1575   csect = NULL;
1576   csect_index = 0;
1577   first_csect = NULL;
1578
1579   symesz = bfd_coff_symesz (abfd);
1580   BFD_ASSERT (symesz == bfd_coff_auxesz (abfd));
1581   esym = (bfd_byte *) obj_coff_external_syms (abfd);
1582   esym_end = esym + symcount * symesz;
1583   while (esym < esym_end)
1584     {
1585       struct internal_syment sym;
1586       union internal_auxent aux;
1587       const char *name;
1588       char buf[SYMNMLEN + 1];
1589       int smtyp;
1590       flagword flags;
1591       asection *section;
1592       bfd_vma value;
1593       struct xcoff_link_hash_entry *set_toc;
1594
1595       bfd_coff_swap_sym_in (abfd, (PTR) esym, (PTR) &sym);
1596
1597       /* In this pass we are only interested in symbols with csect
1598          information.  */
1599       if (sym.n_sclass != C_EXT && sym.n_sclass != C_HIDEXT)
1600         {
1601           if (sym.n_sclass == C_FILE && csect != NULL)
1602             {
1603               xcoff_section_data (abfd, csect)->last_symndx =
1604                 ((esym
1605                   - (bfd_byte *) obj_coff_external_syms (abfd))
1606                  / symesz);
1607               csect = NULL;
1608             }
1609
1610           if (csect != NULL)
1611             *csect_cache = csect;
1612           else if (first_csect == NULL || sym.n_sclass == C_FILE)
1613             *csect_cache = coff_section_from_bfd_index (abfd, sym.n_scnum);
1614           else
1615             *csect_cache = NULL;
1616           esym += (sym.n_numaux + 1) * symesz;
1617           sym_hash += sym.n_numaux + 1;
1618           csect_cache += sym.n_numaux + 1;
1619           continue;
1620         }
1621
1622       name = _bfd_coff_internal_syment_name (abfd, &sym, buf);
1623       if (name == NULL)
1624         goto error_return;
1625
1626       /* If this symbol has line number information attached to it,
1627          and we're not stripping it, count the number of entries and
1628          add them to the count for this csect.  In the final link pass
1629          we are going to attach line number information by symbol,
1630          rather than by section, in order to more easily handle
1631          garbage collection.  */
1632       if ((info->strip == strip_none || info->strip == strip_some)
1633           && sym.n_numaux > 1
1634           && csect != NULL
1635           && ISFCN (sym.n_type))
1636         {
1637           union internal_auxent auxlin;
1638
1639           bfd_coff_swap_aux_in (abfd, (PTR) (esym + symesz),
1640                                 sym.n_type, sym.n_sclass,
1641                                 0, sym.n_numaux, (PTR) &auxlin);
1642           if (auxlin.x_sym.x_fcnary.x_fcn.x_lnnoptr != 0)
1643             {
1644               asection *enclosing;
1645               bfd_size_type linoff;
1646
1647               enclosing = xcoff_section_data (abfd, csect)->enclosing;
1648               if (enclosing == NULL)
1649                 {
1650                   (*_bfd_error_handler)
1651                     ("%s: `%s' has line numbers but no enclosing section",
1652                      bfd_get_filename (abfd), name);
1653                   bfd_set_error (bfd_error_bad_value);
1654                   goto error_return;
1655                 }
1656               linoff = (auxlin.x_sym.x_fcnary.x_fcn.x_lnnoptr
1657                         - enclosing->line_filepos);
1658               if (linoff < enclosing->lineno_count * linesz)
1659                 {
1660                   struct internal_lineno lin;
1661                   bfd_byte *linpstart;
1662
1663                   linpstart = (reloc_info[enclosing->target_index].linenos
1664                                + linoff);
1665                   bfd_coff_swap_lineno_in (abfd, (PTR) linpstart, (PTR) &lin);
1666                   if (lin.l_lnno == 0
1667                       && ((bfd_size_type) lin.l_addr.l_symndx
1668                           == ((esym
1669                                - (bfd_byte *) obj_coff_external_syms (abfd))
1670                               / symesz)))
1671                     {
1672                       bfd_byte *linpend, *linp;
1673
1674                       linpend = (reloc_info[enclosing->target_index].linenos
1675                                  + enclosing->lineno_count * linesz);
1676                       for (linp = linpstart + linesz;
1677                            linp < linpend;
1678                            linp += linesz)
1679                         {
1680                           bfd_coff_swap_lineno_in (abfd, (PTR) linp,
1681                                                    (PTR) &lin);
1682                           if (lin.l_lnno == 0)
1683                             break;
1684                         }
1685                       csect->lineno_count += (linp - linpstart) / linesz;
1686                       /* The setting of line_filepos will only be
1687                          useful if all the line number entries for a
1688                          csect are contiguous; this only matters for
1689                          error reporting.  */
1690                       if (csect->line_filepos == 0)
1691                         csect->line_filepos =
1692                           auxlin.x_sym.x_fcnary.x_fcn.x_lnnoptr;
1693                     }
1694                 }
1695             }
1696         }
1697
1698       /* Pick up the csect auxiliary information.  */
1699
1700       if (sym.n_numaux == 0)
1701         {
1702           (*_bfd_error_handler)
1703             ("%s: class %d symbol `%s' has no aux entries",
1704              bfd_get_filename (abfd), sym.n_sclass, name);
1705           bfd_set_error (bfd_error_bad_value);
1706           goto error_return;
1707         }
1708
1709       bfd_coff_swap_aux_in (abfd,
1710                             (PTR) (esym + symesz * sym.n_numaux),
1711                             sym.n_type, sym.n_sclass,
1712                             sym.n_numaux - 1, sym.n_numaux,
1713                             (PTR) &aux);
1714
1715       smtyp = SMTYP_SMTYP (aux.x_csect.x_smtyp);
1716
1717       flags = BSF_GLOBAL;
1718       section = NULL;
1719       value = 0;
1720       set_toc = NULL;
1721
1722       switch (smtyp)
1723         {
1724         default:
1725           (*_bfd_error_handler)
1726             ("%s: symbol `%s' has unrecognized csect type %d",
1727              bfd_get_filename (abfd), name, smtyp);
1728           bfd_set_error (bfd_error_bad_value);
1729           goto error_return;
1730
1731         case XTY_ER:
1732           /* This is an external reference.  */
1733           if (sym.n_sclass == C_HIDEXT
1734               || sym.n_scnum != N_UNDEF
1735               || aux.x_csect.x_scnlen.l != 0)
1736             {
1737               (*_bfd_error_handler)
1738                 ("%s: bad XTY_ER symbol `%s': class %d scnum %d scnlen %d",
1739                  bfd_get_filename (abfd), name, sym.n_sclass, sym.n_scnum,
1740                  aux.x_csect.x_scnlen.l);
1741               bfd_set_error (bfd_error_bad_value);
1742               goto error_return;
1743             }
1744
1745           /* An XMC_XO external reference is actually a reference to
1746              an absolute location.  */
1747           if (aux.x_csect.x_smclas != XMC_XO)
1748             section = bfd_und_section_ptr;
1749           else
1750             {
1751               section = bfd_abs_section_ptr;
1752               value = sym.n_value;
1753             }
1754           break;
1755
1756         case XTY_SD:
1757           /* This is a csect definition.  */
1758
1759           if (csect != NULL)
1760             {
1761               xcoff_section_data (abfd, csect)->last_symndx =
1762                 ((esym
1763                   - (bfd_byte *) obj_coff_external_syms (abfd))
1764                  / symesz);
1765             }
1766
1767           csect = NULL;
1768           csect_index = -1;
1769
1770           /* When we see a TOC anchor, we record the TOC value.  */
1771           if (aux.x_csect.x_smclas == XMC_TC0)
1772             {
1773               if (sym.n_sclass != C_HIDEXT
1774                   || aux.x_csect.x_scnlen.l != 0)
1775                 {
1776                   (*_bfd_error_handler)
1777                     ("%s: XMC_TC0 symbol `%s' is class %d scnlen %d",
1778                      bfd_get_filename (abfd), name, sym.n_sclass,
1779                      aux.x_csect.x_scnlen.l);
1780                   bfd_set_error (bfd_error_bad_value);
1781                   goto error_return;
1782                 }
1783               xcoff_data (abfd)->toc = sym.n_value;
1784             }
1785
1786           /* We must merge TOC entries for the same symbol.  We can
1787              merge two TOC entries if they are both C_HIDEXT, they
1788              both have the same name, they are both 4 bytes long, and
1789              they both have a relocation table entry for an external
1790              symbol with the same name.  Unfortunately, this means
1791              that we must look through the relocations.  Ick.  */
1792           if (aux.x_csect.x_smclas == XMC_TC
1793               && sym.n_sclass == C_HIDEXT
1794               && aux.x_csect.x_scnlen.l == 4
1795               && info->hash->creator == abfd->xvec)
1796             {
1797               asection *enclosing;
1798               struct internal_reloc *relocs;
1799               bfd_size_type relindx;
1800               struct internal_reloc *rel;
1801
1802               enclosing = coff_section_from_bfd_index (abfd, sym.n_scnum);
1803               if (enclosing == NULL)
1804                 goto error_return;
1805
1806               relocs = reloc_info[enclosing->target_index].relocs;
1807               relindx = xcoff_find_reloc (relocs, enclosing->reloc_count,
1808                                           sym.n_value);
1809               rel = relocs + relindx;
1810               if (relindx < enclosing->reloc_count
1811                   && rel->r_vaddr == (bfd_vma) sym.n_value
1812                   && rel->r_size == 31
1813                   && rel->r_type == R_POS)
1814                 {
1815                   bfd_byte *erelsym;
1816                   struct internal_syment relsym;
1817
1818                   erelsym = ((bfd_byte *) obj_coff_external_syms (abfd)
1819                              + rel->r_symndx * symesz);
1820                   bfd_coff_swap_sym_in (abfd, (PTR) erelsym, (PTR) &relsym);
1821                   if (relsym.n_sclass == C_EXT)
1822                     {
1823                       const char *relname;
1824                       char relbuf[SYMNMLEN + 1];
1825                       boolean copy;
1826                       struct xcoff_link_hash_entry *h;
1827
1828                       /* At this point we know that the TOC entry is
1829                          for an externally visible symbol.  */
1830                       relname = _bfd_coff_internal_syment_name (abfd, &relsym,
1831                                                                 relbuf);
1832                       if (relname == NULL)
1833                         goto error_return;
1834
1835                       /* We only merge TOC entries if the TC name is
1836                          the same as the symbol name.  This handles
1837                          the normal case, but not common cases like
1838                          SYM.P4 which gcc generates to store SYM + 4
1839                          in the TOC.  FIXME.  */
1840                       if (strcmp (name, relname) == 0)
1841                         {
1842                           copy = (! info->keep_memory
1843                                   || relsym._n._n_n._n_zeroes != 0
1844                                   || relsym._n._n_n._n_offset == 0);
1845                           h = xcoff_link_hash_lookup (xcoff_hash_table (info),
1846                                                       relname, true, copy,
1847                                                       false);
1848                           if (h == NULL)
1849                             goto error_return;
1850
1851                           /* At this point h->root.type could be
1852                              bfd_link_hash_new.  That should be OK,
1853                              since we know for sure that we will come
1854                              across this symbol as we step through the
1855                              file.  */
1856
1857                           /* We store h in *sym_hash for the
1858                              convenience of the relocate_section
1859                              function.  */
1860                           *sym_hash = h;
1861
1862                           if (h->toc_section != NULL)
1863                             {
1864                               asection **rel_csects;
1865
1866                               /* We already have a TOC entry for this
1867                                  symbol, so we can just ignore this
1868                                  one.  */
1869                               rel_csects =
1870                                 reloc_info[enclosing->target_index].csects;
1871                               rel_csects[relindx] = bfd_und_section_ptr;
1872                               break;
1873                             }
1874
1875                           /* We are about to create a TOC entry for
1876                              this symbol.  */
1877                           set_toc = h;
1878                         }
1879                     }
1880                 }
1881             }
1882
1883           /* We need to create a new section.  We get the name from
1884              the csect storage mapping class, so that the linker can
1885              accumulate similar csects together.  */
1886           {
1887             static const char *csect_name_by_class[] =
1888               {
1889                 ".pr", ".ro", ".db", ".tc", ".ua", ".rw", ".gl", ".xo",
1890                 ".sv", ".bs", ".ds", ".uc", ".ti", ".tb", NULL, ".tc0",
1891                 ".td"
1892               };
1893             const char *csect_name;
1894             asection *enclosing;
1895
1896             if ((aux.x_csect.x_smclas >=
1897                  sizeof csect_name_by_class / sizeof csect_name_by_class[0])
1898                 || csect_name_by_class[aux.x_csect.x_smclas] == NULL)
1899               {
1900                 (*_bfd_error_handler)
1901                   ("%s: symbol `%s' has unrecognized smclas %d",
1902                    bfd_get_filename (abfd), name, aux.x_csect.x_smclas);
1903                 bfd_set_error (bfd_error_bad_value);
1904                 goto error_return;
1905               }
1906
1907             csect_name = csect_name_by_class[aux.x_csect.x_smclas];
1908             csect = bfd_make_section_anyway (abfd, csect_name);
1909             if (csect == NULL)
1910               goto error_return;
1911             enclosing = coff_section_from_bfd_index (abfd, sym.n_scnum);
1912             if (enclosing == NULL)
1913               goto error_return;
1914             if (! bfd_is_abs_section (enclosing)
1915                 && ((bfd_vma) sym.n_value < enclosing->vma
1916                     || ((bfd_vma) sym.n_value + aux.x_csect.x_scnlen.l
1917                         > enclosing->vma + enclosing->_raw_size)))
1918               {
1919                 (*_bfd_error_handler)
1920                   ("%s: csect `%s' not in enclosing section",
1921                    bfd_get_filename (abfd), name);
1922                 bfd_set_error (bfd_error_bad_value);
1923                 goto error_return;
1924               }
1925             csect->vma = sym.n_value;
1926             csect->filepos = (enclosing->filepos
1927                               + sym.n_value
1928                               - enclosing->vma);
1929             csect->_raw_size = aux.x_csect.x_scnlen.l;
1930             csect->flags |= SEC_ALLOC | SEC_LOAD | SEC_HAS_CONTENTS;
1931             csect->alignment_power = SMTYP_ALIGN (aux.x_csect.x_smtyp);
1932
1933             /* Record the enclosing section in the tdata for this new
1934                section.  */
1935             csect->used_by_bfd =
1936               ((struct coff_section_tdata *)
1937                bfd_zalloc (abfd, sizeof (struct coff_section_tdata)));
1938             if (csect->used_by_bfd == NULL)
1939               goto error_return;
1940             coff_section_data (abfd, csect)->tdata =
1941               bfd_zalloc (abfd, sizeof (struct xcoff_section_tdata));
1942             if (coff_section_data (abfd, csect)->tdata == NULL)
1943               goto error_return;
1944             xcoff_section_data (abfd, csect)->enclosing = enclosing;
1945             xcoff_section_data (abfd, csect)->lineno_count =
1946               enclosing->lineno_count;
1947
1948             if (enclosing->owner == abfd)
1949               {
1950                 struct internal_reloc *relocs;
1951                 bfd_size_type relindx;
1952                 struct internal_reloc *rel;
1953                 asection **rel_csect;
1954
1955                 relocs = reloc_info[enclosing->target_index].relocs;
1956                 relindx = xcoff_find_reloc (relocs, enclosing->reloc_count,
1957                                             csect->vma);
1958                 rel = relocs + relindx;
1959                 rel_csect = (reloc_info[enclosing->target_index].csects
1960                              + relindx);
1961                 csect->rel_filepos = (enclosing->rel_filepos
1962                                       + relindx * bfd_coff_relsz (abfd));
1963                 while (relindx < enclosing->reloc_count
1964                        && *rel_csect == NULL
1965                        && rel->r_vaddr < csect->vma + csect->_raw_size)
1966                   {
1967                     *rel_csect = csect;
1968                     csect->flags |= SEC_RELOC;
1969                     ++csect->reloc_count;
1970                     ++relindx;
1971                     ++rel;
1972                     ++rel_csect;
1973                   }
1974               }
1975
1976             /* There are a number of other fields and section flags
1977                which we do not bother to set.  */
1978
1979             csect_index = ((esym
1980                             - (bfd_byte *) obj_coff_external_syms (abfd))
1981                            / symesz);
1982
1983             xcoff_section_data (abfd, csect)->first_symndx = csect_index;
1984
1985             if (first_csect == NULL)
1986               first_csect = csect;
1987
1988             /* If this symbol is C_EXT, we treat it as starting at the
1989                beginning of the newly created section.  */
1990             if (sym.n_sclass == C_EXT)
1991               {
1992                 section = csect;
1993                 value = 0;
1994               }
1995
1996             /* If this is a TOC section for a symbol, record it.  */
1997             if (set_toc != NULL)
1998               set_toc->toc_section = csect;
1999           }
2000           break;
2001
2002         case XTY_LD:
2003           /* This is a label definition.  The x_scnlen field is the
2004              symbol index of the csect.  I believe that this must
2005              always follow the appropriate XTY_SD symbol, so I will
2006              insist on it.  */
2007           {
2008             boolean bad;
2009
2010             bad = false;
2011             if (aux.x_csect.x_scnlen.l < 0
2012                 || (aux.x_csect.x_scnlen.l
2013                     >= esym - (bfd_byte *) obj_coff_external_syms (abfd)))
2014               bad = true;
2015             if (! bad)
2016               {
2017                 section = xcoff_data (abfd)->csects[aux.x_csect.x_scnlen.l];
2018                 if (section == NULL
2019                     || (section->flags & SEC_HAS_CONTENTS) == 0)
2020                   bad = true;
2021               }
2022             if (bad)
2023               {
2024                 (*_bfd_error_handler)
2025                   ("%s: misplaced XTY_LD `%s'",
2026                    bfd_get_filename (abfd), name);
2027                 bfd_set_error (bfd_error_bad_value);
2028                 goto error_return;
2029               }
2030
2031             value = sym.n_value - csect->vma;
2032           }
2033           break;
2034
2035         case XTY_CM:
2036           /* This is an unitialized csect.  We could base the name on
2037              the storage mapping class, but we don't bother.  If this
2038              csect is externally visible, it is a common symbol.  */
2039
2040           if (csect != NULL)
2041             {
2042               xcoff_section_data (abfd, csect)->last_symndx =
2043                 ((esym
2044                   - (bfd_byte *) obj_coff_external_syms (abfd))
2045                  / symesz);
2046             }
2047
2048           csect = bfd_make_section_anyway (abfd, ".bss");
2049           if (csect == NULL)
2050             goto error_return;
2051           csect->vma = sym.n_value;
2052           csect->_raw_size = aux.x_csect.x_scnlen.l;
2053           csect->flags |= SEC_ALLOC;
2054           csect->alignment_power = SMTYP_ALIGN (aux.x_csect.x_smtyp);
2055           /* There are a number of other fields and section flags
2056              which we do not bother to set.  */
2057
2058           csect_index = ((esym
2059                           - (bfd_byte *) obj_coff_external_syms (abfd))
2060                          / symesz);
2061
2062           csect->used_by_bfd =
2063             ((struct coff_section_tdata *)
2064              bfd_zalloc (abfd, sizeof (struct coff_section_tdata)));
2065           if (csect->used_by_bfd == NULL)
2066             goto error_return;
2067           coff_section_data (abfd, csect)->tdata =
2068             bfd_zalloc (abfd, sizeof (struct xcoff_section_tdata));
2069           if (coff_section_data (abfd, csect)->tdata == NULL)
2070             goto error_return;
2071           xcoff_section_data (abfd, csect)->first_symndx = csect_index;
2072
2073           if (first_csect == NULL)
2074             first_csect = csect;
2075
2076           if (sym.n_sclass == C_EXT)
2077             {
2078               csect->flags |= SEC_IS_COMMON;
2079               csect->_raw_size = 0;
2080               section = csect;
2081               value = aux.x_csect.x_scnlen.l;
2082             }
2083
2084           break;
2085         }
2086
2087       /* Check for magic symbol names.  */
2088       if ((smtyp == XTY_SD || smtyp == XTY_CM)
2089           && aux.x_csect.x_smclas != XMC_TC
2090           && aux.x_csect.x_smclas != XMC_TD)
2091         {
2092           int i;
2093
2094           i = -1;
2095           if (name[0] == '_')
2096             {
2097               if (strcmp (name, "_text") == 0)
2098                 i = 0;
2099               else if (strcmp (name, "_etext") == 0)
2100                 i = 1;
2101               else if (strcmp (name, "_data") == 0)
2102                 i = 2;
2103               else if (strcmp (name, "_edata") == 0)
2104                 i = 3;
2105               else if (strcmp (name, "_end") == 0)
2106                 i = 4;
2107             }
2108           else if (name[0] == 'e' && strcmp (name, "end") == 0)
2109             i = 5;
2110
2111           if (i != -1)
2112             xcoff_hash_table (info)->special_sections[i] = csect;
2113         }
2114
2115       /* Now we have enough information to add the symbol to the
2116          linker hash table.  */
2117
2118       if (sym.n_sclass == C_EXT)
2119         {
2120           boolean copy;
2121
2122           BFD_ASSERT (section != NULL);
2123
2124           /* We must copy the name into memory if we got it from the
2125              syment itself, rather than the string table.  */
2126           copy = default_copy;
2127           if (sym._n._n_n._n_zeroes != 0
2128               || sym._n._n_n._n_offset == 0)
2129             copy = true;
2130
2131           if (info->hash->creator == abfd->xvec)
2132             {
2133               /* If we are statically linking a shared object, it is
2134                  OK for symbol redefinitions to occur.  I can't figure
2135                  out just what the XCOFF linker is doing, but
2136                  something like this is required for -bnso to work.  */
2137               if (! bfd_is_und_section (section))
2138                 *sym_hash = xcoff_link_hash_lookup (xcoff_hash_table (info),
2139                                                     name, true, copy, false);
2140               else
2141                 *sym_hash = ((struct xcoff_link_hash_entry *)
2142                              bfd_wrapped_link_hash_lookup (abfd, info, name,
2143                                                            true, copy, false));
2144               if (*sym_hash == NULL)
2145                 goto error_return;
2146               if (((*sym_hash)->root.type == bfd_link_hash_defined
2147                    || (*sym_hash)->root.type == bfd_link_hash_defweak)
2148                   && ! bfd_is_und_section (section)
2149                   && ! bfd_is_com_section (section))
2150                 {
2151                   /* If the existing symbol is to global linkage code,
2152                      and this symbol is not global linkage code, then
2153                      replace the existing symbol.  */
2154                   if ((abfd->flags & DYNAMIC) != 0
2155                       && ((*sym_hash)->smclas != XMC_GL
2156                           || aux.x_csect.x_smclas == XMC_GL
2157                           || ((*sym_hash)->root.u.def.section->owner->flags
2158                               & DYNAMIC) == 0))
2159                     {
2160                       section = bfd_und_section_ptr;
2161                       value = 0;
2162                     }
2163                   else if (((*sym_hash)->root.u.def.section->owner->flags
2164                             & DYNAMIC) != 0)
2165                     {
2166                       (*sym_hash)->root.type = bfd_link_hash_undefined;
2167                       (*sym_hash)->root.u.undef.abfd =
2168                         (*sym_hash)->root.u.def.section->owner;
2169                     }
2170                 }
2171             }
2172
2173           /* _bfd_generic_link_add_one_symbol may call the linker to
2174              generate an error message, and the linker may try to read
2175              the symbol table to give a good error.  Right now, the
2176              line numbers are in an inconsistent state, since they are
2177              counted both in the real sections and in the new csects.
2178              We need to leave the count in the real sections so that
2179              the linker can report the line number of the error
2180              correctly, so temporarily clobber the link to the csects
2181              so that the linker will not try to read the line numbers
2182              a second time from the csects.  */
2183           BFD_ASSERT (last_real->next == first_csect);
2184           last_real->next = NULL;
2185           if (! (_bfd_generic_link_add_one_symbol
2186                  (info, abfd, name, flags, section, value,
2187                   (const char *) NULL, copy, true,
2188                   (struct bfd_link_hash_entry **) sym_hash)))
2189             goto error_return;
2190           last_real->next = first_csect;
2191
2192           if (smtyp == XTY_CM)
2193             {
2194               if ((*sym_hash)->root.type != bfd_link_hash_common
2195                   || (*sym_hash)->root.u.c.p->section != csect)
2196                 {
2197                   /* We don't need the common csect we just created.  */
2198                   csect->_raw_size = 0;
2199                 }
2200               else
2201                 {
2202                   (*sym_hash)->root.u.c.p->alignment_power
2203                      = csect->alignment_power;
2204                 }
2205             }
2206
2207           if (info->hash->creator == abfd->xvec)
2208             {
2209               int flag;
2210
2211               if (smtyp == XTY_ER || smtyp == XTY_CM)
2212                 flag = XCOFF_REF_REGULAR;
2213               else
2214                 flag = XCOFF_DEF_REGULAR;
2215               (*sym_hash)->flags |= flag;
2216
2217               if ((*sym_hash)->smclas == XMC_UA
2218                   || flag == XCOFF_DEF_REGULAR)
2219                 (*sym_hash)->smclas = aux.x_csect.x_smclas;
2220             }
2221         }
2222
2223       *csect_cache = csect;
2224
2225       esym += (sym.n_numaux + 1) * symesz;
2226       sym_hash += sym.n_numaux + 1;
2227       csect_cache += sym.n_numaux + 1;
2228     }
2229
2230   BFD_ASSERT (last_real == NULL || last_real->next == first_csect);
2231
2232   /* Make sure that we have seen all the relocs.  */
2233   for (o = abfd->sections; o != first_csect; o = o->next)
2234     {
2235       /* Reset the section size and the line number count, since the
2236          data is now attached to the csects.  Don't reset the size of
2237          the .debug section, since we need to read it below in
2238          bfd_xcoff_size_dynamic_sections.  */
2239       if (strcmp (bfd_get_section_name (abfd, o), ".debug") != 0)
2240         o->_raw_size = 0;
2241       o->lineno_count = 0;
2242
2243       if ((o->flags & SEC_RELOC) != 0)
2244         {
2245           bfd_size_type i;
2246           struct internal_reloc *rel;
2247           asection **rel_csect;
2248
2249           rel = reloc_info[o->target_index].relocs;
2250           rel_csect = reloc_info[o->target_index].csects;
2251           for (i = 0; i < o->reloc_count; i++, rel++, rel_csect++)
2252             {
2253               if (*rel_csect == NULL)
2254                 {
2255                   (*_bfd_error_handler)
2256                     ("%s: reloc %s:%d not in csect",
2257                      bfd_get_filename (abfd), o->name, i);
2258                   bfd_set_error (bfd_error_bad_value);
2259                   goto error_return;
2260                 }
2261
2262               /* We identify all symbols which are called, so that we
2263                  can create glue code for calls to functions imported
2264                  from dynamic objects.  */
2265               if (info->hash->creator == abfd->xvec
2266                   && *rel_csect != bfd_und_section_ptr
2267                   && (rel->r_type == R_BR
2268                       || rel->r_type == R_RBR)
2269                   && obj_xcoff_sym_hashes (abfd)[rel->r_symndx] != NULL)
2270                 {
2271                   struct xcoff_link_hash_entry *h;
2272
2273                   h = obj_xcoff_sym_hashes (abfd)[rel->r_symndx];
2274                   h->flags |= XCOFF_CALLED;
2275                   /* If the symbol name starts with a period, it is
2276                      the code of a function.  If the symbol is
2277                      currently undefined, then add an undefined symbol
2278                      for the function descriptor.  This should do no
2279                      harm, because any regular object that defines the
2280                      function should also define the function
2281                      descriptor.  It helps, because it means that we
2282                      will identify the function descriptor with a
2283                      dynamic object if a dynamic object defines it.  */
2284                   if (h->root.root.string[0] == '.'
2285                       && h->descriptor == NULL)
2286                     {
2287                       struct xcoff_link_hash_entry *hds;
2288
2289                       hds = xcoff_link_hash_lookup (xcoff_hash_table (info),
2290                                                     h->root.root.string + 1,
2291                                                     true, false, true);
2292                       if (hds == NULL)
2293                         goto error_return;
2294                       if (hds->root.type == bfd_link_hash_new)
2295                         {
2296                           if (! (_bfd_generic_link_add_one_symbol
2297                                  (info, abfd, hds->root.root.string,
2298                                   (flagword) 0, bfd_und_section_ptr,
2299                                   (bfd_vma) 0, (const char *) NULL, false,
2300                                   true,
2301                                   (struct bfd_link_hash_entry **) &hds)))
2302                             goto error_return;
2303                         }
2304                       hds->flags |= XCOFF_DESCRIPTOR;
2305                       BFD_ASSERT ((hds->flags & XCOFF_CALLED) == 0
2306                                   && (h->flags & XCOFF_DESCRIPTOR) == 0);
2307                       hds->descriptor = h;
2308                       h->descriptor = hds;
2309                     }
2310                 }
2311             }
2312
2313           free (reloc_info[o->target_index].csects);
2314           reloc_info[o->target_index].csects = NULL;
2315
2316           /* Reset SEC_RELOC and the reloc_count, since the reloc
2317              information is now attached to the csects.  */
2318           o->flags &=~ SEC_RELOC;
2319           o->reloc_count = 0;
2320
2321           /* If we are not keeping memory, free the reloc information.  */
2322           if (! info->keep_memory
2323               && coff_section_data (abfd, o) != NULL
2324               && coff_section_data (abfd, o)->relocs != NULL
2325               && ! coff_section_data (abfd, o)->keep_relocs)
2326             {
2327               free (coff_section_data (abfd, o)->relocs);
2328               coff_section_data (abfd, o)->relocs = NULL;
2329             }
2330         }
2331
2332       /* Free up the line numbers.  FIXME: We could cache these
2333          somewhere for the final link, to avoid reading them again.  */
2334       if (reloc_info[o->target_index].linenos != NULL)
2335         {
2336           free (reloc_info[o->target_index].linenos);
2337           reloc_info[o->target_index].linenos = NULL;
2338         }
2339     }
2340
2341   free (reloc_info);
2342
2343   obj_coff_keep_syms (abfd) = keep_syms;
2344
2345   return true;
2346
2347  error_return:
2348   if (reloc_info != NULL)
2349     {
2350       for (o = abfd->sections; o != NULL; o = o->next)
2351         {
2352           if (reloc_info[o->target_index].csects != NULL)
2353             free (reloc_info[o->target_index].csects);
2354           if (reloc_info[o->target_index].linenos != NULL)
2355             free (reloc_info[o->target_index].linenos);
2356         }
2357     free (reloc_info);
2358     }
2359   obj_coff_keep_syms (abfd) = keep_syms;
2360   return false;
2361 }
2362
2363 #undef N_TMASK
2364 #undef N_BTSHFT
2365
2366 /* This function is used to add symbols from a dynamic object to the
2367    global symbol table.  */
2368
2369 static boolean
2370 xcoff_link_add_dynamic_symbols (abfd, info)
2371      bfd *abfd;
2372      struct bfd_link_info *info;
2373 {
2374   asection *lsec;
2375   bfd_byte *buf;
2376   struct internal_ldhdr ldhdr;
2377   const char *strings;
2378   struct external_ldsym *elsym, *elsymend;
2379   struct xcoff_import_file *n;
2380   const char *bname;
2381   const char *mname;
2382   const char *s;
2383   unsigned int c;
2384   struct xcoff_import_file **pp;
2385
2386   /* We can only handle a dynamic object if we are generating an XCOFF
2387      output file.  */
2388   if (info->hash->creator != abfd->xvec)
2389     {
2390       (*_bfd_error_handler)
2391         ("%s: XCOFF shared object when not producing XCOFF output",
2392          bfd_get_filename (abfd));
2393       bfd_set_error (bfd_error_invalid_operation);
2394       return false;
2395     }
2396
2397   /* The symbols we use from a dynamic object are not the symbols in
2398      the normal symbol table, but, rather, the symbols in the export
2399      table.  If there is a global symbol in a dynamic object which is
2400      not in the export table, the loader will not be able to find it,
2401      so we don't want to find it either.  Also, on AIX 4.1.3, shr.o in
2402      libc.a has symbols in the export table which are not in the
2403      symbol table.  */
2404
2405   /* Read in the .loader section.  FIXME: We should really use the
2406      o_snloader field in the a.out header, rather than grabbing the
2407      section by name.  */
2408   lsec = bfd_get_section_by_name (abfd, ".loader");
2409   if (lsec == NULL)
2410     {
2411       (*_bfd_error_handler)
2412         ("%s: dynamic object with no .loader section",
2413          bfd_get_filename (abfd));
2414       bfd_set_error (bfd_error_no_symbols);
2415       return false;
2416     }
2417
2418   if (! xcoff_get_section_contents (abfd, lsec))
2419     return false;
2420   buf = coff_section_data (abfd, lsec)->contents;
2421
2422   /* Remove the sections from this object, so that they do not get
2423      included in the link.  */
2424   abfd->sections = NULL;
2425
2426   xcoff_swap_ldhdr_in (abfd, (struct external_ldhdr *) buf, &ldhdr);
2427
2428   strings = (char *) buf + ldhdr.l_stoff;
2429
2430   elsym = (struct external_ldsym *) (buf + LDHDRSZ);
2431   elsymend = elsym + ldhdr.l_nsyms;
2432   BFD_ASSERT (sizeof (struct external_ldsym) == LDSYMSZ);
2433   for (; elsym < elsymend; elsym++)
2434     {
2435       struct internal_ldsym ldsym;
2436       char nambuf[SYMNMLEN + 1];
2437       const char *name;
2438       struct xcoff_link_hash_entry *h;
2439
2440       xcoff_swap_ldsym_in (abfd, elsym, &ldsym);
2441
2442       /* We are only interested in exported symbols.  */
2443       if ((ldsym.l_smtype & L_EXPORT) == 0)
2444         continue;
2445
2446       if (ldsym._l._l_l._l_zeroes == 0)
2447         name = strings + ldsym._l._l_l._l_offset;
2448       else
2449         {
2450           memcpy (nambuf, ldsym._l._l_name, SYMNMLEN);
2451           nambuf[SYMNMLEN] = '\0';
2452           name = nambuf;
2453         }
2454
2455       /* Normally we could not call xcoff_link_hash_lookup in an add
2456          symbols routine, since we might not be using an XCOFF hash
2457          table.  However, we verified above that we are using an XCOFF
2458          hash table.  */
2459
2460       h = xcoff_link_hash_lookup (xcoff_hash_table (info), name, true,
2461                                   true, true);
2462       if (h == NULL)
2463         return false;
2464
2465       h->flags |= XCOFF_DEF_DYNAMIC;
2466
2467       /* If the symbol is undefined, and the BFD it was found in is
2468          not a dynamic object, change the BFD to this dynamic object,
2469          so that we can get the correct import file ID.  */
2470       if ((h->root.type == bfd_link_hash_undefined
2471            || h->root.type == bfd_link_hash_undefweak)
2472           && (h->root.u.undef.abfd == NULL
2473               || (h->root.u.undef.abfd->flags & DYNAMIC) == 0))
2474         h->root.u.undef.abfd = abfd;
2475
2476       if (h->root.type == bfd_link_hash_new)
2477         {
2478           h->root.type = bfd_link_hash_undefined;
2479           h->root.u.undef.abfd = abfd;
2480           /* We do not want to add this to the undefined symbol list.  */
2481         }
2482
2483       if (h->smclas == XMC_UA
2484           || h->root.type == bfd_link_hash_undefined
2485           || h->root.type == bfd_link_hash_undefweak)
2486         h->smclas = ldsym.l_smclas;
2487
2488       /* Unless this is an XMC_XO symbol, we don't bother to actually
2489          define it, since we don't have a section to put it in anyhow.
2490          Instead, the relocation routines handle the DEF_DYNAMIC flag
2491          correctly.  */
2492
2493       if (h->smclas == XMC_XO
2494           && (h->root.type == bfd_link_hash_undefined
2495               || h->root.type == bfd_link_hash_undefweak))
2496         {
2497           /* This symbol has an absolute value.  */
2498           h->root.type = bfd_link_hash_defined;
2499           h->root.u.def.section = bfd_abs_section_ptr;
2500           h->root.u.def.value = ldsym.l_value;
2501         }
2502     }
2503
2504   if (buf != NULL && ! coff_section_data (abfd, lsec)->keep_contents)
2505     {
2506       free (coff_section_data (abfd, lsec)->contents);
2507       coff_section_data (abfd, lsec)->contents = NULL;
2508     }
2509
2510   /* Record this file in the import files.  */
2511
2512   n = ((struct xcoff_import_file *)
2513        bfd_alloc (abfd, sizeof (struct xcoff_import_file)));
2514   if (n == NULL)
2515     return false;
2516   n->next = NULL;
2517
2518   /* For some reason, the path entry in the import file list for a
2519      shared object appears to always be empty.  The file name is the
2520      base name.  */
2521   n->path = "";
2522   if (abfd->my_archive == NULL)
2523     {
2524       bname = bfd_get_filename (abfd);
2525       mname = "";
2526     }
2527   else
2528     {
2529       bname = bfd_get_filename (abfd->my_archive);
2530       mname = bfd_get_filename (abfd);
2531     }
2532   s = strrchr (bname, '/');
2533   if (s != NULL)
2534     bname = s + 1;
2535   n->file = bname;
2536   n->member = mname;
2537
2538   /* We start c at 1 because the first import file number is reserved
2539      for LIBPATH.  */
2540   for (pp = &xcoff_hash_table (info)->imports, c = 1;
2541        *pp != NULL;
2542        pp = &(*pp)->next, ++c)
2543     ;
2544   *pp = n;
2545
2546   xcoff_data (abfd)->import_file_id = c;
2547
2548   return true;
2549 }
2550 \f
2551 /* Routines that are called after all the input files have been
2552    handled, but before the sections are laid out in memory.  */
2553
2554 /* Mark a symbol as not being garbage, including the section in which
2555    it is defined.  */
2556
2557 static INLINE boolean
2558 xcoff_mark_symbol (info, h)
2559      struct bfd_link_info *info;
2560      struct xcoff_link_hash_entry *h;
2561 {
2562   if ((h->flags & XCOFF_MARK) != 0)
2563     return true;
2564
2565   h->flags |= XCOFF_MARK;
2566   if (h->root.type == bfd_link_hash_defined
2567       || h->root.type == bfd_link_hash_defweak)
2568     {
2569       asection *hsec;
2570
2571       hsec = h->root.u.def.section;
2572       if ((hsec->flags & SEC_MARK) == 0)
2573         {
2574           if (! xcoff_mark (info, hsec))
2575             return false;
2576         }
2577     }
2578
2579   if (h->toc_section != NULL
2580       && (h->toc_section->flags & SEC_MARK) == 0)
2581     {
2582       if (! xcoff_mark (info, h->toc_section))
2583         return false;
2584     }
2585
2586   return true;
2587 }
2588
2589 /* The mark phase of garbage collection.  For a given section, mark
2590    it, and all the sections which define symbols to which it refers.
2591    Because this function needs to look at the relocs, we also count
2592    the number of relocs which need to be copied into the .loader
2593    section.  */
2594
2595 static boolean
2596 xcoff_mark (info, sec)
2597      struct bfd_link_info *info;
2598      asection *sec;
2599 {
2600   if ((sec->flags & SEC_MARK) != 0)
2601     return true;
2602
2603   sec->flags |= SEC_MARK;
2604
2605   if (sec->owner->xvec == info->hash->creator
2606       && coff_section_data (sec->owner, sec) != NULL
2607       && xcoff_section_data (sec->owner, sec) != NULL)
2608     {
2609       register struct xcoff_link_hash_entry **hp, **hpend;
2610       struct internal_reloc *rel, *relend;
2611
2612       /* Mark all the symbols in this section.  */
2613
2614       hp = (obj_xcoff_sym_hashes (sec->owner)
2615             + xcoff_section_data (sec->owner, sec)->first_symndx);
2616       hpend = (obj_xcoff_sym_hashes (sec->owner)
2617                + xcoff_section_data (sec->owner, sec)->last_symndx);
2618       for (; hp < hpend; hp++)
2619         {
2620           register struct xcoff_link_hash_entry *h;
2621
2622           h = *hp;
2623           if (h != NULL
2624               && (h->flags & XCOFF_MARK) == 0)
2625             {
2626               if (! xcoff_mark_symbol (info, h))
2627                 return false;
2628             }
2629         }
2630
2631       /* Look through the section relocs.  */
2632
2633       if ((sec->flags & SEC_RELOC) != 0
2634           && sec->reloc_count > 0)
2635         {
2636           rel = xcoff_read_internal_relocs (sec->owner, sec, true,
2637                                             (bfd_byte *) NULL, false,
2638                                             (struct internal_reloc *) NULL);
2639           if (rel == NULL)
2640             return false;
2641           relend = rel + sec->reloc_count;
2642           for (; rel < relend; rel++)
2643             {
2644               asection *rsec;
2645               struct xcoff_link_hash_entry *h;
2646
2647               if ((unsigned int) rel->r_symndx
2648                   > obj_raw_syment_count (sec->owner))
2649                 continue;
2650
2651               h = obj_xcoff_sym_hashes (sec->owner)[rel->r_symndx];
2652               if (h != NULL
2653                   && (h->flags & XCOFF_MARK) == 0)
2654                 {
2655                   if (! xcoff_mark_symbol (info, h))
2656                     return false;
2657                 }
2658
2659               rsec = xcoff_data (sec->owner)->csects[rel->r_symndx];
2660               if (rsec != NULL
2661                   && (rsec->flags & SEC_MARK) == 0)
2662                 {
2663                   if (! xcoff_mark (info, rsec))
2664                     return false;
2665                 }
2666
2667               /* See if this reloc needs to be copied into the .loader
2668                  section.  */
2669               switch (rel->r_type)
2670                 {
2671                 default:
2672                   if (h == NULL
2673                       || h->root.type == bfd_link_hash_defined
2674                       || h->root.type == bfd_link_hash_defweak
2675                       || h->root.type == bfd_link_hash_common
2676                       || ((h->flags & XCOFF_CALLED) != 0
2677                           && (h->root.type == bfd_link_hash_undefined
2678                               || h->root.type == bfd_link_hash_undefweak)
2679                           && h->root.root.string[0] == '.'
2680                           && h->descriptor != NULL
2681                           && ((h->descriptor->flags & XCOFF_DEF_DYNAMIC) != 0
2682                               || info->shared
2683                               || ((h->descriptor->flags & XCOFF_IMPORT) != 0
2684                                   && (h->descriptor->flags
2685                                       & XCOFF_DEF_REGULAR) == 0))))
2686                     break;
2687                   /* Fall through.  */
2688                 case R_POS:
2689                 case R_NEG:
2690                 case R_RL:
2691                 case R_RLA:
2692                   ++xcoff_hash_table (info)->ldrel_count;
2693                   if (h != NULL)
2694                     h->flags |= XCOFF_LDREL;
2695                   break;
2696                 case R_TOC:
2697                 case R_GL:
2698                 case R_TCL:
2699                 case R_TRL:
2700                 case R_TRLA:
2701                   /* We should never need a .loader reloc for a TOC
2702                      relative reloc.  */
2703                   break;
2704                 }
2705             }
2706
2707           if (! info->keep_memory
2708               && coff_section_data (sec->owner, sec) != NULL
2709               && coff_section_data (sec->owner, sec)->relocs != NULL
2710               && ! coff_section_data (sec->owner, sec)->keep_relocs)
2711             {
2712               free (coff_section_data (sec->owner, sec)->relocs);
2713               coff_section_data (sec->owner, sec)->relocs = NULL;
2714             }
2715         }
2716     }
2717
2718   return true;
2719 }
2720
2721 /* The sweep phase of garbage collection.  Remove all garbage
2722    sections.  */
2723
2724 static void
2725 xcoff_sweep (info)
2726      struct bfd_link_info *info;
2727 {
2728   bfd *sub;
2729
2730   for (sub = info->input_bfds; sub != NULL; sub = sub->link_next)
2731     {
2732       asection *o;
2733
2734       for (o = sub->sections; o != NULL; o = o->next)
2735         {
2736           if ((o->flags & SEC_MARK) == 0)
2737             {
2738               /* Keep all sections from non-XCOFF input files.  Keep
2739                  special sections.  Keep .debug sections for the
2740                  moment.  */
2741               if (sub->xvec != info->hash->creator
2742                   || o == xcoff_hash_table (info)->debug_section
2743                   || o == xcoff_hash_table (info)->loader_section
2744                   || o == xcoff_hash_table (info)->linkage_section
2745                   || o == xcoff_hash_table (info)->toc_section
2746                   || o == xcoff_hash_table (info)->descriptor_section
2747                   || strcmp (o->name, ".debug") == 0)
2748                 o->flags |= SEC_MARK;
2749               else
2750                 {
2751                   o->_raw_size = 0;
2752                   o->reloc_count = 0;
2753                   o->lineno_count = 0;
2754                 }
2755             }
2756         }
2757     }
2758 }
2759
2760 /* Record the number of elements in a set.  This is used to output the
2761    correct csect length.  */
2762
2763 boolean
2764 bfd_xcoff_link_record_set (output_bfd, info, harg, size)
2765      bfd *output_bfd;
2766      struct bfd_link_info *info;
2767      struct bfd_link_hash_entry *harg;
2768      bfd_size_type size;
2769 {
2770   struct xcoff_link_hash_entry *h = (struct xcoff_link_hash_entry *) harg;
2771   struct xcoff_link_size_list *n;
2772
2773   if (! XCOFF_XVECP (output_bfd->xvec))
2774     return true;
2775
2776   /* This will hardly ever be called.  I don't want to burn four bytes
2777      per global symbol, so instead the size is kept on a linked list
2778      attached to the hash table.  */
2779
2780   n = ((struct xcoff_link_size_list *)
2781        bfd_alloc (output_bfd, sizeof (struct xcoff_link_size_list)));
2782   if (n == NULL)
2783     return false;
2784   n->next = xcoff_hash_table (info)->size_list;
2785   n->h = h;
2786   n->size = size;
2787   xcoff_hash_table (info)->size_list = n;
2788
2789   h->flags |= XCOFF_HAS_SIZE;
2790
2791   return true;
2792 }
2793
2794 /* Import a symbol.  */
2795
2796 boolean
2797 bfd_xcoff_import_symbol (output_bfd, info, harg, val, imppath, impfile,
2798                          impmember)
2799      bfd *output_bfd;
2800      struct bfd_link_info *info;
2801      struct bfd_link_hash_entry *harg;
2802      bfd_vma val;
2803      const char *imppath;
2804      const char *impfile;
2805      const char *impmember;
2806 {
2807   struct xcoff_link_hash_entry *h = (struct xcoff_link_hash_entry *) harg;
2808
2809   if (! XCOFF_XVECP (output_bfd->xvec))
2810     return true;
2811
2812   h->flags |= XCOFF_IMPORT;
2813
2814   if (val != (bfd_vma) -1)
2815     {
2816       if (h->root.type == bfd_link_hash_defined
2817           && (! bfd_is_abs_section (h->root.u.def.section)
2818               || h->root.u.def.value != val))
2819         {
2820           if (! ((*info->callbacks->multiple_definition)
2821                  (info, h->root.root.string, h->root.u.def.section->owner,
2822                   h->root.u.def.section, h->root.u.def.value,
2823                   output_bfd, bfd_abs_section_ptr, val)))
2824             return false;
2825         }
2826
2827       h->root.type = bfd_link_hash_defined;
2828       h->root.u.def.section = bfd_abs_section_ptr;
2829       h->root.u.def.value = val;
2830     }
2831
2832   if (h->ldsym == NULL)
2833     {
2834       h->ldsym = ((struct internal_ldsym *)
2835                   bfd_zalloc (output_bfd, sizeof (struct internal_ldsym)));
2836       if (h->ldsym == NULL)
2837         return false;
2838     }
2839
2840   if (imppath == NULL)
2841     h->ldsym->l_ifile = (bfd_size_type) -1;
2842   else
2843     {
2844       unsigned int c;
2845       struct xcoff_import_file **pp;
2846
2847       /* We start c at 1 because the first entry in the import list is
2848          reserved for the library search path.  */
2849       for (pp = &xcoff_hash_table (info)->imports, c = 1;
2850            *pp != NULL;
2851            pp = &(*pp)->next, ++c)
2852         {
2853           if (strcmp ((*pp)->path, imppath) == 0
2854               && strcmp ((*pp)->file, impfile) == 0
2855               && strcmp ((*pp)->member, impmember) == 0)
2856             break;
2857         }
2858
2859       if (*pp == NULL)
2860         {
2861           struct xcoff_import_file *n;
2862
2863           n = ((struct xcoff_import_file *)
2864                bfd_alloc (output_bfd, sizeof (struct xcoff_import_file)));
2865           if (n == NULL)
2866             return false;
2867           n->next = NULL;
2868           n->path = imppath;
2869           n->file = impfile;
2870           n->member = impmember;
2871           *pp = n;
2872         }
2873
2874       h->ldsym->l_ifile = c;
2875     }
2876
2877   return true;
2878 }
2879
2880 /* Export a symbol.  */
2881
2882 boolean
2883 bfd_xcoff_export_symbol (output_bfd, info, harg, syscall)
2884      bfd *output_bfd;
2885      struct bfd_link_info *info;
2886      struct bfd_link_hash_entry *harg;
2887      boolean syscall;
2888 {
2889   struct xcoff_link_hash_entry *h = (struct xcoff_link_hash_entry *) harg;
2890
2891   if (! XCOFF_XVECP (output_bfd->xvec))
2892     return true;
2893
2894   h->flags |= XCOFF_EXPORT;
2895
2896   /* FIXME: I'm not at all sure what syscall is supposed to mean, so
2897      I'm just going to ignore it until somebody explains it.  */
2898
2899   /* See if this is a function descriptor.  It may be one even though
2900      it is not so marked.  */
2901   if ((h->flags & XCOFF_DESCRIPTOR) == 0
2902       && h->root.root.string[0] != '.')
2903     {
2904       char *fnname;
2905       struct xcoff_link_hash_entry *hfn;
2906
2907       fnname = (char *) bfd_malloc (strlen (h->root.root.string) + 2);
2908       if (fnname == NULL)
2909         return false;
2910       fnname[0] = '.';
2911       strcpy (fnname + 1, h->root.root.string);
2912       hfn = xcoff_link_hash_lookup (xcoff_hash_table (info),
2913                                     fnname, false, false, true);
2914       free (fnname);
2915       if (hfn != NULL
2916           && hfn->smclas == XMC_PR
2917           && (hfn->root.type == bfd_link_hash_defined
2918               || hfn->root.type == bfd_link_hash_defweak))
2919         {
2920           h->flags |= XCOFF_DESCRIPTOR;
2921           h->descriptor = hfn;
2922           hfn->descriptor = h;
2923         }
2924     }
2925
2926   /* Make sure we don't garbage collect this symbol.  */
2927   if (! xcoff_mark_symbol (info, h))
2928     return false;
2929
2930   /* If this is a function descriptor, make sure we don't garbage
2931      collect the associated function code.  We normally don't have to
2932      worry about this, because the descriptor will be attached to a
2933      section with relocs, but if we are creating the descriptor
2934      ourselves those relocs will not be visible to the mark code.  */
2935   if ((h->flags & XCOFF_DESCRIPTOR) != 0)
2936     {
2937       if (! xcoff_mark_symbol (info, h->descriptor))
2938         return false;
2939     }
2940
2941   return true;
2942 }
2943
2944 /* Count a reloc against a symbol.  This is called for relocs
2945    generated by the linker script, typically for global constructors
2946    and destructors.  */
2947
2948 boolean
2949 bfd_xcoff_link_count_reloc (output_bfd, info, name)
2950      bfd *output_bfd;
2951      struct bfd_link_info *info;
2952      const char *name;
2953 {
2954   struct xcoff_link_hash_entry *h;
2955
2956   if (! XCOFF_XVECP (output_bfd->xvec))
2957     return true;
2958
2959   h = ((struct xcoff_link_hash_entry *)
2960        bfd_wrapped_link_hash_lookup (output_bfd, info, name, false, false,
2961                                      false));
2962   if (h == NULL)
2963     {
2964       (*_bfd_error_handler) ("%s: no such symbol", name);
2965       bfd_set_error (bfd_error_no_symbols);
2966       return false;
2967     }
2968
2969   h->flags |= XCOFF_REF_REGULAR | XCOFF_LDREL;
2970   ++xcoff_hash_table (info)->ldrel_count;
2971   
2972   /* Mark the symbol to avoid garbage collection.  */
2973   if (! xcoff_mark_symbol (info, h))
2974     return false;
2975
2976   return true;
2977 }
2978
2979 /* This function is called for each symbol to which the linker script
2980    assigns a value.  */
2981
2982 boolean
2983 bfd_xcoff_record_link_assignment (output_bfd, info, name)
2984      bfd *output_bfd;
2985      struct bfd_link_info *info;
2986      const char *name;
2987 {
2988   struct xcoff_link_hash_entry *h;
2989
2990   if (! XCOFF_XVECP (output_bfd->xvec))
2991     return true;
2992
2993   h = xcoff_link_hash_lookup (xcoff_hash_table (info), name, true, true,
2994                               false);
2995   if (h == NULL)
2996     return false;
2997
2998   h->flags |= XCOFF_DEF_REGULAR;
2999
3000   return true;
3001 }
3002
3003 /* This structure is used to pass information through
3004    xcoff_link_hash_traverse.  */
3005
3006 struct xcoff_loader_info
3007 {
3008   /* Set if a problem occurred.  */
3009   boolean failed;
3010   /* Output BFD.  */
3011   bfd *output_bfd;
3012   /* Link information structure.  */
3013   struct bfd_link_info *info;
3014   /* Whether all defined symbols should be exported.  */
3015   boolean export_defineds;
3016   /* Number of ldsym structures.  */
3017   size_t ldsym_count;
3018   /* Size of string table.  */
3019   size_t string_size;
3020   /* String table.  */
3021   bfd_byte *strings;
3022   /* Allocated size of string table.  */
3023   size_t string_alc;
3024 };
3025
3026 /* Build the .loader section.  This is called by the XCOFF linker
3027    emulation before_allocation routine.  We must set the size of the
3028    .loader section before the linker lays out the output file.
3029    LIBPATH is the library path to search for shared objects; this is
3030    normally built from the -L arguments passed to the linker.  ENTRY
3031    is the name of the entry point symbol (the -e linker option).
3032    FILE_ALIGN is the alignment to use for sections within the file
3033    (the -H linker option).  MAXSTACK is the maximum stack size (the
3034    -bmaxstack linker option).  MAXDATA is the maximum data size (the
3035    -bmaxdata linker option).  GC is whether to do garbage collection
3036    (the -bgc linker option).  MODTYPE is the module type (the
3037    -bmodtype linker option).  TEXTRO is whether the text section must
3038    be read only (the -btextro linker option).  EXPORT_DEFINEDS is
3039    whether all defined symbols should be exported (the -unix linker
3040    option).  SPECIAL_SECTIONS is set by this routine to csects with
3041    magic names like _end.  */
3042
3043 boolean
3044 bfd_xcoff_size_dynamic_sections (output_bfd, info, libpath, entry,
3045                                  file_align, maxstack, maxdata, gc,
3046                                  modtype, textro, export_defineds,
3047                                  special_sections)
3048      bfd *output_bfd;
3049      struct bfd_link_info *info;
3050      const char *libpath;
3051      const char *entry;
3052      unsigned long file_align;
3053      unsigned long maxstack;
3054      unsigned long maxdata;
3055      boolean gc;
3056      int modtype;
3057      boolean textro;
3058      boolean export_defineds;
3059      asection **special_sections;
3060 {
3061   struct xcoff_link_hash_entry *hentry;
3062   asection *lsec;
3063   struct xcoff_loader_info ldinfo;
3064   int i;
3065   size_t impsize, impcount;
3066   struct xcoff_import_file *fl;
3067   struct internal_ldhdr *ldhdr;
3068   bfd_size_type stoff;
3069   register char *out;
3070   asection *sec;
3071   bfd *sub;
3072   struct bfd_strtab_hash *debug_strtab;
3073   bfd_byte *debug_contents = NULL;
3074
3075   if (! XCOFF_XVECP (output_bfd->xvec))
3076     {
3077       for (i = 0; i < 6; i++)
3078         special_sections[i] = NULL;
3079       return true;
3080     }
3081
3082   ldinfo.failed = false;
3083   ldinfo.output_bfd = output_bfd;
3084   ldinfo.info = info;
3085   ldinfo.export_defineds = export_defineds;
3086   ldinfo.ldsym_count = 0;
3087   ldinfo.string_size = 0;
3088   ldinfo.strings = NULL;
3089   ldinfo.string_alc = 0;
3090
3091   xcoff_data (output_bfd)->maxstack = maxstack;
3092   xcoff_data (output_bfd)->maxdata = maxdata;
3093   xcoff_data (output_bfd)->modtype = modtype;
3094
3095   xcoff_hash_table (info)->file_align = file_align;
3096   xcoff_hash_table (info)->textro = textro;
3097
3098   hentry = xcoff_link_hash_lookup (xcoff_hash_table (info), entry,
3099                                    false, false, true);
3100   if (hentry != NULL)
3101     hentry->flags |= XCOFF_ENTRY;
3102
3103   /* Garbage collect unused sections.  */
3104   if (info->relocateable
3105       || ! gc
3106       || hentry == NULL
3107       || (hentry->root.type != bfd_link_hash_defined
3108           && hentry->root.type != bfd_link_hash_defweak))
3109     {
3110       gc = false;
3111       xcoff_hash_table (info)->gc = false;
3112
3113       /* We still need to call xcoff_mark, in order to set ldrel_count
3114          correctly.  */
3115       for (sub = info->input_bfds; sub != NULL; sub = sub->link_next)
3116         {
3117           asection *o;
3118
3119           for (o = sub->sections; o != NULL; o = o->next)
3120             {
3121               if ((o->flags & SEC_MARK) == 0)
3122                 {
3123                   if (! xcoff_mark (info, o))
3124                     goto error_return;
3125                 }
3126             }
3127         }
3128     }
3129   else
3130     {
3131       if (! xcoff_mark (info, hentry->root.u.def.section))
3132         goto error_return;
3133       xcoff_sweep (info);
3134       xcoff_hash_table (info)->gc = true;
3135     }
3136
3137   /* Return special sections to the caller.  */
3138   for (i = 0; i < 6; i++)
3139     {
3140       asection *sec;
3141
3142       sec = xcoff_hash_table (info)->special_sections[i];
3143       if (sec != NULL
3144           && gc
3145           && (sec->flags & SEC_MARK) == 0)
3146         sec = NULL;
3147       special_sections[i] = sec;
3148     }
3149
3150   if (info->input_bfds == NULL)
3151     {
3152       /* I'm not sure what to do in this bizarre case.  */
3153       return true;
3154     }
3155
3156   xcoff_link_hash_traverse (xcoff_hash_table (info), xcoff_build_ldsyms,
3157                             (PTR) &ldinfo);
3158   if (ldinfo.failed)
3159     goto error_return;
3160
3161   /* Work out the size of the import file names.  Each import file ID
3162      consists of three null terminated strings: the path, the file
3163      name, and the archive member name.  The first entry in the list
3164      of names is the path to use to find objects, which the linker has
3165      passed in as the libpath argument.  For some reason, the path
3166      entry in the other import file names appears to always be empty.  */
3167   impsize = strlen (libpath) + 3;
3168   impcount = 1;
3169   for (fl = xcoff_hash_table (info)->imports; fl != NULL; fl = fl->next)
3170     {
3171       ++impcount;
3172       impsize += (strlen (fl->path)
3173                   + strlen (fl->file)
3174                   + strlen (fl->member)
3175                   + 3);
3176     }
3177
3178   /* Set up the .loader section header.  */
3179   ldhdr = &xcoff_hash_table (info)->ldhdr;
3180   ldhdr->l_version = 1;
3181   ldhdr->l_nsyms = ldinfo.ldsym_count;
3182   ldhdr->l_nreloc = xcoff_hash_table (info)->ldrel_count;
3183   ldhdr->l_istlen = impsize;
3184   ldhdr->l_nimpid = impcount;
3185   ldhdr->l_impoff = (LDHDRSZ
3186                      + ldhdr->l_nsyms * LDSYMSZ
3187                      + ldhdr->l_nreloc * LDRELSZ);
3188   ldhdr->l_stlen = ldinfo.string_size;
3189   stoff = ldhdr->l_impoff + impsize;
3190   if (ldinfo.string_size == 0)
3191     ldhdr->l_stoff = 0;
3192   else
3193     ldhdr->l_stoff = stoff;
3194
3195   /* We now know the final size of the .loader section.  Allocate
3196      space for it.  */
3197   lsec = xcoff_hash_table (info)->loader_section;
3198   lsec->_raw_size = stoff + ldhdr->l_stlen;
3199   lsec->contents = (bfd_byte *) bfd_zalloc (output_bfd, lsec->_raw_size);
3200   if (lsec->contents == NULL)
3201     goto error_return;
3202
3203   /* Set up the header.  */
3204   xcoff_swap_ldhdr_out (output_bfd, ldhdr,
3205                         (struct external_ldhdr *) lsec->contents);
3206
3207   /* Set up the import file names.  */
3208   out = (char *) lsec->contents + ldhdr->l_impoff;
3209   strcpy (out, libpath);
3210   out += strlen (libpath) + 1;
3211   *out++ = '\0';
3212   *out++ = '\0';
3213   for (fl = xcoff_hash_table (info)->imports; fl != NULL; fl = fl->next)
3214     {
3215       register const char *s;
3216
3217       s = fl->path;
3218       while ((*out++ = *s++) != '\0')
3219         ;
3220       s = fl->file;
3221       while ((*out++ = *s++) != '\0')
3222         ;
3223       s = fl->member;
3224       while ((*out++ = *s++) != '\0')
3225         ;
3226     }
3227
3228   BFD_ASSERT ((bfd_size_type) ((bfd_byte *) out - lsec->contents) == stoff);
3229
3230   /* Set up the symbol string table.  */
3231   if (ldinfo.string_size > 0)
3232     {
3233       memcpy (out, ldinfo.strings, ldinfo.string_size);
3234       free (ldinfo.strings);
3235       ldinfo.strings = NULL;
3236     }
3237
3238   /* We can't set up the symbol table or the relocs yet, because we
3239      don't yet know the final position of the various sections.  The
3240      .loader symbols are written out when the corresponding normal
3241      symbols are written out in xcoff_link_input_bfd or
3242      xcoff_write_global_symbol.  The .loader relocs are written out
3243      when the corresponding normal relocs are handled in
3244      xcoff_link_input_bfd.  */
3245
3246   /* Allocate space for the magic sections.  */
3247   sec = xcoff_hash_table (info)->linkage_section;
3248   if (sec->_raw_size > 0)
3249     {
3250       sec->contents = (bfd_byte *) bfd_zalloc (output_bfd, sec->_raw_size);
3251       if (sec->contents == NULL)
3252         goto error_return;
3253     }
3254   sec = xcoff_hash_table (info)->toc_section;
3255   if (sec->_raw_size > 0)
3256     {
3257       sec->contents = (bfd_byte *) bfd_zalloc (output_bfd, sec->_raw_size);
3258       if (sec->contents == NULL)
3259         goto error_return;
3260     }
3261   sec = xcoff_hash_table (info)->descriptor_section;
3262   if (sec->_raw_size > 0)
3263     {
3264       sec->contents = (bfd_byte *) bfd_zalloc (output_bfd, sec->_raw_size);
3265       if (sec->contents == NULL)
3266         goto error_return;
3267     }
3268
3269   /* Now that we've done garbage collection, figure out the contents
3270      of the .debug section.  */
3271   debug_strtab = xcoff_hash_table (info)->debug_strtab;
3272
3273   for (sub = info->input_bfds; sub != NULL; sub = sub->link_next)
3274     {
3275       asection *subdeb;
3276       bfd_size_type symcount;
3277       unsigned long *debug_index;
3278       asection **csectpp;
3279       bfd_byte *esym, *esymend;
3280       bfd_size_type symesz;
3281
3282       if (sub->xvec != info->hash->creator)
3283         continue;
3284       subdeb = bfd_get_section_by_name (sub, ".debug");
3285       if (subdeb == NULL || subdeb->_raw_size == 0)
3286         continue;
3287
3288       if (info->strip == strip_all
3289           || info->strip == strip_debugger
3290           || info->discard == discard_all)
3291         {
3292           subdeb->_raw_size = 0;
3293           continue;
3294         }
3295
3296       if (! _bfd_coff_get_external_symbols (sub))
3297         goto error_return;
3298
3299       symcount = obj_raw_syment_count (sub);
3300       debug_index = ((unsigned long *)
3301                      bfd_zalloc (sub, symcount * sizeof (unsigned long)));
3302       if (debug_index == NULL)
3303         goto error_return;
3304       xcoff_data (sub)->debug_indices = debug_index;
3305
3306       /* Grab the contents of the .debug section.  We use malloc and
3307          copy the neams into the debug stringtab, rather than
3308          bfd_alloc, because I expect that, when linking many files
3309          together, many of the strings will be the same.  Storing the
3310          strings in the hash table should save space in this case.  */
3311       debug_contents = (bfd_byte *) bfd_malloc (subdeb->_raw_size);
3312       if (debug_contents == NULL)
3313         goto error_return;
3314       if (! bfd_get_section_contents (sub, subdeb, (PTR) debug_contents,
3315                                       (file_ptr) 0, subdeb->_raw_size))
3316         goto error_return;
3317
3318       csectpp = xcoff_data (sub)->csects;
3319
3320       symesz = bfd_coff_symesz (sub);
3321       esym = (bfd_byte *) obj_coff_external_syms (sub);
3322       esymend = esym + symcount * symesz;
3323       while (esym < esymend)
3324         {
3325           struct internal_syment sym;
3326
3327           bfd_coff_swap_sym_in (sub, (PTR) esym, (PTR) &sym);
3328
3329           *debug_index = (unsigned long) -1;
3330
3331           if (sym._n._n_n._n_zeroes == 0
3332               && *csectpp != NULL
3333               && (! gc
3334                   || ((*csectpp)->flags & SEC_MARK) != 0
3335                   || *csectpp == bfd_abs_section_ptr)
3336               && bfd_coff_symname_in_debug (sub, &sym))
3337             {
3338               char *name;
3339               bfd_size_type indx;
3340
3341               name = (char *) debug_contents + sym._n._n_n._n_offset;
3342               indx = _bfd_stringtab_add (debug_strtab, name, true, true);
3343               if (indx == (bfd_size_type) -1)
3344                 goto error_return;
3345               *debug_index = indx;
3346             }
3347
3348           esym += (sym.n_numaux + 1) * symesz;
3349           csectpp += sym.n_numaux + 1;
3350           debug_index += sym.n_numaux + 1;
3351         }
3352
3353       free (debug_contents);
3354       debug_contents = NULL;
3355
3356       /* Clear the size of subdeb, so that it is not included directly
3357          in the output file.  */
3358       subdeb->_raw_size = 0;
3359
3360       if (! info->keep_memory)
3361         {
3362           if (! _bfd_coff_free_symbols (sub))
3363             goto error_return;
3364         }
3365     }
3366
3367   xcoff_hash_table (info)->debug_section->_raw_size =
3368     _bfd_stringtab_size (debug_strtab);
3369
3370   return true;
3371
3372  error_return:
3373   if (ldinfo.strings != NULL)
3374     free (ldinfo.strings);
3375   if (debug_contents != NULL)
3376     free (debug_contents);
3377   return false;
3378 }
3379
3380 /* Add a symbol to the .loader symbols, if necessary.  */
3381
3382 static boolean
3383 xcoff_build_ldsyms (h, p)
3384      struct xcoff_link_hash_entry *h;
3385      PTR p;
3386 {
3387   struct xcoff_loader_info *ldinfo = (struct xcoff_loader_info *) p;
3388   size_t len;
3389
3390   /* If this is a final link, and the symbol was defined as a common
3391      symbol in a regular object file, and there was no definition in
3392      any dynamic object, then the linker will have allocated space for
3393      the symbol in a common section but the XCOFF_DEF_REGULAR flag
3394      will not have been set.  */
3395   if (h->root.type == bfd_link_hash_defined
3396       && (h->flags & XCOFF_DEF_REGULAR) == 0
3397       && (h->flags & XCOFF_REF_REGULAR) != 0
3398       && (h->flags & XCOFF_DEF_DYNAMIC) == 0
3399       && (h->root.u.def.section->owner->flags & DYNAMIC) == 0)
3400     h->flags |= XCOFF_DEF_REGULAR;
3401
3402   /* If all defined symbols should be exported, mark them now.  We
3403      don't want to export the actual functions, just the function
3404      descriptors.  */
3405   if (ldinfo->export_defineds
3406       && (h->flags & XCOFF_DEF_REGULAR) != 0
3407       && h->root.root.string[0] != '.')
3408     h->flags |= XCOFF_EXPORT;
3409
3410   /* We don't want to garbage collect symbols which are not defined in
3411      XCOFF files.  This is a convenient place to mark them.  */
3412   if (xcoff_hash_table (ldinfo->info)->gc
3413       && (h->flags & XCOFF_MARK) == 0
3414       && (h->root.type == bfd_link_hash_defined
3415           || h->root.type == bfd_link_hash_defweak)
3416       && (h->root.u.def.section->owner == NULL
3417           || (h->root.u.def.section->owner->xvec
3418               != ldinfo->info->hash->creator)))
3419     h->flags |= XCOFF_MARK;
3420
3421   /* If this symbol is called and defined in a dynamic object, or not
3422      defined at all when building a shared object, or imported, then
3423      we need to set up global linkage code for it.  (Unless we did
3424      garbage collection and we didn't need this symbol.)  */
3425   if ((h->flags & XCOFF_CALLED) != 0
3426       && (h->root.type == bfd_link_hash_undefined
3427           || h->root.type == bfd_link_hash_undefweak)
3428       && h->root.root.string[0] == '.'
3429       && h->descriptor != NULL
3430       && ((h->descriptor->flags & XCOFF_DEF_DYNAMIC) != 0
3431           || ldinfo->info->shared
3432           || ((h->descriptor->flags & XCOFF_IMPORT) != 0
3433               && (h->descriptor->flags & XCOFF_DEF_REGULAR) == 0))
3434       && (! xcoff_hash_table (ldinfo->info)->gc
3435           || (h->flags & XCOFF_MARK) != 0))
3436     {
3437       asection *sec;
3438       struct xcoff_link_hash_entry *hds;
3439
3440       sec = xcoff_hash_table (ldinfo->info)->linkage_section;
3441       h->root.type = bfd_link_hash_defined;
3442       h->root.u.def.section = sec;
3443       h->root.u.def.value = sec->_raw_size;
3444       h->smclas = XMC_GL;
3445       h->flags |= XCOFF_DEF_REGULAR;
3446       sec->_raw_size += XCOFF_GLINK_SIZE;
3447
3448       /* The global linkage code requires a TOC entry for the
3449          descriptor.  */
3450       hds = h->descriptor;
3451       BFD_ASSERT ((hds->root.type == bfd_link_hash_undefined
3452                    || hds->root.type == bfd_link_hash_undefweak)
3453                   && (hds->flags & XCOFF_DEF_REGULAR) == 0);
3454       hds->flags |= XCOFF_MARK;
3455       if (hds->toc_section == NULL)
3456         {
3457           hds->toc_section = xcoff_hash_table (ldinfo->info)->toc_section;
3458           hds->u.toc_offset = hds->toc_section->_raw_size;
3459           hds->toc_section->_raw_size += 4;
3460           ++xcoff_hash_table (ldinfo->info)->ldrel_count;
3461           ++hds->toc_section->reloc_count;
3462           hds->indx = -2;
3463           hds->flags |= XCOFF_SET_TOC | XCOFF_LDREL;
3464
3465           /* We need to call xcoff_build_ldsyms recursively here,
3466              because we may already have passed hds on the traversal.  */
3467           xcoff_build_ldsyms (hds, p);
3468         }
3469     }
3470
3471   /* If this symbol is exported, but not defined, we need to try to
3472      define it.  */
3473   if ((h->flags & XCOFF_EXPORT) != 0
3474       && (h->flags & XCOFF_IMPORT) == 0
3475       && (h->flags & XCOFF_DEF_REGULAR) == 0
3476       && (h->flags & XCOFF_DEF_DYNAMIC) == 0
3477       && (h->root.type == bfd_link_hash_undefined
3478           || h->root.type == bfd_link_hash_undefweak))
3479     {
3480       if ((h->flags & XCOFF_DESCRIPTOR) != 0
3481           && (h->descriptor->root.type == bfd_link_hash_defined
3482               || h->descriptor->root.type == bfd_link_hash_defweak))
3483         {
3484           asection *sec;
3485
3486           /* This is an undefined function descriptor associated with
3487              a defined entry point.  We can build up a function
3488              descriptor ourselves.  Believe it or not, the AIX linker
3489              actually does this, and there are cases where we need to
3490              do it as well.  */
3491           sec = xcoff_hash_table (ldinfo->info)->descriptor_section;
3492           h->root.type = bfd_link_hash_defined;
3493           h->root.u.def.section = sec;
3494           h->root.u.def.value = sec->_raw_size;
3495           h->smclas = XMC_DS;
3496           h->flags |= XCOFF_DEF_REGULAR;
3497           sec->_raw_size += 12;
3498
3499           /* A function descriptor uses two relocs: one for the
3500              associated code, and one for the TOC address.  */
3501           xcoff_hash_table (ldinfo->info)->ldrel_count += 2;
3502           sec->reloc_count += 2;
3503
3504           /* We handle writing out the contents of the descriptor in
3505              xcoff_write_global_symbol.  */
3506         }
3507       else
3508         {
3509           (*_bfd_error_handler)
3510             ("warning: attempt to export undefined symbol `%s'",
3511              h->root.root.string);
3512           h->ldsym = NULL;
3513           return true;
3514         }
3515     }
3516
3517   /* If this is still a common symbol, and it wasn't garbage
3518      collected, we need to actually allocate space for it in the .bss
3519      section.  */
3520   if (h->root.type == bfd_link_hash_common
3521       && (! xcoff_hash_table (ldinfo->info)->gc
3522           || (h->flags & XCOFF_MARK) != 0)
3523       && h->root.u.c.p->section->_raw_size == 0)
3524     {
3525       BFD_ASSERT (bfd_is_com_section (h->root.u.c.p->section));
3526       h->root.u.c.p->section->_raw_size = h->root.u.c.size;
3527     }
3528
3529   /* We need to add a symbol to the .loader section if it is mentioned
3530      in a reloc which we are copying to the .loader section and it was
3531      not defined or common, or if it is the entry point, or if it is
3532      being exported.  */
3533
3534   if (((h->flags & XCOFF_LDREL) == 0
3535        || h->root.type == bfd_link_hash_defined
3536        || h->root.type == bfd_link_hash_defweak
3537        || h->root.type == bfd_link_hash_common)
3538       && (h->flags & XCOFF_ENTRY) == 0
3539       && (h->flags & XCOFF_EXPORT) == 0)
3540     {
3541       h->ldsym = NULL;
3542       return true;
3543     }
3544
3545   /* We don't need to add this symbol if we did garbage collection and
3546      we did not mark this symbol.  */
3547   if (xcoff_hash_table (ldinfo->info)->gc
3548       && (h->flags & XCOFF_MARK) == 0)
3549     {
3550       h->ldsym = NULL;
3551       return true;
3552     }
3553
3554   /* We may have already processed this symbol due to the recursive
3555      call above.  */
3556   if ((h->flags & XCOFF_BUILT_LDSYM) != 0)
3557     return true;
3558
3559   /* We need to add this symbol to the .loader symbols.  */
3560
3561   /* h->ldsym will already have been allocated for an explicitly
3562      imported symbol.  */
3563   if (h->ldsym == NULL)
3564     {
3565       h->ldsym = ((struct internal_ldsym *)
3566                   bfd_zalloc (ldinfo->output_bfd,
3567                               sizeof (struct internal_ldsym)));
3568       if (h->ldsym == NULL)
3569         {
3570           ldinfo->failed = true;
3571           return false;
3572         }
3573     }
3574
3575   /* The first 3 symbol table indices are reserved to indicate the
3576      sections.  */
3577   h->ldindx = ldinfo->ldsym_count + 3;
3578
3579   ++ldinfo->ldsym_count;
3580
3581   len = strlen (h->root.root.string);
3582   if (len <= SYMNMLEN)
3583     strncpy (h->ldsym->_l._l_name, h->root.root.string, SYMNMLEN);
3584   else
3585     {
3586       if (ldinfo->string_size + len + 3 > ldinfo->string_alc)
3587         {
3588           size_t newalc;
3589           bfd_byte *newstrings;
3590
3591           newalc = ldinfo->string_alc * 2;
3592           if (newalc == 0)
3593             newalc = 32;
3594           while (ldinfo->string_size + len + 3 > newalc)
3595             newalc *= 2;
3596
3597           newstrings = ((bfd_byte *)
3598                         bfd_realloc ((PTR) ldinfo->strings, newalc));
3599           if (newstrings == NULL)
3600             {
3601               ldinfo->failed = true;
3602               return false;
3603             }
3604           ldinfo->string_alc = newalc;
3605           ldinfo->strings = newstrings;
3606         }
3607
3608       bfd_put_16 (ldinfo->output_bfd, len + 1,
3609                   ldinfo->strings + ldinfo->string_size);
3610       strcpy (ldinfo->strings + ldinfo->string_size + 2, h->root.root.string);
3611       h->ldsym->_l._l_l._l_zeroes = 0;
3612       h->ldsym->_l._l_l._l_offset = ldinfo->string_size + 2;
3613       ldinfo->string_size += len + 3;
3614     }
3615
3616   h->flags |= XCOFF_BUILT_LDSYM;
3617
3618   return true;
3619 }
3620 \f
3621 /* Do the final link step.  */
3622
3623 boolean
3624 _bfd_xcoff_bfd_final_link (abfd, info)
3625      bfd *abfd;
3626      struct bfd_link_info *info;
3627 {
3628   bfd_size_type symesz;
3629   struct xcoff_final_link_info finfo;
3630   asection *o;
3631   struct bfd_link_order *p;
3632   size_t max_contents_size;
3633   size_t max_sym_count;
3634   size_t max_lineno_count;
3635   size_t max_reloc_count;
3636   size_t max_output_reloc_count;
3637   file_ptr rel_filepos;
3638   unsigned int relsz;
3639   file_ptr line_filepos;
3640   unsigned int linesz;
3641   bfd *sub;
3642   bfd_byte *external_relocs = NULL;
3643   char strbuf[STRING_SIZE_SIZE];
3644
3645   if (info->shared)
3646     abfd->flags |= DYNAMIC;
3647
3648   symesz = bfd_coff_symesz (abfd);
3649
3650   finfo.info = info;
3651   finfo.output_bfd = abfd;
3652   finfo.strtab = NULL;
3653   finfo.section_info = NULL;
3654   finfo.last_file_index = -1;
3655   finfo.toc_symindx = -1;
3656   finfo.internal_syms = NULL;
3657   finfo.sym_indices = NULL;
3658   finfo.outsyms = NULL;
3659   finfo.linenos = NULL;
3660   finfo.contents = NULL;
3661   finfo.external_relocs = NULL;
3662
3663   finfo.ldsym = ((struct external_ldsym *)
3664                  (xcoff_hash_table (info)->loader_section->contents
3665                   + LDHDRSZ));
3666   finfo.ldrel = ((struct external_ldrel *)
3667                  (xcoff_hash_table (info)->loader_section->contents
3668                   + LDHDRSZ
3669                   + xcoff_hash_table (info)->ldhdr.l_nsyms * LDSYMSZ));
3670
3671   xcoff_data (abfd)->coff.link_info = info;
3672
3673   finfo.strtab = _bfd_stringtab_init ();
3674   if (finfo.strtab == NULL)
3675     goto error_return;
3676
3677   /* Count the line number and relocation entries required for the
3678      output file.  Determine a few maximum sizes.  */
3679   max_contents_size = 0;
3680   max_lineno_count = 0;
3681   max_reloc_count = 0;
3682   for (o = abfd->sections; o != NULL; o = o->next)
3683     {
3684       o->reloc_count = 0;
3685       o->lineno_count = 0;
3686       for (p = o->link_order_head; p != NULL; p = p->next)
3687         {
3688           if (p->type == bfd_indirect_link_order)
3689             {
3690               asection *sec;
3691
3692               sec = p->u.indirect.section;
3693
3694               /* Mark all sections which are to be included in the
3695                  link.  This will normally be every section.  We need
3696                  to do this so that we can identify any sections which
3697                  the linker has decided to not include.  */
3698               sec->linker_mark = true;
3699
3700               if (info->strip == strip_none
3701                   || info->strip == strip_some)
3702                 o->lineno_count += sec->lineno_count;
3703
3704               o->reloc_count += sec->reloc_count;
3705
3706               if (sec->_raw_size > max_contents_size)
3707                 max_contents_size = sec->_raw_size;
3708               if (sec->lineno_count > max_lineno_count)
3709                 max_lineno_count = sec->lineno_count;
3710               if (coff_section_data (sec->owner, sec) != NULL
3711                   && xcoff_section_data (sec->owner, sec) != NULL
3712                   && (xcoff_section_data (sec->owner, sec)->lineno_count
3713                       > max_lineno_count))
3714                 max_lineno_count =
3715                   xcoff_section_data (sec->owner, sec)->lineno_count;
3716               if (sec->reloc_count > max_reloc_count)
3717                 max_reloc_count = sec->reloc_count;
3718             }
3719           else if (p->type == bfd_section_reloc_link_order
3720                    || p->type == bfd_symbol_reloc_link_order)
3721             ++o->reloc_count;
3722         }
3723     }
3724
3725   /* Compute the file positions for all the sections.  */
3726   if (abfd->output_has_begun)
3727     {
3728       if (xcoff_hash_table (info)->file_align != 0)
3729         abort ();
3730     }
3731   else
3732     {
3733       bfd_vma file_align;
3734
3735       file_align = xcoff_hash_table (info)->file_align;
3736       if (file_align != 0)
3737         {
3738           boolean saw_contents;
3739           int indx;
3740           asection **op;
3741           file_ptr sofar;
3742
3743           /* Insert .pad sections before every section which has
3744              contents and is loaded, if it is preceded by some other
3745              section which has contents and is loaded.  */
3746           saw_contents = true;
3747           for (op = &abfd->sections; *op != NULL; op = &(*op)->next)
3748             {
3749               (*op)->target_index = indx;
3750               if (strcmp ((*op)->name, ".pad") == 0)
3751                 saw_contents = false;
3752               else if (((*op)->flags & SEC_HAS_CONTENTS) != 0
3753                        && ((*op)->flags & SEC_LOAD) != 0)
3754                 {
3755                   if (! saw_contents)
3756                     saw_contents = true;
3757                   else
3758                     {
3759                       asection *n, *hold;
3760
3761                       hold = *op;
3762                       *op = NULL;
3763                       n = bfd_make_section_anyway (abfd, ".pad");
3764                       BFD_ASSERT (*op == n);
3765                       n->next = hold;
3766                       n->flags = SEC_HAS_CONTENTS;
3767                       n->alignment_power = 0;
3768                       saw_contents = false;
3769                     }
3770                 }
3771             }
3772
3773           /* Reset the section indices after inserting the new
3774              sections.  */
3775           indx = 0;
3776           for (o = abfd->sections; o != NULL; o = o->next)
3777             {
3778               ++indx;
3779               o->target_index = indx;
3780             }
3781           BFD_ASSERT ((unsigned int) indx == abfd->section_count);
3782
3783           /* Work out appropriate sizes for the .pad sections to force
3784              each section to land on a page boundary.  This bit of
3785              code knows what compute_section_file_positions is going
3786              to do.  */
3787           sofar = bfd_coff_filhsz (abfd);
3788           sofar += bfd_coff_aoutsz (abfd);
3789           sofar += abfd->section_count * bfd_coff_scnhsz (abfd);
3790           for (o = abfd->sections; o != NULL; o = o->next)
3791             if (o->reloc_count >= 0xffff || o->lineno_count >= 0xffff)
3792               sofar += bfd_coff_scnhsz (abfd);
3793
3794           for (o = abfd->sections; o != NULL; o = o->next)
3795             {
3796               if (strcmp (o->name, ".pad") == 0)
3797                 {
3798                   bfd_vma pageoff;
3799
3800                   BFD_ASSERT (o->_raw_size == 0);
3801                   pageoff = sofar & (file_align - 1);
3802                   if (pageoff != 0)
3803                     {
3804                       o->_raw_size = file_align - pageoff;
3805                       sofar += file_align - pageoff;
3806                       o->flags |= SEC_HAS_CONTENTS;
3807                     }
3808                 }
3809               else
3810                 {
3811                   if ((o->flags & SEC_HAS_CONTENTS) != 0)
3812                     sofar += BFD_ALIGN (o->_raw_size,
3813                                         1 << o->alignment_power);
3814                 }
3815             }
3816         }
3817
3818       bfd_coff_compute_section_file_positions (abfd);
3819     }
3820
3821   /* Allocate space for the pointers we need to keep for the relocs.  */
3822   {
3823     unsigned int i;
3824
3825     /* We use section_count + 1, rather than section_count, because
3826        the target_index fields are 1 based.  */
3827     finfo.section_info =
3828       ((struct xcoff_link_section_info *)
3829        bfd_malloc ((abfd->section_count + 1)
3830                    * sizeof (struct xcoff_link_section_info)));
3831     if (finfo.section_info == NULL)
3832       goto error_return;
3833     for (i = 0; i <= abfd->section_count; i++)
3834       {
3835         finfo.section_info[i].relocs = NULL;
3836         finfo.section_info[i].rel_hashes = NULL;
3837         finfo.section_info[i].toc_rel_hashes = NULL;
3838       }
3839   }
3840
3841   /* Set the file positions for the relocs.  */
3842   rel_filepos = obj_relocbase (abfd);
3843   relsz = bfd_coff_relsz (abfd);
3844   max_output_reloc_count = 0;
3845   for (o = abfd->sections; o != NULL; o = o->next)
3846     {
3847       if (o->reloc_count == 0)
3848         o->rel_filepos = 0;
3849       else
3850         {
3851           o->flags |= SEC_RELOC;
3852           o->rel_filepos = rel_filepos;
3853           rel_filepos += o->reloc_count * relsz;
3854
3855           /* We don't know the indices of global symbols until we have
3856              written out all the local symbols.  For each section in
3857              the output file, we keep an array of pointers to hash
3858              table entries.  Each entry in the array corresponds to a
3859              reloc.  When we find a reloc against a global symbol, we
3860              set the corresponding entry in this array so that we can
3861              fix up the symbol index after we have written out all the
3862              local symbols.
3863
3864              Because of this problem, we also keep the relocs in
3865              memory until the end of the link.  This wastes memory.
3866              We could backpatch the file later, I suppose, although it
3867              would be slow.  */
3868           finfo.section_info[o->target_index].relocs =
3869             ((struct internal_reloc *)
3870              bfd_malloc (o->reloc_count * sizeof (struct internal_reloc)));
3871           finfo.section_info[o->target_index].rel_hashes =
3872             ((struct xcoff_link_hash_entry **)
3873              bfd_malloc (o->reloc_count
3874                      * sizeof (struct xcoff_link_hash_entry *)));
3875           if (finfo.section_info[o->target_index].relocs == NULL
3876               || finfo.section_info[o->target_index].rel_hashes == NULL)
3877             goto error_return;
3878
3879           if (o->reloc_count > max_output_reloc_count)
3880             max_output_reloc_count = o->reloc_count;
3881         }
3882     }
3883
3884   /* We now know the size of the relocs, so we can determine the file
3885      positions of the line numbers.  */
3886   line_filepos = rel_filepos;
3887   finfo.line_filepos = line_filepos;
3888   linesz = bfd_coff_linesz (abfd);
3889   for (o = abfd->sections; o != NULL; o = o->next)
3890     {
3891       if (o->lineno_count == 0)
3892         o->line_filepos = 0;
3893       else
3894         {
3895           o->line_filepos = line_filepos;
3896           line_filepos += o->lineno_count * linesz;
3897         }
3898
3899       /* Reset the reloc and lineno counts, so that we can use them to
3900          count the number of entries we have output so far.  */
3901       o->reloc_count = 0;
3902       o->lineno_count = 0;
3903     }
3904
3905   obj_sym_filepos (abfd) = line_filepos;
3906
3907   /* Figure out the largest number of symbols in an input BFD.  Take
3908      the opportunity to clear the output_has_begun fields of all the
3909      input BFD's.  We want at least 4 symbols, since that is the
3910      number which xcoff_write_global_symbol may need.  */
3911   max_sym_count = 4;
3912   for (sub = info->input_bfds; sub != NULL; sub = sub->link_next)
3913     {
3914       size_t sz;
3915
3916       sub->output_has_begun = false;
3917       sz = obj_raw_syment_count (sub);
3918       if (sz > max_sym_count)
3919         max_sym_count = sz;
3920     }
3921
3922   /* Allocate some buffers used while linking.  */
3923   finfo.internal_syms = ((struct internal_syment *)
3924                          bfd_malloc (max_sym_count
3925                                      * sizeof (struct internal_syment)));
3926   finfo.sym_indices = (long *) bfd_malloc (max_sym_count * sizeof (long));
3927   finfo.outsyms = ((bfd_byte *)
3928                    bfd_malloc ((size_t) ((max_sym_count + 1) * symesz)));
3929   finfo.linenos = (bfd_byte *) bfd_malloc (max_lineno_count
3930                                            * bfd_coff_linesz (abfd));
3931   finfo.contents = (bfd_byte *) bfd_malloc (max_contents_size);
3932   finfo.external_relocs = (bfd_byte *) bfd_malloc (max_reloc_count * relsz);
3933   if ((finfo.internal_syms == NULL && max_sym_count > 0)
3934       || (finfo.sym_indices == NULL && max_sym_count > 0)
3935       || finfo.outsyms == NULL
3936       || (finfo.linenos == NULL && max_lineno_count > 0)
3937       || (finfo.contents == NULL && max_contents_size > 0)
3938       || (finfo.external_relocs == NULL && max_reloc_count > 0))
3939     goto error_return;
3940
3941   obj_raw_syment_count (abfd) = 0;
3942   xcoff_data (abfd)->toc = (bfd_vma) -1;
3943
3944   /* We now know the position of everything in the file, except that
3945      we don't know the size of the symbol table and therefore we don't
3946      know where the string table starts.  We just build the string
3947      table in memory as we go along.  We process all the relocations
3948      for a single input file at once.  */
3949   for (o = abfd->sections; o != NULL; o = o->next)
3950     {
3951       for (p = o->link_order_head; p != NULL; p = p->next)
3952         {
3953           if (p->type == bfd_indirect_link_order
3954               && p->u.indirect.section->owner->xvec == abfd->xvec)
3955             {
3956               sub = p->u.indirect.section->owner;
3957               if (! sub->output_has_begun)
3958                 {
3959                   if (! xcoff_link_input_bfd (&finfo, sub))
3960                     goto error_return;
3961                   sub->output_has_begun = true;
3962                 }
3963             }
3964           else if (p->type == bfd_section_reloc_link_order
3965                    || p->type == bfd_symbol_reloc_link_order)
3966             {
3967               if (! xcoff_reloc_link_order (abfd, &finfo, o, p))
3968                 goto error_return;
3969             }
3970           else
3971             {
3972               if (! _bfd_default_link_order (abfd, info, o, p))
3973                 goto error_return;
3974             }
3975         }
3976     }
3977
3978   /* Free up the buffers used by xcoff_link_input_bfd.  */
3979
3980   if (finfo.internal_syms != NULL)
3981     {
3982       free (finfo.internal_syms);
3983       finfo.internal_syms = NULL;
3984     }
3985   if (finfo.sym_indices != NULL)
3986     {
3987       free (finfo.sym_indices);
3988       finfo.sym_indices = NULL;
3989     }
3990   if (finfo.linenos != NULL)
3991     {
3992       free (finfo.linenos);
3993       finfo.linenos = NULL;
3994     }
3995   if (finfo.contents != NULL)
3996     {
3997       free (finfo.contents);
3998       finfo.contents = NULL;
3999     }
4000   if (finfo.external_relocs != NULL)
4001     {
4002       free (finfo.external_relocs);
4003       finfo.external_relocs = NULL;
4004     }
4005
4006   /* The value of the last C_FILE symbol is supposed to be -1.  Write
4007      it out again.  */
4008   if (finfo.last_file_index != -1)
4009     {
4010       finfo.last_file.n_value = -1;
4011       bfd_coff_swap_sym_out (abfd, (PTR) &finfo.last_file,
4012                              (PTR) finfo.outsyms);
4013       if (bfd_seek (abfd,
4014                     (obj_sym_filepos (abfd)
4015                      + finfo.last_file_index * symesz),
4016                     SEEK_SET) != 0
4017           || bfd_write (finfo.outsyms, symesz, 1, abfd) != symesz)
4018         goto error_return;
4019     }
4020
4021   /* Write out all the global symbols which do not come from XCOFF
4022      input files.  */
4023   xcoff_link_hash_traverse (xcoff_hash_table (info),
4024                             xcoff_write_global_symbol,
4025                             (PTR) &finfo);
4026
4027   if (finfo.outsyms != NULL)
4028     {
4029       free (finfo.outsyms);
4030       finfo.outsyms = NULL;
4031     }
4032
4033   /* Now that we have written out all the global symbols, we know the
4034      symbol indices to use for relocs against them, and we can finally
4035      write out the relocs.  */
4036   external_relocs = (bfd_byte *) malloc (max_output_reloc_count * relsz);
4037   if (external_relocs == NULL && max_output_reloc_count != 0)
4038     {
4039       bfd_set_error (bfd_error_no_memory);
4040       goto error_return;
4041     }
4042
4043   for (o = abfd->sections; o != NULL; o = o->next)
4044     {
4045       struct internal_reloc *irel;
4046       struct internal_reloc *irelend;
4047       struct xcoff_link_hash_entry **rel_hash;
4048       struct xcoff_toc_rel_hash *toc_rel_hash;
4049       bfd_byte *erel;
4050
4051       if (o->reloc_count == 0)
4052         continue;
4053
4054       irel = finfo.section_info[o->target_index].relocs;
4055       irelend = irel + o->reloc_count;
4056       rel_hash = finfo.section_info[o->target_index].rel_hashes;
4057       for (; irel < irelend; irel++, rel_hash++, erel += relsz)
4058         {
4059           if (*rel_hash != NULL)
4060             {
4061               if ((*rel_hash)->indx < 0)
4062                 {
4063                   if (! ((*info->callbacks->unattached_reloc)
4064                          (info, (*rel_hash)->root.root.string,
4065                           (bfd *) NULL, o, irel->r_vaddr)))
4066                     goto error_return;
4067                   (*rel_hash)->indx = 0;
4068                 }
4069               irel->r_symndx = (*rel_hash)->indx;
4070             }
4071         }
4072
4073       for (toc_rel_hash = finfo.section_info[o->target_index].toc_rel_hashes;
4074            toc_rel_hash != NULL;
4075            toc_rel_hash = toc_rel_hash->next)
4076         {
4077           if (toc_rel_hash->h->u.toc_indx < 0)
4078             {
4079               if (! ((*info->callbacks->unattached_reloc)
4080                      (info, toc_rel_hash->h->root.root.string,
4081                       (bfd *) NULL, o, toc_rel_hash->rel->r_vaddr)))
4082                 goto error_return;
4083               toc_rel_hash->h->u.toc_indx = 0;
4084             }
4085           toc_rel_hash->rel->r_symndx = toc_rel_hash->h->u.toc_indx;
4086         }
4087
4088       /* XCOFF requires that the relocs be sorted by address.  We tend
4089          to produce them in the order in which their containing csects
4090          appear in the symbol table, which is not necessarily by
4091          address.  So we sort them here.  There may be a better way to
4092          do this.  */
4093       qsort ((PTR) finfo.section_info[o->target_index].relocs,
4094              o->reloc_count, sizeof (struct internal_reloc),
4095              xcoff_sort_relocs);
4096
4097       irel = finfo.section_info[o->target_index].relocs;
4098       irelend = irel + o->reloc_count;
4099       erel = external_relocs;
4100       for (; irel < irelend; irel++, rel_hash++, erel += relsz)
4101         bfd_coff_swap_reloc_out (abfd, (PTR) irel, (PTR) erel);
4102
4103       if (bfd_seek (abfd, o->rel_filepos, SEEK_SET) != 0
4104           || bfd_write ((PTR) external_relocs, relsz, o->reloc_count,
4105                         abfd) != relsz * o->reloc_count)
4106         goto error_return;
4107     }
4108
4109   if (external_relocs != NULL)
4110     {
4111       free (external_relocs);
4112       external_relocs = NULL;
4113     }
4114
4115   /* Free up the section information.  */
4116   if (finfo.section_info != NULL)
4117     {
4118       unsigned int i;
4119
4120       for (i = 0; i < abfd->section_count; i++)
4121         {
4122           if (finfo.section_info[i].relocs != NULL)
4123             free (finfo.section_info[i].relocs);
4124           if (finfo.section_info[i].rel_hashes != NULL)
4125             free (finfo.section_info[i].rel_hashes);
4126         }
4127       free (finfo.section_info);
4128       finfo.section_info = NULL;
4129     }
4130
4131   /* Write out the loader section contents.  */
4132   BFD_ASSERT ((bfd_byte *) finfo.ldrel
4133               == (xcoff_hash_table (info)->loader_section->contents
4134                   + xcoff_hash_table (info)->ldhdr.l_impoff));
4135   o = xcoff_hash_table (info)->loader_section;
4136   if (! bfd_set_section_contents (abfd, o->output_section,
4137                                   o->contents, o->output_offset,
4138                                   o->_raw_size))
4139     goto error_return;
4140
4141   /* Write out the magic sections.  */
4142   o = xcoff_hash_table (info)->linkage_section;
4143   if (o->_raw_size > 0
4144       && ! bfd_set_section_contents (abfd, o->output_section, o->contents,
4145                                      o->output_offset, o->_raw_size))
4146     goto error_return;
4147   o = xcoff_hash_table (info)->toc_section;
4148   if (o->_raw_size > 0
4149       && ! bfd_set_section_contents (abfd, o->output_section, o->contents,
4150                                      o->output_offset, o->_raw_size))
4151     goto error_return;
4152   o = xcoff_hash_table (info)->descriptor_section;
4153   if (o->_raw_size > 0
4154       && ! bfd_set_section_contents (abfd, o->output_section, o->contents,
4155                                      o->output_offset, o->_raw_size))
4156     goto error_return;
4157
4158   /* Write out the string table.  */
4159   if (bfd_seek (abfd,
4160                 (obj_sym_filepos (abfd)
4161                  + obj_raw_syment_count (abfd) * symesz),
4162                 SEEK_SET) != 0)
4163     goto error_return;
4164   bfd_h_put_32 (abfd,
4165                 _bfd_stringtab_size (finfo.strtab) + STRING_SIZE_SIZE,
4166                 (bfd_byte *) strbuf);
4167   if (bfd_write (strbuf, 1, STRING_SIZE_SIZE, abfd) != STRING_SIZE_SIZE)
4168     goto error_return;
4169   if (! _bfd_stringtab_emit (abfd, finfo.strtab))
4170     goto error_return;
4171
4172   _bfd_stringtab_free (finfo.strtab);
4173
4174   /* Write out the debugging string table.  */
4175   o = xcoff_hash_table (info)->debug_section;
4176   if (o != NULL)
4177     {
4178       struct bfd_strtab_hash *debug_strtab;
4179
4180       debug_strtab = xcoff_hash_table (info)->debug_strtab;
4181       BFD_ASSERT (o->output_section->_raw_size - o->output_offset
4182                   >= _bfd_stringtab_size (debug_strtab));
4183       if (bfd_seek (abfd,
4184                     o->output_section->filepos + o->output_offset,
4185                     SEEK_SET) != 0)
4186         goto error_return;
4187       if (! _bfd_stringtab_emit (abfd, debug_strtab))
4188         goto error_return;
4189     }
4190
4191   /* Setting bfd_get_symcount to 0 will cause write_object_contents to
4192      not try to write out the symbols.  */
4193   bfd_get_symcount (abfd) = 0;
4194
4195   return true;
4196
4197  error_return:
4198   if (finfo.strtab != NULL)
4199     _bfd_stringtab_free (finfo.strtab);
4200   if (finfo.section_info != NULL)
4201     {
4202       unsigned int i;
4203
4204       for (i = 0; i < abfd->section_count; i++)
4205         {
4206           if (finfo.section_info[i].relocs != NULL)
4207             free (finfo.section_info[i].relocs);
4208           if (finfo.section_info[i].rel_hashes != NULL)
4209             free (finfo.section_info[i].rel_hashes);
4210         }
4211       free (finfo.section_info);
4212     }
4213   if (finfo.internal_syms != NULL)
4214     free (finfo.internal_syms);
4215   if (finfo.sym_indices != NULL)
4216     free (finfo.sym_indices);
4217   if (finfo.outsyms != NULL)
4218     free (finfo.outsyms);
4219   if (finfo.linenos != NULL)
4220     free (finfo.linenos);
4221   if (finfo.contents != NULL)
4222     free (finfo.contents);
4223   if (finfo.external_relocs != NULL)
4224     free (finfo.external_relocs);
4225   if (external_relocs != NULL)
4226     free (external_relocs);
4227   return false;
4228 }
4229
4230 /* Link an input file into the linker output file.  This function
4231    handles all the sections and relocations of the input file at once.  */
4232
4233 static boolean
4234 xcoff_link_input_bfd (finfo, input_bfd)
4235      struct xcoff_final_link_info *finfo;
4236      bfd *input_bfd;
4237 {
4238   bfd *output_bfd;
4239   const char *strings;
4240   bfd_size_type syment_base;
4241   unsigned int n_tmask;
4242   unsigned int n_btshft;
4243   boolean copy, hash;
4244   bfd_size_type isymesz;
4245   bfd_size_type osymesz;
4246   bfd_size_type linesz;
4247   bfd_byte *esym;
4248   bfd_byte *esym_end;
4249   struct xcoff_link_hash_entry **sym_hash;
4250   struct internal_syment *isymp;
4251   asection **csectpp;
4252   unsigned long *debug_index;
4253   long *indexp;
4254   unsigned long output_index;
4255   bfd_byte *outsym;
4256   unsigned int incls;
4257   asection *oline;
4258   boolean keep_syms;
4259   asection *o;
4260
4261   /* We can just skip DYNAMIC files, unless this is a static link.  */
4262   if ((input_bfd->flags & DYNAMIC) != 0
4263       && ! finfo->info->static_link)
4264     return true;
4265
4266   /* Move all the symbols to the output file.  */
4267
4268   output_bfd = finfo->output_bfd;
4269   strings = NULL;
4270   syment_base = obj_raw_syment_count (output_bfd);
4271   isymesz = bfd_coff_symesz (input_bfd);
4272   osymesz = bfd_coff_symesz (output_bfd);
4273   linesz = bfd_coff_linesz (input_bfd);
4274   BFD_ASSERT (linesz == bfd_coff_linesz (output_bfd));
4275
4276   n_tmask = coff_data (input_bfd)->local_n_tmask;
4277   n_btshft = coff_data (input_bfd)->local_n_btshft;
4278
4279   /* Define macros so that ISFCN, et. al., macros work correctly.  */
4280 #define N_TMASK n_tmask
4281 #define N_BTSHFT n_btshft
4282
4283   copy = false;
4284   if (! finfo->info->keep_memory)
4285     copy = true;
4286   hash = true;
4287   if ((output_bfd->flags & BFD_TRADITIONAL_FORMAT) != 0)
4288     hash = false;
4289
4290   if (! _bfd_coff_get_external_symbols (input_bfd))
4291     return false;
4292
4293   esym = (bfd_byte *) obj_coff_external_syms (input_bfd);
4294   esym_end = esym + obj_raw_syment_count (input_bfd) * isymesz;
4295   sym_hash = obj_xcoff_sym_hashes (input_bfd);
4296   csectpp = xcoff_data (input_bfd)->csects;
4297   debug_index = xcoff_data (input_bfd)->debug_indices;
4298   isymp = finfo->internal_syms;
4299   indexp = finfo->sym_indices;
4300   output_index = syment_base;
4301   outsym = finfo->outsyms;
4302   incls = 0;
4303   oline = NULL;
4304
4305   while (esym < esym_end)
4306     {
4307       struct internal_syment isym;
4308       union internal_auxent aux;
4309       int smtyp = 0;
4310       boolean skip;
4311       boolean require;
4312       int add;
4313
4314       bfd_coff_swap_sym_in (input_bfd, (PTR) esym, (PTR) isymp);
4315
4316       /* If this is a C_EXT or C_HIDEXT symbol, we need the csect
4317          information.  */
4318       if (isymp->n_sclass == C_EXT || isymp->n_sclass == C_HIDEXT)
4319         {
4320           BFD_ASSERT (isymp->n_numaux > 0);
4321           bfd_coff_swap_aux_in (input_bfd,
4322                                 (PTR) (esym + isymesz * isymp->n_numaux),
4323                                 isymp->n_type, isymp->n_sclass,
4324                                 isymp->n_numaux - 1, isymp->n_numaux,
4325                                 (PTR) &aux);
4326           smtyp = SMTYP_SMTYP (aux.x_csect.x_smtyp);
4327         }
4328
4329       /* Make a copy of *isymp so that the relocate_section function
4330          always sees the original values.  This is more reliable than
4331          always recomputing the symbol value even if we are stripping
4332          the symbol.  */
4333       isym = *isymp;
4334
4335       /* If this symbol is in the .loader section, swap out the
4336          .loader symbol information.  If this is an external symbol
4337          reference to a defined symbol, though, then wait until we get
4338          to the definition.  */
4339       if (isym.n_sclass == C_EXT
4340           && *sym_hash != NULL
4341           && (*sym_hash)->ldsym != NULL
4342           && (smtyp != XTY_ER
4343               || (*sym_hash)->root.type == bfd_link_hash_undefined))
4344         {
4345           struct xcoff_link_hash_entry *h;
4346           struct internal_ldsym *ldsym;
4347
4348           h = *sym_hash;
4349           ldsym = h->ldsym;
4350           if (isym.n_scnum > 0)
4351             {
4352               ldsym->l_scnum = (*csectpp)->output_section->target_index;
4353               ldsym->l_value = (isym.n_value
4354                                 + (*csectpp)->output_section->vma
4355                                 + (*csectpp)->output_offset
4356                                 - (*csectpp)->vma);
4357             }
4358           else
4359             {
4360               ldsym->l_scnum = isym.n_scnum;
4361               ldsym->l_value = isym.n_value;
4362             }
4363
4364           ldsym->l_smtype = smtyp;
4365           if (((h->flags & XCOFF_DEF_REGULAR) == 0
4366                && (h->flags & XCOFF_DEF_DYNAMIC) != 0)
4367               || (h->flags & XCOFF_IMPORT) != 0)
4368             ldsym->l_smtype |= L_IMPORT;
4369           if (((h->flags & XCOFF_DEF_REGULAR) != 0
4370                && (h->flags & XCOFF_DEF_DYNAMIC) != 0)
4371               || (h->flags & XCOFF_EXPORT) != 0)
4372             ldsym->l_smtype |= L_EXPORT;
4373           if ((h->flags & XCOFF_ENTRY) != 0)
4374             ldsym->l_smtype |= L_ENTRY;
4375
4376           ldsym->l_smclas = aux.x_csect.x_smclas;
4377
4378           if (ldsym->l_ifile == (bfd_size_type) -1)
4379             ldsym->l_ifile = 0;
4380           else if (ldsym->l_ifile == 0)
4381             {
4382               if ((ldsym->l_smtype & L_IMPORT) == 0)
4383                 ldsym->l_ifile = 0;
4384               else
4385                 {
4386                   bfd *impbfd;
4387
4388                   if (h->root.type == bfd_link_hash_defined
4389                       || h->root.type == bfd_link_hash_defweak)
4390                     impbfd = h->root.u.def.section->owner;
4391                   else if (h->root.type == bfd_link_hash_undefined
4392                            || h->root.type == bfd_link_hash_undefweak)
4393                     impbfd = h->root.u.undef.abfd;
4394                   else
4395                     impbfd = NULL;
4396
4397                   if (impbfd == NULL)
4398                     ldsym->l_ifile = 0;
4399                   else
4400                     {
4401                       BFD_ASSERT (impbfd->xvec == finfo->output_bfd->xvec);
4402                       ldsym->l_ifile = xcoff_data (impbfd)->import_file_id;
4403                     }
4404                 }
4405             }
4406
4407           ldsym->l_parm = 0;
4408
4409           BFD_ASSERT (h->ldindx >= 0);
4410           BFD_ASSERT (LDSYMSZ == sizeof (struct external_ldsym));
4411           xcoff_swap_ldsym_out (finfo->output_bfd, ldsym,
4412                                 finfo->ldsym + h->ldindx - 3);
4413           h->ldsym = NULL;
4414
4415           /* Fill in snentry now that we know the target_index.  */
4416           if ((h->flags & XCOFF_ENTRY) != 0
4417               && (h->root.type == bfd_link_hash_defined
4418                   || h->root.type == bfd_link_hash_defweak))
4419             xcoff_data (output_bfd)->snentry =
4420               h->root.u.def.section->output_section->target_index;
4421         }
4422
4423       *indexp = -1;
4424
4425       skip = false;
4426       require = false;
4427       add = 1 + isym.n_numaux;
4428
4429       /* If we are skipping this csect, we want to skip this symbol.  */
4430       if (*csectpp == NULL)
4431         skip = true;
4432
4433       /* If we garbage collected this csect, we want to skip this
4434          symbol.  */
4435       if (! skip
4436           && xcoff_hash_table (finfo->info)->gc
4437           && ((*csectpp)->flags & SEC_MARK) == 0
4438           && *csectpp != bfd_abs_section_ptr)
4439         skip = true;
4440
4441       /* An XCOFF linker always skips C_STAT symbols.  */
4442       if (! skip
4443           && isymp->n_sclass == C_STAT)
4444         skip = true;
4445
4446       /* We skip all but the first TOC anchor.  */
4447       if (! skip
4448           && isymp->n_sclass == C_HIDEXT
4449           && aux.x_csect.x_smclas == XMC_TC0)
4450         {
4451           if (finfo->toc_symindx != -1)
4452             skip = true;
4453           else
4454             {
4455               bfd_vma tocval, tocend;
4456
4457               tocval = ((*csectpp)->output_section->vma
4458                         + (*csectpp)->output_offset
4459                         + isym.n_value
4460                         - (*csectpp)->vma);
4461               /* We want to find out if tocval is a good value to use
4462                  as the TOC anchor--that is, whether we can access all
4463                  of the TOC using a 16 bit offset from tocval.  This
4464                  test assumes that the TOC comes at the end of the
4465                  output section, as it does in the default linker
4466                  script.  */
4467
4468               tocend = ((*csectpp)->output_section->vma
4469                         + (*csectpp)->output_section->_raw_size);
4470
4471               if (tocval + 0x10000 < tocend)
4472                 {
4473                   (*_bfd_error_handler)
4474                     ("TOC overflow: 0x%lx > 0x10000; try -mminimal-toc when compiling",
4475                      (unsigned long) (tocend - tocval));
4476                   bfd_set_error (bfd_error_file_too_big);
4477                   return false;
4478                 }
4479
4480               if (tocval + 0x8000 < tocend)
4481                 {
4482                   bfd_vma tocadd;
4483
4484                   tocadd = tocend - (tocval + 0x8000);
4485                   tocval += tocadd;
4486                   isym.n_value += tocadd;
4487                 }
4488
4489               finfo->toc_symindx = output_index;
4490               xcoff_data (finfo->output_bfd)->toc = tocval;
4491               xcoff_data (finfo->output_bfd)->sntoc =
4492                 (*csectpp)->output_section->target_index;
4493               require = true;
4494             }
4495         }
4496
4497       /* If we are stripping all symbols, we want to skip this one.  */
4498       if (! skip
4499           && finfo->info->strip == strip_all)
4500         skip = true;
4501
4502       /* We can skip resolved external references.  */
4503       if (! skip
4504           && isym.n_sclass == C_EXT
4505           && smtyp == XTY_ER
4506           && (*sym_hash)->root.type != bfd_link_hash_undefined)
4507         skip = true;
4508
4509       /* We can skip common symbols if they got defined somewhere
4510          else.  */
4511       if (! skip
4512           && isym.n_sclass == C_EXT
4513           && smtyp == XTY_CM
4514           && ((*sym_hash)->root.type != bfd_link_hash_common
4515               || (*sym_hash)->root.u.c.p->section != *csectpp)
4516           && ((*sym_hash)->root.type != bfd_link_hash_defined
4517               || (*sym_hash)->root.u.def.section != *csectpp))
4518         skip = true;
4519
4520       /* Skip local symbols if we are discarding them.  */
4521       if (! skip
4522           && finfo->info->discard == discard_all
4523           && isym.n_sclass != C_EXT
4524           && (isym.n_sclass != C_HIDEXT
4525               || smtyp != XTY_SD))
4526         skip = true;
4527
4528       /* If we stripping debugging symbols, and this is a debugging
4529          symbol, then skip it.  */
4530       if (! skip
4531           && finfo->info->strip == strip_debugger
4532           && isym.n_scnum == N_DEBUG)
4533         skip = true;
4534
4535       /* If some symbols are stripped based on the name, work out the
4536          name and decide whether to skip this symbol.  We don't handle
4537          this correctly for symbols whose names are in the .debug
4538          section; to get it right we would need a new bfd_strtab_hash
4539          function to return the string given the index.  */
4540       if (! skip
4541           && (finfo->info->strip == strip_some
4542               || finfo->info->discard == discard_l)
4543           && (debug_index == NULL || *debug_index == (unsigned long) -1))
4544         {
4545           const char *name;
4546           char buf[SYMNMLEN + 1];
4547
4548           name = _bfd_coff_internal_syment_name (input_bfd, &isym, buf);
4549           if (name == NULL)
4550             return false;
4551
4552           if ((finfo->info->strip == strip_some
4553                && (bfd_hash_lookup (finfo->info->keep_hash, name, false,
4554                                     false) == NULL))
4555               || (finfo->info->discard == discard_l
4556                   && (isym.n_sclass != C_EXT
4557                       && (isym.n_sclass != C_HIDEXT
4558                           || smtyp != XTY_SD))
4559                   && strncmp (name, finfo->info->lprefix,
4560                               finfo->info->lprefix_len) == 0))
4561             skip = true;
4562         }
4563
4564       /* We can not skip the first TOC anchor.  */
4565       if (skip
4566           && require
4567           && finfo->info->strip != strip_all)
4568         skip = false;
4569
4570       /* We now know whether we are to skip this symbol or not.  */
4571       if (! skip)
4572         {
4573           /* Adjust the symbol in order to output it.  */
4574
4575           if (isym._n._n_n._n_zeroes == 0
4576               && isym._n._n_n._n_offset != 0)
4577             {
4578               /* This symbol has a long name.  Enter it in the string
4579                  table we are building.  If *debug_index != -1, the
4580                  name has already been entered in the .debug section.  */
4581               if (debug_index != NULL && *debug_index != (unsigned long) -1)
4582                 isym._n._n_n._n_offset = *debug_index;
4583               else
4584                 {
4585                   const char *name;
4586                   bfd_size_type indx;
4587
4588                   name = _bfd_coff_internal_syment_name (input_bfd, &isym,
4589                                                          (char *) NULL);
4590                   if (name == NULL)
4591                     return false;
4592                   indx = _bfd_stringtab_add (finfo->strtab, name, hash, copy);
4593                   if (indx == (bfd_size_type) -1)
4594                     return false;
4595                   isym._n._n_n._n_offset = STRING_SIZE_SIZE + indx;
4596                 }
4597             }
4598
4599           if (isym.n_sclass != C_BSTAT
4600               && isym.n_sclass != C_ESTAT
4601               && isym.n_sclass != C_DECL
4602               && isym.n_scnum > 0)
4603             {
4604               isym.n_scnum = (*csectpp)->output_section->target_index;
4605               isym.n_value += ((*csectpp)->output_section->vma
4606                                + (*csectpp)->output_offset
4607                                - (*csectpp)->vma);
4608             }
4609
4610           /* The value of a C_FILE symbol is the symbol index of the
4611              next C_FILE symbol.  The value of the last C_FILE symbol
4612              is -1.  We try to get this right, below, just before we
4613              write the symbols out, but in the general case we may
4614              have to write the symbol out twice.  */
4615           if (isym.n_sclass == C_FILE)
4616             {
4617               if (finfo->last_file_index != -1
4618                   && finfo->last_file.n_value != (long) output_index)
4619                 {
4620                   /* We must correct the value of the last C_FILE entry.  */
4621                   finfo->last_file.n_value = output_index;
4622                   if ((bfd_size_type) finfo->last_file_index >= syment_base)
4623                     {
4624                       /* The last C_FILE symbol is in this input file.  */
4625                       bfd_coff_swap_sym_out (output_bfd,
4626                                              (PTR) &finfo->last_file,
4627                                              (PTR) (finfo->outsyms
4628                                                     + ((finfo->last_file_index
4629                                                         - syment_base)
4630                                                        * osymesz)));
4631                     }
4632                   else
4633                     {
4634                       /* We have already written out the last C_FILE
4635                          symbol.  We need to write it out again.  We
4636                          borrow *outsym temporarily.  */
4637                       bfd_coff_swap_sym_out (output_bfd,
4638                                              (PTR) &finfo->last_file,
4639                                              (PTR) outsym);
4640                       if (bfd_seek (output_bfd,
4641                                     (obj_sym_filepos (output_bfd)
4642                                      + finfo->last_file_index * osymesz),
4643                                     SEEK_SET) != 0
4644                           || (bfd_write (outsym, osymesz, 1, output_bfd)
4645                               != osymesz))
4646                         return false;
4647                     }
4648                 }
4649
4650               finfo->last_file_index = output_index;
4651               finfo->last_file = isym;
4652             }
4653
4654           /* The value of a C_BINCL or C_EINCL symbol is a file offset
4655              into the line numbers.  We update the symbol values when
4656              we handle the line numbers.  */
4657           if (isym.n_sclass == C_BINCL
4658               || isym.n_sclass == C_EINCL)
4659             {
4660               isym.n_value = finfo->line_filepos;
4661               ++incls;
4662             }
4663
4664           /* Output the symbol.  */
4665
4666           bfd_coff_swap_sym_out (output_bfd, (PTR) &isym, (PTR) outsym);
4667
4668           *indexp = output_index;
4669
4670           if (isym.n_sclass == C_EXT)
4671             {
4672               long indx;
4673               struct xcoff_link_hash_entry *h;
4674
4675               indx = ((esym - (bfd_byte *) obj_coff_external_syms (input_bfd))
4676                       / isymesz);
4677               h = obj_xcoff_sym_hashes (input_bfd)[indx];
4678               BFD_ASSERT (h != NULL);
4679               h->indx = output_index;
4680             }
4681
4682           /* If this is a symbol in the TOC which we may have merged
4683              (class XMC_TC), remember the symbol index of the TOC
4684              symbol.  */
4685           if (isym.n_sclass == C_HIDEXT
4686               && aux.x_csect.x_smclas == XMC_TC
4687               && *sym_hash != NULL)
4688             {
4689               BFD_ASSERT (((*sym_hash)->flags & XCOFF_SET_TOC) == 0);
4690               BFD_ASSERT ((*sym_hash)->toc_section != NULL);
4691               (*sym_hash)->u.toc_indx = output_index;
4692             }
4693
4694           output_index += add;
4695           outsym += add * osymesz;
4696         }
4697
4698       esym += add * isymesz;
4699       isymp += add;
4700       csectpp += add;
4701       sym_hash += add;
4702       if (debug_index != NULL)
4703         debug_index += add;
4704       ++indexp;
4705       for (--add; add > 0; --add)
4706         *indexp++ = -1;
4707     }
4708
4709   /* Fix up the aux entries and the C_BSTAT symbols.  This must be
4710      done in a separate pass, because we don't know the correct symbol
4711      indices until we have already decided which symbols we are going
4712      to keep.  */
4713
4714   esym = (bfd_byte *) obj_coff_external_syms (input_bfd);
4715   esym_end = esym + obj_raw_syment_count (input_bfd) * isymesz;
4716   isymp = finfo->internal_syms;
4717   indexp = finfo->sym_indices;
4718   csectpp = xcoff_data (input_bfd)->csects;
4719   outsym = finfo->outsyms;
4720   while (esym < esym_end)
4721     {
4722       int add;
4723
4724       add = 1 + isymp->n_numaux;
4725
4726       if (*indexp < 0)
4727         esym += add * isymesz;
4728       else
4729         {
4730           int i;
4731
4732           if (isymp->n_sclass == C_BSTAT)
4733             {
4734               struct internal_syment isym;
4735               unsigned long indx;
4736
4737               /* The value of a C_BSTAT symbol is the symbol table
4738                  index of the containing csect.  */
4739               bfd_coff_swap_sym_in (output_bfd, (PTR) outsym, (PTR) &isym);
4740               indx = isym.n_value;
4741               if (indx < obj_raw_syment_count (input_bfd))
4742                 {
4743                   long symindx;
4744
4745                   symindx = finfo->sym_indices[indx];
4746                   if (symindx < 0)
4747                     isym.n_value = 0;
4748                   else
4749                     isym.n_value = symindx;
4750                   bfd_coff_swap_sym_out (output_bfd, (PTR) &isym,
4751                                          (PTR) outsym);
4752                 }
4753             }
4754
4755           esym += isymesz;
4756           outsym += osymesz;
4757
4758           for (i = 0; i < isymp->n_numaux && esym < esym_end; i++)
4759             {
4760               union internal_auxent aux;
4761
4762               bfd_coff_swap_aux_in (input_bfd, (PTR) esym, isymp->n_type,
4763                                     isymp->n_sclass, i, isymp->n_numaux,
4764                                     (PTR) &aux);
4765
4766               if (isymp->n_sclass == C_FILE)
4767                 {
4768                   /* This is the file name (or some comment put in by
4769                      the compiler).  If it is long, we must put it in
4770                      the string table.  */
4771                   if (aux.x_file.x_n.x_zeroes == 0
4772                       && aux.x_file.x_n.x_offset != 0)
4773                     {
4774                       const char *filename;
4775                       bfd_size_type indx;
4776
4777                       BFD_ASSERT (aux.x_file.x_n.x_offset
4778                                   >= STRING_SIZE_SIZE);
4779                       if (strings == NULL)
4780                         {
4781                           strings = _bfd_coff_read_string_table (input_bfd);
4782                           if (strings == NULL)
4783                             return false;
4784                         }
4785                       filename = strings + aux.x_file.x_n.x_offset;
4786                       indx = _bfd_stringtab_add (finfo->strtab, filename,
4787                                                  hash, copy);
4788                       if (indx == (bfd_size_type) -1)
4789                         return false;
4790                       aux.x_file.x_n.x_offset = STRING_SIZE_SIZE + indx;
4791                     }
4792                 }
4793               else if ((isymp->n_sclass == C_EXT
4794                         || isymp->n_sclass == C_HIDEXT)
4795                        && i + 1 == isymp->n_numaux)
4796                 {
4797                   /* We don't support type checking.  I don't know if
4798                      anybody does.  */
4799                   aux.x_csect.x_parmhash = 0;
4800                   /* I don't think anybody uses these fields, but we'd
4801                      better clobber them just in case.  */
4802                   aux.x_csect.x_stab = 0;
4803                   aux.x_csect.x_snstab = 0;
4804                   if (SMTYP_SMTYP (aux.x_csect.x_smtyp) == XTY_LD)
4805                     {
4806                       unsigned long indx;
4807
4808                       indx = aux.x_csect.x_scnlen.l;
4809                       if (indx < obj_raw_syment_count (input_bfd))
4810                         {
4811                           long symindx;
4812
4813                           symindx = finfo->sym_indices[indx];
4814                           if (symindx < 0)
4815                             aux.x_sym.x_tagndx.l = 0;
4816                           else
4817                             aux.x_sym.x_tagndx.l = symindx;
4818                         }
4819                     }
4820                 }
4821               else if (isymp->n_sclass != C_STAT || isymp->n_type != T_NULL)
4822                 {
4823                   unsigned long indx;
4824
4825                   if (ISFCN (isymp->n_type)
4826                       || ISTAG (isymp->n_sclass)
4827                       || isymp->n_sclass == C_BLOCK
4828                       || isymp->n_sclass == C_FCN)
4829                     {
4830                       indx = aux.x_sym.x_fcnary.x_fcn.x_endndx.l;
4831                       if (indx > 0
4832                           && indx < obj_raw_syment_count (input_bfd))
4833                         {
4834                           /* We look forward through the symbol for
4835                              the index of the next symbol we are going
4836                              to include.  I don't know if this is
4837                              entirely right.  */
4838                           while (finfo->sym_indices[indx] < 0
4839                                  && indx < obj_raw_syment_count (input_bfd))
4840                             ++indx;
4841                           if (indx >= obj_raw_syment_count (input_bfd))
4842                             indx = output_index;
4843                           else
4844                             indx = finfo->sym_indices[indx];
4845                           aux.x_sym.x_fcnary.x_fcn.x_endndx.l = indx;
4846                         }
4847                     }
4848
4849                   indx = aux.x_sym.x_tagndx.l;
4850                   if (indx > 0 && indx < obj_raw_syment_count (input_bfd))
4851                     {
4852                       long symindx;
4853
4854                       symindx = finfo->sym_indices[indx];
4855                       if (symindx < 0)
4856                         aux.x_sym.x_tagndx.l = 0;
4857                       else
4858                         aux.x_sym.x_tagndx.l = symindx;
4859                     }
4860                 }
4861
4862               /* Copy over the line numbers, unless we are stripping
4863                  them.  We do this on a symbol by symbol basis in
4864                  order to more easily handle garbage collection.  */
4865               if ((isymp->n_sclass == C_EXT
4866                    || isymp->n_sclass == C_HIDEXT)
4867                   && i == 0
4868                   && isymp->n_numaux > 1
4869                   && ISFCN (isymp->n_type)
4870                   && aux.x_sym.x_fcnary.x_fcn.x_lnnoptr != 0)
4871                 {
4872                   if (finfo->info->strip != strip_none
4873                       && finfo->info->strip != strip_some)
4874                     aux.x_sym.x_fcnary.x_fcn.x_lnnoptr = 0;
4875                   else
4876                     {
4877                       asection *enclosing;
4878                       unsigned int enc_count;
4879                       bfd_size_type linoff;
4880                       struct internal_lineno lin;
4881
4882                       o = *csectpp;
4883                       enclosing = xcoff_section_data (abfd, o)->enclosing;
4884                       enc_count = xcoff_section_data (abfd, o)->lineno_count;
4885                       if (oline != enclosing)
4886                         {
4887                           if (bfd_seek (input_bfd,
4888                                         enclosing->line_filepos,
4889                                         SEEK_SET) != 0
4890                               || (bfd_read (finfo->linenos, linesz,
4891                                             enc_count, input_bfd)
4892                                   != linesz * enc_count))
4893                             return false;
4894                           oline = enclosing;
4895                         }
4896
4897                       linoff = (aux.x_sym.x_fcnary.x_fcn.x_lnnoptr
4898                                 - enclosing->line_filepos);
4899
4900                       bfd_coff_swap_lineno_in (input_bfd,
4901                                                (PTR) (finfo->linenos + linoff),
4902                                                (PTR) &lin);
4903                       if (lin.l_lnno != 0
4904                           || ((bfd_size_type) lin.l_addr.l_symndx
4905                               != ((esym
4906                                    - isymesz
4907                                    - ((bfd_byte *)
4908                                       obj_coff_external_syms (input_bfd)))
4909                                   / isymesz)))
4910                         aux.x_sym.x_fcnary.x_fcn.x_lnnoptr = 0;
4911                       else
4912                         {
4913                           bfd_byte *linpend, *linp;
4914                           bfd_vma offset;
4915                           bfd_size_type count;
4916
4917                           lin.l_addr.l_symndx = *indexp;
4918                           bfd_coff_swap_lineno_out (output_bfd, (PTR) &lin,
4919                                                     (PTR) (finfo->linenos
4920                                                            + linoff));
4921
4922                           linpend = (finfo->linenos
4923                                      + enc_count * linesz);
4924                           offset = (o->output_section->vma
4925                                     + o->output_offset
4926                                     - o->vma);
4927                           for (linp = finfo->linenos + linoff + linesz;
4928                                linp < linpend;
4929                                linp += linesz)
4930                             {
4931                               bfd_coff_swap_lineno_in (input_bfd, (PTR) linp,
4932                                                        (PTR) &lin);
4933                               if (lin.l_lnno == 0)
4934                                 break;
4935                               lin.l_addr.l_paddr += offset;
4936                               bfd_coff_swap_lineno_out (output_bfd,
4937                                                         (PTR) &lin,
4938                                                         (PTR) linp);
4939                             }
4940
4941                           count = (linp - (finfo->linenos + linoff)) / linesz;
4942
4943                           aux.x_sym.x_fcnary.x_fcn.x_lnnoptr =
4944                             (o->output_section->line_filepos
4945                              + o->output_section->lineno_count * linesz);
4946
4947                           if (bfd_seek (output_bfd,
4948                                         aux.x_sym.x_fcnary.x_fcn.x_lnnoptr,
4949                                         SEEK_SET) != 0
4950                               || (bfd_write (finfo->linenos + linoff,
4951                                              linesz, count, output_bfd)
4952                                   != linesz * count))
4953                             return false;
4954
4955                           o->output_section->lineno_count += count;
4956
4957                           if (incls > 0)
4958                             {
4959                               struct internal_syment *iisp, *iispend;
4960                               long *iindp;
4961                               bfd_byte *oos;
4962                               int iiadd;
4963
4964                               /* Update any C_BINCL or C_EINCL symbols
4965                                  that refer to a line number in the
4966                                  range we just output.  */
4967                               iisp = finfo->internal_syms;
4968                               iispend = (iisp
4969                                          + obj_raw_syment_count (input_bfd));
4970                               iindp = finfo->sym_indices;
4971                               oos = finfo->outsyms;
4972                               while (iisp < iispend)
4973                                 {
4974                                   if (*iindp >= 0
4975                                       && (iisp->n_sclass == C_BINCL
4976                                           || iisp->n_sclass == C_EINCL)
4977                                       && ((bfd_size_type) iisp->n_value
4978                                           >= enclosing->line_filepos + linoff)
4979                                       && ((bfd_size_type) iisp->n_value
4980                                           < (enclosing->line_filepos
4981                                              + enc_count * linesz)))
4982                                     {
4983                                       struct internal_syment iis;
4984
4985                                       bfd_coff_swap_sym_in (output_bfd,
4986                                                             (PTR) oos,
4987                                                             (PTR) &iis);
4988                                       iis.n_value =
4989                                         (iisp->n_value
4990                                          - enclosing->line_filepos
4991                                          - linoff
4992                                          + aux.x_sym.x_fcnary.x_fcn.x_lnnoptr);
4993                                       bfd_coff_swap_sym_out (output_bfd,
4994                                                              (PTR) &iis,
4995                                                              (PTR) oos);
4996                                       --incls;
4997                                     }
4998
4999                                   iiadd = 1 + iisp->n_numaux;
5000                                   if (*iindp >= 0)
5001                                     oos += iiadd * osymesz;
5002                                   iisp += iiadd;
5003                                   iindp += iiadd;
5004                                 }
5005                             }
5006                         }
5007                     }
5008                 }
5009
5010               bfd_coff_swap_aux_out (output_bfd, (PTR) &aux, isymp->n_type,
5011                                      isymp->n_sclass, i, isymp->n_numaux,
5012                                      (PTR) outsym);
5013               outsym += osymesz;
5014               esym += isymesz;
5015             }
5016         }
5017
5018       indexp += add;
5019       isymp += add;
5020       csectpp += add;
5021     }
5022
5023   /* If we swapped out a C_FILE symbol, guess that the next C_FILE
5024      symbol will be the first symbol in the next input file.  In the
5025      normal case, this will save us from writing out the C_FILE symbol
5026      again.  */
5027   if (finfo->last_file_index != -1
5028       && (bfd_size_type) finfo->last_file_index >= syment_base)
5029     {
5030       finfo->last_file.n_value = output_index;
5031       bfd_coff_swap_sym_out (output_bfd, (PTR) &finfo->last_file,
5032                              (PTR) (finfo->outsyms
5033                                     + ((finfo->last_file_index - syment_base)
5034                                        * osymesz)));
5035     }
5036
5037   /* Write the modified symbols to the output file.  */
5038   if (outsym > finfo->outsyms)
5039     {
5040       if (bfd_seek (output_bfd,
5041                     obj_sym_filepos (output_bfd) + syment_base * osymesz,
5042                     SEEK_SET) != 0
5043           || (bfd_write (finfo->outsyms, outsym - finfo->outsyms, 1,
5044                         output_bfd)
5045               != (bfd_size_type) (outsym - finfo->outsyms)))
5046         return false;
5047
5048       BFD_ASSERT ((obj_raw_syment_count (output_bfd)
5049                    + (outsym - finfo->outsyms) / osymesz)
5050                   == output_index);
5051
5052       obj_raw_syment_count (output_bfd) = output_index;
5053     }
5054
5055   /* Don't let the linker relocation routines discard the symbols.  */
5056   keep_syms = obj_coff_keep_syms (input_bfd);
5057   obj_coff_keep_syms (input_bfd) = true;
5058
5059   /* Relocate the contents of each section.  */
5060   for (o = input_bfd->sections; o != NULL; o = o->next)
5061     {
5062       bfd_byte *contents;
5063
5064       if (! o->linker_mark)
5065         {
5066           /* This section was omitted from the link.  */
5067           continue;
5068         }
5069
5070       if ((o->flags & SEC_HAS_CONTENTS) == 0
5071           || o->_raw_size == 0
5072           || (o->flags & SEC_IN_MEMORY) != 0)
5073         continue;
5074
5075       /* We have set filepos correctly for the sections we created to
5076          represent csects, so bfd_get_section_contents should work.  */
5077       if (coff_section_data (input_bfd, o) != NULL
5078           && coff_section_data (input_bfd, o)->contents != NULL)
5079         contents = coff_section_data (input_bfd, o)->contents;
5080       else
5081         {
5082           if (! bfd_get_section_contents (input_bfd, o, finfo->contents,
5083                                           (file_ptr) 0, o->_raw_size))
5084             return false;
5085           contents = finfo->contents;
5086         }
5087
5088       if ((o->flags & SEC_RELOC) != 0)
5089         {
5090           int target_index;
5091           struct internal_reloc *internal_relocs;
5092           struct internal_reloc *irel;
5093           bfd_vma offset;
5094           struct internal_reloc *irelend;
5095           struct xcoff_link_hash_entry **rel_hash;
5096           long r_symndx;
5097
5098           /* Read in the relocs.  */
5099           target_index = o->output_section->target_index;
5100           internal_relocs = (xcoff_read_internal_relocs
5101                              (input_bfd, o, false, finfo->external_relocs,
5102                               true,
5103                               (finfo->section_info[target_index].relocs
5104                                + o->output_section->reloc_count)));
5105           if (internal_relocs == NULL)
5106             return false;
5107
5108           /* Call processor specific code to relocate the section
5109              contents.  */
5110           if (! bfd_coff_relocate_section (output_bfd, finfo->info,
5111                                            input_bfd, o,
5112                                            contents,
5113                                            internal_relocs,
5114                                            finfo->internal_syms,
5115                                            xcoff_data (input_bfd)->csects))
5116             return false;
5117
5118           offset = o->output_section->vma + o->output_offset - o->vma;
5119           irel = internal_relocs;
5120           irelend = irel + o->reloc_count;
5121           rel_hash = (finfo->section_info[target_index].rel_hashes
5122                       + o->output_section->reloc_count);
5123           for (; irel < irelend; irel++, rel_hash++)
5124             {
5125               struct xcoff_link_hash_entry *h = NULL;
5126               struct internal_ldrel ldrel;
5127
5128               *rel_hash = NULL;
5129
5130               /* Adjust the reloc address and symbol index.  */
5131
5132               irel->r_vaddr += offset;
5133
5134               r_symndx = irel->r_symndx;
5135
5136               if (r_symndx != -1)
5137                 {
5138                   h = obj_xcoff_sym_hashes (input_bfd)[r_symndx];
5139                   if (h != NULL
5140                       && h->smclas != XMC_TD
5141                       && (irel->r_type == R_TOC
5142                           || irel->r_type == R_GL
5143                           || irel->r_type == R_TCL
5144                           || irel->r_type == R_TRL
5145                           || irel->r_type == R_TRLA))
5146                     {
5147                       /* This is a TOC relative reloc with a symbol
5148                          attached.  The symbol should be the one which
5149                          this reloc is for.  We want to make this
5150                          reloc against the TOC address of the symbol,
5151                          not the symbol itself.  */
5152                       BFD_ASSERT (h->toc_section != NULL);
5153                       BFD_ASSERT ((h->flags & XCOFF_SET_TOC) == 0);
5154                       if (h->u.toc_indx != -1)
5155                         irel->r_symndx = h->u.toc_indx;
5156                       else
5157                         {
5158                           struct xcoff_toc_rel_hash *n;
5159                           struct xcoff_link_section_info *si;
5160
5161                           n = ((struct xcoff_toc_rel_hash *)
5162                                bfd_alloc (finfo->output_bfd,
5163                                           sizeof (struct xcoff_toc_rel_hash)));
5164                           if (n == NULL)
5165                             return false;
5166                           si = finfo->section_info + target_index;
5167                           n->next = si->toc_rel_hashes;
5168                           n->h = h;
5169                           n->rel = irel;
5170                           si->toc_rel_hashes = n;
5171                         }
5172                     }
5173                   else if (h != NULL)
5174                     {
5175                       /* This is a global symbol.  */
5176                       if (h->indx >= 0)
5177                         irel->r_symndx = h->indx;
5178                       else
5179                         {
5180                           /* This symbol is being written at the end
5181                              of the file, and we do not yet know the
5182                              symbol index.  We save the pointer to the
5183                              hash table entry in the rel_hash list.
5184                              We set the indx field to -2 to indicate
5185                              that this symbol must not be stripped.  */
5186                           *rel_hash = h;
5187                           h->indx = -2;
5188                         }
5189                     }
5190                   else
5191                     {
5192                       long indx;
5193
5194                       indx = finfo->sym_indices[r_symndx];
5195
5196                       if (indx == -1)
5197                         {
5198                           struct internal_syment *is;
5199
5200                           /* Relocations against a TC0 TOC anchor are
5201                              automatically transformed to be against
5202                              the TOC anchor in the output file.  */
5203                           is = finfo->internal_syms + r_symndx;
5204                           if (is->n_sclass == C_HIDEXT
5205                               && is->n_numaux > 0)
5206                             {
5207                               PTR auxptr;
5208                               union internal_auxent aux;
5209
5210                               auxptr = ((PTR)
5211                                         (((bfd_byte *)
5212                                           obj_coff_external_syms (input_bfd))
5213                                          + ((r_symndx + is->n_numaux)
5214                                             * isymesz)));
5215                               bfd_coff_swap_aux_in (input_bfd, auxptr,
5216                                                     is->n_type, is->n_sclass,
5217                                                     is->n_numaux - 1,
5218                                                     is->n_numaux,
5219                                                     (PTR) &aux);
5220                               if (SMTYP_SMTYP (aux.x_csect.x_smtyp) == XTY_SD
5221                                   && aux.x_csect.x_smclas == XMC_TC0)
5222                                 indx = finfo->toc_symindx;
5223                             }
5224                         }
5225
5226                       if (indx != -1)
5227                         irel->r_symndx = indx;
5228                       else
5229                         {
5230                           struct internal_syment *is;
5231                           const char *name;
5232                           char buf[SYMNMLEN + 1];
5233
5234                           /* This reloc is against a symbol we are
5235                              stripping.  It would be possible to handle
5236                              this case, but I don't think it's worth it.  */
5237                           is = finfo->internal_syms + r_symndx;
5238
5239                           name = (_bfd_coff_internal_syment_name
5240                                   (input_bfd, is, buf));
5241                           if (name == NULL)
5242                             return false;
5243
5244                           if (! ((*finfo->info->callbacks->unattached_reloc)
5245                                  (finfo->info, name, input_bfd, o,
5246                                   irel->r_vaddr)))
5247                             return false;
5248                         }
5249                     }
5250                 }
5251
5252               switch (irel->r_type)
5253                 {
5254                 default:
5255                   if (h == NULL
5256                       || h->root.type == bfd_link_hash_defined
5257                       || h->root.type == bfd_link_hash_defweak
5258                       || h->root.type == bfd_link_hash_common)
5259                     break;
5260                   /* Fall through.  */
5261                 case R_POS:
5262                 case R_NEG:
5263                 case R_RL:
5264                 case R_RLA:
5265                   /* This reloc needs to be copied into the .loader
5266                      section.  */
5267                   ldrel.l_vaddr = irel->r_vaddr;
5268                   if (r_symndx == -1)
5269                     ldrel.l_symndx = -1;
5270                   else if (h == NULL
5271                            || (h->root.type == bfd_link_hash_defined
5272                                || h->root.type == bfd_link_hash_defweak
5273                                || h->root.type == bfd_link_hash_common))
5274                     {
5275                       asection *sec;
5276
5277                       if (h == NULL)
5278                         sec = xcoff_data (input_bfd)->csects[r_symndx];
5279                       else if (h->root.type == bfd_link_hash_common)
5280                         sec = h->root.u.c.p->section;
5281                       else
5282                         sec = h->root.u.def.section;
5283                       sec = sec->output_section;
5284
5285                       if (strcmp (sec->name, ".text") == 0)
5286                         ldrel.l_symndx = 0;
5287                       else if (strcmp (sec->name, ".data") == 0)
5288                         ldrel.l_symndx = 1;
5289                       else if (strcmp (sec->name, ".bss") == 0)
5290                         ldrel.l_symndx = 2;
5291                       else
5292                         {
5293                           (*_bfd_error_handler)
5294                             ("%s: loader reloc in unrecognized section `%s'",
5295                              bfd_get_filename (input_bfd),
5296                              sec->name);
5297                           bfd_set_error (bfd_error_nonrepresentable_section);
5298                           return false;
5299                         }
5300                     }
5301                   else
5302                     {
5303                       if (h->ldindx < 0)
5304                         {
5305                           (*_bfd_error_handler)
5306                             ("%s: `%s' in loader reloc but not loader sym",
5307                              bfd_get_filename (input_bfd),
5308                              h->root.root.string);
5309                           bfd_set_error (bfd_error_bad_value);
5310                           return false;
5311                         }
5312                       ldrel.l_symndx = h->ldindx;
5313                     }
5314                   ldrel.l_rtype = (irel->r_size << 8) | irel->r_type;
5315                   ldrel.l_rsecnm = o->output_section->target_index;
5316                   if (xcoff_hash_table (finfo->info)->textro
5317                       && strcmp (o->output_section->name, ".text") == 0)
5318                     {
5319                       (*_bfd_error_handler)
5320                         ("%s: loader reloc in read-only section %s",
5321                          bfd_get_filename (input_bfd),
5322                          bfd_get_section_name (finfo->output_bfd,
5323                                                o->output_section));
5324                       bfd_set_error (bfd_error_invalid_operation);
5325                       return false;
5326                     }
5327                   xcoff_swap_ldrel_out (output_bfd, &ldrel,
5328                                         finfo->ldrel);
5329                   BFD_ASSERT (sizeof (struct external_ldrel) == LDRELSZ);
5330                   ++finfo->ldrel;
5331                   break;
5332
5333                 case R_TOC:
5334                 case R_GL:
5335                 case R_TCL:
5336                 case R_TRL:
5337                 case R_TRLA:
5338                   /* We should never need a .loader reloc for a TOC
5339                      relative reloc.  */
5340                   break;
5341                 }
5342             }
5343
5344           o->output_section->reloc_count += o->reloc_count;
5345         }
5346
5347       /* Write out the modified section contents.  */
5348       if (! bfd_set_section_contents (output_bfd, o->output_section,
5349                                       contents, o->output_offset,
5350                                       (o->_cooked_size != 0
5351                                        ? o->_cooked_size
5352                                        : o->_raw_size)))
5353         return false;
5354     }
5355
5356   obj_coff_keep_syms (input_bfd) = keep_syms;
5357
5358   if (! finfo->info->keep_memory)
5359     {
5360       if (! _bfd_coff_free_symbols (input_bfd))
5361         return false;
5362     }
5363
5364   return true;
5365 }
5366
5367 #undef N_TMASK
5368 #undef N_BTSHFT
5369
5370 /* Write out a non-XCOFF global symbol.  */
5371
5372 static boolean
5373 xcoff_write_global_symbol (h, p)
5374      struct xcoff_link_hash_entry *h;
5375      PTR p;
5376 {
5377   struct xcoff_final_link_info *finfo = (struct xcoff_final_link_info *) p;
5378   bfd *output_bfd;
5379   bfd_byte *outsym;
5380   struct internal_syment isym;
5381   union internal_auxent aux;
5382
5383   output_bfd = finfo->output_bfd;
5384
5385   /* If this symbol was garbage collected, just skip it.  */
5386   if (xcoff_hash_table (finfo->info)->gc
5387       && (h->flags & XCOFF_MARK) == 0)
5388     return true;
5389
5390   /* If we need a .loader section entry, write it out.  */
5391   if (h->ldsym != NULL)
5392     {
5393       struct internal_ldsym *ldsym;
5394       bfd *impbfd;
5395
5396       ldsym = h->ldsym;
5397
5398       if (h->root.type == bfd_link_hash_undefined
5399           || h->root.type == bfd_link_hash_undefweak)
5400         {
5401           ldsym->l_value = 0;
5402           ldsym->l_scnum = N_UNDEF;
5403           ldsym->l_smtype = XTY_ER;
5404           impbfd = h->root.u.undef.abfd;
5405         }
5406       else if (h->root.type == bfd_link_hash_defined
5407                || h->root.type == bfd_link_hash_defweak)
5408         {
5409           asection *sec;
5410
5411           sec = h->root.u.def.section;
5412           ldsym->l_value = (sec->output_section->vma
5413                             + sec->output_offset
5414                             + h->root.u.def.value);
5415           ldsym->l_scnum = sec->output_section->target_index;
5416           ldsym->l_smtype = XTY_SD;
5417           impbfd = sec->owner;
5418         }
5419       else
5420         abort ();
5421
5422       if (((h->flags & XCOFF_DEF_REGULAR) == 0
5423            && (h->flags & XCOFF_DEF_DYNAMIC) != 0)
5424           || (h->flags & XCOFF_IMPORT) != 0)
5425         ldsym->l_smtype |= L_IMPORT;
5426       if (((h->flags & XCOFF_DEF_REGULAR) != 0
5427            && (h->flags & XCOFF_DEF_DYNAMIC) != 0)
5428           || (h->flags & XCOFF_EXPORT) != 0)
5429         ldsym->l_smtype |= L_EXPORT;
5430       if ((h->flags & XCOFF_ENTRY) != 0)
5431         ldsym->l_smtype |= L_ENTRY;
5432
5433       ldsym->l_smclas = h->smclas;
5434
5435       if (ldsym->l_ifile == (bfd_size_type) -1)
5436         ldsym->l_ifile = 0;
5437       else if (ldsym->l_ifile == 0)
5438         {
5439           if ((ldsym->l_smtype & L_IMPORT) == 0)
5440             ldsym->l_ifile = 0;
5441           else if (impbfd == NULL)
5442             ldsym->l_ifile = 0;
5443           else
5444             {
5445               BFD_ASSERT (impbfd->xvec == output_bfd->xvec);
5446               ldsym->l_ifile = xcoff_data (impbfd)->import_file_id;
5447             }
5448         }
5449
5450       ldsym->l_parm = 0;
5451
5452       BFD_ASSERT (h->ldindx >= 0);
5453       BFD_ASSERT (LDSYMSZ == sizeof (struct external_ldsym));
5454       xcoff_swap_ldsym_out (output_bfd, ldsym, finfo->ldsym + h->ldindx - 3);
5455       h->ldsym = NULL;
5456     }
5457
5458   /* If this symbol needs global linkage code, write it out.  */
5459   if (h->root.type == bfd_link_hash_defined
5460       && (h->root.u.def.section
5461           == xcoff_hash_table (finfo->info)->linkage_section))
5462     {
5463       bfd_byte *p;
5464       bfd_vma tocoff;
5465       unsigned int i;
5466
5467       p = h->root.u.def.section->contents + h->root.u.def.value;
5468
5469       /* The first instruction in the global linkage code loads a
5470          specific TOC element.  */
5471       tocoff = (h->descriptor->toc_section->output_section->vma
5472                 + h->descriptor->toc_section->output_offset
5473                 - xcoff_data (output_bfd)->toc);
5474       if ((h->descriptor->flags & XCOFF_SET_TOC) != 0)
5475         tocoff += h->descriptor->u.toc_offset;
5476       bfd_put_32 (output_bfd, XCOFF_GLINK_FIRST | (tocoff & 0xffff), p);
5477       for (i = 0, p += 4;
5478            i < sizeof xcoff_glink_code / sizeof xcoff_glink_code[0];
5479            i++, p += 4)
5480         bfd_put_32 (output_bfd, xcoff_glink_code[i], p);
5481     }
5482
5483   /* If we created a TOC entry for this symbol, write out the required
5484      relocs.  */
5485   if ((h->flags & XCOFF_SET_TOC) != 0)
5486     {
5487       asection *tocsec;
5488       asection *osec;
5489       int oindx;
5490       struct internal_reloc *irel;
5491       struct internal_ldrel ldrel;
5492
5493       tocsec = h->toc_section;
5494       osec = tocsec->output_section;
5495       oindx = osec->target_index;
5496       irel = finfo->section_info[oindx].relocs + osec->reloc_count;
5497       irel->r_vaddr = (osec->vma
5498                        + tocsec->output_offset
5499                        + h->u.toc_offset);
5500       if (h->indx >= 0)
5501         irel->r_symndx = h->indx;
5502       else
5503         {
5504           h->indx = -2;
5505           irel->r_symndx = obj_raw_syment_count (output_bfd);
5506         }
5507       irel->r_type = R_POS;
5508       irel->r_size = 31;
5509       finfo->section_info[oindx].rel_hashes[osec->reloc_count] = NULL;
5510       ++osec->reloc_count;
5511
5512       BFD_ASSERT (h->ldindx >= 0);
5513       ldrel.l_vaddr = irel->r_vaddr;
5514       ldrel.l_symndx = h->ldindx;
5515       ldrel.l_rtype = (31 << 8) | R_POS;
5516       ldrel.l_rsecnm = oindx;
5517       xcoff_swap_ldrel_out (output_bfd, &ldrel, finfo->ldrel);
5518       ++finfo->ldrel;
5519     }
5520
5521   /* If this symbol is a specially defined function descriptor, write
5522      it out.  The first word is the address of the function code
5523      itself, the second word is the address of the TOC, and the third
5524      word is zero.  */
5525   if ((h->flags & XCOFF_DESCRIPTOR) != 0
5526       && h->root.type == bfd_link_hash_defined
5527       && (h->root.u.def.section
5528           == xcoff_hash_table (finfo->info)->descriptor_section))
5529     {
5530       asection *sec;
5531       asection *osec;
5532       int oindx;
5533       bfd_byte *p;
5534       struct xcoff_link_hash_entry *hentry;
5535       asection *esec;
5536       struct internal_reloc *irel;
5537       struct internal_ldrel ldrel;
5538       asection *tsec;
5539
5540       sec = h->root.u.def.section;
5541       osec = sec->output_section;
5542       oindx = osec->target_index;
5543       p = sec->contents + h->root.u.def.value;
5544
5545       hentry = h->descriptor;
5546       BFD_ASSERT (hentry != NULL
5547                   && (hentry->root.type == bfd_link_hash_defined
5548                       || hentry->root.type == bfd_link_hash_defweak));
5549       esec = hentry->root.u.def.section;
5550       bfd_put_32 (output_bfd,
5551                   (esec->output_section->vma
5552                    + esec->output_offset
5553                    + hentry->root.u.def.value),
5554                   p);
5555
5556       irel = finfo->section_info[oindx].relocs + osec->reloc_count;
5557       irel->r_vaddr = (osec->vma
5558                        + sec->output_offset
5559                        + h->root.u.def.value);
5560       irel->r_symndx = esec->output_section->target_index;
5561       irel->r_type = R_POS;
5562       irel->r_size = 31;
5563       finfo->section_info[oindx].rel_hashes[osec->reloc_count] = NULL;
5564       ++osec->reloc_count;
5565
5566       ldrel.l_vaddr = irel->r_vaddr;
5567       if (strcmp (esec->output_section->name, ".text") == 0)
5568         ldrel.l_symndx = 0;
5569       else if (strcmp (esec->output_section->name, ".data") == 0)
5570         ldrel.l_symndx = 1;
5571       else if (strcmp (esec->output_section->name, ".bss") == 0)
5572         ldrel.l_symndx = 2;
5573       else
5574         {
5575           (*_bfd_error_handler)
5576             ("%s: loader reloc in unrecognized section `%s'",
5577              bfd_get_filename (output_bfd),
5578              esec->output_section->name);
5579           bfd_set_error (bfd_error_nonrepresentable_section);
5580           return false;
5581         }
5582       ldrel.l_rtype = (31 << 8) | R_POS;
5583       ldrel.l_rsecnm = oindx;
5584       xcoff_swap_ldrel_out (output_bfd, &ldrel, finfo->ldrel);
5585       ++finfo->ldrel;
5586
5587       bfd_put_32 (output_bfd, xcoff_data (output_bfd)->toc, p + 4);
5588
5589       tsec = coff_section_from_bfd_index (output_bfd,
5590                                           xcoff_data (output_bfd)->sntoc);
5591
5592       ++irel;
5593       irel->r_vaddr = (osec->vma
5594                        + sec->output_offset
5595                        + h->root.u.def.value
5596                        + 4);
5597       irel->r_symndx = tsec->output_section->target_index;
5598       irel->r_type = R_POS;
5599       irel->r_size = 31;
5600       finfo->section_info[oindx].rel_hashes[osec->reloc_count] = NULL;
5601       ++osec->reloc_count;
5602
5603       ldrel.l_vaddr = irel->r_vaddr;
5604       if (strcmp (tsec->output_section->name, ".text") == 0)
5605         ldrel.l_symndx = 0;
5606       else if (strcmp (tsec->output_section->name, ".data") == 0)
5607         ldrel.l_symndx = 1;
5608       else if (strcmp (tsec->output_section->name, ".bss") == 0)
5609         ldrel.l_symndx = 2;
5610       else
5611         {
5612           (*_bfd_error_handler)
5613             ("%s: loader reloc in unrecognized section `%s'",
5614              bfd_get_filename (output_bfd),
5615              tsec->output_section->name);
5616           bfd_set_error (bfd_error_nonrepresentable_section);
5617           return false;
5618         }
5619       ldrel.l_rtype = (31 << 8) | R_POS;
5620       ldrel.l_rsecnm = oindx;
5621       xcoff_swap_ldrel_out (output_bfd, &ldrel, finfo->ldrel);
5622       ++finfo->ldrel;
5623     }
5624
5625   if (h->indx >= 0)
5626     return true;
5627
5628   if (h->indx != -2
5629       && (finfo->info->strip == strip_all
5630           || (finfo->info->strip == strip_some
5631               && (bfd_hash_lookup (finfo->info->keep_hash,
5632                                    h->root.root.string, false, false)
5633                   == NULL))))
5634     return true;
5635
5636   if (h->indx != -2
5637       && (h->flags & (XCOFF_REF_REGULAR | XCOFF_DEF_REGULAR)) == 0)
5638     return true;
5639
5640   outsym = finfo->outsyms;
5641
5642   memset (&aux, 0, sizeof aux);
5643
5644   h->indx = obj_raw_syment_count (output_bfd);
5645
5646   if (strlen (h->root.root.string) <= SYMNMLEN)
5647     strncpy (isym._n._n_name, h->root.root.string, SYMNMLEN);
5648   else
5649     {
5650       boolean hash;
5651       bfd_size_type indx;
5652
5653       hash = true;
5654       if ((output_bfd->flags & BFD_TRADITIONAL_FORMAT) != 0)
5655         hash = false;
5656       indx = _bfd_stringtab_add (finfo->strtab, h->root.root.string, hash,
5657                                  false);
5658       if (indx == (bfd_size_type) -1)
5659         return false;
5660       isym._n._n_n._n_zeroes = 0;
5661       isym._n._n_n._n_offset = STRING_SIZE_SIZE + indx;
5662     }
5663
5664   if (h->root.type == bfd_link_hash_undefined
5665       || h->root.type == bfd_link_hash_undefweak)
5666     {
5667       isym.n_value = 0;
5668       isym.n_scnum = N_UNDEF;
5669       isym.n_sclass = C_EXT;
5670       aux.x_csect.x_smtyp = XTY_ER;
5671     }
5672   else if (h->root.type == bfd_link_hash_defined
5673            || h->root.type == bfd_link_hash_defweak)
5674     {
5675       struct xcoff_link_size_list *l;
5676
5677       isym.n_value = (h->root.u.def.section->output_section->vma
5678                       + h->root.u.def.section->output_offset
5679                       + h->root.u.def.value);
5680       isym.n_scnum = h->root.u.def.section->output_section->target_index;
5681       isym.n_sclass = C_HIDEXT;
5682       aux.x_csect.x_smtyp = XTY_SD;
5683
5684       if ((h->flags & XCOFF_HAS_SIZE) != 0)
5685         {
5686           for (l = xcoff_hash_table (finfo->info)->size_list;
5687                l != NULL;
5688                l = l->next)
5689             {
5690               if (l->h == h)
5691                 {
5692                   aux.x_csect.x_scnlen.l = l->size;
5693                   break;
5694                 }
5695             }
5696         }
5697     }
5698   else if (h->root.type == bfd_link_hash_common)
5699     {
5700       isym.n_value = (h->root.u.c.p->section->output_section->vma
5701                       + h->root.u.c.p->section->output_offset);
5702       isym.n_scnum = h->root.u.c.p->section->output_section->target_index;
5703       isym.n_sclass = C_EXT;
5704       aux.x_csect.x_smtyp = XTY_CM;
5705       aux.x_csect.x_scnlen.l = h->root.u.c.size;
5706     }
5707   else
5708     abort ();
5709
5710   isym.n_type = T_NULL;
5711   isym.n_numaux = 1;
5712
5713   bfd_coff_swap_sym_out (output_bfd, (PTR) &isym, (PTR) outsym);
5714   outsym += bfd_coff_symesz (output_bfd);
5715
5716   aux.x_csect.x_smclas = h->smclas;
5717
5718   bfd_coff_swap_aux_out (output_bfd, (PTR) &aux, T_NULL, isym.n_sclass, 0, 1,
5719                          (PTR) outsym);
5720   outsym += bfd_coff_auxesz (output_bfd);
5721
5722   if (h->root.type == bfd_link_hash_defined
5723       || h->root.type == bfd_link_hash_defweak)
5724     {
5725       /* We just output an SD symbol.  Now output an LD symbol.  */
5726
5727       h->indx += 2;
5728
5729       isym.n_sclass = C_EXT;
5730       bfd_coff_swap_sym_out (output_bfd, (PTR) &isym, (PTR) outsym);
5731       outsym += bfd_coff_symesz (output_bfd);
5732
5733       aux.x_csect.x_smtyp = XTY_LD;
5734       aux.x_csect.x_scnlen.l = obj_raw_syment_count (output_bfd);
5735
5736       bfd_coff_swap_aux_out (output_bfd, (PTR) &aux, T_NULL, C_EXT, 0, 1,
5737                              (PTR) outsym);
5738       outsym += bfd_coff_auxesz (output_bfd);
5739     }
5740
5741   if (bfd_seek (output_bfd,
5742                 (obj_sym_filepos (output_bfd)
5743                  + (obj_raw_syment_count (output_bfd)
5744                     * bfd_coff_symesz (output_bfd))),
5745                 SEEK_SET) != 0
5746       || (bfd_write (finfo->outsyms, outsym - finfo->outsyms, 1, output_bfd)
5747           != (bfd_size_type) (outsym - finfo->outsyms)))
5748     return false;
5749   obj_raw_syment_count (output_bfd) +=
5750     (outsym - finfo->outsyms) / bfd_coff_symesz (output_bfd);
5751
5752   return true;
5753 }
5754
5755 /* Handle a link order which is supposed to generate a reloc.  */
5756
5757 static boolean
5758 xcoff_reloc_link_order (output_bfd, finfo, output_section, link_order)
5759      bfd *output_bfd;
5760      struct xcoff_final_link_info *finfo;
5761      asection *output_section;
5762      struct bfd_link_order *link_order;
5763 {
5764   reloc_howto_type *howto;
5765   struct xcoff_link_hash_entry *h;
5766   asection *hsec;
5767   bfd_vma hval;
5768   bfd_vma addend;
5769   struct internal_reloc *irel;
5770   struct xcoff_link_hash_entry **rel_hash_ptr;
5771   struct internal_ldrel ldrel;
5772
5773   if (link_order->type == bfd_section_reloc_link_order)
5774     {
5775       /* We need to somehow locate a symbol in the right section.  The
5776          symbol must either have a value of zero, or we must adjust
5777          the addend by the value of the symbol.  FIXME: Write this
5778          when we need it.  The old linker couldn't handle this anyhow.  */
5779       abort ();
5780     }
5781
5782   howto = bfd_reloc_type_lookup (output_bfd, link_order->u.reloc.p->reloc);
5783   if (howto == NULL)
5784     {
5785       bfd_set_error (bfd_error_bad_value);
5786       return false;
5787     }
5788
5789   h = ((struct xcoff_link_hash_entry *)
5790        bfd_wrapped_link_hash_lookup (output_bfd, finfo->info,
5791                                      link_order->u.reloc.p->u.name,
5792                                      false, false, true));
5793   if (h == NULL)
5794     {
5795       if (! ((*finfo->info->callbacks->unattached_reloc)
5796              (finfo->info, link_order->u.reloc.p->u.name, (bfd *) NULL,
5797               (asection *) NULL, (bfd_vma) 0)))
5798         return false;
5799       return true;
5800     }
5801
5802   if (h->root.type == bfd_link_hash_common)
5803     {
5804       hsec = h->root.u.c.p->section;
5805       hval = 0;
5806     }
5807   else if (h->root.type == bfd_link_hash_defined
5808            || h->root.type == bfd_link_hash_defweak)
5809     {
5810       hsec = h->root.u.def.section;
5811       hval = h->root.u.def.value;
5812     }
5813   else
5814     {
5815       hsec = NULL;
5816       hval = 0;
5817     }
5818
5819   addend = link_order->u.reloc.p->addend;
5820   if (hsec != NULL)
5821     addend += (hsec->output_section->vma
5822                + hsec->output_offset
5823                + hval);
5824
5825   if (addend != 0)
5826     {
5827       bfd_size_type size;
5828       bfd_byte *buf;
5829       bfd_reloc_status_type rstat;
5830       boolean ok;
5831
5832       size = bfd_get_reloc_size (howto);
5833       buf = (bfd_byte *) bfd_zmalloc (size);
5834       if (buf == NULL)
5835         return false;
5836
5837       rstat = _bfd_relocate_contents (howto, output_bfd, addend, buf);
5838       switch (rstat)
5839         {
5840         case bfd_reloc_ok:
5841           break;
5842         default:
5843         case bfd_reloc_outofrange:
5844           abort ();
5845         case bfd_reloc_overflow:
5846           if (! ((*finfo->info->callbacks->reloc_overflow)
5847                  (finfo->info, link_order->u.reloc.p->u.name,
5848                   howto->name, addend, (bfd *) NULL, (asection *) NULL,
5849                   (bfd_vma) 0)))
5850             {
5851               free (buf);
5852               return false;
5853             }
5854           break;
5855         }
5856       ok = bfd_set_section_contents (output_bfd, output_section, (PTR) buf,
5857                                      (file_ptr) link_order->offset, size);
5858       free (buf);
5859       if (! ok)
5860         return false;
5861     }
5862
5863   /* Store the reloc information in the right place.  It will get
5864      swapped and written out at the end of the final_link routine.  */
5865
5866   irel = (finfo->section_info[output_section->target_index].relocs
5867           + output_section->reloc_count);
5868   rel_hash_ptr = (finfo->section_info[output_section->target_index].rel_hashes
5869                   + output_section->reloc_count);
5870
5871   memset (irel, 0, sizeof (struct internal_reloc));
5872   *rel_hash_ptr = NULL;
5873
5874   irel->r_vaddr = output_section->vma + link_order->offset;
5875
5876   if (h->indx >= 0)
5877     irel->r_symndx = h->indx;
5878   else
5879     {
5880       /* Set the index to -2 to force this symbol to get written out.  */
5881       h->indx = -2;
5882       *rel_hash_ptr = h;
5883       irel->r_symndx = 0;
5884     }
5885
5886   irel->r_type = howto->type;
5887   irel->r_size = howto->bitsize - 1;
5888   if (howto->complain_on_overflow == complain_overflow_signed)
5889     irel->r_size |= 0x80;
5890
5891   ++output_section->reloc_count;
5892
5893   /* Now output the reloc to the .loader section.  */
5894
5895   ldrel.l_vaddr = irel->r_vaddr;
5896
5897   if (hsec != NULL)
5898     {
5899       const char *secname;
5900
5901       secname = hsec->output_section->name;
5902
5903       if (strcmp (secname, ".text") == 0)
5904         ldrel.l_symndx = 0;
5905       else if (strcmp (secname, ".data") == 0)
5906         ldrel.l_symndx = 1;
5907       else if (strcmp (secname, ".bss") == 0)
5908         ldrel.l_symndx = 2;
5909       else
5910         {
5911           (*_bfd_error_handler)
5912             ("%s: loader reloc in unrecognized section `%s'",
5913              bfd_get_filename (output_bfd), secname);
5914           bfd_set_error (bfd_error_nonrepresentable_section);
5915           return false;
5916         }
5917     }
5918   else
5919     {
5920       if (h->ldindx < 0)
5921         {
5922           (*_bfd_error_handler)
5923             ("%s: `%s' in loader reloc but not loader sym",
5924              bfd_get_filename (output_bfd),
5925              h->root.root.string);
5926           bfd_set_error (bfd_error_bad_value);
5927           return false;
5928         }
5929       ldrel.l_symndx = h->ldindx;
5930     }
5931
5932   ldrel.l_rtype = (irel->r_size << 8) | irel->r_type;
5933   ldrel.l_rsecnm = output_section->target_index;
5934   xcoff_swap_ldrel_out (output_bfd, &ldrel, finfo->ldrel);
5935   ++finfo->ldrel;
5936
5937   return true;
5938 }
5939
5940 /* Sort relocs by VMA.  This is called via qsort.  */
5941
5942 static int
5943 xcoff_sort_relocs (p1, p2)
5944      const PTR p1;
5945      const PTR p2;
5946 {
5947   const struct internal_reloc *r1 = (const struct internal_reloc *) p1;
5948   const struct internal_reloc *r2 = (const struct internal_reloc *) p2;
5949
5950   if (r1->r_vaddr > r2->r_vaddr)
5951     return 1;
5952   else if (r1->r_vaddr < r2->r_vaddr)
5953     return -1;
5954   else
5955     return 0;
5956 }
5957
5958 /* This is the relocation function for the RS/6000/POWER/PowerPC.
5959    This is currently the only processor which uses XCOFF; I hope that
5960    will never change.  */
5961
5962 boolean
5963 _bfd_ppc_xcoff_relocate_section (output_bfd, info, input_bfd,
5964                                  input_section, contents, relocs, syms,
5965                                  sections)
5966      bfd *output_bfd;
5967      struct bfd_link_info *info;
5968      bfd *input_bfd;
5969      asection *input_section;
5970      bfd_byte *contents;
5971      struct internal_reloc *relocs;
5972      struct internal_syment *syms;
5973      asection **sections;
5974 {
5975   struct internal_reloc *rel;
5976   struct internal_reloc *relend;
5977
5978   rel = relocs;
5979   relend = rel + input_section->reloc_count;
5980   for (; rel < relend; rel++)
5981     {
5982       long symndx;
5983       struct xcoff_link_hash_entry *h;
5984       struct internal_syment *sym;
5985       bfd_vma addend;
5986       bfd_vma val;
5987       struct reloc_howto_struct howto;
5988       bfd_reloc_status_type rstat;
5989
5990       /* Relocation type R_REF is a special relocation type which is
5991          merely used to prevent garbage collection from occurring for
5992          the csect including the symbol which it references.  */
5993       if (rel->r_type == R_REF)
5994         continue;
5995
5996       symndx = rel->r_symndx;
5997
5998       if (symndx == -1)
5999         {
6000           h = NULL;
6001           sym = NULL;
6002           addend = 0;
6003         }
6004       else
6005         {    
6006           h = obj_xcoff_sym_hashes (input_bfd)[symndx];
6007           sym = syms + symndx;
6008           addend = - sym->n_value;
6009         }
6010
6011       /* We build the howto information on the fly.  */
6012
6013       howto.type = rel->r_type;
6014       howto.rightshift = 0;
6015       howto.size = 2;
6016       howto.bitsize = (rel->r_size & 0x1f) + 1;
6017       howto.pc_relative = false;
6018       howto.bitpos = 0;
6019       if ((rel->r_size & 0x80) != 0)
6020         howto.complain_on_overflow = complain_overflow_signed;
6021       else
6022         howto.complain_on_overflow = complain_overflow_bitfield;
6023       howto.special_function = NULL;
6024       howto.name = "internal";
6025       howto.partial_inplace = true;
6026       if (howto.bitsize == 32)
6027         howto.src_mask = howto.dst_mask = 0xffffffff;
6028       else
6029         {
6030           howto.src_mask = howto.dst_mask = (1 << howto.bitsize) - 1;
6031           if (howto.bitsize == 16)
6032             howto.size = 1;
6033         }
6034       howto.pcrel_offset = false;
6035
6036       val = 0;
6037
6038       if (h == NULL)
6039         {
6040           asection *sec;
6041
6042           if (symndx == -1)
6043             {
6044               sec = bfd_abs_section_ptr;
6045               val = 0;
6046             }
6047           else
6048             {
6049               sec = sections[symndx];
6050               /* Hack to make sure we use the right TOC anchor value
6051                  if this reloc is against the TOC anchor.  */
6052               if (sec->name[3] == '0'
6053                   && strcmp (sec->name, ".tc0") == 0)
6054                 val = xcoff_data (output_bfd)->toc;
6055               else
6056                 val = (sec->output_section->vma
6057                        + sec->output_offset
6058                        + sym->n_value
6059                        - sec->vma);
6060             }
6061         }
6062       else
6063         {
6064           if (h->root.type == bfd_link_hash_defined
6065               || h->root.type == bfd_link_hash_defweak)
6066             {
6067               asection *sec;
6068
6069               sec = h->root.u.def.section;
6070               val = (h->root.u.def.value
6071                      + sec->output_section->vma
6072                      + sec->output_offset);
6073             }
6074           else if (h->root.type == bfd_link_hash_common)
6075             {
6076               asection *sec;
6077
6078               sec = h->root.u.c.p->section;
6079               val = (sec->output_section->vma
6080                      + sec->output_offset);
6081             }
6082           else if ((h->flags & XCOFF_DEF_DYNAMIC) != 0
6083                    || (h->flags & XCOFF_IMPORT) != 0)
6084             {
6085               /* Every symbol in a shared object is defined somewhere.  */
6086               val = 0;
6087             }
6088           else if (! info->relocateable)
6089             {
6090               if (! ((*info->callbacks->undefined_symbol)
6091                      (info, h->root.root.string, input_bfd, input_section,
6092                       rel->r_vaddr - input_section->vma)))
6093                 return false;
6094             }
6095         }
6096
6097       /* I took the relocation type definitions from two documents:
6098          the PowerPC AIX Version 4 Application Binary Interface, First
6099          Edition (April 1992), and the PowerOpen ABI, Big-Endian
6100          32-Bit Hardware Implementation (June 30, 1994).  Differences
6101          between the documents are noted below.  */
6102
6103       switch (rel->r_type)
6104         {
6105         case R_RTB:
6106         case R_RRTBI:
6107         case R_RRTBA:
6108           /* These relocs are defined by the PowerPC ABI to be
6109              relative branches which use half of the difference
6110              between the symbol and the program counter.  I can't
6111              quite figure out when this is useful.  These relocs are
6112              not defined by the PowerOpen ABI.  */
6113         default:
6114           (*_bfd_error_handler)
6115             ("%s: unsupported relocation type 0x%02x",
6116              bfd_get_filename (input_bfd), (unsigned int) rel->r_type);
6117           bfd_set_error (bfd_error_bad_value);
6118           return false;
6119         case R_POS:
6120           /* Simple positive relocation.  */
6121           break;
6122         case R_NEG:
6123           /* Simple negative relocation.  */
6124           val = - val;
6125           break;
6126         case R_REL:
6127           /* Simple PC relative relocation.  */
6128           howto.pc_relative = true;
6129           break;
6130         case R_TOC:
6131           /* TOC relative relocation.  The value in the instruction in
6132              the input file is the offset from the input file TOC to
6133              the desired location.  We want the offset from the final
6134              TOC to the desired location.  We have:
6135                  isym = iTOC + in
6136                  iinsn = in + o
6137                  osym = oTOC + on
6138                  oinsn = on + o
6139              so we must change insn by on - in.
6140              */
6141         case R_GL:
6142           /* Global linkage relocation.  The value of this relocation
6143              is the address of the entry in the TOC section.  */
6144         case R_TCL:
6145           /* Local object TOC address.  I can't figure out the
6146              difference between this and case R_GL.  */
6147         case R_TRL:
6148           /* TOC relative relocation.  A TOC relative load instruction
6149              which may be changed to a load address instruction.
6150              FIXME: We don't currently implement this optimization.  */
6151         case R_TRLA:
6152           /* TOC relative relocation.  This is a TOC relative load
6153              address instruction which may be changed to a load
6154              instruction.  FIXME: I don't know if this is the correct
6155              implementation.  */
6156           if (h != NULL && h->smclas != XMC_TD)
6157             {
6158               if (h->toc_section == NULL)
6159                 {
6160                   (*_bfd_error_handler)
6161                     ("%s: TOC reloc at 0x%x to symbol `%s' with no TOC entry",
6162                      bfd_get_filename (input_bfd), rel->r_vaddr,
6163                      h->root.root.string);
6164                   bfd_set_error (bfd_error_bad_value);
6165                   return false;
6166                 }
6167
6168               BFD_ASSERT ((h->flags & XCOFF_SET_TOC) == 0);
6169               val = (h->toc_section->output_section->vma
6170                      + h->toc_section->output_offset);
6171             }
6172
6173           val = ((val - xcoff_data (output_bfd)->toc)
6174                  - (sym->n_value - xcoff_data (input_bfd)->toc));
6175           addend = 0;
6176           break;
6177         case R_BA:
6178           /* Absolute branch.  We don't want to mess with the lower
6179              two bits of the instruction.  */
6180         case R_CAI:
6181           /* The PowerPC ABI defines this as an absolute call which
6182              may be modified to become a relative call.  The PowerOpen
6183              ABI does not define this relocation type.  */
6184         case R_RBA:
6185           /* Absolute branch which may be modified to become a
6186              relative branch.  */
6187         case R_RBAC:
6188           /* The PowerPC ABI defines this as an absolute branch to a
6189              fixed address which may be modified to an absolute branch
6190              to a symbol.  The PowerOpen ABI does not define this
6191              relocation type.  */
6192         case R_RBRC:
6193           /* The PowerPC ABI defines this as an absolute branch to a
6194              fixed address which may be modified to a relative branch.
6195              The PowerOpen ABI does not define this relocation type.  */
6196           howto.src_mask &= ~3;
6197           howto.dst_mask = howto.src_mask;
6198           break;
6199         case R_BR:
6200           /* Relative branch.  We don't want to mess with the lower
6201              two bits of the instruction.  */
6202         case R_CREL:
6203           /* The PowerPC ABI defines this as a relative call which may
6204              be modified to become an absolute call.  The PowerOpen
6205              ABI does not define this relocation type.  */
6206         case R_RBR:
6207           /* A relative branch which may be modified to become an
6208              absolute branch.  FIXME: We don't implement this,
6209              although we should for symbols of storage mapping class
6210              XMC_XO.  */
6211           howto.pc_relative = true;
6212           howto.src_mask &= ~3;
6213           howto.dst_mask = howto.src_mask;
6214           break;
6215         case R_RL:
6216           /* The PowerPC AIX ABI describes this as a load which may be
6217              changed to a load address.  The PowerOpen ABI says this
6218              is the same as case R_POS.  */
6219           break;
6220         case R_RLA:
6221           /* The PowerPC AIX ABI describes this as a load address
6222              which may be changed to a load.  The PowerOpen ABI says
6223              this is the same as R_POS.  */
6224           break;
6225         }
6226
6227       /* If we see an R_BR or R_RBR reloc which is jumping to global
6228          linkage code, and it is followed by an appropriate cror nop
6229          instruction, we replace the cror with lwz r2,20(r1).  This
6230          restores the TOC after the glink code.  Contrariwise, if the
6231          call is followed by a lwz r2,20(r1), but the call is not
6232          going to global linkage code, we can replace the load with a
6233          cror.  */
6234       if ((rel->r_type == R_BR || rel->r_type == R_RBR)
6235           && h != NULL
6236           && h->root.type == bfd_link_hash_defined
6237           && (rel->r_vaddr - input_section->vma + 8
6238               <= input_section->_cooked_size))
6239         {
6240           bfd_byte *pnext;
6241           unsigned long next;
6242
6243           pnext = contents + (rel->r_vaddr - input_section->vma) + 4;
6244           next = bfd_get_32 (input_bfd, pnext);
6245
6246           /* The _ptrgl function is magic.  It is used by the AIX
6247              compiler to call a function through a pointer.  */
6248           if (h->smclas == XMC_GL
6249               || strcmp (h->root.root.string, "._ptrgl") == 0)
6250             {
6251               if (next == 0x4def7b82            /* cror 15,15,15 */
6252                   || next == 0x4ffffb82)        /* cror 31,31,31 */
6253                 bfd_put_32 (input_bfd, 0x80410014, pnext); /* lwz r1,20(r1) */
6254             }
6255           else
6256             {
6257               if (next == 0x80410014)           /* lwz r1,20(r1) */
6258                 bfd_put_32 (input_bfd, 0x4ffffb82, pnext); /* cror 31,31,31 */
6259             }
6260         }
6261
6262       /* A PC relative reloc includes the section address.  */
6263       if (howto.pc_relative)
6264         addend += input_section->vma;
6265
6266       rstat = _bfd_final_link_relocate (&howto, input_bfd, input_section,
6267                                         contents,
6268                                         rel->r_vaddr - input_section->vma,
6269                                         val, addend);
6270
6271       switch (rstat)
6272         {
6273         default:
6274           abort ();
6275         case bfd_reloc_ok:
6276           break;
6277         case bfd_reloc_overflow:
6278           {
6279             const char *name;
6280             char buf[SYMNMLEN + 1];
6281             char howto_name[10];
6282
6283             if (symndx == -1)
6284               name = "*ABS*";
6285             else if (h != NULL)
6286               name = h->root.root.string;
6287             else
6288               {
6289                 name = _bfd_coff_internal_syment_name (input_bfd, sym, buf);
6290                 if (name == NULL)
6291                   return false;
6292               }
6293             sprintf (howto_name, "0x%02x", rel->r_type);
6294
6295             if (! ((*info->callbacks->reloc_overflow)
6296                    (info, name, howto_name, (bfd_vma) 0, input_bfd,
6297                     input_section, rel->r_vaddr - input_section->vma)))
6298               return false;
6299           }
6300         }
6301     }
6302
6303   return true;
6304 }