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