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