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