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