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