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