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