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