]> CyberLeo.Net >> Repos - FreeBSD/releng/10.0.git/blob - contrib/binutils/gas/write.c
- Copy stable/10 (r259064) to releng/10.0 as part of the
[FreeBSD/releng/10.0.git] / contrib / binutils / 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
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 2, 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     (void) 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
1088   s = bfd_install_relocation (stdoutput, reloc,
1089                               fragp->fr_literal, fragp->fr_address,
1090                               sec, &err);
1091   switch (s)
1092     {
1093     case bfd_reloc_ok:
1094       break;
1095     case bfd_reloc_overflow:
1096       as_bad_where (file, line, _("relocation overflow"));
1097       break;
1098     case bfd_reloc_outofrange:
1099       as_bad_where (file, line, _("relocation out of range"));
1100       break;
1101     default:
1102       as_fatal (_("%s:%u: bad return from bfd_install_relocation: %x"),
1103                 file, line, s);
1104     }
1105 }
1106
1107 static void
1108 write_relocs (bfd *abfd, asection *sec, void *xxx ATTRIBUTE_UNUSED)
1109 {
1110   segment_info_type *seginfo = seg_info (sec);
1111   unsigned int i;
1112   unsigned int n;
1113   struct reloc_list *my_reloc_list, **rp, *r;
1114   arelent **relocs;
1115   fixS *fixp;
1116
1117   /* If seginfo is NULL, we did not create this section; don't do
1118      anything with it.  */
1119   if (seginfo == NULL)
1120     return;
1121
1122   n = 0;
1123   for (fixp = seginfo->fix_root; fixp; fixp = fixp->fx_next)
1124     if (!fixp->fx_done)
1125       n++;
1126
1127 #ifdef RELOC_EXPANSION_POSSIBLE
1128   n *= MAX_RELOC_EXPANSION;
1129 #endif
1130
1131   /* Extract relocs for this section from reloc_list.  */
1132   rp = &reloc_list;
1133   my_reloc_list = NULL;
1134   while ((r = *rp) != NULL)
1135     {
1136       if (r->u.b.sec == sec)
1137         {
1138           *rp = r->next;
1139           r->next = my_reloc_list;
1140           my_reloc_list = r;
1141           n++;
1142         }
1143       else
1144         rp = &r->next;
1145     }
1146
1147   relocs = xcalloc (n, sizeof (arelent *));
1148
1149   i = 0;
1150   for (fixp = seginfo->fix_root; fixp != (fixS *) NULL; fixp = fixp->fx_next)
1151     {
1152       int j;
1153       int fx_size, slack;
1154       offsetT loc;
1155
1156       if (fixp->fx_done)
1157         continue;
1158
1159       fx_size = fixp->fx_size;
1160       slack = TC_FX_SIZE_SLACK (fixp);
1161       if (slack > 0)
1162         fx_size = fx_size > slack ? fx_size - slack : 0;
1163       loc = fixp->fx_where + fx_size;
1164       if (slack >= 0 && loc > fixp->fx_frag->fr_fix)
1165         as_bad_where (fixp->fx_file, fixp->fx_line,
1166                       _("internal error: fixup not contained within frag"));
1167
1168 #ifndef RELOC_EXPANSION_POSSIBLE
1169       {
1170         arelent *reloc = tc_gen_reloc (sec, fixp);
1171
1172         if (!reloc)
1173           continue;
1174         relocs[i++] = reloc;
1175         j = 1;
1176       }
1177 #else
1178       {
1179         arelent **reloc = tc_gen_reloc (sec, fixp);
1180
1181         for (j = 0; reloc[j]; j++)
1182           relocs[i++] = reloc[j];
1183       }
1184 #endif
1185
1186       for ( ; j != 0; --j)
1187         install_reloc (sec, relocs[i - j], fixp->fx_frag,
1188                        fixp->fx_file, fixp->fx_line);
1189     }
1190   n = i;
1191
1192 #ifdef DEBUG4
1193   {
1194     unsigned int i, j, nsyms;
1195     asymbol **sympp;
1196     sympp = bfd_get_outsymbols (stdoutput);
1197     nsyms = bfd_get_symcount (stdoutput);
1198     for (i = 0; i < n; i++)
1199       if (((*relocs[i]->sym_ptr_ptr)->flags & BSF_SECTION_SYM) == 0)
1200         {
1201           for (j = 0; j < nsyms; j++)
1202             if (sympp[j] == *relocs[i]->sym_ptr_ptr)
1203               break;
1204           if (j == nsyms)
1205             abort ();
1206         }
1207   }
1208 #endif
1209
1210   for (r = my_reloc_list; r != NULL; r = r->next)
1211     {
1212       fragS *f;
1213       for (f = seginfo->frchainP->frch_root; f; f = f->fr_next)
1214         if (f->fr_address <= r->u.b.r.address
1215             && r->u.b.r.address < f->fr_address + f->fr_fix)
1216           break;
1217       if (f == NULL)
1218         as_bad_where (r->file, r->line,
1219                       _("reloc not within (fixed part of) section"));
1220       else
1221         {
1222           relocs[n++] = &r->u.b.r;
1223           install_reloc (sec, &r->u.b.r, f, r->file, r->line);
1224         }
1225     }
1226
1227   if (n)
1228     {
1229       flagword flags = bfd_get_section_flags (abfd, sec);
1230       flags |= SEC_RELOC;
1231       bfd_set_section_flags (abfd, sec, flags);
1232       bfd_set_reloc (stdoutput, sec, relocs, n);
1233     }
1234
1235 #ifdef SET_SECTION_RELOCS
1236   SET_SECTION_RELOCS (sec, relocs, n);
1237 #endif
1238
1239 #ifdef DEBUG3
1240   {
1241     unsigned int i;
1242     arelent *r;
1243     asymbol *s;
1244     fprintf (stderr, "relocs for sec %s\n", sec->name);
1245     for (i = 0; i < n; i++)
1246       {
1247         r = relocs[i];
1248         s = *r->sym_ptr_ptr;
1249         fprintf (stderr, "  reloc %2d @%p off %4lx : sym %-10s addend %lx\n",
1250                  i, r, (unsigned long)r->address, s->name, (unsigned long)r->addend);
1251       }
1252   }
1253 #endif
1254 }
1255
1256 static void
1257 write_contents (bfd *abfd ATTRIBUTE_UNUSED,
1258                 asection *sec,
1259                 void *xxx ATTRIBUTE_UNUSED)
1260 {
1261   segment_info_type *seginfo = seg_info (sec);
1262   addressT offset = 0;
1263   fragS *f;
1264
1265   /* Write out the frags.  */
1266   if (seginfo == NULL
1267       || !(bfd_get_section_flags (abfd, sec) & SEC_HAS_CONTENTS))
1268     return;
1269
1270   for (f = seginfo->frchainP->frch_root;
1271        f;
1272        f = f->fr_next)
1273     {
1274       int x;
1275       addressT fill_size;
1276       char *fill_literal;
1277       offsetT count;
1278
1279       assert (f->fr_type == rs_fill);
1280       if (f->fr_fix)
1281         {
1282           x = bfd_set_section_contents (stdoutput, sec,
1283                                         f->fr_literal, (file_ptr) offset,
1284                                         (bfd_size_type) f->fr_fix);
1285           if (!x)
1286             as_fatal (_("can't write %s: %s"), stdoutput->filename,
1287                       bfd_errmsg (bfd_get_error ()));
1288           offset += f->fr_fix;
1289         }
1290       fill_literal = f->fr_literal + f->fr_fix;
1291       fill_size = f->fr_var;
1292       count = f->fr_offset;
1293       assert (count >= 0);
1294       if (fill_size && count)
1295         {
1296           char buf[256];
1297           if (fill_size > sizeof (buf))
1298             {
1299               /* Do it the old way. Can this ever happen?  */
1300               while (count--)
1301                 {
1302                   x = bfd_set_section_contents (stdoutput, sec,
1303                                                 fill_literal,
1304                                                 (file_ptr) offset,
1305                                                 (bfd_size_type) fill_size);
1306                   if (!x)
1307                     as_fatal (_("can't write %s: %s"), stdoutput->filename,
1308                               bfd_errmsg (bfd_get_error ()));
1309                   offset += fill_size;
1310                 }
1311             }
1312           else
1313             {
1314               /* Build a buffer full of fill objects and output it as
1315                  often as necessary. This saves on the overhead of
1316                  potentially lots of bfd_set_section_contents calls.  */
1317               int n_per_buf, i;
1318               if (fill_size == 1)
1319                 {
1320                   n_per_buf = sizeof (buf);
1321                   memset (buf, *fill_literal, n_per_buf);
1322                 }
1323               else
1324                 {
1325                   char *bufp;
1326                   n_per_buf = sizeof (buf) / fill_size;
1327                   for (i = n_per_buf, bufp = buf; i; i--, bufp += fill_size)
1328                     memcpy (bufp, fill_literal, fill_size);
1329                 }
1330               for (; count > 0; count -= n_per_buf)
1331                 {
1332                   n_per_buf = n_per_buf > count ? count : n_per_buf;
1333                   x = bfd_set_section_contents
1334                     (stdoutput, sec, buf, (file_ptr) offset,
1335                      (bfd_size_type) n_per_buf * fill_size);
1336                   if (!x)
1337                     as_fatal (_("cannot write to output file"));
1338                   offset += n_per_buf * fill_size;
1339                 }
1340             }
1341         }
1342     }
1343 }
1344
1345 static void
1346 merge_data_into_text (void)
1347 {
1348   seg_info (text_section)->frchainP->frch_last->fr_next =
1349     seg_info (data_section)->frchainP->frch_root;
1350   seg_info (text_section)->frchainP->frch_last =
1351     seg_info (data_section)->frchainP->frch_last;
1352   seg_info (data_section)->frchainP = 0;
1353 }
1354
1355 static void
1356 set_symtab (void)
1357 {
1358   int nsyms;
1359   asymbol **asympp;
1360   symbolS *symp;
1361   bfd_boolean result;
1362
1363   /* Count symbols.  We can't rely on a count made by the loop in
1364      write_object_file, because *_frob_file may add a new symbol or
1365      two.  */
1366   nsyms = 0;
1367   for (symp = symbol_rootP; symp; symp = symbol_next (symp))
1368     nsyms++;
1369
1370   if (nsyms)
1371     {
1372       int i;
1373       bfd_size_type amt = (bfd_size_type) nsyms * sizeof (asymbol *);
1374
1375       asympp = bfd_alloc (stdoutput, amt);
1376       symp = symbol_rootP;
1377       for (i = 0; i < nsyms; i++, symp = symbol_next (symp))
1378         {
1379           asympp[i] = symbol_get_bfdsym (symp);
1380           symbol_mark_written (symp);
1381         }
1382     }
1383   else
1384     asympp = 0;
1385   result = bfd_set_symtab (stdoutput, asympp, nsyms);
1386   assert (result);
1387   symbol_table_frozen = 1;
1388 }
1389
1390 /* Finish the subsegments.  After every sub-segment, we fake an
1391    ".align ...".  This conforms to BSD4.2 brane-damage.  We then fake
1392    ".fill 0" because that is the kind of frag that requires least
1393    thought.  ".align" frags like to have a following frag since that
1394    makes calculating their intended length trivial.  */
1395
1396 #ifndef SUB_SEGMENT_ALIGN
1397 #ifdef HANDLE_ALIGN
1398 /* The last subsegment gets an alignment corresponding to the alignment
1399    of the section.  This allows proper nop-filling at the end of
1400    code-bearing sections.  */
1401 #define SUB_SEGMENT_ALIGN(SEG, FRCHAIN)                                 \
1402   (!(FRCHAIN)->frch_next ? get_recorded_alignment (SEG) : 0)
1403 #else
1404 #define SUB_SEGMENT_ALIGN(SEG, FRCHAIN) 0
1405 #endif
1406 #endif
1407
1408 void
1409 subsegs_finish (void)
1410 {
1411   struct frchain *frchainP;
1412   asection *s;
1413
1414   for (s = stdoutput->sections; s; s = s->next)
1415     {
1416       segment_info_type *seginfo = seg_info (s);
1417       if (!seginfo)
1418         continue;
1419
1420       for (frchainP = seginfo->frchainP;
1421            frchainP != NULL;
1422            frchainP = frchainP->frch_next)
1423         {
1424           int alignment = 0;
1425
1426           subseg_set (s, frchainP->frch_subseg);
1427
1428           /* This now gets called even if we had errors.  In that case,
1429              any alignment is meaningless, and, moreover, will look weird
1430              if we are generating a listing.  */
1431           if (!had_errors ())
1432             {
1433               alignment = SUB_SEGMENT_ALIGN (now_seg, frchainP);
1434               if ((bfd_get_section_flags (now_seg->owner, now_seg) & SEC_MERGE)
1435                   && now_seg->entsize)
1436                 {
1437                   unsigned int entsize = now_seg->entsize;
1438                   int entalign = 0;
1439
1440                   while ((entsize & 1) == 0)
1441                     {
1442                       ++entalign;
1443                       entsize >>= 1;
1444                     }
1445                   if (entalign > alignment)
1446                     alignment = entalign;
1447                 }
1448             }
1449
1450           if (subseg_text_p (now_seg))
1451             frag_align_code (alignment, 0);
1452           else
1453             frag_align (alignment, 0, 0);
1454
1455           /* frag_align will have left a new frag.
1456              Use this last frag for an empty ".fill".
1457
1458              For this segment ...
1459              Create a last frag. Do not leave a "being filled in frag".  */
1460           frag_wane (frag_now);
1461           frag_now->fr_fix = 0;
1462           know (frag_now->fr_next == NULL);
1463         }
1464     }
1465 }
1466
1467 /* Write the object file.  */
1468
1469 void
1470 write_object_file (void)
1471 {
1472   struct relax_seg_info rsi;
1473 #ifndef WORKING_DOT_WORD
1474   fragS *fragP;                 /* Track along all frags.  */
1475 #endif
1476
1477   /* Do we really want to write it?  */
1478   {
1479     int n_warns, n_errs;
1480     n_warns = had_warnings ();
1481     n_errs = had_errors ();
1482     /* The -Z flag indicates that an object file should be generated,
1483        regardless of warnings and errors.  */
1484     if (flag_always_generate_output)
1485       {
1486         if (n_warns || n_errs)
1487           as_warn (_("%d error%s, %d warning%s, generating bad object file"),
1488                    n_errs, n_errs == 1 ? "" : "s",
1489                    n_warns, n_warns == 1 ? "" : "s");
1490       }
1491     else
1492       {
1493         if (n_errs)
1494           as_fatal (_("%d error%s, %d warning%s, no object file generated"),
1495                     n_errs, n_errs == 1 ? "" : "s",
1496                     n_warns, n_warns == 1 ? "" : "s");
1497       }
1498   }
1499
1500 #ifdef  OBJ_VMS
1501   /* Under VMS we try to be compatible with VAX-11 "C".  Thus, we call
1502      a routine to check for the definition of the procedure "_main",
1503      and if so -- fix it up so that it can be program entry point.  */
1504   vms_check_for_main ();
1505 #endif /* OBJ_VMS  */
1506
1507   /* From now on, we don't care about sub-segments.  Build one frag chain
1508      for each segment. Linked thru fr_next.  */
1509
1510   /* Remove the sections created by gas for its own purposes.  */
1511   {
1512     int i;
1513
1514     bfd_section_list_remove (stdoutput, reg_section);
1515     bfd_section_list_remove (stdoutput, expr_section);
1516     stdoutput->section_count -= 2;
1517     i = 0;
1518     bfd_map_over_sections (stdoutput, renumber_sections, &i);
1519   }
1520
1521   bfd_map_over_sections (stdoutput, chain_frchains_together, (char *) 0);
1522
1523   /* We have two segments. If user gave -R flag, then we must put the
1524      data frags into the text segment. Do this before relaxing so
1525      we know to take advantage of -R and make shorter addresses.  */
1526   if (flag_readonly_data_in_text)
1527     {
1528       merge_data_into_text ();
1529     }
1530
1531   rsi.pass = 0;
1532   while (1)
1533     {
1534 #ifndef WORKING_DOT_WORD
1535       /* We need to reset the markers in the broken word list and
1536          associated frags between calls to relax_segment (via
1537          relax_seg).  Since the broken word list is global, we do it
1538          once per round, rather than locally in relax_segment for each
1539          segment.  */
1540       struct broken_word *brokp;
1541
1542       for (brokp = broken_words;
1543            brokp != (struct broken_word *) NULL;
1544            brokp = brokp->next_broken_word)
1545         {
1546           brokp->added = 0;
1547
1548           if (brokp->dispfrag != (fragS *) NULL
1549               && brokp->dispfrag->fr_type == rs_broken_word)
1550             brokp->dispfrag->fr_subtype = 0;
1551         }
1552 #endif
1553
1554       rsi.changed = 0;
1555       bfd_map_over_sections (stdoutput, relax_seg, &rsi);
1556       rsi.pass++;
1557       if (!rsi.changed)
1558         break;
1559     }
1560
1561   /* Note - Most ports will use the default value of
1562      TC_FINALIZE_SYMS_BEFORE_SIZE_SEG, which 1.  This will force
1563      local symbols to be resolved, removing their frag information.
1564      Some ports however, will not have finished relaxing all of
1565      their frags and will still need the local symbol frag
1566      information.  These ports can set
1567      TC_FINALIZE_SYMS_BEFORE_SIZE_SEG to 0.  */
1568   finalize_syms = TC_FINALIZE_SYMS_BEFORE_SIZE_SEG;
1569
1570   bfd_map_over_sections (stdoutput, size_seg, (char *) 0);
1571
1572   /* Relaxation has completed.  Freeze all syms.  */
1573   finalize_syms = 1;
1574
1575 #ifdef md_post_relax_hook
1576   md_post_relax_hook;
1577 #endif
1578
1579 #ifndef WORKING_DOT_WORD
1580   {
1581     struct broken_word *lie;
1582     struct broken_word **prevP;
1583
1584     prevP = &broken_words;
1585     for (lie = broken_words; lie; lie = lie->next_broken_word)
1586       if (!lie->added)
1587         {
1588           expressionS exp;
1589
1590           subseg_change (lie->seg, lie->subseg);
1591           exp.X_op = O_subtract;
1592           exp.X_add_symbol = lie->add;
1593           exp.X_op_symbol = lie->sub;
1594           exp.X_add_number = lie->addnum;
1595 #ifdef TC_CONS_FIX_NEW
1596           TC_CONS_FIX_NEW (lie->frag,
1597                            lie->word_goes_here - lie->frag->fr_literal,
1598                            2, &exp);
1599 #else
1600           fix_new_exp (lie->frag,
1601                        lie->word_goes_here - lie->frag->fr_literal,
1602                        2, &exp, 0, BFD_RELOC_16);
1603 #endif
1604           *prevP = lie->next_broken_word;
1605         }
1606       else
1607         prevP = &(lie->next_broken_word);
1608
1609     for (lie = broken_words; lie;)
1610       {
1611         struct broken_word *untruth;
1612         char *table_ptr;
1613         addressT table_addr;
1614         addressT from_addr, to_addr;
1615         int n, m;
1616
1617         subseg_change (lie->seg, lie->subseg);
1618         fragP = lie->dispfrag;
1619
1620         /* Find out how many broken_words go here.  */
1621         n = 0;
1622         for (untruth = lie;
1623              untruth && untruth->dispfrag == fragP;
1624              untruth = untruth->next_broken_word)
1625           if (untruth->added == 1)
1626             n++;
1627
1628         table_ptr = lie->dispfrag->fr_opcode;
1629         table_addr = (lie->dispfrag->fr_address
1630                       + (table_ptr - lie->dispfrag->fr_literal));
1631         /* Create the jump around the long jumps.  This is a short
1632            jump from table_ptr+0 to table_ptr+n*long_jump_size.  */
1633         from_addr = table_addr;
1634         to_addr = table_addr + md_short_jump_size + n * md_long_jump_size;
1635         md_create_short_jump (table_ptr, from_addr, to_addr, lie->dispfrag,
1636                               lie->add);
1637         table_ptr += md_short_jump_size;
1638         table_addr += md_short_jump_size;
1639
1640         for (m = 0;
1641              lie && lie->dispfrag == fragP;
1642              m++, lie = lie->next_broken_word)
1643           {
1644             if (lie->added == 2)
1645               continue;
1646             /* Patch the jump table.  */
1647             /* This is the offset from ??? to table_ptr+0.  */
1648             to_addr = table_addr - S_GET_VALUE (lie->sub);
1649 #ifdef TC_CHECK_ADJUSTED_BROKEN_DOT_WORD
1650             TC_CHECK_ADJUSTED_BROKEN_DOT_WORD (to_addr, lie);
1651 #endif
1652             md_number_to_chars (lie->word_goes_here, to_addr, 2);
1653             for (untruth = lie->next_broken_word;
1654                  untruth && untruth->dispfrag == fragP;
1655                  untruth = untruth->next_broken_word)
1656               {
1657                 if (untruth->use_jump == lie)
1658                   md_number_to_chars (untruth->word_goes_here, to_addr, 2);
1659               }
1660
1661             /* Install the long jump.  */
1662             /* This is a long jump from table_ptr+0 to the final target.  */
1663             from_addr = table_addr;
1664             to_addr = S_GET_VALUE (lie->add) + lie->addnum;
1665             md_create_long_jump (table_ptr, from_addr, to_addr, lie->dispfrag,
1666                                  lie->add);
1667             table_ptr += md_long_jump_size;
1668             table_addr += md_long_jump_size;
1669           }
1670       }
1671   }
1672 #endif /* not WORKING_DOT_WORD  */
1673
1674   /* Resolve symbol values.  This needs to be done before processing
1675      the relocations.  */
1676   if (symbol_rootP)
1677     {
1678       symbolS *symp;
1679
1680       for (symp = symbol_rootP; symp; symp = symbol_next (symp))
1681         resolve_symbol_value (symp);
1682     }
1683   resolve_local_symbol_values ();
1684   resolve_reloc_expr_symbols ();
1685
1686   PROGRESS (1);
1687
1688 #ifdef tc_frob_file_before_adjust
1689   tc_frob_file_before_adjust ();
1690 #endif
1691 #ifdef obj_frob_file_before_adjust
1692   obj_frob_file_before_adjust ();
1693 #endif
1694
1695   bfd_map_over_sections (stdoutput, adjust_reloc_syms, (char *) 0);
1696
1697 #ifdef tc_frob_file_before_fix
1698   tc_frob_file_before_fix ();
1699 #endif
1700 #ifdef obj_frob_file_before_fix
1701   obj_frob_file_before_fix ();
1702 #endif
1703
1704   bfd_map_over_sections (stdoutput, fix_segment, (char *) 0);
1705
1706   /* Set up symbol table, and write it out.  */
1707   if (symbol_rootP)
1708     {
1709       symbolS *symp;
1710       bfd_boolean skip_next_symbol = FALSE;
1711
1712       for (symp = symbol_rootP; symp; symp = symbol_next (symp))
1713         {
1714           int punt = 0;
1715           const char *name;
1716
1717           if (skip_next_symbol)
1718             {
1719               /* Don't do anything besides moving the value of the
1720                  symbol from the GAS value-field to the BFD value-field.  */
1721               symbol_get_bfdsym (symp)->value = S_GET_VALUE (symp);
1722               skip_next_symbol = FALSE;
1723               continue;
1724             }
1725
1726           if (symbol_mri_common_p (symp))
1727             {
1728               if (S_IS_EXTERNAL (symp))
1729                 as_bad (_("%s: global symbols not supported in common sections"),
1730                         S_GET_NAME (symp));
1731               symbol_remove (symp, &symbol_rootP, &symbol_lastP);
1732               continue;
1733             }
1734
1735           name = S_GET_NAME (symp);
1736           if (name)
1737             {
1738               const char *name2 =
1739                 decode_local_label_name ((char *) S_GET_NAME (symp));
1740               /* They only differ if `name' is a fb or dollar local
1741                  label name.  */
1742               if (name2 != name && ! S_IS_DEFINED (symp))
1743                 as_bad (_("local label `%s' is not defined"), name2);
1744             }
1745
1746           /* Do it again, because adjust_reloc_syms might introduce
1747              more symbols.  They'll probably only be section symbols,
1748              but they'll still need to have the values computed.  */
1749           resolve_symbol_value (symp);
1750
1751           /* Skip symbols which were equated to undefined or common
1752              symbols.  */
1753           if (symbol_equated_reloc_p (symp)
1754               || S_IS_WEAKREFR (symp))
1755             {
1756               const char *name = S_GET_NAME (symp);
1757               if (S_IS_COMMON (symp)
1758                   && !TC_FAKE_LABEL (name)
1759                   && !S_IS_WEAKREFR (symp)
1760                   && (!S_IS_EXTERNAL (symp) || S_IS_LOCAL (symp)))
1761                 {
1762                   expressionS *e = symbol_get_value_expression (symp);
1763                   as_bad (_("Local symbol `%s' can't be equated to common symbol `%s'"),
1764                           name, S_GET_NAME (e->X_add_symbol));
1765                 }
1766               symbol_remove (symp, &symbol_rootP, &symbol_lastP);
1767               continue;
1768             }
1769
1770 #ifdef obj_frob_symbol
1771           obj_frob_symbol (symp, punt);
1772 #endif
1773 #ifdef tc_frob_symbol
1774           if (! punt || symbol_used_in_reloc_p (symp))
1775             tc_frob_symbol (symp, punt);
1776 #endif
1777
1778           /* If we don't want to keep this symbol, splice it out of
1779              the chain now.  If EMIT_SECTION_SYMBOLS is 0, we never
1780              want section symbols.  Otherwise, we skip local symbols
1781              and symbols that the frob_symbol macros told us to punt,
1782              but we keep such symbols if they are used in relocs.  */
1783           if (symp == abs_section_sym
1784               || (! EMIT_SECTION_SYMBOLS
1785                   && symbol_section_p (symp))
1786               /* Note that S_IS_EXTERNAL and S_IS_LOCAL are not always
1787                  opposites.  Sometimes the former checks flags and the
1788                  latter examines the name...  */
1789               || (!S_IS_EXTERNAL (symp)
1790                   && (punt || S_IS_LOCAL (symp) ||
1791                       (S_IS_WEAKREFD (symp) && ! symbol_used_p (symp)))
1792                   && ! symbol_used_in_reloc_p (symp)))
1793             {
1794               symbol_remove (symp, &symbol_rootP, &symbol_lastP);
1795
1796               /* After symbol_remove, symbol_next(symp) still returns
1797                  the one that came after it in the chain.  So we don't
1798                  need to do any extra cleanup work here.  */
1799               continue;
1800             }
1801
1802           /* Make sure we really got a value for the symbol.  */
1803           if (! symbol_resolved_p (symp))
1804             {
1805               as_bad (_("can't resolve value for symbol `%s'"),
1806                       S_GET_NAME (symp));
1807               symbol_mark_resolved (symp);
1808             }
1809
1810           /* Set the value into the BFD symbol.  Up til now the value
1811              has only been kept in the gas symbolS struct.  */
1812           symbol_get_bfdsym (symp)->value = S_GET_VALUE (symp);
1813
1814           /* A warning construct is a warning symbol followed by the
1815              symbol warned about.  Don't let anything object-format or
1816              target-specific muck with it; it's ready for output.  */
1817           if (symbol_get_bfdsym (symp)->flags & BSF_WARNING)
1818             skip_next_symbol = TRUE;
1819         }
1820     }
1821
1822   PROGRESS (1);
1823
1824   /* Now do any format-specific adjustments to the symbol table, such
1825      as adding file symbols.  */
1826 #ifdef tc_adjust_symtab
1827   tc_adjust_symtab ();
1828 #endif
1829 #ifdef obj_adjust_symtab
1830   obj_adjust_symtab ();
1831 #endif
1832
1833   /* Now that all the sizes are known, and contents correct, we can
1834      start writing to the file.  */
1835   set_symtab ();
1836
1837   /* If *_frob_file changes the symbol value at this point, it is
1838      responsible for moving the changed value into symp->bsym->value
1839      as well.  Hopefully all symbol value changing can be done in
1840      *_frob_symbol.  */
1841 #ifdef tc_frob_file
1842   tc_frob_file ();
1843 #endif
1844 #ifdef obj_frob_file
1845   obj_frob_file ();
1846 #endif
1847
1848   bfd_map_over_sections (stdoutput, write_relocs, (char *) 0);
1849
1850 #ifdef tc_frob_file_after_relocs
1851   tc_frob_file_after_relocs ();
1852 #endif
1853 #ifdef obj_frob_file_after_relocs
1854   obj_frob_file_after_relocs ();
1855 #endif
1856
1857   bfd_map_over_sections (stdoutput, write_contents, (char *) 0);
1858 }
1859
1860 #ifdef TC_GENERIC_RELAX_TABLE
1861 /* Relax a fragment by scanning TC_GENERIC_RELAX_TABLE.  */
1862
1863 long
1864 relax_frag (segT segment, fragS *fragP, long stretch)
1865 {
1866   const relax_typeS *this_type;
1867   const relax_typeS *start_type;
1868   relax_substateT next_state;
1869   relax_substateT this_state;
1870   offsetT growth;
1871   offsetT aim;
1872   addressT target;
1873   addressT address;
1874   symbolS *symbolP;
1875   const relax_typeS *table;
1876
1877   target = fragP->fr_offset;
1878   address = fragP->fr_address;
1879   table = TC_GENERIC_RELAX_TABLE;
1880   this_state = fragP->fr_subtype;
1881   start_type = this_type = table + this_state;
1882   symbolP = fragP->fr_symbol;
1883
1884   if (symbolP)
1885     {
1886       fragS *sym_frag;
1887
1888       sym_frag = symbol_get_frag (symbolP);
1889
1890 #ifndef DIFF_EXPR_OK
1891       know (sym_frag != NULL);
1892 #endif
1893       know (S_GET_SEGMENT (symbolP) != absolute_section
1894             || sym_frag == &zero_address_frag);
1895       target += S_GET_VALUE (symbolP);
1896
1897       /* If frag has yet to be reached on this pass,
1898          assume it will move by STRETCH just as we did.
1899          If this is not so, it will be because some frag
1900          between grows, and that will force another pass.  */
1901
1902       if (stretch != 0
1903           && sym_frag->relax_marker != fragP->relax_marker
1904           && S_GET_SEGMENT (symbolP) == segment)
1905         {
1906           target += stretch;
1907         }
1908     }
1909
1910   aim = target - address - fragP->fr_fix;
1911 #ifdef TC_PCREL_ADJUST
1912   /* Currently only the ns32k family needs this.  */
1913   aim += TC_PCREL_ADJUST (fragP);
1914 #endif
1915
1916 #ifdef md_prepare_relax_scan
1917   /* Formerly called M68K_AIM_KLUDGE.  */
1918   md_prepare_relax_scan (fragP, address, aim, this_state, this_type);
1919 #endif
1920
1921   if (aim < 0)
1922     {
1923       /* Look backwards.  */
1924       for (next_state = this_type->rlx_more; next_state;)
1925         if (aim >= this_type->rlx_backward)
1926           next_state = 0;
1927         else
1928           {
1929             /* Grow to next state.  */
1930             this_state = next_state;
1931             this_type = table + this_state;
1932             next_state = this_type->rlx_more;
1933           }
1934     }
1935   else
1936     {
1937       /* Look forwards.  */
1938       for (next_state = this_type->rlx_more; next_state;)
1939         if (aim <= this_type->rlx_forward)
1940           next_state = 0;
1941         else
1942           {
1943             /* Grow to next state.  */
1944             this_state = next_state;
1945             this_type = table + this_state;
1946             next_state = this_type->rlx_more;
1947           }
1948     }
1949
1950   growth = this_type->rlx_length - start_type->rlx_length;
1951   if (growth != 0)
1952     fragP->fr_subtype = this_state;
1953   return growth;
1954 }
1955
1956 #endif /* defined (TC_GENERIC_RELAX_TABLE)  */
1957
1958 /* Relax_align. Advance location counter to next address that has 'alignment'
1959    lowest order bits all 0s, return size of adjustment made.  */
1960 static relax_addressT
1961 relax_align (register relax_addressT address,   /* Address now.  */
1962              register int alignment     /* Alignment (binary).  */)
1963 {
1964   relax_addressT mask;
1965   relax_addressT new_address;
1966
1967   mask = ~((~0) << alignment);
1968   new_address = (address + mask) & (~mask);
1969 #ifdef LINKER_RELAXING_SHRINKS_ONLY
1970   if (linkrelax)
1971     /* We must provide lots of padding, so the linker can discard it
1972        when needed.  The linker will not add extra space, ever.  */
1973     new_address += (1 << alignment);
1974 #endif
1975   return (new_address - address);
1976 }
1977
1978 /* Now we have a segment, not a crowd of sub-segments, we can make
1979    fr_address values.
1980
1981    Relax the frags.
1982
1983    After this, all frags in this segment have addresses that are correct
1984    within the segment. Since segments live in different file addresses,
1985    these frag addresses may not be the same as final object-file
1986    addresses.  */
1987
1988 int
1989 relax_segment (struct frag *segment_frag_root, segT segment, int pass)
1990 {
1991   unsigned long frag_count;
1992   struct frag *fragP;
1993   relax_addressT address;
1994   int ret;
1995
1996   /* In case md_estimate_size_before_relax() wants to make fixSs.  */
1997   subseg_change (segment, 0);
1998
1999   /* For each frag in segment: count and store  (a 1st guess of)
2000      fr_address.  */
2001   address = 0;
2002   for (frag_count = 0, fragP = segment_frag_root;
2003        fragP;
2004        fragP = fragP->fr_next, frag_count ++)
2005     {
2006       fragP->relax_marker = 0;
2007       fragP->fr_address = address;
2008       address += fragP->fr_fix;
2009
2010       switch (fragP->fr_type)
2011         {
2012         case rs_fill:
2013           address += fragP->fr_offset * fragP->fr_var;
2014           break;
2015
2016         case rs_align:
2017         case rs_align_code:
2018         case rs_align_test:
2019           {
2020             addressT offset = relax_align (address, (int) fragP->fr_offset);
2021
2022             if (fragP->fr_subtype != 0 && offset > fragP->fr_subtype)
2023               offset = 0;
2024
2025             if (offset % fragP->fr_var != 0)
2026               {
2027                 as_bad_where (fragP->fr_file, fragP->fr_line,
2028                               _("alignment padding (%lu bytes) not a multiple of %ld"),
2029                               (unsigned long) offset, (long) fragP->fr_var);
2030                 offset -= (offset % fragP->fr_var);
2031               }
2032
2033             address += offset;
2034           }
2035           break;
2036
2037         case rs_org:
2038         case rs_space:
2039           /* Assume .org is nugatory. It will grow with 1st relax.  */
2040           break;
2041
2042         case rs_machine_dependent:
2043           /* If fr_symbol is an expression, this call to
2044              resolve_symbol_value sets up the correct segment, which will
2045              likely be needed in md_estimate_size_before_relax.  */
2046           if (fragP->fr_symbol)
2047             resolve_symbol_value (fragP->fr_symbol);
2048
2049           address += md_estimate_size_before_relax (fragP, segment);
2050           break;
2051
2052 #ifndef WORKING_DOT_WORD
2053           /* Broken words don't concern us yet.  */
2054         case rs_broken_word:
2055           break;
2056 #endif
2057
2058         case rs_leb128:
2059           /* Initial guess is always 1; doing otherwise can result in
2060              stable solutions that are larger than the minimum.  */
2061           address += fragP->fr_offset = 1;
2062           break;
2063
2064         case rs_cfa:
2065           address += eh_frame_estimate_size_before_relax (fragP);
2066           break;
2067
2068         case rs_dwarf2dbg:
2069           address += dwarf2dbg_estimate_size_before_relax (fragP);
2070           break;
2071
2072         default:
2073           BAD_CASE (fragP->fr_type);
2074           break;
2075         }
2076     }
2077
2078   /* Do relax().  */
2079   {
2080     unsigned long max_iterations;
2081
2082     /* Cumulative address adjustment.  */
2083     offsetT stretch;
2084
2085     /* Have we made any adjustment this pass?  We can't just test
2086        stretch because one piece of code may have grown and another
2087        shrank.  */
2088     int stretched;
2089
2090     /* Most horrible, but gcc may give us some exception data that
2091        is impossible to assemble, of the form
2092
2093        .align 4
2094        .byte 0, 0
2095        .uleb128 end - start
2096        start:
2097        .space 128*128 - 1
2098        .align 4
2099        end:
2100
2101        If the leb128 is two bytes in size, then end-start is 128*128,
2102        which requires a three byte leb128.  If the leb128 is three
2103        bytes in size, then end-start is 128*128-1, which requires a
2104        two byte leb128.  We work around this dilemma by inserting
2105        an extra 4 bytes of alignment just after the .align.  This
2106        works because the data after the align is accessed relative to
2107        the end label.
2108
2109        This counter is used in a tiny state machine to detect
2110        whether a leb128 followed by an align is impossible to
2111        relax.  */
2112     int rs_leb128_fudge = 0;
2113
2114     /* We want to prevent going into an infinite loop where one frag grows
2115        depending upon the location of a symbol which is in turn moved by
2116        the growing frag.  eg:
2117
2118          foo = .
2119          .org foo+16
2120          foo = .
2121
2122        So we dictate that this algorithm can be at most O2.  */
2123     max_iterations = frag_count * frag_count;
2124     /* Check for overflow.  */
2125     if (max_iterations < frag_count)
2126       max_iterations = frag_count;
2127
2128     ret = 0;
2129     do
2130       {
2131         stretch = 0;
2132         stretched = 0;
2133
2134         for (fragP = segment_frag_root; fragP; fragP = fragP->fr_next)
2135           {
2136             offsetT growth = 0;
2137             addressT was_address;
2138             offsetT offset;
2139             symbolS *symbolP;
2140
2141             fragP->relax_marker ^= 1;
2142             was_address = fragP->fr_address;
2143             address = fragP->fr_address += stretch;
2144             symbolP = fragP->fr_symbol;
2145             offset = fragP->fr_offset;
2146
2147             switch (fragP->fr_type)
2148               {
2149               case rs_fill:     /* .fill never relaxes.  */
2150                 growth = 0;
2151                 break;
2152
2153 #ifndef WORKING_DOT_WORD
2154                 /* JF:  This is RMS's idea.  I do *NOT* want to be blamed
2155                    for it I do not want to write it.  I do not want to have
2156                    anything to do with it.  This is not the proper way to
2157                    implement this misfeature.  */
2158               case rs_broken_word:
2159                 {
2160                   struct broken_word *lie;
2161                   struct broken_word *untruth;
2162
2163                   /* Yes this is ugly (storing the broken_word pointer
2164                      in the symbol slot).  Still, this whole chunk of
2165                      code is ugly, and I don't feel like doing anything
2166                      about it.  Think of it as stubbornness in action.  */
2167                   growth = 0;
2168                   for (lie = (struct broken_word *) (fragP->fr_symbol);
2169                        lie && lie->dispfrag == fragP;
2170                        lie = lie->next_broken_word)
2171                     {
2172
2173                       if (lie->added)
2174                         continue;
2175
2176                       offset = (S_GET_VALUE (lie->add)
2177                                 + lie->addnum
2178                                 - S_GET_VALUE (lie->sub));
2179                       if (offset <= -32768 || offset >= 32767)
2180                         {
2181                           if (flag_warn_displacement)
2182                             {
2183                               char buf[50];
2184                               sprint_value (buf, (addressT) lie->addnum);
2185                               as_warn_where (fragP->fr_file, fragP->fr_line,
2186                                              _(".word %s-%s+%s didn't fit"),
2187                                              S_GET_NAME (lie->add),
2188                                              S_GET_NAME (lie->sub),
2189                                              buf);
2190                             }
2191                           lie->added = 1;
2192                           if (fragP->fr_subtype == 0)
2193                             {
2194                               fragP->fr_subtype++;
2195                               growth += md_short_jump_size;
2196                             }
2197                           for (untruth = lie->next_broken_word;
2198                                untruth && untruth->dispfrag == lie->dispfrag;
2199                                untruth = untruth->next_broken_word)
2200                             if ((symbol_get_frag (untruth->add)
2201                                  == symbol_get_frag (lie->add))
2202                                 && (S_GET_VALUE (untruth->add)
2203                                     == S_GET_VALUE (lie->add)))
2204                               {
2205                                 untruth->added = 2;
2206                                 untruth->use_jump = lie;
2207                               }
2208                           growth += md_long_jump_size;
2209                         }
2210                     }
2211
2212                   break;
2213                 }               /* case rs_broken_word  */
2214 #endif
2215               case rs_align:
2216               case rs_align_code:
2217               case rs_align_test:
2218                 {
2219                   addressT oldoff, newoff;
2220
2221                   oldoff = relax_align (was_address + fragP->fr_fix,
2222                                         (int) offset);
2223                   newoff = relax_align (address + fragP->fr_fix,
2224                                         (int) offset);
2225
2226                   if (fragP->fr_subtype != 0)
2227                     {
2228                       if (oldoff > fragP->fr_subtype)
2229                         oldoff = 0;
2230                       if (newoff > fragP->fr_subtype)
2231                         newoff = 0;
2232                     }
2233
2234                   growth = newoff - oldoff;
2235
2236                   /* If this align happens to follow a leb128 and
2237                      we have determined that the leb128 is bouncing
2238                      in size, then break the cycle by inserting an
2239                      extra alignment.  */
2240                   if (growth < 0
2241                       && (rs_leb128_fudge & 16) != 0
2242                       && (rs_leb128_fudge & 15) >= 2)
2243                     {
2244                       segment_info_type *seginfo = seg_info (segment);
2245                       struct obstack *ob = &seginfo->frchainP->frch_obstack;
2246                       struct frag *newf;
2247
2248                       newf = frag_alloc (ob);
2249                       obstack_blank_fast (ob, fragP->fr_var);
2250                       (void) obstack_finish (ob);
2251                       memcpy (newf, fragP, SIZEOF_STRUCT_FRAG);
2252                       memcpy (newf->fr_literal,
2253                               fragP->fr_literal + fragP->fr_fix,
2254                               fragP->fr_var);
2255                       newf->fr_type = rs_fill;
2256                       newf->fr_fix = 0;
2257                       newf->fr_offset = (((offsetT) 1 << fragP->fr_offset)
2258                                          / fragP->fr_var);
2259                       if (newf->fr_offset * newf->fr_var
2260                           != (offsetT) 1 << fragP->fr_offset)
2261                         {
2262                           newf->fr_offset = (offsetT) 1 << fragP->fr_offset;
2263                           newf->fr_var = 1;
2264                         }
2265                       /* Include growth of new frag, because rs_fill
2266                          frags don't normally grow.  */
2267                       growth += newf->fr_offset * newf->fr_var;
2268                       /* The new frag address is newoff.  Adjust this
2269                          for the amount we'll add when we process the
2270                          new frag.  */
2271                       newf->fr_address = newoff - stretch - growth;
2272                       newf->relax_marker ^= 1;
2273                       fragP->fr_next = newf;
2274 #ifdef DEBUG
2275                       as_warn (_("padding added"));
2276 #endif
2277                     }
2278                 }
2279                 break;
2280
2281               case rs_org:
2282                 {
2283                   addressT target = offset;
2284                   addressT after;
2285
2286                   if (symbolP)
2287                     {
2288                       /* Convert from an actual address to an octet offset
2289                          into the section.  Here it is assumed that the
2290                          section's VMA is zero, and can omit subtracting it
2291                          from the symbol's value to get the address offset.  */
2292                       know (S_GET_SEGMENT (symbolP)->vma == 0);
2293                       target += S_GET_VALUE (symbolP) * OCTETS_PER_BYTE;
2294                     }
2295
2296                   know (fragP->fr_next);
2297                   after = fragP->fr_next->fr_address;
2298                   growth = target - after;
2299                   if (growth < 0)
2300                     {
2301                       growth = 0;
2302
2303                       /* Don't error on first few frag relax passes.
2304                          The symbol might be an expression involving
2305                          symbol values from other sections.  If those
2306                          sections have not yet been processed their
2307                          frags will all have zero addresses, so we
2308                          will calculate incorrect values for them.  The
2309                          number of passes we allow before giving an
2310                          error is somewhat arbitrary.  It should be at
2311                          least one, with larger values requiring
2312                          increasingly contrived dependencies between
2313                          frags to trigger a false error.  */
2314                       if (pass < 2)
2315                         {
2316                           /* Force another pass.  */
2317                           ret = 1;
2318                           break;
2319                         }
2320
2321                       /* Growth may be negative, but variable part of frag
2322                          cannot have fewer than 0 chars.  That is, we can't
2323                          .org backwards.  */
2324                       as_bad_where (fragP->fr_file, fragP->fr_line,
2325                                     _("attempt to move .org backwards"));
2326
2327                       /* We've issued an error message.  Change the
2328                          frag to avoid cascading errors.  */
2329                       fragP->fr_type = rs_align;
2330                       fragP->fr_subtype = 0;
2331                       fragP->fr_offset = 0;
2332                       fragP->fr_fix = after - was_address;
2333                       break;
2334                     }
2335
2336                   /* This is an absolute growth factor  */
2337                   growth -= stretch;
2338                   break;
2339                 }
2340
2341               case rs_space:
2342                 growth = 0;
2343                 if (symbolP)
2344                   {
2345                     offsetT amount;
2346
2347                     amount = S_GET_VALUE (symbolP);
2348                     if (S_GET_SEGMENT (symbolP) != absolute_section
2349                         || S_IS_COMMON (symbolP)
2350                         || ! S_IS_DEFINED (symbolP))
2351                       {
2352                         as_bad_where (fragP->fr_file, fragP->fr_line,
2353                                       _(".space specifies non-absolute value"));
2354                         /* Prevent repeat of this error message.  */
2355                         fragP->fr_symbol = 0;
2356                       }
2357                     else if (amount < 0)
2358                       {
2359                         /* Don't error on first few frag relax passes.
2360                            See rs_org comment for a longer explanation.  */
2361                         if (pass < 2)
2362                           {
2363                             ret = 1;
2364                             break;
2365                           }
2366
2367                         as_warn_where (fragP->fr_file, fragP->fr_line,
2368                                        _(".space or .fill with negative value, ignored"));
2369                         fragP->fr_symbol = 0;
2370                       }
2371                     else
2372                       growth = (was_address + fragP->fr_fix + amount
2373                                 - fragP->fr_next->fr_address);
2374                   }
2375                 break;
2376
2377               case rs_machine_dependent:
2378 #ifdef md_relax_frag
2379                 growth = md_relax_frag (segment, fragP, stretch);
2380 #else
2381 #ifdef TC_GENERIC_RELAX_TABLE
2382                 /* The default way to relax a frag is to look through
2383                    TC_GENERIC_RELAX_TABLE.  */
2384                 growth = relax_frag (segment, fragP, stretch);
2385 #endif /* TC_GENERIC_RELAX_TABLE  */
2386 #endif
2387                 break;
2388
2389               case rs_leb128:
2390                 {
2391                   valueT value;
2392                   offsetT size;
2393
2394                   value = resolve_symbol_value (fragP->fr_symbol);
2395                   size = sizeof_leb128 (value, fragP->fr_subtype);
2396                   growth = size - fragP->fr_offset;
2397                   fragP->fr_offset = size;
2398                 }
2399                 break;
2400
2401               case rs_cfa:
2402                 growth = eh_frame_relax_frag (fragP);
2403                 break;
2404
2405               case rs_dwarf2dbg:
2406                 growth = dwarf2dbg_relax_frag (fragP);
2407                 break;
2408
2409               default:
2410                 BAD_CASE (fragP->fr_type);
2411                 break;
2412               }
2413             if (growth)
2414               {
2415                 stretch += growth;
2416                 stretched = 1;
2417                 if (fragP->fr_type == rs_leb128)
2418                   rs_leb128_fudge += 16;
2419                 else if (fragP->fr_type == rs_align
2420                          && (rs_leb128_fudge & 16) != 0
2421                          && stretch == 0)
2422                   rs_leb128_fudge += 16;
2423                 else
2424                   rs_leb128_fudge = 0;
2425               }
2426           }
2427
2428         if (stretch == 0
2429             && (rs_leb128_fudge & 16) == 0
2430             && (rs_leb128_fudge & -16) != 0)
2431           rs_leb128_fudge += 1;
2432         else
2433           rs_leb128_fudge = 0;
2434       }
2435     /* Until nothing further to relax.  */
2436     while (stretched && -- max_iterations);
2437
2438     if (stretched)
2439       as_fatal (_("Infinite loop encountered whilst attempting to compute the addresses of symbols in section %s"),
2440                 segment_name (segment));
2441   }
2442
2443   for (fragP = segment_frag_root; fragP; fragP = fragP->fr_next)
2444     if (fragP->last_fr_address != fragP->fr_address)
2445       {
2446         fragP->last_fr_address = fragP->fr_address;
2447         ret = 1;
2448       }
2449   return ret;
2450 }
2451
2452 void
2453 number_to_chars_bigendian (char *buf, valueT val, int n)
2454 {
2455   if (n <= 0)
2456     abort ();
2457   while (n--)
2458     {
2459       buf[n] = val & 0xff;
2460       val >>= 8;
2461     }
2462 }
2463
2464 void
2465 number_to_chars_littleendian (char *buf, valueT val, int n)
2466 {
2467   if (n <= 0)
2468     abort ();
2469   while (n--)
2470     {
2471       *buf++ = val & 0xff;
2472       val >>= 8;
2473     }
2474 }
2475
2476 void
2477 write_print_statistics (FILE *file)
2478 {
2479   fprintf (file, "fixups: %d\n", n_fixups);
2480 }
2481
2482 /* For debugging.  */
2483 extern int indent_level;
2484
2485 void
2486 print_fixup (fixS *fixp)
2487 {
2488   indent_level = 1;
2489   fprintf (stderr, "fix %lx %s:%d", (long) fixp, fixp->fx_file, fixp->fx_line);
2490   if (fixp->fx_pcrel)
2491     fprintf (stderr, " pcrel");
2492   if (fixp->fx_pcrel_adjust)
2493     fprintf (stderr, " pcrel_adjust=%d", fixp->fx_pcrel_adjust);
2494   if (fixp->fx_im_disp)
2495     {
2496 #ifdef TC_NS32K
2497       fprintf (stderr, " im_disp=%d", fixp->fx_im_disp);
2498 #else
2499       fprintf (stderr, " im_disp");
2500 #endif
2501     }
2502   if (fixp->fx_tcbit)
2503     fprintf (stderr, " tcbit");
2504   if (fixp->fx_done)
2505     fprintf (stderr, " done");
2506   fprintf (stderr, "\n    size=%d frag=%lx where=%ld offset=%lx addnumber=%lx",
2507            fixp->fx_size, (long) fixp->fx_frag, (long) fixp->fx_where,
2508            (long) fixp->fx_offset, (long) fixp->fx_addnumber);
2509   fprintf (stderr, "\n    %s (%d)", bfd_get_reloc_code_name (fixp->fx_r_type),
2510            fixp->fx_r_type);
2511   if (fixp->fx_addsy)
2512     {
2513       fprintf (stderr, "\n   +<");
2514       print_symbol_value_1 (stderr, fixp->fx_addsy);
2515       fprintf (stderr, ">");
2516     }
2517   if (fixp->fx_subsy)
2518     {
2519       fprintf (stderr, "\n   -<");
2520       print_symbol_value_1 (stderr, fixp->fx_subsy);
2521       fprintf (stderr, ">");
2522     }
2523   fprintf (stderr, "\n");
2524 #ifdef TC_FIX_DATA_PRINT
2525   TC_FIX_DATA_PRINT (stderr, fixp);
2526 #endif
2527 }