* write.c (install_reloc): Correct EMIT_SECTION_SYMBOLS test.
[platform/upstream/binutils.git] / gas / write.c
1 /* write.c - emit .o file
2    Copyright 1986, 1987, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
3    1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
4    Free Software Foundation, Inc.
5
6    This file is part of GAS, the GNU Assembler.
7
8    GAS is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3, or (at your option)
11    any later version.
12
13    GAS is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with GAS; see the file COPYING.  If not, write to the Free
20    Software Foundation, 51 Franklin Street - Fifth Floor, Boston, MA
21    02110-1301, USA.  */
22
23 /* This thing should be set up to do byteordering correctly.  But...  */
24
25 #include "as.h"
26 #include "subsegs.h"
27 #include "obstack.h"
28 #include "output-file.h"
29 #include "dwarf2dbg.h"
30 #include "libbfd.h"
31
32 #ifndef TC_ADJUST_RELOC_COUNT
33 #define TC_ADJUST_RELOC_COUNT(FIX, COUNT)
34 #endif
35
36 #ifndef TC_FORCE_RELOCATION
37 #define TC_FORCE_RELOCATION(FIX)                \
38   (generic_force_reloc (FIX))
39 #endif
40
41 #ifndef TC_FORCE_RELOCATION_ABS
42 #define TC_FORCE_RELOCATION_ABS(FIX)            \
43   (TC_FORCE_RELOCATION (FIX))
44 #endif
45
46 #ifndef TC_FORCE_RELOCATION_LOCAL
47 #define TC_FORCE_RELOCATION_LOCAL(FIX)          \
48   (!(FIX)->fx_pcrel                             \
49    || TC_FORCE_RELOCATION (FIX))
50 #endif
51
52 #ifndef TC_FORCE_RELOCATION_SUB_SAME
53 #define TC_FORCE_RELOCATION_SUB_SAME(FIX, SEG)  \
54   (! SEG_NORMAL (SEG))
55 #endif
56
57 #ifndef TC_FORCE_RELOCATION_SUB_ABS
58 #define TC_FORCE_RELOCATION_SUB_ABS(FIX)        0
59 #endif
60
61 #ifndef TC_FORCE_RELOCATION_SUB_LOCAL
62 #ifdef DIFF_EXPR_OK
63 #define TC_FORCE_RELOCATION_SUB_LOCAL(FIX)      0
64 #else
65 #define TC_FORCE_RELOCATION_SUB_LOCAL(FIX)      1
66 #endif
67 #endif
68
69 #ifndef TC_VALIDATE_FIX_SUB
70 #ifdef UNDEFINED_DIFFERENCE_OK
71 /* The PA needs this for PIC code generation.  */
72 #define TC_VALIDATE_FIX_SUB(FIX) 1
73 #else
74 #define TC_VALIDATE_FIX_SUB(FIX)                \
75   ((FIX)->fx_r_type == BFD_RELOC_GPREL32        \
76    || (FIX)->fx_r_type == BFD_RELOC_GPREL16)
77 #endif
78 #endif
79
80 #ifndef TC_LINKRELAX_FIXUP
81 #define TC_LINKRELAX_FIXUP(SEG) 1
82 #endif
83
84 #ifndef MD_APPLY_SYM_VALUE
85 #define MD_APPLY_SYM_VALUE(FIX) 1
86 #endif
87
88 #ifndef TC_FINALIZE_SYMS_BEFORE_SIZE_SEG
89 #define TC_FINALIZE_SYMS_BEFORE_SIZE_SEG 1
90 #endif
91
92 #ifndef MD_PCREL_FROM_SECTION
93 #define MD_PCREL_FROM_SECTION(FIX, SEC) md_pcrel_from (FIX)
94 #endif
95
96 #ifndef TC_FAKE_LABEL
97 #define TC_FAKE_LABEL(NAME) (strcmp ((NAME), FAKE_LABEL_NAME) == 0)
98 #endif
99
100 /* Positive values of TC_FX_SIZE_SLACK allow a target to define
101    fixups that far past the end of a frag.  Having such fixups
102    is of course most most likely a bug in setting fx_size correctly.
103    A negative value disables the fixup check entirely, which is
104    appropriate for something like the Renesas / SuperH SH_COUNT
105    reloc.  */
106 #ifndef TC_FX_SIZE_SLACK
107 #define TC_FX_SIZE_SLACK(FIX) 0
108 #endif
109
110 /* Used to control final evaluation of expressions.  */
111 int finalize_syms = 0;
112
113 int symbol_table_frozen;
114
115 symbolS *abs_section_sym;
116
117 /* Remember the value of dot when parsing expressions.  */
118 addressT dot_value;
119
120 /* Relocs generated by ".reloc" pseudo.  */
121 struct reloc_list* reloc_list;
122
123 void print_fixup (fixS *);
124
125 /* We generally attach relocs to frag chains.  However, after we have
126    chained these all together into a segment, any relocs we add after
127    that must be attached to a segment.  This will include relocs added
128    in md_estimate_size_for_relax, for example.  */
129 static int frags_chained = 0;
130
131 static int n_fixups;
132
133 #define RELOC_ENUM enum bfd_reloc_code_real
134
135 /* Create a fixS in obstack 'notes'.  */
136
137 static fixS *
138 fix_new_internal (fragS *frag,          /* Which frag?  */
139                   int where,            /* Where in that frag?  */
140                   int size,             /* 1, 2, or 4 usually.  */
141                   symbolS *add_symbol,  /* X_add_symbol.  */
142                   symbolS *sub_symbol,  /* X_op_symbol.  */
143                   offsetT offset,       /* X_add_number.  */
144                   int pcrel,            /* TRUE if PC-relative relocation.  */
145                   RELOC_ENUM r_type ATTRIBUTE_UNUSED /* Relocation type.  */)
146 {
147   fixS *fixP;
148
149   n_fixups++;
150
151   fixP = obstack_alloc (&notes, sizeof (fixS));
152
153   fixP->fx_frag = frag;
154   fixP->fx_where = where;
155   fixP->fx_size = size;
156   /* We've made fx_size a narrow field; check that it's wide enough.  */
157   if (fixP->fx_size != size)
158     {
159       as_bad (_("field fx_size too small to hold %d"), size);
160       abort ();
161     }
162   fixP->fx_addsy = add_symbol;
163   fixP->fx_subsy = sub_symbol;
164   fixP->fx_offset = offset;
165   fixP->fx_dot_value = dot_value;
166   fixP->fx_pcrel = pcrel;
167   fixP->fx_r_type = r_type;
168   fixP->fx_im_disp = 0;
169   fixP->fx_pcrel_adjust = 0;
170   fixP->fx_bit_fixP = 0;
171   fixP->fx_addnumber = 0;
172   fixP->fx_tcbit = 0;
173   fixP->fx_tcbit2 = 0;
174   fixP->fx_done = 0;
175   fixP->fx_no_overflow = 0;
176   fixP->fx_signed = 0;
177
178 #ifdef USING_CGEN
179   fixP->fx_cgen.insn = NULL;
180   fixP->fx_cgen.opinfo = 0;
181 #endif
182
183 #ifdef TC_FIX_TYPE
184   TC_INIT_FIX_DATA (fixP);
185 #endif
186
187   as_where (&fixP->fx_file, &fixP->fx_line);
188
189   /* Usually, we want relocs sorted numerically, but while
190      comparing to older versions of gas that have relocs
191      reverse sorted, it is convenient to have this compile
192      time option.  xoxorich.  */
193   {
194
195     fixS **seg_fix_rootP = (frags_chained
196                             ? &seg_info (now_seg)->fix_root
197                             : &frchain_now->fix_root);
198     fixS **seg_fix_tailP = (frags_chained
199                             ? &seg_info (now_seg)->fix_tail
200                             : &frchain_now->fix_tail);
201
202 #ifdef REVERSE_SORT_RELOCS
203
204     fixP->fx_next = *seg_fix_rootP;
205     *seg_fix_rootP = fixP;
206
207 #else /* REVERSE_SORT_RELOCS  */
208
209     fixP->fx_next = NULL;
210
211     if (*seg_fix_tailP)
212       (*seg_fix_tailP)->fx_next = fixP;
213     else
214       *seg_fix_rootP = fixP;
215     *seg_fix_tailP = fixP;
216
217 #endif /* REVERSE_SORT_RELOCS  */
218   }
219
220   return fixP;
221 }
222
223 /* Create a fixup relative to a symbol (plus a constant).  */
224
225 fixS *
226 fix_new (fragS *frag,           /* Which frag?  */
227          int where,                     /* Where in that frag?  */
228          int size,                      /* 1, 2, or 4 usually.  */
229          symbolS *add_symbol,   /* X_add_symbol.  */
230          offsetT offset,                /* X_add_number.  */
231          int pcrel,                     /* TRUE if PC-relative relocation.  */
232          RELOC_ENUM r_type              /* Relocation type.  */)
233 {
234   return fix_new_internal (frag, where, size, add_symbol,
235                            (symbolS *) NULL, offset, pcrel, r_type);
236 }
237
238 /* Create a fixup for an expression.  Currently we only support fixups
239    for difference expressions.  That is itself more than most object
240    file formats support anyhow.  */
241
242 fixS *
243 fix_new_exp (fragS *frag,               /* Which frag?  */
244              int where,                 /* Where in that frag?  */
245              int size,                  /* 1, 2, or 4 usually.  */
246              expressionS *exp,          /* Expression.  */
247              int pcrel,                 /* TRUE if PC-relative relocation.  */
248              RELOC_ENUM r_type          /* Relocation type.  */)
249 {
250   symbolS *add = NULL;
251   symbolS *sub = NULL;
252   offsetT off = 0;
253
254   switch (exp->X_op)
255     {
256     case O_absent:
257       break;
258
259     case O_register:
260       as_bad (_("register value used as expression"));
261       break;
262
263     case O_add:
264       /* This comes up when _GLOBAL_OFFSET_TABLE_+(.-L0) is read, if
265          the difference expression cannot immediately be reduced.  */
266       {
267         symbolS *stmp = make_expr_symbol (exp);
268
269         exp->X_op = O_symbol;
270         exp->X_op_symbol = 0;
271         exp->X_add_symbol = stmp;
272         exp->X_add_number = 0;
273
274         return fix_new_exp (frag, where, size, exp, pcrel, r_type);
275       }
276
277     case O_symbol_rva:
278       add = exp->X_add_symbol;
279       off = exp->X_add_number;
280       r_type = BFD_RELOC_RVA;
281       break;
282
283     case O_uminus:
284       sub = exp->X_add_symbol;
285       off = exp->X_add_number;
286       break;
287
288     case O_subtract:
289       sub = exp->X_op_symbol;
290       /* Fall through.  */
291     case O_symbol:
292       add = exp->X_add_symbol;
293       /* Fall through.  */
294     case O_constant:
295       off = exp->X_add_number;
296       break;
297
298     default:
299       add = make_expr_symbol (exp);
300       break;
301     }
302
303   return fix_new_internal (frag, where, size, add, sub, off, pcrel, r_type);
304 }
305
306 /* Generic function to determine whether a fixup requires a relocation.  */
307 int
308 generic_force_reloc (fixS *fix)
309 {
310   if (fix->fx_r_type == BFD_RELOC_VTABLE_INHERIT
311       || fix->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
312     return 1;
313
314   if (fix->fx_addsy == NULL)
315     return 0;
316
317   return S_FORCE_RELOC (fix->fx_addsy, fix->fx_subsy == NULL);
318 }
319
320 /* Append a string onto another string, bumping the pointer along.  */
321 void
322 append (char **charPP, char *fromP, unsigned long length)
323 {
324   /* Don't trust memcpy() of 0 chars.  */
325   if (length == 0)
326     return;
327
328   memcpy (*charPP, fromP, length);
329   *charPP += length;
330 }
331
332 /* This routine records the largest alignment seen for each segment.
333    If the beginning of the segment is aligned on the worst-case
334    boundary, all of the other alignments within it will work.  At
335    least one object format really uses this info.  */
336
337 void
338 record_alignment (/* Segment to which alignment pertains.  */
339                   segT seg,
340                   /* Alignment, as a power of 2 (e.g., 1 => 2-byte
341                      boundary, 2 => 4-byte boundary, etc.)  */
342                   int align)
343 {
344   if (seg == absolute_section)
345     return;
346
347   if ((unsigned int) align > bfd_get_section_alignment (stdoutput, seg))
348     bfd_set_section_alignment (stdoutput, seg, align);
349 }
350
351 int
352 get_recorded_alignment (segT seg)
353 {
354   if (seg == absolute_section)
355     return 0;
356
357   return bfd_get_section_alignment (stdoutput, seg);
358 }
359
360 /* Reset the section indices after removing the gas created sections.  */
361
362 static void
363 renumber_sections (bfd *abfd ATTRIBUTE_UNUSED, asection *sec, void *countparg)
364 {
365   int *countp = (int *) countparg;
366
367   sec->index = *countp;
368   ++*countp;
369 }
370
371 static fragS *
372 chain_frchains_together_1 (segT section, struct frchain *frchp)
373 {
374   fragS dummy, *prev_frag = &dummy;
375   fixS fix_dummy, *prev_fix = &fix_dummy;
376
377   for (; frchp; frchp = frchp->frch_next)
378     {
379       prev_frag->fr_next = frchp->frch_root;
380       prev_frag = frchp->frch_last;
381       assert (prev_frag->fr_type != 0);
382       if (frchp->fix_root != (fixS *) NULL)
383         {
384           if (seg_info (section)->fix_root == (fixS *) NULL)
385             seg_info (section)->fix_root = frchp->fix_root;
386           prev_fix->fx_next = frchp->fix_root;
387           seg_info (section)->fix_tail = frchp->fix_tail;
388           prev_fix = frchp->fix_tail;
389         }
390     }
391   assert (prev_frag->fr_type != 0);
392   assert (prev_frag != &dummy);
393   prev_frag->fr_next = 0;
394   return prev_frag;
395 }
396
397 static void
398 chain_frchains_together (bfd *abfd ATTRIBUTE_UNUSED,
399                          segT section,
400                          void *xxx ATTRIBUTE_UNUSED)
401 {
402   segment_info_type *info;
403
404   /* BFD may have introduced its own sections without using
405      subseg_new, so it is possible that seg_info is NULL.  */
406   info = seg_info (section);
407   if (info != (segment_info_type *) NULL)
408     info->frchainP->frch_last
409       = chain_frchains_together_1 (section, info->frchainP);
410
411   /* Now that we've chained the frags together, we must add new fixups
412      to the segment, not to the frag chain.  */
413   frags_chained = 1;
414 }
415
416 static void
417 cvt_frag_to_fill (segT sec ATTRIBUTE_UNUSED, fragS *fragP)
418 {
419   switch (fragP->fr_type)
420     {
421     case rs_align:
422     case rs_align_code:
423     case rs_align_test:
424     case rs_org:
425     case rs_space:
426 #ifdef HANDLE_ALIGN
427       HANDLE_ALIGN (fragP);
428 #endif
429       know (fragP->fr_next != NULL);
430       fragP->fr_offset = (fragP->fr_next->fr_address
431                           - fragP->fr_address
432                           - fragP->fr_fix) / fragP->fr_var;
433       if (fragP->fr_offset < 0)
434         {
435           as_bad_where (fragP->fr_file, fragP->fr_line,
436                         _("attempt to .org/.space backwards? (%ld)"),
437                         (long) fragP->fr_offset);
438           fragP->fr_offset = 0;
439         }
440       fragP->fr_type = rs_fill;
441       break;
442
443     case rs_fill:
444       break;
445
446     case rs_leb128:
447       {
448         valueT value = S_GET_VALUE (fragP->fr_symbol);
449         int size;
450
451         size = output_leb128 (fragP->fr_literal + fragP->fr_fix, value,
452                               fragP->fr_subtype);
453
454         fragP->fr_fix += size;
455         fragP->fr_type = rs_fill;
456         fragP->fr_var = 0;
457         fragP->fr_offset = 0;
458         fragP->fr_symbol = NULL;
459       }
460       break;
461
462     case rs_cfa:
463       eh_frame_convert_frag (fragP);
464       break;
465
466     case rs_dwarf2dbg:
467       dwarf2dbg_convert_frag (fragP);
468       break;
469
470     case rs_machine_dependent:
471       md_convert_frag (stdoutput, sec, fragP);
472
473       assert (fragP->fr_next == NULL
474               || ((offsetT) (fragP->fr_next->fr_address - fragP->fr_address)
475                   == fragP->fr_fix));
476
477       /* After md_convert_frag, we make the frag into a ".space 0".
478          md_convert_frag() should set up any fixSs and constants
479          required.  */
480       frag_wane (fragP);
481       break;
482
483 #ifndef WORKING_DOT_WORD
484     case rs_broken_word:
485       {
486         struct broken_word *lie;
487
488         if (fragP->fr_subtype)
489           {
490             fragP->fr_fix += md_short_jump_size;
491             for (lie = (struct broken_word *) (fragP->fr_symbol);
492                  lie && lie->dispfrag == fragP;
493                  lie = lie->next_broken_word)
494               if (lie->added == 1)
495                 fragP->fr_fix += md_long_jump_size;
496           }
497         frag_wane (fragP);
498       }
499       break;
500 #endif
501
502     default:
503       BAD_CASE (fragP->fr_type);
504       break;
505     }
506 #ifdef md_frag_check
507   md_frag_check (fragP);
508 #endif
509 }
510
511 struct relax_seg_info
512 {
513   int pass;
514   int changed;
515 };
516
517 static void
518 relax_seg (bfd *abfd ATTRIBUTE_UNUSED, asection *sec, void *xxx)
519 {
520   segment_info_type *seginfo = seg_info (sec);
521   struct relax_seg_info *info = (struct relax_seg_info *) xxx;
522
523   if (seginfo && seginfo->frchainP
524       && relax_segment (seginfo->frchainP->frch_root, sec, info->pass))
525     info->changed = 1;
526 }
527
528 static void
529 size_seg (bfd *abfd, asection *sec, void *xxx ATTRIBUTE_UNUSED)
530 {
531   flagword flags;
532   fragS *fragp;
533   segment_info_type *seginfo;
534   int x;
535   valueT size, newsize;
536
537   subseg_change (sec, 0);
538
539   seginfo = seg_info (sec);
540   if (seginfo && seginfo->frchainP)
541     {
542       for (fragp = seginfo->frchainP->frch_root; fragp; fragp = fragp->fr_next)
543         cvt_frag_to_fill (sec, fragp);
544       for (fragp = seginfo->frchainP->frch_root;
545            fragp->fr_next;
546            fragp = fragp->fr_next)
547         /* Walk to last elt.  */
548         ;
549       size = fragp->fr_address + fragp->fr_fix;
550     }
551   else
552     size = 0;
553
554   flags = bfd_get_section_flags (abfd, sec);
555
556   if (size > 0 && ! seginfo->bss)
557     flags |= SEC_HAS_CONTENTS;
558
559   flags &= ~SEC_RELOC;
560   x = bfd_set_section_flags (abfd, sec, flags);
561   assert (x);
562
563   newsize = md_section_align (sec, size);
564   x = bfd_set_section_size (abfd, sec, newsize);
565   assert (x);
566
567   /* If the size had to be rounded up, add some padding in the last
568      non-empty frag.  */
569   assert (newsize >= size);
570   if (size != newsize)
571     {
572       fragS *last = seginfo->frchainP->frch_last;
573       fragp = seginfo->frchainP->frch_root;
574       while (fragp->fr_next != last)
575         fragp = fragp->fr_next;
576       last->fr_address = size;
577       if ((newsize - size) % fragp->fr_var == 0)
578         fragp->fr_offset += (newsize - size) / fragp->fr_var;
579       else
580         /* If we hit this abort, it's likely due to subsegs_finish not
581            providing sufficient alignment on the last frag, and the
582            machine dependent code using alignment frags with fr_var
583            greater than 1.  */
584         abort ();
585     }
586
587 #ifdef tc_frob_section
588   tc_frob_section (sec);
589 #endif
590 #ifdef obj_frob_section
591   obj_frob_section (sec);
592 #endif
593 }
594
595 #ifdef DEBUG2
596 static void
597 dump_section_relocs (bfd *abfd ATTRIBUTE_UNUSED, asection *sec, FILE *stream)
598 {
599   segment_info_type *seginfo = seg_info (sec);
600   fixS *fixp = seginfo->fix_root;
601
602   if (!fixp)
603     return;
604
605   fprintf (stream, "sec %s relocs:\n", sec->name);
606   while (fixp)
607     {
608       symbolS *s = fixp->fx_addsy;
609
610       fprintf (stream, "  %08lx: type %d ", (unsigned long) fixp,
611                (int) fixp->fx_r_type);
612       if (s == NULL)
613         fprintf (stream, "no sym\n");
614       else
615         {
616           print_symbol_value_1 (stream, s);
617           fprintf (stream, "\n");
618         }
619       fixp = fixp->fx_next;
620     }
621 }
622 #else
623 #define dump_section_relocs(ABFD,SEC,STREAM)    ((void) 0)
624 #endif
625
626 #ifndef EMIT_SECTION_SYMBOLS
627 #define EMIT_SECTION_SYMBOLS 1
628 #endif
629
630 /* Resolve U.A.OFFSET_SYM and U.A.SYM fields of RELOC_LIST entries,
631    and check for validity.  Convert RELOC_LIST from using U.A fields
632    to U.B fields.  */
633 static void
634 resolve_reloc_expr_symbols (void)
635 {
636   struct reloc_list *r;
637
638   for (r = reloc_list; r; r = r->next)
639     {
640       expressionS *symval;
641       symbolS *sym;
642       bfd_vma offset, addend;
643       asection *sec;
644       reloc_howto_type *howto;
645
646       resolve_symbol_value (r->u.a.offset_sym);
647       symval = symbol_get_value_expression (r->u.a.offset_sym);
648
649       offset = 0;
650       sym = NULL;
651       if (symval->X_op == O_constant)
652         sym = r->u.a.offset_sym;
653       else if (symval->X_op == O_symbol)
654         {
655           sym = symval->X_add_symbol;
656           offset = symval->X_add_number;
657           symval = symbol_get_value_expression (symval->X_add_symbol);
658         }
659       if (sym == NULL
660           || symval->X_op != O_constant
661           || (sec = S_GET_SEGMENT (sym)) == NULL
662           || !SEG_NORMAL (sec))
663         {
664           as_bad_where (r->file, r->line, _("invalid offset expression"));
665           sec = NULL;
666         }
667       else
668         offset += S_GET_VALUE (sym);
669
670       sym = NULL;
671       addend = r->u.a.addend;
672       if (r->u.a.sym != NULL)
673         {
674           resolve_symbol_value (r->u.a.sym);
675           symval = symbol_get_value_expression (r->u.a.sym);
676           if (symval->X_op == O_constant)
677             sym = r->u.a.sym;
678           else if (symval->X_op == O_symbol)
679             {
680               sym = symval->X_add_symbol;
681               addend += symval->X_add_number;
682               symval = symbol_get_value_expression (symval->X_add_symbol);
683             }
684           if (symval->X_op != O_constant)
685             {
686               as_bad_where (r->file, r->line, _("invalid reloc expression"));
687               sec = NULL;
688             }
689           else if (sym != NULL)
690             symbol_mark_used_in_reloc (sym);
691         }
692       if (sym == NULL)
693         {
694           if (abs_section_sym == NULL)
695             abs_section_sym = section_symbol (absolute_section);
696           sym = abs_section_sym;
697         }
698
699       howto = r->u.a.howto;
700
701       r->u.b.sec = sec;
702       r->u.b.s = symbol_get_bfdsym (sym);
703       r->u.b.r.sym_ptr_ptr = &r->u.b.s;
704       r->u.b.r.address = offset;
705       r->u.b.r.addend = addend;
706       r->u.b.r.howto = howto;
707     }
708 }
709
710 /* This pass over fixups decides whether symbols can be replaced with
711    section symbols.  */
712
713 static void
714 adjust_reloc_syms (bfd *abfd ATTRIBUTE_UNUSED,
715                    asection *sec,
716                    void *xxx ATTRIBUTE_UNUSED)
717 {
718   segment_info_type *seginfo = seg_info (sec);
719   fixS *fixp;
720
721   if (seginfo == NULL)
722     return;
723
724   dump_section_relocs (abfd, sec, stderr);
725
726   for (fixp = seginfo->fix_root; fixp; fixp = fixp->fx_next)
727     if (fixp->fx_done)
728       /* Ignore it.  */
729       ;
730     else if (fixp->fx_addsy)
731       {
732         symbolS *sym;
733         asection *symsec;
734
735 #ifdef DEBUG5
736         fprintf (stderr, "\n\nadjusting fixup:\n");
737         print_fixup (fixp);
738 #endif
739
740         sym = fixp->fx_addsy;
741
742         /* All symbols should have already been resolved at this
743            point.  It is possible to see unresolved expression
744            symbols, though, since they are not in the regular symbol
745            table.  */
746         resolve_symbol_value (sym);
747
748         if (fixp->fx_subsy != NULL)
749           resolve_symbol_value (fixp->fx_subsy);
750
751         /* If this symbol is equated to an undefined or common symbol,
752            convert the fixup to being against that symbol.  */
753         while (symbol_equated_reloc_p (sym)
754                || S_IS_WEAKREFR (sym))
755           {
756             symbolS *newsym = symbol_get_value_expression (sym)->X_add_symbol;
757             if (sym == newsym)
758               break;
759             fixp->fx_offset += symbol_get_value_expression (sym)->X_add_number;
760             fixp->fx_addsy = newsym;
761             sym = newsym;
762           }
763
764         if (symbol_mri_common_p (sym))
765           {
766             fixp->fx_offset += S_GET_VALUE (sym);
767             fixp->fx_addsy = symbol_get_value_expression (sym)->X_add_symbol;
768             continue;
769           }
770
771         /* If the symbol is undefined, common, weak, or global (ELF
772            shared libs), we can't replace it with the section symbol.  */
773         if (S_FORCE_RELOC (fixp->fx_addsy, 1))
774           continue;
775
776         /* Is there some other (target cpu dependent) reason we can't adjust
777            this one?  (E.g. relocations involving function addresses on
778            the PA.  */
779 #ifdef tc_fix_adjustable
780         if (! tc_fix_adjustable (fixp))
781           continue;
782 #endif
783
784         /* Since we're reducing to section symbols, don't attempt to reduce
785            anything that's already using one.  */
786         if (symbol_section_p (sym))
787           continue;
788
789         symsec = S_GET_SEGMENT (sym);
790         if (symsec == NULL)
791           abort ();
792
793         if (bfd_is_abs_section (symsec))
794           {
795             /* The fixup_segment routine normally will not use this
796                symbol in a relocation.  */
797             continue;
798           }
799
800         /* Don't try to reduce relocs which refer to non-local symbols
801            in .linkonce sections.  It can lead to confusion when a
802            debugging section refers to a .linkonce section.  I hope
803            this will always be correct.  */
804         if (symsec != sec && ! S_IS_LOCAL (sym))
805           {
806             if ((symsec->flags & SEC_LINK_ONCE) != 0
807                 || (IS_ELF
808                     /* The GNU toolchain uses an extension for ELF: a
809                        section beginning with the magic string
810                        .gnu.linkonce is a linkonce section.  */
811                     && strncmp (segment_name (symsec), ".gnu.linkonce",
812                                 sizeof ".gnu.linkonce" - 1) == 0))
813               continue;
814           }
815
816         /* Never adjust a reloc against local symbol in a merge section
817            with non-zero addend.  */
818         if ((symsec->flags & SEC_MERGE) != 0
819             && (fixp->fx_offset != 0 || fixp->fx_subsy != NULL))
820           continue;
821
822         /* Never adjust a reloc against TLS local symbol.  */
823         if ((symsec->flags & SEC_THREAD_LOCAL) != 0)
824           continue;
825
826         /* We refetch the segment when calling section_symbol, rather
827            than using symsec, because S_GET_VALUE may wind up changing
828            the section when it calls resolve_symbol_value.  */
829         fixp->fx_offset += S_GET_VALUE (sym);
830         fixp->fx_addsy = section_symbol (S_GET_SEGMENT (sym));
831 #ifdef DEBUG5
832         fprintf (stderr, "\nadjusted fixup:\n");
833         print_fixup (fixp);
834 #endif
835       }
836
837   dump_section_relocs (abfd, sec, stderr);
838 }
839
840 /* fixup_segment()
841
842    Go through all the fixS's in a segment and see which ones can be
843    handled now.  (These consist of fixS where we have since discovered
844    the value of a symbol, or the address of the frag involved.)
845    For each one, call md_apply_fix to put the fix into the frag data.
846
847    Result is a count of how many relocation structs will be needed to
848    handle the remaining fixS's that we couldn't completely handle here.
849    These will be output later by emit_relocations().  */
850
851 static long
852 fixup_segment (fixS *fixP, segT this_segment)
853 {
854   long seg_reloc_count = 0;
855   valueT add_number;
856   fragS *fragP;
857   segT add_symbol_segment = absolute_section;
858
859   if (fixP != NULL && abs_section_sym == NULL)
860     abs_section_sym = section_symbol (absolute_section);
861
862   /* If the linker is doing the relaxing, we must not do any fixups.
863
864      Well, strictly speaking that's not true -- we could do any that
865      are PC-relative and don't cross regions that could change size.
866      And for the i960 we might be able to turn callx/callj into bal
867      anyways in cases where we know the maximum displacement.  */
868   if (linkrelax && TC_LINKRELAX_FIXUP (this_segment))
869     {
870       for (; fixP; fixP = fixP->fx_next)
871         if (!fixP->fx_done)
872           {
873             if (fixP->fx_addsy == NULL)
874               {
875                 /* There was no symbol required by this relocation.
876                    However, BFD doesn't really handle relocations
877                    without symbols well. So fake up a local symbol in
878                    the absolute section.  */
879                 fixP->fx_addsy = abs_section_sym;
880               }
881             symbol_mark_used_in_reloc (fixP->fx_addsy);
882             if (fixP->fx_subsy != NULL)
883               symbol_mark_used_in_reloc (fixP->fx_subsy);
884             seg_reloc_count++;
885           }
886       TC_ADJUST_RELOC_COUNT (fixP, seg_reloc_count);
887       return seg_reloc_count;
888     }
889
890   for (; fixP; fixP = fixP->fx_next)
891     {
892 #ifdef DEBUG5
893       fprintf (stderr, "\nprocessing fixup:\n");
894       print_fixup (fixP);
895 #endif
896
897       fragP = fixP->fx_frag;
898       know (fragP);
899 #ifdef TC_VALIDATE_FIX
900       TC_VALIDATE_FIX (fixP, this_segment, skip);
901 #endif
902       add_number = fixP->fx_offset;
903
904       if (fixP->fx_addsy != NULL)
905         add_symbol_segment = S_GET_SEGMENT (fixP->fx_addsy);
906
907       if (fixP->fx_subsy != NULL)
908         {
909           segT sub_symbol_segment;
910           resolve_symbol_value (fixP->fx_subsy);
911           sub_symbol_segment = S_GET_SEGMENT (fixP->fx_subsy);
912           if (fixP->fx_addsy != NULL
913               && sub_symbol_segment == add_symbol_segment
914               && !TC_FORCE_RELOCATION_SUB_SAME (fixP, add_symbol_segment))
915             {
916               add_number += S_GET_VALUE (fixP->fx_addsy);
917               add_number -= S_GET_VALUE (fixP->fx_subsy);
918               fixP->fx_offset = add_number;
919               fixP->fx_addsy = NULL;
920               fixP->fx_subsy = NULL;
921 #ifdef TC_M68K
922               /* See the comment below about 68k weirdness.  */
923               fixP->fx_pcrel = 0;
924 #endif
925             }
926           else if (sub_symbol_segment == absolute_section
927                    && !TC_FORCE_RELOCATION_SUB_ABS (fixP))
928             {
929               add_number -= S_GET_VALUE (fixP->fx_subsy);
930               fixP->fx_offset = add_number;
931               fixP->fx_subsy = NULL;
932             }
933           else if (sub_symbol_segment == this_segment
934                    && !TC_FORCE_RELOCATION_SUB_LOCAL (fixP))
935             {
936               add_number -= S_GET_VALUE (fixP->fx_subsy);
937               fixP->fx_offset = (add_number + fixP->fx_dot_value
938                                  + fixP->fx_frag->fr_address);
939
940               /* Make it pc-relative.  If the back-end code has not
941                  selected a pc-relative reloc, cancel the adjustment
942                  we do later on all pc-relative relocs.  */
943               if (0
944 #ifdef TC_M68K
945                   /* Do this for m68k even if it's already described
946                      as pc-relative.  On the m68k, an operand of
947                      "pc@(foo-.-2)" should address "foo" in a
948                      pc-relative mode.  */
949                   || 1
950 #endif
951                   || !fixP->fx_pcrel)
952                 add_number += MD_PCREL_FROM_SECTION (fixP, this_segment);
953               fixP->fx_subsy = NULL;
954               fixP->fx_pcrel = 1;
955             }
956           else if (!TC_VALIDATE_FIX_SUB (fixP))
957             {
958               as_bad_where (fixP->fx_file, fixP->fx_line,
959                             _("can't resolve `%s' {%s section} - `%s' {%s section}"),
960                             fixP->fx_addsy ? S_GET_NAME (fixP->fx_addsy) : "0",
961                             segment_name (add_symbol_segment),
962                             S_GET_NAME (fixP->fx_subsy),
963                             segment_name (sub_symbol_segment));
964             }
965         }
966
967       if (fixP->fx_addsy)
968         {
969           if (add_symbol_segment == this_segment
970               && !TC_FORCE_RELOCATION_LOCAL (fixP))
971             {
972               /* This fixup was made when the symbol's segment was
973                  SEG_UNKNOWN, but it is now in the local segment.
974                  So we know how to do the address without relocation.  */
975               add_number += S_GET_VALUE (fixP->fx_addsy);
976               fixP->fx_offset = add_number;
977               if (fixP->fx_pcrel)
978                 add_number -= MD_PCREL_FROM_SECTION (fixP, this_segment);
979               fixP->fx_addsy = NULL;
980               fixP->fx_pcrel = 0;
981             }
982           else if (add_symbol_segment == absolute_section
983                    && !TC_FORCE_RELOCATION_ABS (fixP))
984             {
985               add_number += S_GET_VALUE (fixP->fx_addsy);
986               fixP->fx_offset = add_number;
987               fixP->fx_addsy = NULL;
988             }
989           else if (add_symbol_segment != undefined_section
990                    && ! bfd_is_com_section (add_symbol_segment)
991                    && MD_APPLY_SYM_VALUE (fixP))
992             add_number += S_GET_VALUE (fixP->fx_addsy);
993         }
994
995       if (fixP->fx_pcrel)
996         {
997           add_number -= MD_PCREL_FROM_SECTION (fixP, this_segment);
998           if (!fixP->fx_done && fixP->fx_addsy == NULL)
999             {
1000               /* There was no symbol required by this relocation.
1001                  However, BFD doesn't really handle relocations
1002                  without symbols well. So fake up a local symbol in
1003                  the absolute section.  */
1004               fixP->fx_addsy = abs_section_sym;
1005             }
1006         }
1007
1008       if (!fixP->fx_done)
1009         md_apply_fix (fixP, &add_number, this_segment);
1010
1011       if (!fixP->fx_done)
1012         {
1013           ++seg_reloc_count;
1014           if (fixP->fx_addsy == NULL)
1015             fixP->fx_addsy = abs_section_sym;
1016           symbol_mark_used_in_reloc (fixP->fx_addsy);
1017           if (fixP->fx_subsy != NULL)
1018             symbol_mark_used_in_reloc (fixP->fx_subsy);
1019         }
1020
1021       if (!fixP->fx_bit_fixP && !fixP->fx_no_overflow && fixP->fx_size != 0)
1022         {
1023           if (fixP->fx_size < sizeof (valueT))
1024             {
1025               valueT mask;
1026
1027               mask = 0;
1028               mask--;           /* Set all bits to one.  */
1029               mask <<= fixP->fx_size * 8 - (fixP->fx_signed ? 1 : 0);
1030               if ((add_number & mask) != 0 && (add_number & mask) != mask)
1031                 {
1032                   char buf[50], buf2[50];
1033                   sprint_value (buf, fragP->fr_address + fixP->fx_where);
1034                   if (add_number > 1000)
1035                     sprint_value (buf2, add_number);
1036                   else
1037                     sprintf (buf2, "%ld", (long) add_number);
1038                   as_bad_where (fixP->fx_file, fixP->fx_line,
1039                                 _("value of %s too large for field of %d bytes at %s"),
1040                                 buf2, fixP->fx_size, buf);
1041                 } /* Generic error checking.  */
1042             }
1043 #ifdef WARN_SIGNED_OVERFLOW_WORD
1044           /* Warn if a .word value is too large when treated as a signed
1045              number.  We already know it is not too negative.  This is to
1046              catch over-large switches generated by gcc on the 68k.  */
1047           if (!flag_signed_overflow_ok
1048               && fixP->fx_size == 2
1049               && add_number > 0x7fff)
1050             as_bad_where (fixP->fx_file, fixP->fx_line,
1051                           _("signed .word overflow; switch may be too large; %ld at 0x%lx"),
1052                           (long) add_number,
1053                           (long) (fragP->fr_address + fixP->fx_where));
1054 #endif
1055         }                       /* Not a bit fix.  */
1056
1057 #ifdef TC_VALIDATE_FIX
1058     skip:  ATTRIBUTE_UNUSED_LABEL
1059       ;
1060 #endif
1061 #ifdef DEBUG5
1062       fprintf (stderr, "result:\n");
1063       print_fixup (fixP);
1064 #endif
1065     }                           /* For each fixS in this segment.  */
1066
1067   TC_ADJUST_RELOC_COUNT (fixP, seg_reloc_count);
1068   return seg_reloc_count;
1069 }
1070
1071 static void
1072 fix_segment (bfd *abfd ATTRIBUTE_UNUSED,
1073              asection *sec,
1074              void *xxx ATTRIBUTE_UNUSED)
1075 {
1076   segment_info_type *seginfo = seg_info (sec);
1077
1078   fixup_segment (seginfo->fix_root, sec);
1079 }
1080
1081 static void
1082 install_reloc (asection *sec, arelent *reloc, fragS *fragp,
1083                char *file, unsigned int line)
1084 {
1085   char *err;
1086   bfd_reloc_status_type s;
1087   asymbol *sym;
1088
1089   if (reloc->sym_ptr_ptr != NULL
1090       && (sym = *reloc->sym_ptr_ptr) != NULL
1091       && (sym->flags & BSF_KEEP) == 0
1092       && ((sym->flags & BSF_SECTION_SYM) == 0
1093           || (EMIT_SECTION_SYMBOLS
1094               && !bfd_is_abs_section (sym->section))))
1095     as_bad_where (file, line, _("redefined symbol cannot be used on reloc"));
1096
1097   s = bfd_install_relocation (stdoutput, reloc,
1098                               fragp->fr_literal, fragp->fr_address,
1099                               sec, &err);
1100   switch (s)
1101     {
1102     case bfd_reloc_ok:
1103       break;
1104     case bfd_reloc_overflow:
1105       as_bad_where (file, line, _("relocation overflow"));
1106       break;
1107     case bfd_reloc_outofrange:
1108       as_bad_where (file, line, _("relocation out of range"));
1109       break;
1110     default:
1111       as_fatal (_("%s:%u: bad return from bfd_install_relocation: %x"),
1112                 file, line, s);
1113     }
1114 }
1115
1116 static void
1117 write_relocs (bfd *abfd, asection *sec, void *xxx ATTRIBUTE_UNUSED)
1118 {
1119   segment_info_type *seginfo = seg_info (sec);
1120   unsigned int i;
1121   unsigned int n;
1122   struct reloc_list *my_reloc_list, **rp, *r;
1123   arelent **relocs;
1124   fixS *fixp;
1125
1126   /* If seginfo is NULL, we did not create this section; don't do
1127      anything with it.  */
1128   if (seginfo == NULL)
1129     return;
1130
1131   n = 0;
1132   for (fixp = seginfo->fix_root; fixp; fixp = fixp->fx_next)
1133     if (!fixp->fx_done)
1134       n++;
1135
1136 #ifdef RELOC_EXPANSION_POSSIBLE
1137   n *= MAX_RELOC_EXPANSION;
1138 #endif
1139
1140   /* Extract relocs for this section from reloc_list.  */
1141   rp = &reloc_list;
1142   my_reloc_list = NULL;
1143   while ((r = *rp) != NULL)
1144     {
1145       if (r->u.b.sec == sec)
1146         {
1147           *rp = r->next;
1148           r->next = my_reloc_list;
1149           my_reloc_list = r;
1150           n++;
1151         }
1152       else
1153         rp = &r->next;
1154     }
1155
1156   relocs = xcalloc (n, sizeof (arelent *));
1157
1158   i = 0;
1159   for (fixp = seginfo->fix_root; fixp != (fixS *) NULL; fixp = fixp->fx_next)
1160     {
1161       int j;
1162       int fx_size, slack;
1163       offsetT loc;
1164
1165       if (fixp->fx_done)
1166         continue;
1167
1168       fx_size = fixp->fx_size;
1169       slack = TC_FX_SIZE_SLACK (fixp);
1170       if (slack > 0)
1171         fx_size = fx_size > slack ? fx_size - slack : 0;
1172       loc = fixp->fx_where + fx_size;
1173       if (slack >= 0 && loc > fixp->fx_frag->fr_fix)
1174         as_bad_where (fixp->fx_file, fixp->fx_line,
1175                       _("internal error: fixup not contained within frag"));
1176
1177 #ifndef RELOC_EXPANSION_POSSIBLE
1178       {
1179         arelent *reloc = tc_gen_reloc (sec, fixp);
1180
1181         if (!reloc)
1182           continue;
1183         relocs[i++] = reloc;
1184         j = 1;
1185       }
1186 #else
1187       {
1188         arelent **reloc = tc_gen_reloc (sec, fixp);
1189
1190         for (j = 0; reloc[j]; j++)
1191           relocs[i++] = reloc[j];
1192       }
1193 #endif
1194
1195       for ( ; j != 0; --j)
1196         install_reloc (sec, relocs[i - j], fixp->fx_frag,
1197                        fixp->fx_file, fixp->fx_line);
1198     }
1199   n = i;
1200
1201 #ifdef DEBUG4
1202   {
1203     unsigned int i, j, nsyms;
1204     asymbol **sympp;
1205     sympp = bfd_get_outsymbols (stdoutput);
1206     nsyms = bfd_get_symcount (stdoutput);
1207     for (i = 0; i < n; i++)
1208       if (((*relocs[i]->sym_ptr_ptr)->flags & BSF_SECTION_SYM) == 0)
1209         {
1210           for (j = 0; j < nsyms; j++)
1211             if (sympp[j] == *relocs[i]->sym_ptr_ptr)
1212               break;
1213           if (j == nsyms)
1214             abort ();
1215         }
1216   }
1217 #endif
1218
1219   for (r = my_reloc_list; r != NULL; r = r->next)
1220     {
1221       fragS *f;
1222       for (f = seginfo->frchainP->frch_root; f; f = f->fr_next)
1223         if (f->fr_address <= r->u.b.r.address
1224             && r->u.b.r.address < f->fr_address + f->fr_fix)
1225           break;
1226       if (f == NULL)
1227         as_bad_where (r->file, r->line,
1228                       _("reloc not within (fixed part of) section"));
1229       else
1230         {
1231           relocs[n++] = &r->u.b.r;
1232           install_reloc (sec, &r->u.b.r, f, r->file, r->line);
1233         }
1234     }
1235
1236   if (n)
1237     {
1238       flagword flags = bfd_get_section_flags (abfd, sec);
1239       flags |= SEC_RELOC;
1240       bfd_set_section_flags (abfd, sec, flags);
1241       bfd_set_reloc (stdoutput, sec, relocs, n);
1242     }
1243
1244 #ifdef SET_SECTION_RELOCS
1245   SET_SECTION_RELOCS (sec, relocs, n);
1246 #endif
1247
1248 #ifdef DEBUG3
1249   {
1250     unsigned int i;
1251     arelent *r;
1252     asymbol *s;
1253     fprintf (stderr, "relocs for sec %s\n", sec->name);
1254     for (i = 0; i < n; i++)
1255       {
1256         r = relocs[i];
1257         s = *r->sym_ptr_ptr;
1258         fprintf (stderr, "  reloc %2d @%p off %4lx : sym %-10s addend %lx\n",
1259                  i, r, (unsigned long)r->address, s->name, (unsigned long)r->addend);
1260       }
1261   }
1262 #endif
1263 }
1264
1265 static void
1266 write_contents (bfd *abfd ATTRIBUTE_UNUSED,
1267                 asection *sec,
1268                 void *xxx ATTRIBUTE_UNUSED)
1269 {
1270   segment_info_type *seginfo = seg_info (sec);
1271   addressT offset = 0;
1272   fragS *f;
1273
1274   /* Write out the frags.  */
1275   if (seginfo == NULL
1276       || !(bfd_get_section_flags (abfd, sec) & SEC_HAS_CONTENTS))
1277     return;
1278
1279   for (f = seginfo->frchainP->frch_root;
1280        f;
1281        f = f->fr_next)
1282     {
1283       int x;
1284       addressT fill_size;
1285       char *fill_literal;
1286       offsetT count;
1287
1288       assert (f->fr_type == rs_fill);
1289       if (f->fr_fix)
1290         {
1291           x = bfd_set_section_contents (stdoutput, sec,
1292                                         f->fr_literal, (file_ptr) offset,
1293                                         (bfd_size_type) f->fr_fix);
1294           if (!x)
1295             as_fatal (_("can't write %s: %s"), stdoutput->filename,
1296                       bfd_errmsg (bfd_get_error ()));
1297           offset += f->fr_fix;
1298         }
1299       fill_literal = f->fr_literal + f->fr_fix;
1300       fill_size = f->fr_var;
1301       count = f->fr_offset;
1302       assert (count >= 0);
1303       if (fill_size && count)
1304         {
1305           char buf[256];
1306           if (fill_size > sizeof (buf))
1307             {
1308               /* Do it the old way. Can this ever happen?  */
1309               while (count--)
1310                 {
1311                   x = bfd_set_section_contents (stdoutput, sec,
1312                                                 fill_literal,
1313                                                 (file_ptr) offset,
1314                                                 (bfd_size_type) fill_size);
1315                   if (!x)
1316                     as_fatal (_("can't write %s: %s"), stdoutput->filename,
1317                               bfd_errmsg (bfd_get_error ()));
1318                   offset += fill_size;
1319                 }
1320             }
1321           else
1322             {
1323               /* Build a buffer full of fill objects and output it as
1324                  often as necessary. This saves on the overhead of
1325                  potentially lots of bfd_set_section_contents calls.  */
1326               int n_per_buf, i;
1327               if (fill_size == 1)
1328                 {
1329                   n_per_buf = sizeof (buf);
1330                   memset (buf, *fill_literal, n_per_buf);
1331                 }
1332               else
1333                 {
1334                   char *bufp;
1335                   n_per_buf = sizeof (buf) / fill_size;
1336                   for (i = n_per_buf, bufp = buf; i; i--, bufp += fill_size)
1337                     memcpy (bufp, fill_literal, fill_size);
1338                 }
1339               for (; count > 0; count -= n_per_buf)
1340                 {
1341                   n_per_buf = n_per_buf > count ? count : n_per_buf;
1342                   x = bfd_set_section_contents
1343                     (stdoutput, sec, buf, (file_ptr) offset,
1344                      (bfd_size_type) n_per_buf * fill_size);
1345                   if (!x)
1346                     as_fatal (_("cannot write to output file"));
1347                   offset += n_per_buf * fill_size;
1348                 }
1349             }
1350         }
1351     }
1352 }
1353
1354 static void
1355 merge_data_into_text (void)
1356 {
1357   seg_info (text_section)->frchainP->frch_last->fr_next =
1358     seg_info (data_section)->frchainP->frch_root;
1359   seg_info (text_section)->frchainP->frch_last =
1360     seg_info (data_section)->frchainP->frch_last;
1361   seg_info (data_section)->frchainP = 0;
1362 }
1363
1364 static void
1365 set_symtab (void)
1366 {
1367   int nsyms;
1368   asymbol **asympp;
1369   symbolS *symp;
1370   bfd_boolean result;
1371
1372   /* Count symbols.  We can't rely on a count made by the loop in
1373      write_object_file, because *_frob_file may add a new symbol or
1374      two.  */
1375   nsyms = 0;
1376   for (symp = symbol_rootP; symp; symp = symbol_next (symp))
1377     nsyms++;
1378
1379   if (nsyms)
1380     {
1381       int i;
1382       bfd_size_type amt = (bfd_size_type) nsyms * sizeof (asymbol *);
1383
1384       asympp = bfd_alloc (stdoutput, amt);
1385       symp = symbol_rootP;
1386       for (i = 0; i < nsyms; i++, symp = symbol_next (symp))
1387         {
1388           asympp[i] = symbol_get_bfdsym (symp);
1389           if (asympp[i]->flags != BSF_SECTION_SYM
1390               || !(bfd_is_const_section (asympp[i]->section)
1391                    && asympp[i]->section->symbol == asympp[i]))
1392             asympp[i]->flags |= BSF_KEEP;
1393           symbol_mark_written (symp);
1394         }
1395     }
1396   else
1397     asympp = 0;
1398   result = bfd_set_symtab (stdoutput, asympp, nsyms);
1399   assert (result);
1400   symbol_table_frozen = 1;
1401 }
1402
1403 /* Finish the subsegments.  After every sub-segment, we fake an
1404    ".align ...".  This conforms to BSD4.2 brane-damage.  We then fake
1405    ".fill 0" because that is the kind of frag that requires least
1406    thought.  ".align" frags like to have a following frag since that
1407    makes calculating their intended length trivial.  */
1408
1409 #ifndef SUB_SEGMENT_ALIGN
1410 #ifdef HANDLE_ALIGN
1411 /* The last subsegment gets an alignment corresponding to the alignment
1412    of the section.  This allows proper nop-filling at the end of
1413    code-bearing sections.  */
1414 #define SUB_SEGMENT_ALIGN(SEG, FRCHAIN)                                 \
1415   (!(FRCHAIN)->frch_next ? get_recorded_alignment (SEG) : 0)
1416 #else
1417 #define SUB_SEGMENT_ALIGN(SEG, FRCHAIN) 0
1418 #endif
1419 #endif
1420
1421 void
1422 subsegs_finish (void)
1423 {
1424   struct frchain *frchainP;
1425   asection *s;
1426
1427   for (s = stdoutput->sections; s; s = s->next)
1428     {
1429       segment_info_type *seginfo = seg_info (s);
1430       if (!seginfo)
1431         continue;
1432
1433       for (frchainP = seginfo->frchainP;
1434            frchainP != NULL;
1435            frchainP = frchainP->frch_next)
1436         {
1437           int alignment = 0;
1438
1439           subseg_set (s, frchainP->frch_subseg);
1440
1441           /* This now gets called even if we had errors.  In that case,
1442              any alignment is meaningless, and, moreover, will look weird
1443              if we are generating a listing.  */
1444           if (!had_errors ())
1445             {
1446               alignment = SUB_SEGMENT_ALIGN (now_seg, frchainP);
1447               if ((bfd_get_section_flags (now_seg->owner, now_seg) & SEC_MERGE)
1448                   && now_seg->entsize)
1449                 {
1450                   unsigned int entsize = now_seg->entsize;
1451                   int entalign = 0;
1452
1453                   while ((entsize & 1) == 0)
1454                     {
1455                       ++entalign;
1456                       entsize >>= 1;
1457                     }
1458                   if (entalign > alignment)
1459                     alignment = entalign;
1460                 }
1461             }
1462
1463           if (subseg_text_p (now_seg))
1464             frag_align_code (alignment, 0);
1465           else
1466             frag_align (alignment, 0, 0);
1467
1468           /* frag_align will have left a new frag.
1469              Use this last frag for an empty ".fill".
1470
1471              For this segment ...
1472              Create a last frag. Do not leave a "being filled in frag".  */
1473           frag_wane (frag_now);
1474           frag_now->fr_fix = 0;
1475           know (frag_now->fr_next == NULL);
1476         }
1477     }
1478 }
1479
1480 /* Write the object file.  */
1481
1482 void
1483 write_object_file (void)
1484 {
1485   struct relax_seg_info rsi;
1486 #ifndef WORKING_DOT_WORD
1487   fragS *fragP;                 /* Track along all frags.  */
1488 #endif
1489
1490   /* Do we really want to write it?  */
1491   {
1492     int n_warns, n_errs;
1493     n_warns = had_warnings ();
1494     n_errs = had_errors ();
1495     /* The -Z flag indicates that an object file should be generated,
1496        regardless of warnings and errors.  */
1497     if (flag_always_generate_output)
1498       {
1499         if (n_warns || n_errs)
1500           as_warn (_("%d error%s, %d warning%s, generating bad object file"),
1501                    n_errs, n_errs == 1 ? "" : "s",
1502                    n_warns, n_warns == 1 ? "" : "s");
1503       }
1504     else
1505       {
1506         if (n_errs)
1507           as_fatal (_("%d error%s, %d warning%s, no object file generated"),
1508                     n_errs, n_errs == 1 ? "" : "s",
1509                     n_warns, n_warns == 1 ? "" : "s");
1510       }
1511   }
1512
1513 #ifdef  OBJ_VMS
1514   /* Under VMS we try to be compatible with VAX-11 "C".  Thus, we call
1515      a routine to check for the definition of the procedure "_main",
1516      and if so -- fix it up so that it can be program entry point.  */
1517   vms_check_for_main ();
1518 #endif /* OBJ_VMS  */
1519
1520   /* From now on, we don't care about sub-segments.  Build one frag chain
1521      for each segment. Linked thru fr_next.  */
1522
1523   /* Remove the sections created by gas for its own purposes.  */
1524   {
1525     int i;
1526
1527     bfd_section_list_remove (stdoutput, reg_section);
1528     bfd_section_list_remove (stdoutput, expr_section);
1529     stdoutput->section_count -= 2;
1530     i = 0;
1531     bfd_map_over_sections (stdoutput, renumber_sections, &i);
1532   }
1533
1534   bfd_map_over_sections (stdoutput, chain_frchains_together, (char *) 0);
1535
1536   /* We have two segments. If user gave -R flag, then we must put the
1537      data frags into the text segment. Do this before relaxing so
1538      we know to take advantage of -R and make shorter addresses.  */
1539   if (flag_readonly_data_in_text)
1540     {
1541       merge_data_into_text ();
1542     }
1543
1544   rsi.pass = 0;
1545   while (1)
1546     {
1547 #ifndef WORKING_DOT_WORD
1548       /* We need to reset the markers in the broken word list and
1549          associated frags between calls to relax_segment (via
1550          relax_seg).  Since the broken word list is global, we do it
1551          once per round, rather than locally in relax_segment for each
1552          segment.  */
1553       struct broken_word *brokp;
1554
1555       for (brokp = broken_words;
1556            brokp != (struct broken_word *) NULL;
1557            brokp = brokp->next_broken_word)
1558         {
1559           brokp->added = 0;
1560
1561           if (brokp->dispfrag != (fragS *) NULL
1562               && brokp->dispfrag->fr_type == rs_broken_word)
1563             brokp->dispfrag->fr_subtype = 0;
1564         }
1565 #endif
1566
1567       rsi.changed = 0;
1568       bfd_map_over_sections (stdoutput, relax_seg, &rsi);
1569       rsi.pass++;
1570       if (!rsi.changed)
1571         break;
1572     }
1573
1574   /* Note - Most ports will use the default value of
1575      TC_FINALIZE_SYMS_BEFORE_SIZE_SEG, which 1.  This will force
1576      local symbols to be resolved, removing their frag information.
1577      Some ports however, will not have finished relaxing all of
1578      their frags and will still need the local symbol frag
1579      information.  These ports can set
1580      TC_FINALIZE_SYMS_BEFORE_SIZE_SEG to 0.  */
1581   finalize_syms = TC_FINALIZE_SYMS_BEFORE_SIZE_SEG;
1582
1583   bfd_map_over_sections (stdoutput, size_seg, (char *) 0);
1584
1585   /* Relaxation has completed.  Freeze all syms.  */
1586   finalize_syms = 1;
1587
1588 #ifdef md_post_relax_hook
1589   md_post_relax_hook;
1590 #endif
1591
1592 #ifndef WORKING_DOT_WORD
1593   {
1594     struct broken_word *lie;
1595     struct broken_word **prevP;
1596
1597     prevP = &broken_words;
1598     for (lie = broken_words; lie; lie = lie->next_broken_word)
1599       if (!lie->added)
1600         {
1601           expressionS exp;
1602
1603           subseg_change (lie->seg, lie->subseg);
1604           exp.X_op = O_subtract;
1605           exp.X_add_symbol = lie->add;
1606           exp.X_op_symbol = lie->sub;
1607           exp.X_add_number = lie->addnum;
1608 #ifdef TC_CONS_FIX_NEW
1609           TC_CONS_FIX_NEW (lie->frag,
1610                            lie->word_goes_here - lie->frag->fr_literal,
1611                            2, &exp);
1612 #else
1613           fix_new_exp (lie->frag,
1614                        lie->word_goes_here - lie->frag->fr_literal,
1615                        2, &exp, 0, BFD_RELOC_16);
1616 #endif
1617           *prevP = lie->next_broken_word;
1618         }
1619       else
1620         prevP = &(lie->next_broken_word);
1621
1622     for (lie = broken_words; lie;)
1623       {
1624         struct broken_word *untruth;
1625         char *table_ptr;
1626         addressT table_addr;
1627         addressT from_addr, to_addr;
1628         int n, m;
1629
1630         subseg_change (lie->seg, lie->subseg);
1631         fragP = lie->dispfrag;
1632
1633         /* Find out how many broken_words go here.  */
1634         n = 0;
1635         for (untruth = lie;
1636              untruth && untruth->dispfrag == fragP;
1637              untruth = untruth->next_broken_word)
1638           if (untruth->added == 1)
1639             n++;
1640
1641         table_ptr = lie->dispfrag->fr_opcode;
1642         table_addr = (lie->dispfrag->fr_address
1643                       + (table_ptr - lie->dispfrag->fr_literal));
1644         /* Create the jump around the long jumps.  This is a short
1645            jump from table_ptr+0 to table_ptr+n*long_jump_size.  */
1646         from_addr = table_addr;
1647         to_addr = table_addr + md_short_jump_size + n * md_long_jump_size;
1648         md_create_short_jump (table_ptr, from_addr, to_addr, lie->dispfrag,
1649                               lie->add);
1650         table_ptr += md_short_jump_size;
1651         table_addr += md_short_jump_size;
1652
1653         for (m = 0;
1654              lie && lie->dispfrag == fragP;
1655              m++, lie = lie->next_broken_word)
1656           {
1657             if (lie->added == 2)
1658               continue;
1659             /* Patch the jump table.  */
1660             /* This is the offset from ??? to table_ptr+0.  */
1661             to_addr = table_addr - S_GET_VALUE (lie->sub);
1662 #ifdef TC_CHECK_ADJUSTED_BROKEN_DOT_WORD
1663             TC_CHECK_ADJUSTED_BROKEN_DOT_WORD (to_addr, lie);
1664 #endif
1665             md_number_to_chars (lie->word_goes_here, to_addr, 2);
1666             for (untruth = lie->next_broken_word;
1667                  untruth && untruth->dispfrag == fragP;
1668                  untruth = untruth->next_broken_word)
1669               {
1670                 if (untruth->use_jump == lie)
1671                   md_number_to_chars (untruth->word_goes_here, to_addr, 2);
1672               }
1673
1674             /* Install the long jump.  */
1675             /* This is a long jump from table_ptr+0 to the final target.  */
1676             from_addr = table_addr;
1677             to_addr = S_GET_VALUE (lie->add) + lie->addnum;
1678             md_create_long_jump (table_ptr, from_addr, to_addr, lie->dispfrag,
1679                                  lie->add);
1680             table_ptr += md_long_jump_size;
1681             table_addr += md_long_jump_size;
1682           }
1683       }
1684   }
1685 #endif /* not WORKING_DOT_WORD  */
1686
1687   /* Resolve symbol values.  This needs to be done before processing
1688      the relocations.  */
1689   if (symbol_rootP)
1690     {
1691       symbolS *symp;
1692
1693       for (symp = symbol_rootP; symp; symp = symbol_next (symp))
1694         resolve_symbol_value (symp);
1695     }
1696   resolve_local_symbol_values ();
1697   resolve_reloc_expr_symbols ();
1698
1699   PROGRESS (1);
1700
1701 #ifdef tc_frob_file_before_adjust
1702   tc_frob_file_before_adjust ();
1703 #endif
1704 #ifdef obj_frob_file_before_adjust
1705   obj_frob_file_before_adjust ();
1706 #endif
1707
1708   bfd_map_over_sections (stdoutput, adjust_reloc_syms, (char *) 0);
1709
1710 #ifdef tc_frob_file_before_fix
1711   tc_frob_file_before_fix ();
1712 #endif
1713 #ifdef obj_frob_file_before_fix
1714   obj_frob_file_before_fix ();
1715 #endif
1716
1717   bfd_map_over_sections (stdoutput, fix_segment, (char *) 0);
1718
1719   /* Set up symbol table, and write it out.  */
1720   if (symbol_rootP)
1721     {
1722       symbolS *symp;
1723       bfd_boolean skip_next_symbol = FALSE;
1724
1725       for (symp = symbol_rootP; symp; symp = symbol_next (symp))
1726         {
1727           int punt = 0;
1728           const char *name;
1729
1730           if (skip_next_symbol)
1731             {
1732               /* Don't do anything besides moving the value of the
1733                  symbol from the GAS value-field to the BFD value-field.  */
1734               symbol_get_bfdsym (symp)->value = S_GET_VALUE (symp);
1735               skip_next_symbol = FALSE;
1736               continue;
1737             }
1738
1739           if (symbol_mri_common_p (symp))
1740             {
1741               if (S_IS_EXTERNAL (symp))
1742                 as_bad (_("%s: global symbols not supported in common sections"),
1743                         S_GET_NAME (symp));
1744               symbol_remove (symp, &symbol_rootP, &symbol_lastP);
1745               continue;
1746             }
1747
1748           name = S_GET_NAME (symp);
1749           if (name)
1750             {
1751               const char *name2 =
1752                 decode_local_label_name ((char *) S_GET_NAME (symp));
1753               /* They only differ if `name' is a fb or dollar local
1754                  label name.  */
1755               if (name2 != name && ! S_IS_DEFINED (symp))
1756                 as_bad (_("local label `%s' is not defined"), name2);
1757             }
1758
1759           /* Do it again, because adjust_reloc_syms might introduce
1760              more symbols.  They'll probably only be section symbols,
1761              but they'll still need to have the values computed.  */
1762           resolve_symbol_value (symp);
1763
1764           /* Skip symbols which were equated to undefined or common
1765              symbols.  */
1766           if (symbol_equated_reloc_p (symp)
1767               || S_IS_WEAKREFR (symp))
1768             {
1769               const char *name = S_GET_NAME (symp);
1770               if (S_IS_COMMON (symp)
1771                   && !TC_FAKE_LABEL (name)
1772                   && !S_IS_WEAKREFR (symp)
1773                   && (!S_IS_EXTERNAL (symp) || S_IS_LOCAL (symp)))
1774                 {
1775                   expressionS *e = symbol_get_value_expression (symp);
1776                   as_bad (_("Local symbol `%s' can't be equated to common symbol `%s'"),
1777                           name, S_GET_NAME (e->X_add_symbol));
1778                 }
1779               if (S_GET_SEGMENT (symp) == reg_section)
1780                 {
1781                   /* Report error only if we know the symbol name.  */
1782                   if (S_GET_NAME (symp) != reg_section->name)
1783                     as_bad (_("can't make global register symbol `%s'"),
1784                             name);
1785                 }
1786               symbol_remove (symp, &symbol_rootP, &symbol_lastP);
1787               continue;
1788             }
1789
1790 #ifdef obj_frob_symbol
1791           obj_frob_symbol (symp, punt);
1792 #endif
1793 #ifdef tc_frob_symbol
1794           if (! punt || symbol_used_in_reloc_p (symp))
1795             tc_frob_symbol (symp, punt);
1796 #endif
1797
1798           /* If we don't want to keep this symbol, splice it out of
1799              the chain now.  If EMIT_SECTION_SYMBOLS is 0, we never
1800              want section symbols.  Otherwise, we skip local symbols
1801              and symbols that the frob_symbol macros told us to punt,
1802              but we keep such symbols if they are used in relocs.  */
1803           if (symp == abs_section_sym
1804               || (! EMIT_SECTION_SYMBOLS
1805                   && symbol_section_p (symp))
1806               /* Note that S_IS_EXTERNAL and S_IS_LOCAL are not always
1807                  opposites.  Sometimes the former checks flags and the
1808                  latter examines the name...  */
1809               || (!S_IS_EXTERNAL (symp)
1810                   && (punt || S_IS_LOCAL (symp) ||
1811                       (S_IS_WEAKREFD (symp) && ! symbol_used_p (symp)))
1812                   && ! symbol_used_in_reloc_p (symp)))
1813             {
1814               symbol_remove (symp, &symbol_rootP, &symbol_lastP);
1815
1816               /* After symbol_remove, symbol_next(symp) still returns
1817                  the one that came after it in the chain.  So we don't
1818                  need to do any extra cleanup work here.  */
1819               continue;
1820             }
1821
1822           /* Make sure we really got a value for the symbol.  */
1823           if (! symbol_resolved_p (symp))
1824             {
1825               as_bad (_("can't resolve value for symbol `%s'"),
1826                       S_GET_NAME (symp));
1827               symbol_mark_resolved (symp);
1828             }
1829
1830           /* Set the value into the BFD symbol.  Up til now the value
1831              has only been kept in the gas symbolS struct.  */
1832           symbol_get_bfdsym (symp)->value = S_GET_VALUE (symp);
1833
1834           /* A warning construct is a warning symbol followed by the
1835              symbol warned about.  Don't let anything object-format or
1836              target-specific muck with it; it's ready for output.  */
1837           if (symbol_get_bfdsym (symp)->flags & BSF_WARNING)
1838             skip_next_symbol = TRUE;
1839         }
1840     }
1841
1842   PROGRESS (1);
1843
1844   /* Now do any format-specific adjustments to the symbol table, such
1845      as adding file symbols.  */
1846 #ifdef tc_adjust_symtab
1847   tc_adjust_symtab ();
1848 #endif
1849 #ifdef obj_adjust_symtab
1850   obj_adjust_symtab ();
1851 #endif
1852
1853   /* Stop if there is an error.  */
1854   if (had_errors ())
1855     return;
1856
1857   /* Now that all the sizes are known, and contents correct, we can
1858      start writing to the file.  */
1859   set_symtab ();
1860
1861   /* If *_frob_file changes the symbol value at this point, it is
1862      responsible for moving the changed value into symp->bsym->value
1863      as well.  Hopefully all symbol value changing can be done in
1864      *_frob_symbol.  */
1865 #ifdef tc_frob_file
1866   tc_frob_file ();
1867 #endif
1868 #ifdef obj_frob_file
1869   obj_frob_file ();
1870 #endif
1871
1872   bfd_map_over_sections (stdoutput, write_relocs, (char *) 0);
1873
1874 #ifdef tc_frob_file_after_relocs
1875   tc_frob_file_after_relocs ();
1876 #endif
1877 #ifdef obj_frob_file_after_relocs
1878   obj_frob_file_after_relocs ();
1879 #endif
1880
1881   bfd_map_over_sections (stdoutput, write_contents, (char *) 0);
1882 }
1883
1884 #ifdef TC_GENERIC_RELAX_TABLE
1885 /* Relax a fragment by scanning TC_GENERIC_RELAX_TABLE.  */
1886
1887 long
1888 relax_frag (segT segment, fragS *fragP, long stretch)
1889 {
1890   const relax_typeS *this_type;
1891   const relax_typeS *start_type;
1892   relax_substateT next_state;
1893   relax_substateT this_state;
1894   offsetT growth;
1895   offsetT aim;
1896   addressT target;
1897   addressT address;
1898   symbolS *symbolP;
1899   const relax_typeS *table;
1900
1901   target = fragP->fr_offset;
1902   address = fragP->fr_address;
1903   table = TC_GENERIC_RELAX_TABLE;
1904   this_state = fragP->fr_subtype;
1905   start_type = this_type = table + this_state;
1906   symbolP = fragP->fr_symbol;
1907
1908   if (symbolP)
1909     {
1910       fragS *sym_frag;
1911
1912       sym_frag = symbol_get_frag (symbolP);
1913
1914 #ifndef DIFF_EXPR_OK
1915       know (sym_frag != NULL);
1916 #endif
1917       know (S_GET_SEGMENT (symbolP) != absolute_section
1918             || sym_frag == &zero_address_frag);
1919       target += S_GET_VALUE (symbolP);
1920
1921       /* If frag has yet to be reached on this pass,
1922          assume it will move by STRETCH just as we did.
1923          If this is not so, it will be because some frag
1924          between grows, and that will force another pass.  */
1925
1926       if (stretch != 0
1927           && sym_frag->relax_marker != fragP->relax_marker
1928           && S_GET_SEGMENT (symbolP) == segment)
1929         {
1930           target += stretch;
1931         }
1932     }
1933
1934   aim = target - address - fragP->fr_fix;
1935 #ifdef TC_PCREL_ADJUST
1936   /* Currently only the ns32k family needs this.  */
1937   aim += TC_PCREL_ADJUST (fragP);
1938 #endif
1939
1940 #ifdef md_prepare_relax_scan
1941   /* Formerly called M68K_AIM_KLUDGE.  */
1942   md_prepare_relax_scan (fragP, address, aim, this_state, this_type);
1943 #endif
1944
1945   if (aim < 0)
1946     {
1947       /* Look backwards.  */
1948       for (next_state = this_type->rlx_more; next_state;)
1949         if (aim >= this_type->rlx_backward)
1950           next_state = 0;
1951         else
1952           {
1953             /* Grow to next state.  */
1954             this_state = next_state;
1955             this_type = table + this_state;
1956             next_state = this_type->rlx_more;
1957           }
1958     }
1959   else
1960     {
1961       /* Look forwards.  */
1962       for (next_state = this_type->rlx_more; next_state;)
1963         if (aim <= this_type->rlx_forward)
1964           next_state = 0;
1965         else
1966           {
1967             /* Grow to next state.  */
1968             this_state = next_state;
1969             this_type = table + this_state;
1970             next_state = this_type->rlx_more;
1971           }
1972     }
1973
1974   growth = this_type->rlx_length - start_type->rlx_length;
1975   if (growth != 0)
1976     fragP->fr_subtype = this_state;
1977   return growth;
1978 }
1979
1980 #endif /* defined (TC_GENERIC_RELAX_TABLE)  */
1981
1982 /* Relax_align. Advance location counter to next address that has 'alignment'
1983    lowest order bits all 0s, return size of adjustment made.  */
1984 static relax_addressT
1985 relax_align (register relax_addressT address,   /* Address now.  */
1986              register int alignment     /* Alignment (binary).  */)
1987 {
1988   relax_addressT mask;
1989   relax_addressT new_address;
1990
1991   mask = ~((~0) << alignment);
1992   new_address = (address + mask) & (~mask);
1993 #ifdef LINKER_RELAXING_SHRINKS_ONLY
1994   if (linkrelax)
1995     /* We must provide lots of padding, so the linker can discard it
1996        when needed.  The linker will not add extra space, ever.  */
1997     new_address += (1 << alignment);
1998 #endif
1999   return (new_address - address);
2000 }
2001
2002 /* Now we have a segment, not a crowd of sub-segments, we can make
2003    fr_address values.
2004
2005    Relax the frags.
2006
2007    After this, all frags in this segment have addresses that are correct
2008    within the segment. Since segments live in different file addresses,
2009    these frag addresses may not be the same as final object-file
2010    addresses.  */
2011
2012 int
2013 relax_segment (struct frag *segment_frag_root, segT segment, int pass)
2014 {
2015   unsigned long frag_count;
2016   struct frag *fragP;
2017   relax_addressT address;
2018   int ret;
2019
2020   /* In case md_estimate_size_before_relax() wants to make fixSs.  */
2021   subseg_change (segment, 0);
2022
2023   /* For each frag in segment: count and store  (a 1st guess of)
2024      fr_address.  */
2025   address = 0;
2026   for (frag_count = 0, fragP = segment_frag_root;
2027        fragP;
2028        fragP = fragP->fr_next, frag_count ++)
2029     {
2030       fragP->relax_marker = 0;
2031       fragP->fr_address = address;
2032       address += fragP->fr_fix;
2033
2034       switch (fragP->fr_type)
2035         {
2036         case rs_fill:
2037           address += fragP->fr_offset * fragP->fr_var;
2038           break;
2039
2040         case rs_align:
2041         case rs_align_code:
2042         case rs_align_test:
2043           {
2044             addressT offset = relax_align (address, (int) fragP->fr_offset);
2045
2046             if (fragP->fr_subtype != 0 && offset > fragP->fr_subtype)
2047               offset = 0;
2048
2049             if (offset % fragP->fr_var != 0)
2050               {
2051                 as_bad_where (fragP->fr_file, fragP->fr_line,
2052                               _("alignment padding (%lu bytes) not a multiple of %ld"),
2053                               (unsigned long) offset, (long) fragP->fr_var);
2054                 offset -= (offset % fragP->fr_var);
2055               }
2056
2057             address += offset;
2058           }
2059           break;
2060
2061         case rs_org:
2062         case rs_space:
2063           /* Assume .org is nugatory. It will grow with 1st relax.  */
2064           break;
2065
2066         case rs_machine_dependent:
2067           /* If fr_symbol is an expression, this call to
2068              resolve_symbol_value sets up the correct segment, which will
2069              likely be needed in md_estimate_size_before_relax.  */
2070           if (fragP->fr_symbol)
2071             resolve_symbol_value (fragP->fr_symbol);
2072
2073           address += md_estimate_size_before_relax (fragP, segment);
2074           break;
2075
2076 #ifndef WORKING_DOT_WORD
2077           /* Broken words don't concern us yet.  */
2078         case rs_broken_word:
2079           break;
2080 #endif
2081
2082         case rs_leb128:
2083           /* Initial guess is always 1; doing otherwise can result in
2084              stable solutions that are larger than the minimum.  */
2085           address += fragP->fr_offset = 1;
2086           break;
2087
2088         case rs_cfa:
2089           address += eh_frame_estimate_size_before_relax (fragP);
2090           break;
2091
2092         case rs_dwarf2dbg:
2093           address += dwarf2dbg_estimate_size_before_relax (fragP);
2094           break;
2095
2096         default:
2097           BAD_CASE (fragP->fr_type);
2098           break;
2099         }
2100     }
2101
2102   /* Do relax().  */
2103   {
2104     unsigned long max_iterations;
2105
2106     /* Cumulative address adjustment.  */
2107     offsetT stretch;
2108
2109     /* Have we made any adjustment this pass?  We can't just test
2110        stretch because one piece of code may have grown and another
2111        shrank.  */
2112     int stretched;
2113
2114     /* Most horrible, but gcc may give us some exception data that
2115        is impossible to assemble, of the form
2116
2117        .align 4
2118        .byte 0, 0
2119        .uleb128 end - start
2120        start:
2121        .space 128*128 - 1
2122        .align 4
2123        end:
2124
2125        If the leb128 is two bytes in size, then end-start is 128*128,
2126        which requires a three byte leb128.  If the leb128 is three
2127        bytes in size, then end-start is 128*128-1, which requires a
2128        two byte leb128.  We work around this dilemma by inserting
2129        an extra 4 bytes of alignment just after the .align.  This
2130        works because the data after the align is accessed relative to
2131        the end label.
2132
2133        This counter is used in a tiny state machine to detect
2134        whether a leb128 followed by an align is impossible to
2135        relax.  */
2136     int rs_leb128_fudge = 0;
2137
2138     /* We want to prevent going into an infinite loop where one frag grows
2139        depending upon the location of a symbol which is in turn moved by
2140        the growing frag.  eg:
2141
2142          foo = .
2143          .org foo+16
2144          foo = .
2145
2146        So we dictate that this algorithm can be at most O2.  */
2147     max_iterations = frag_count * frag_count;
2148     /* Check for overflow.  */
2149     if (max_iterations < frag_count)
2150       max_iterations = frag_count;
2151
2152     ret = 0;
2153     do
2154       {
2155         stretch = 0;
2156         stretched = 0;
2157
2158         for (fragP = segment_frag_root; fragP; fragP = fragP->fr_next)
2159           {
2160             offsetT growth = 0;
2161             addressT was_address;
2162             offsetT offset;
2163             symbolS *symbolP;
2164
2165             fragP->relax_marker ^= 1;
2166             was_address = fragP->fr_address;
2167             address = fragP->fr_address += stretch;
2168             symbolP = fragP->fr_symbol;
2169             offset = fragP->fr_offset;
2170
2171             switch (fragP->fr_type)
2172               {
2173               case rs_fill:     /* .fill never relaxes.  */
2174                 growth = 0;
2175                 break;
2176
2177 #ifndef WORKING_DOT_WORD
2178                 /* JF:  This is RMS's idea.  I do *NOT* want to be blamed
2179                    for it I do not want to write it.  I do not want to have
2180                    anything to do with it.  This is not the proper way to
2181                    implement this misfeature.  */
2182               case rs_broken_word:
2183                 {
2184                   struct broken_word *lie;
2185                   struct broken_word *untruth;
2186
2187                   /* Yes this is ugly (storing the broken_word pointer
2188                      in the symbol slot).  Still, this whole chunk of
2189                      code is ugly, and I don't feel like doing anything
2190                      about it.  Think of it as stubbornness in action.  */
2191                   growth = 0;
2192                   for (lie = (struct broken_word *) (fragP->fr_symbol);
2193                        lie && lie->dispfrag == fragP;
2194                        lie = lie->next_broken_word)
2195                     {
2196
2197                       if (lie->added)
2198                         continue;
2199
2200                       offset = (S_GET_VALUE (lie->add)
2201                                 + lie->addnum
2202                                 - S_GET_VALUE (lie->sub));
2203                       if (offset <= -32768 || offset >= 32767)
2204                         {
2205                           if (flag_warn_displacement)
2206                             {
2207                               char buf[50];
2208                               sprint_value (buf, (addressT) lie->addnum);
2209                               as_warn_where (fragP->fr_file, fragP->fr_line,
2210                                              _(".word %s-%s+%s didn't fit"),
2211                                              S_GET_NAME (lie->add),
2212                                              S_GET_NAME (lie->sub),
2213                                              buf);
2214                             }
2215                           lie->added = 1;
2216                           if (fragP->fr_subtype == 0)
2217                             {
2218                               fragP->fr_subtype++;
2219                               growth += md_short_jump_size;
2220                             }
2221                           for (untruth = lie->next_broken_word;
2222                                untruth && untruth->dispfrag == lie->dispfrag;
2223                                untruth = untruth->next_broken_word)
2224                             if ((symbol_get_frag (untruth->add)
2225                                  == symbol_get_frag (lie->add))
2226                                 && (S_GET_VALUE (untruth->add)
2227                                     == S_GET_VALUE (lie->add)))
2228                               {
2229                                 untruth->added = 2;
2230                                 untruth->use_jump = lie;
2231                               }
2232                           growth += md_long_jump_size;
2233                         }
2234                     }
2235
2236                   break;
2237                 }               /* case rs_broken_word  */
2238 #endif
2239               case rs_align:
2240               case rs_align_code:
2241               case rs_align_test:
2242                 {
2243                   addressT oldoff, newoff;
2244
2245                   oldoff = relax_align (was_address + fragP->fr_fix,
2246                                         (int) offset);
2247                   newoff = relax_align (address + fragP->fr_fix,
2248                                         (int) offset);
2249
2250                   if (fragP->fr_subtype != 0)
2251                     {
2252                       if (oldoff > fragP->fr_subtype)
2253                         oldoff = 0;
2254                       if (newoff > fragP->fr_subtype)
2255                         newoff = 0;
2256                     }
2257
2258                   growth = newoff - oldoff;
2259
2260                   /* If this align happens to follow a leb128 and
2261                      we have determined that the leb128 is bouncing
2262                      in size, then break the cycle by inserting an
2263                      extra alignment.  */
2264                   if (growth < 0
2265                       && (rs_leb128_fudge & 16) != 0
2266                       && (rs_leb128_fudge & 15) >= 2)
2267                     {
2268                       segment_info_type *seginfo = seg_info (segment);
2269                       struct obstack *ob = &seginfo->frchainP->frch_obstack;
2270                       struct frag *newf;
2271
2272                       newf = frag_alloc (ob);
2273                       obstack_blank_fast (ob, fragP->fr_var);
2274                       obstack_finish (ob);
2275                       memcpy (newf, fragP, SIZEOF_STRUCT_FRAG);
2276                       memcpy (newf->fr_literal,
2277                               fragP->fr_literal + fragP->fr_fix,
2278                               fragP->fr_var);
2279                       newf->fr_type = rs_fill;
2280                       newf->fr_fix = 0;
2281                       newf->fr_offset = (((offsetT) 1 << fragP->fr_offset)
2282                                          / fragP->fr_var);
2283                       if (newf->fr_offset * newf->fr_var
2284                           != (offsetT) 1 << fragP->fr_offset)
2285                         {
2286                           newf->fr_offset = (offsetT) 1 << fragP->fr_offset;
2287                           newf->fr_var = 1;
2288                         }
2289                       /* Include growth of new frag, because rs_fill
2290                          frags don't normally grow.  */
2291                       growth += newf->fr_offset * newf->fr_var;
2292                       /* The new frag address is newoff.  Adjust this
2293                          for the amount we'll add when we process the
2294                          new frag.  */
2295                       newf->fr_address = newoff - stretch - growth;
2296                       newf->relax_marker ^= 1;
2297                       fragP->fr_next = newf;
2298 #ifdef DEBUG
2299                       as_warn (_("padding added"));
2300 #endif
2301                     }
2302                 }
2303                 break;
2304
2305               case rs_org:
2306                 {
2307                   addressT target = offset;
2308                   addressT after;
2309
2310                   if (symbolP)
2311                     {
2312                       /* Convert from an actual address to an octet offset
2313                          into the section.  Here it is assumed that the
2314                          section's VMA is zero, and can omit subtracting it
2315                          from the symbol's value to get the address offset.  */
2316                       know (S_GET_SEGMENT (symbolP)->vma == 0);
2317                       target += S_GET_VALUE (symbolP) * OCTETS_PER_BYTE;
2318                     }
2319
2320                   know (fragP->fr_next);
2321                   after = fragP->fr_next->fr_address + stretch;
2322                   growth = target - after;
2323                   if (growth < 0)
2324                     {
2325                       growth = 0;
2326
2327                       /* Don't error on first few frag relax passes.
2328                          The symbol might be an expression involving
2329                          symbol values from other sections.  If those
2330                          sections have not yet been processed their
2331                          frags will all have zero addresses, so we
2332                          will calculate incorrect values for them.  The
2333                          number of passes we allow before giving an
2334                          error is somewhat arbitrary.  It should be at
2335                          least one, with larger values requiring
2336                          increasingly contrived dependencies between
2337                          frags to trigger a false error.  */
2338                       if (pass < 2)
2339                         {
2340                           /* Force another pass.  */
2341                           ret = 1;
2342                           break;
2343                         }
2344
2345                       /* Growth may be negative, but variable part of frag
2346                          cannot have fewer than 0 chars.  That is, we can't
2347                          .org backwards.  */
2348                       as_bad_where (fragP->fr_file, fragP->fr_line,
2349                                     _("attempt to move .org backwards"));
2350
2351                       /* We've issued an error message.  Change the
2352                          frag to avoid cascading errors.  */
2353                       fragP->fr_type = rs_align;
2354                       fragP->fr_subtype = 0;
2355                       fragP->fr_offset = 0;
2356                       fragP->fr_fix = after - address;
2357                     }
2358                 }
2359                 break;
2360
2361               case rs_space:
2362                 growth = 0;
2363                 if (symbolP)
2364                   {
2365                     offsetT amount;
2366
2367                     amount = S_GET_VALUE (symbolP);
2368                     if (S_GET_SEGMENT (symbolP) != absolute_section
2369                         || S_IS_COMMON (symbolP)
2370                         || ! S_IS_DEFINED (symbolP))
2371                       {
2372                         as_bad_where (fragP->fr_file, fragP->fr_line,
2373                                       _(".space specifies non-absolute value"));
2374                         /* Prevent repeat of this error message.  */
2375                         fragP->fr_symbol = 0;
2376                       }
2377                     else if (amount < 0)
2378                       {
2379                         /* Don't error on first few frag relax passes.
2380                            See rs_org comment for a longer explanation.  */
2381                         if (pass < 2)
2382                           {
2383                             ret = 1;
2384                             break;
2385                           }
2386
2387                         as_warn_where (fragP->fr_file, fragP->fr_line,
2388                                        _(".space or .fill with negative value, ignored"));
2389                         fragP->fr_symbol = 0;
2390                       }
2391                     else
2392                       growth = (was_address + fragP->fr_fix + amount
2393                                 - fragP->fr_next->fr_address);
2394                   }
2395                 break;
2396
2397               case rs_machine_dependent:
2398 #ifdef md_relax_frag
2399                 growth = md_relax_frag (segment, fragP, stretch);
2400 #else
2401 #ifdef TC_GENERIC_RELAX_TABLE
2402                 /* The default way to relax a frag is to look through
2403                    TC_GENERIC_RELAX_TABLE.  */
2404                 growth = relax_frag (segment, fragP, stretch);
2405 #endif /* TC_GENERIC_RELAX_TABLE  */
2406 #endif
2407                 break;
2408
2409               case rs_leb128:
2410                 {
2411                   valueT value;
2412                   offsetT size;
2413
2414                   value = resolve_symbol_value (fragP->fr_symbol);
2415                   size = sizeof_leb128 (value, fragP->fr_subtype);
2416                   growth = size - fragP->fr_offset;
2417                   fragP->fr_offset = size;
2418                 }
2419                 break;
2420
2421               case rs_cfa:
2422                 growth = eh_frame_relax_frag (fragP);
2423                 break;
2424
2425               case rs_dwarf2dbg:
2426                 growth = dwarf2dbg_relax_frag (fragP);
2427                 break;
2428
2429               default:
2430                 BAD_CASE (fragP->fr_type);
2431                 break;
2432               }
2433             if (growth)
2434               {
2435                 stretch += growth;
2436                 stretched = 1;
2437                 if (fragP->fr_type == rs_leb128)
2438                   rs_leb128_fudge += 16;
2439                 else if (fragP->fr_type == rs_align
2440                          && (rs_leb128_fudge & 16) != 0
2441                          && stretch == 0)
2442                   rs_leb128_fudge += 16;
2443                 else
2444                   rs_leb128_fudge = 0;
2445               }
2446           }
2447
2448         if (stretch == 0
2449             && (rs_leb128_fudge & 16) == 0
2450             && (rs_leb128_fudge & -16) != 0)
2451           rs_leb128_fudge += 1;
2452         else
2453           rs_leb128_fudge = 0;
2454       }
2455     /* Until nothing further to relax.  */
2456     while (stretched && -- max_iterations);
2457
2458     if (stretched)
2459       as_fatal (_("Infinite loop encountered whilst attempting to compute the addresses of symbols in section %s"),
2460                 segment_name (segment));
2461   }
2462
2463   for (fragP = segment_frag_root; fragP; fragP = fragP->fr_next)
2464     if (fragP->last_fr_address != fragP->fr_address)
2465       {
2466         fragP->last_fr_address = fragP->fr_address;
2467         ret = 1;
2468       }
2469   return ret;
2470 }
2471
2472 void
2473 number_to_chars_bigendian (char *buf, valueT val, int n)
2474 {
2475   if (n <= 0)
2476     abort ();
2477   while (n--)
2478     {
2479       buf[n] = val & 0xff;
2480       val >>= 8;
2481     }
2482 }
2483
2484 void
2485 number_to_chars_littleendian (char *buf, valueT val, int n)
2486 {
2487   if (n <= 0)
2488     abort ();
2489   while (n--)
2490     {
2491       *buf++ = val & 0xff;
2492       val >>= 8;
2493     }
2494 }
2495
2496 void
2497 write_print_statistics (FILE *file)
2498 {
2499   fprintf (file, "fixups: %d\n", n_fixups);
2500 }
2501
2502 /* For debugging.  */
2503 extern int indent_level;
2504
2505 void
2506 print_fixup (fixS *fixp)
2507 {
2508   indent_level = 1;
2509   fprintf (stderr, "fix ");
2510   fprintf_vma (stderr, (bfd_vma)((bfd_hostptr_t) fixp));
2511   fprintf (stderr, " %s:%d",fixp->fx_file, fixp->fx_line);
2512   if (fixp->fx_pcrel)
2513     fprintf (stderr, " pcrel");
2514   if (fixp->fx_pcrel_adjust)
2515     fprintf (stderr, " pcrel_adjust=%d", fixp->fx_pcrel_adjust);
2516   if (fixp->fx_im_disp)
2517     {
2518 #ifdef TC_NS32K
2519       fprintf (stderr, " im_disp=%d", fixp->fx_im_disp);
2520 #else
2521       fprintf (stderr, " im_disp");
2522 #endif
2523     }
2524   if (fixp->fx_tcbit)
2525     fprintf (stderr, " tcbit");
2526   if (fixp->fx_done)
2527     fprintf (stderr, " done");
2528   fprintf (stderr, "\n    size=%d frag=", fixp->fx_size);
2529   fprintf_vma (stderr, (bfd_vma) ((bfd_hostptr_t) fixp->fx_frag));
2530   fprintf (stderr, " where=%ld offset=%lx addnumber=%lx",
2531            (long) fixp->fx_where,
2532            (unsigned long) fixp->fx_offset,
2533            (unsigned long) fixp->fx_addnumber);
2534   fprintf (stderr, "\n    %s (%d)", bfd_get_reloc_code_name (fixp->fx_r_type),
2535            fixp->fx_r_type);
2536   if (fixp->fx_addsy)
2537     {
2538       fprintf (stderr, "\n   +<");
2539       print_symbol_value_1 (stderr, fixp->fx_addsy);
2540       fprintf (stderr, ">");
2541     }
2542   if (fixp->fx_subsy)
2543     {
2544       fprintf (stderr, "\n   -<");
2545       print_symbol_value_1 (stderr, fixp->fx_subsy);
2546       fprintf (stderr, ">");
2547     }
2548   fprintf (stderr, "\n");
2549 #ifdef TC_FIX_DATA_PRINT
2550   TC_FIX_DATA_PRINT (stderr, fixp);
2551 #endif
2552 }