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