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