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