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