This commit was generated by cvs2svn to track changes on a CVS vendor
[external/binutils.git] / gas / write.c
1 /* write.c - emit .o file
2    Copyright (C) 1986, 87, 90, 91, 92, 93, 94, 95, 96, 97, 98, 1999
3    Free Software Foundation, Inc.
4
5    This file is part of GAS, the GNU Assembler.
6
7    GAS is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2, or (at your option)
10    any later version.
11
12    GAS is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with GAS; see the file COPYING.  If not, write to the Free
19    Software Foundation, 59 Temple Place - Suite 330, Boston, MA
20    02111-1307, USA.  */
21
22 /* This thing should be set up to do byteordering correctly.  But... */
23
24 #include "as.h"
25 #include "subsegs.h"
26 #include "obstack.h"
27 #include "output-file.h"
28
29 /* This looks like a good idea.  Let's try turning it on always, for now.  */
30 #undef  BFD_FAST_SECTION_FILL
31 #define BFD_FAST_SECTION_FILL
32
33 /* The NOP_OPCODE is for the alignment fill value.  Fill it with a nop
34    instruction so that the disassembler does not choke on it.  */
35 #ifndef NOP_OPCODE
36 #define NOP_OPCODE 0x00
37 #endif
38
39 #ifndef TC_ADJUST_RELOC_COUNT
40 #define TC_ADJUST_RELOC_COUNT(FIXP,COUNT)
41 #endif
42
43 #ifndef TC_FORCE_RELOCATION
44 #define TC_FORCE_RELOCATION(FIXP) 0
45 #endif
46
47 #ifndef TC_FORCE_RELOCATION_SECTION
48 #define TC_FORCE_RELOCATION_SECTION(FIXP,SEG) TC_FORCE_RELOCATION(FIXP)
49 #endif
50
51 #ifndef MD_PCREL_FROM_SECTION
52 #define MD_PCREL_FROM_SECTION(FIXP, SEC) md_pcrel_from(FIXP)
53 #endif
54
55 #ifndef WORKING_DOT_WORD
56 extern CONST int md_short_jump_size;
57 extern CONST int md_long_jump_size;
58 #endif
59
60 int symbol_table_frozen;
61 void print_fixup PARAMS ((fixS *));
62
63 #ifdef BFD_ASSEMBLER
64 static void renumber_sections PARAMS ((bfd *, asection *, PTR));
65
66 /* We generally attach relocs to frag chains.  However, after we have
67    chained these all together into a segment, any relocs we add after
68    that must be attached to a segment.  This will include relocs added
69    in md_estimate_size_for_relax, for example.  */
70 static int frags_chained = 0;
71 #endif
72
73 #ifndef BFD_ASSEMBLER
74
75 #ifndef MANY_SEGMENTS
76 struct frag *text_frag_root;
77 struct frag *data_frag_root;
78 struct frag *bss_frag_root;
79
80 struct frag *text_last_frag;    /* Last frag in segment. */
81 struct frag *data_last_frag;    /* Last frag in segment. */
82 static struct frag *bss_last_frag;      /* Last frag in segment. */
83 #endif
84
85 #ifndef BFD
86 static object_headers headers;
87 #endif
88
89 long string_byte_count;
90 char *next_object_file_charP;   /* Tracks object file bytes. */
91
92 #ifndef OBJ_VMS
93 int magic_number_for_object_file = DEFAULT_MAGIC_NUMBER_FOR_OBJECT_FILE;
94 #endif
95
96 #endif /* BFD_ASSEMBLER */
97
98 static int n_fixups;
99
100 #ifdef BFD_ASSEMBLER
101 static fixS *fix_new_internal PARAMS ((fragS *, int where, int size,
102                                        symbolS *add, symbolS *sub,
103                                        offsetT offset, int pcrel,
104                                        bfd_reloc_code_real_type r_type));
105 #else
106 static fixS *fix_new_internal PARAMS ((fragS *, int where, int size,
107                                        symbolS *add, symbolS *sub,
108                                        offsetT offset, int pcrel,
109                                        int r_type));
110 #endif
111 #if defined (BFD_ASSEMBLER) || (!defined (BFD) && !defined (OBJ_VMS))
112 static long fixup_segment PARAMS ((fixS * fixP, segT this_segment_type));
113 #endif
114 static relax_addressT relax_align PARAMS ((relax_addressT addr, int align));
115 #if defined (BFD_ASSEMBLER) || ! defined (BFD)
116 static fragS *chain_frchains_together_1 PARAMS ((segT, struct frchain *));
117 #endif
118 #ifdef BFD_ASSEMBLER
119 static void chain_frchains_together PARAMS ((bfd *, segT, PTR));
120 static void cvt_frag_to_fill PARAMS ((segT, fragS *));
121 static void relax_and_size_seg PARAMS ((bfd *, asection *, PTR));
122 static void adjust_reloc_syms PARAMS ((bfd *, asection *, PTR));
123 static void write_relocs PARAMS ((bfd *, asection *, PTR));
124 static void write_contents PARAMS ((bfd *, asection *, PTR));
125 static void set_symtab PARAMS ((void));
126 #endif
127 #if defined (BFD_ASSEMBLER) || (! defined (BFD) && ! defined (OBJ_AOUT))
128 static void merge_data_into_text PARAMS ((void));
129 #endif
130 #if ! defined (BFD_ASSEMBLER) && ! defined (BFD)
131 static void cvt_frag_to_fill PARAMS ((object_headers *, segT, fragS *));
132 static void remove_subsegs PARAMS ((frchainS *, int, fragS **, fragS **));
133 static void relax_and_size_all_segments PARAMS ((void));
134 #endif
135 #if defined (BFD_ASSEMBLER) && defined (OBJ_COFF) && defined (TE_GO32)
136 static void set_segment_vma PARAMS ((bfd *, asection *, PTR));
137 #endif
138
139 /*
140  *                      fix_new()
141  *
142  * Create a fixS in obstack 'notes'.
143  */
144 static fixS *
145 fix_new_internal (frag, where, size, add_symbol, sub_symbol, offset, pcrel,
146                   r_type)
147      fragS *frag;               /* Which frag? */
148      int where;                 /* Where in that frag? */
149      int size;                  /* 1, 2, or 4 usually. */
150      symbolS *add_symbol;       /* X_add_symbol. */
151      symbolS *sub_symbol;       /* X_op_symbol. */
152      offsetT offset;            /* X_add_number. */
153      int pcrel;                 /* TRUE if PC-relative relocation. */
154 #ifdef BFD_ASSEMBLER
155      bfd_reloc_code_real_type r_type; /* Relocation type */
156 #else
157      int r_type;                /* Relocation type */
158 #endif
159 {
160   fixS *fixP;
161
162   n_fixups++;
163
164   fixP = (fixS *) obstack_alloc (&notes, sizeof (fixS));
165
166   fixP->fx_frag = frag;
167   fixP->fx_where = where;
168   fixP->fx_size = size;
169   /* We've made fx_size a narrow field; check that it's wide enough.  */
170   if (fixP->fx_size != size)
171     {
172       as_bad (_("field fx_size too small to hold %d"), size);
173       abort ();
174     }
175   fixP->fx_addsy = add_symbol;
176   fixP->fx_subsy = sub_symbol;
177   fixP->fx_offset = offset;
178   fixP->fx_pcrel = pcrel;
179   fixP->fx_plt = 0;
180 #if defined(NEED_FX_R_TYPE) || defined (BFD_ASSEMBLER)
181   fixP->fx_r_type = r_type;
182 #endif
183   fixP->fx_im_disp = 0;
184   fixP->fx_pcrel_adjust = 0;
185   fixP->fx_bit_fixP = 0;
186   fixP->fx_addnumber = 0;
187   fixP->fx_tcbit = 0;
188   fixP->fx_done = 0;
189   fixP->fx_no_overflow = 0;
190   fixP->fx_signed = 0;
191
192 #ifdef USING_CGEN
193   fixP->fx_cgen.insn = NULL;
194   fixP->fx_cgen.opinfo = 0;
195 #endif
196
197 #ifdef TC_FIX_TYPE
198   TC_INIT_FIX_DATA(fixP);
199 #endif
200
201   as_where (&fixP->fx_file, &fixP->fx_line);
202
203   /* Usually, we want relocs sorted numerically, but while
204      comparing to older versions of gas that have relocs
205      reverse sorted, it is convenient to have this compile
206      time option.  xoxorich. */
207
208   {
209
210 #ifdef BFD_ASSEMBLER
211     fixS **seg_fix_rootP = (frags_chained
212                             ? &seg_info (now_seg)->fix_root
213                             : &frchain_now->fix_root);
214     fixS **seg_fix_tailP = (frags_chained
215                             ? &seg_info (now_seg)->fix_tail
216                             : &frchain_now->fix_tail);
217 #endif
218
219 #ifdef REVERSE_SORT_RELOCS
220
221     fixP->fx_next = *seg_fix_rootP;
222     *seg_fix_rootP = fixP;
223
224 #else /* REVERSE_SORT_RELOCS */
225
226     fixP->fx_next = NULL;
227
228     if (*seg_fix_tailP)
229       (*seg_fix_tailP)->fx_next = fixP;
230     else
231       *seg_fix_rootP = fixP;
232     *seg_fix_tailP = fixP;
233
234 #endif /* REVERSE_SORT_RELOCS */
235
236   }
237
238   return fixP;
239 }
240
241 /* Create a fixup relative to a symbol (plus a constant).  */
242
243 fixS *
244 fix_new (frag, where, size, add_symbol, offset, pcrel, r_type)
245      fragS *frag;               /* Which frag? */
246      int where;                 /* Where in that frag? */
247      int size;                  /* 1, 2, or 4 usually. */
248      symbolS *add_symbol;       /* X_add_symbol. */
249      offsetT offset;            /* X_add_number. */
250      int pcrel;                 /* TRUE if PC-relative relocation. */
251 #ifdef BFD_ASSEMBLER
252      bfd_reloc_code_real_type r_type; /* Relocation type */
253 #else
254      int r_type;                /* Relocation type */
255 #endif
256 {
257   return fix_new_internal (frag, where, size, add_symbol,
258                            (symbolS *) NULL, offset, pcrel, r_type);
259 }
260
261 /* Create a fixup for an expression.  Currently we only support fixups
262    for difference expressions.  That is itself more than most object
263    file formats support anyhow.  */
264
265 fixS *
266 fix_new_exp (frag, where, size, exp, pcrel, r_type)
267      fragS *frag;               /* Which frag? */
268      int where;                 /* Where in that frag? */
269      int size;                  /* 1, 2, or 4 usually. */
270      expressionS *exp;          /* Expression.  */
271      int pcrel;                 /* TRUE if PC-relative relocation. */
272 #ifdef BFD_ASSEMBLER
273      bfd_reloc_code_real_type r_type; /* Relocation type */
274 #else
275      int r_type;                /* Relocation type */
276 #endif
277 {
278   symbolS *add = NULL;
279   symbolS *sub = NULL;
280   offsetT off = 0;
281
282   switch (exp->X_op)
283     {
284     case O_absent:
285       break;
286
287     case O_add:
288       /* This comes up when _GLOBAL_OFFSET_TABLE_+(.-L0) is read, if
289          the difference expression cannot immediately be reduced.  */
290       {
291         symbolS *stmp = make_expr_symbol (exp);
292         exp->X_op = O_symbol;
293         exp->X_op_symbol = 0;
294         exp->X_add_symbol = stmp;
295         exp->X_add_number = 0;
296         return fix_new_exp (frag, where, size, exp, pcrel, r_type);
297       }
298
299     case O_symbol_rva:
300       add = exp->X_add_symbol;
301       off = exp->X_add_number;
302
303 #if defined(BFD_ASSEMBLER)
304       r_type = BFD_RELOC_RVA;
305 #else
306 #if defined(TC_RVA_RELOC)
307       r_type = TC_RVA_RELOC;
308 #else
309       as_fatal(_("rva not supported"));
310 #endif
311 #endif
312       break;
313
314     case O_uminus:
315       sub = exp->X_add_symbol;
316       off = exp->X_add_number;
317       break;
318
319     case O_subtract:
320       sub = exp->X_op_symbol;
321       /* Fall through.  */
322     case O_symbol:
323       add = exp->X_add_symbol;
324       /* Fall through.   */
325     case O_constant:
326       off = exp->X_add_number;
327       break;
328
329     default:
330       add = make_expr_symbol (exp);
331       break;
332     }
333
334   return fix_new_internal (frag, where, size, add, sub, off,
335                            pcrel, r_type);
336 }
337
338 /* Append a string onto another string, bumping the pointer along.  */
339 void
340 append (charPP, fromP, length)
341      char **charPP;
342      char *fromP;
343      unsigned long length;
344 {
345   /* Don't trust memcpy() of 0 chars. */
346   if (length == 0)
347     return;
348
349   memcpy (*charPP, fromP, length);
350   *charPP += length;
351 }
352
353 #ifndef BFD_ASSEMBLER
354 int section_alignment[SEG_MAXIMUM_ORDINAL];
355 #endif
356
357 /*
358  * This routine records the largest alignment seen for each segment.
359  * If the beginning of the segment is aligned on the worst-case
360  * boundary, all of the other alignments within it will work.  At
361  * least one object format really uses this info.
362  */
363 void
364 record_alignment (seg, align)
365      /* Segment to which alignment pertains */
366      segT seg;
367      /* Alignment, as a power of 2 (e.g., 1 => 2-byte boundary, 2 => 4-byte
368         boundary, etc.)  */
369      int align;
370 {
371   if (seg == absolute_section)
372     return;
373 #ifdef BFD_ASSEMBLER
374   if ((unsigned int) align > bfd_get_section_alignment (stdoutput, seg))
375     bfd_set_section_alignment (stdoutput, seg, align);
376 #else
377   if (align > section_alignment[(int) seg])
378     section_alignment[(int) seg] = align;
379 #endif
380 }
381
382 #ifdef BFD_ASSEMBLER
383
384 /* Reset the section indices after removing the gas created sections.  */
385
386 static void
387 renumber_sections (abfd, sec, countparg)
388      bfd *abfd ATTRIBUTE_UNUSED;
389      asection *sec;
390      PTR countparg;
391 {
392   int *countp = (int *) countparg;
393
394   sec->index = *countp;
395   ++*countp;
396 }
397
398 #endif /* defined (BFD_ASSEMBLER) */
399
400 #if defined (BFD_ASSEMBLER) || ! defined (BFD)
401
402 static fragS *
403 chain_frchains_together_1 (section, frchp)
404      segT section;
405      struct frchain *frchp;
406 {
407   fragS dummy, *prev_frag = &dummy;
408 #ifdef BFD_ASSEMBLER
409   fixS fix_dummy, *prev_fix = &fix_dummy;
410 #endif
411
412   for (; frchp && frchp->frch_seg == section; frchp = frchp->frch_next)
413     {
414       prev_frag->fr_next = frchp->frch_root;
415       prev_frag = frchp->frch_last;
416       assert (prev_frag->fr_type != 0);
417 #ifdef BFD_ASSEMBLER
418       if (frchp->fix_root != (fixS *) NULL)
419         {
420           if (seg_info (section)->fix_root == (fixS *) NULL)
421             seg_info (section)->fix_root = frchp->fix_root;
422           prev_fix->fx_next = frchp->fix_root;
423           seg_info (section)->fix_tail = frchp->fix_tail;
424           prev_fix = frchp->fix_tail;
425         }
426 #endif
427     }
428   assert (prev_frag->fr_type != 0);
429   prev_frag->fr_next = 0;
430   return prev_frag;
431 }
432
433 #endif
434
435 #ifdef BFD_ASSEMBLER
436
437 static void
438 chain_frchains_together (abfd, section, xxx)
439      bfd *abfd ATTRIBUTE_UNUSED;
440      segT section;
441      PTR xxx ATTRIBUTE_UNUSED;
442 {
443   segment_info_type *info;
444
445   /* BFD may have introduced its own sections without using
446      subseg_new, so it is possible that seg_info is NULL.  */
447   info = seg_info (section);
448   if (info != (segment_info_type *) NULL)
449    info->frchainP->frch_last
450      = chain_frchains_together_1 (section, info->frchainP);
451
452   /* Now that we've chained the frags together, we must add new fixups
453      to the segment, not to the frag chain.  */
454   frags_chained = 1;
455 }
456
457 #endif
458
459 #if !defined (BFD) && !defined (BFD_ASSEMBLER)
460
461 static void
462 remove_subsegs (head, seg, root, last)
463      frchainS *head;
464      int seg;
465      fragS **root;
466      fragS **last;
467 {
468   *root = head->frch_root;
469   *last = chain_frchains_together_1 (seg, head);
470 }
471
472 #endif /* BFD */
473
474 #if defined (BFD_ASSEMBLER) || !defined (BFD)
475
476 #ifdef BFD_ASSEMBLER
477 static void
478 cvt_frag_to_fill (sec, fragP)
479      segT sec;
480      fragS *fragP;
481 #else
482 static void
483 cvt_frag_to_fill (headersP, sec, fragP)
484      object_headers *headersP;
485      segT sec;
486      fragS *fragP;
487 #endif
488 {
489   switch (fragP->fr_type)
490     {
491     case rs_align:
492     case rs_align_code:
493     case rs_org:
494     case rs_space:
495 #ifdef HANDLE_ALIGN
496       HANDLE_ALIGN (fragP);
497 #endif
498       know (fragP->fr_next != NULL);
499       fragP->fr_offset = (fragP->fr_next->fr_address
500                           - fragP->fr_address
501                           - fragP->fr_fix) / fragP->fr_var;
502       if (fragP->fr_offset < 0)
503         {
504           as_bad_where (fragP->fr_file, fragP->fr_line,
505                         _("attempt to .org/.space backwards? (%ld)"),
506                         (long) fragP->fr_offset);
507         }
508       fragP->fr_type = rs_fill;
509       break;
510
511     case rs_fill:
512       break;
513
514     case rs_leb128:
515       {
516         valueT value = S_GET_VALUE (fragP->fr_symbol);
517         int size;
518
519         size = output_leb128 (fragP->fr_literal + fragP->fr_fix, value,
520                               fragP->fr_subtype);
521
522         fragP->fr_fix += size;
523         fragP->fr_type = rs_fill;
524         fragP->fr_var = 0;
525         fragP->fr_offset = 0;
526         fragP->fr_symbol = NULL;
527       }
528       break;
529
530     case rs_cfa:
531       eh_frame_convert_frag (fragP);
532       break;
533
534     case rs_machine_dependent:
535 #ifdef BFD_ASSEMBLER
536       md_convert_frag (stdoutput, sec, fragP);
537 #else
538       md_convert_frag (headersP, sec, fragP);
539 #endif
540
541       assert (fragP->fr_next == NULL
542               || ((offsetT) (fragP->fr_next->fr_address - fragP->fr_address)
543                   == fragP->fr_fix));
544
545       /*
546        * After md_convert_frag, we make the frag into a ".space 0".
547        * Md_convert_frag() should set up any fixSs and constants
548        * required.
549        */
550       frag_wane (fragP);
551       break;
552
553 #ifndef WORKING_DOT_WORD
554     case rs_broken_word:
555       {
556         struct broken_word *lie;
557
558         if (fragP->fr_subtype)
559           {
560             fragP->fr_fix += md_short_jump_size;
561             for (lie = (struct broken_word *) (fragP->fr_symbol);
562                  lie && lie->dispfrag == fragP;
563                  lie = lie->next_broken_word)
564               if (lie->added == 1)
565                 fragP->fr_fix += md_long_jump_size;
566           }
567         frag_wane (fragP);
568       }
569       break;
570 #endif
571
572     default:
573       BAD_CASE (fragP->fr_type);
574       break;
575     }
576 }
577
578 #endif /* defined (BFD_ASSEMBLER) || !defined (BFD) */
579
580 #ifdef BFD_ASSEMBLER
581 static void
582 relax_and_size_seg (abfd, sec, xxx)
583      bfd *abfd;
584      asection *sec;
585      PTR xxx ATTRIBUTE_UNUSED;
586 {
587   flagword flags;
588   fragS *fragp;
589   segment_info_type *seginfo;
590   int x;
591   valueT size, newsize;
592
593   subseg_change (sec, 0);
594
595   flags = bfd_get_section_flags (abfd, sec);
596
597   seginfo = seg_info (sec);
598   if (seginfo && seginfo->frchainP)
599     {
600       relax_segment (seginfo->frchainP->frch_root, sec);
601       for (fragp = seginfo->frchainP->frch_root; fragp; fragp = fragp->fr_next)
602         cvt_frag_to_fill (sec, fragp);
603       for (fragp = seginfo->frchainP->frch_root;
604            fragp->fr_next;
605            fragp = fragp->fr_next)
606         /* walk to last elt */;
607       size = fragp->fr_address + fragp->fr_fix;
608     }
609   else
610     size = 0;
611
612   if (size > 0 && ! seginfo->bss)
613     flags |= SEC_HAS_CONTENTS;
614
615   /* @@ This is just an approximation.  */
616   if (seginfo && seginfo->fix_root)
617     flags |= SEC_RELOC;
618   else
619     flags &= ~SEC_RELOC;
620   x = bfd_set_section_flags (abfd, sec, flags);
621   assert (x == true);
622
623   newsize = md_section_align (sec, size);
624   x = bfd_set_section_size (abfd, sec, newsize);
625   assert (x == true);
626
627   /* If the size had to be rounded up, add some padding in the last
628      non-empty frag.  */
629   assert (newsize >= size);
630   if (size != newsize)
631     {
632       fragS *last = seginfo->frchainP->frch_last;
633       fragp = seginfo->frchainP->frch_root;
634       while (fragp->fr_next != last)
635         fragp = fragp->fr_next;
636       last->fr_address = size;
637       fragp->fr_offset += newsize - size;
638     }
639
640 #ifdef tc_frob_section
641   tc_frob_section (sec);
642 #endif
643 #ifdef obj_frob_section
644   obj_frob_section (sec);
645 #endif
646 }
647
648 #ifdef DEBUG2
649 static void
650 dump_section_relocs (abfd, sec, stream_)
651      bfd *abfd ATTRIBUTE_UNUSED;
652      asection *sec;
653      char *stream_;
654 {
655   FILE *stream = (FILE *) stream_;
656   segment_info_type *seginfo = seg_info (sec);
657   fixS *fixp = seginfo->fix_root;
658
659   if (!fixp)
660     return;
661
662   fprintf (stream, "sec %s relocs:\n", sec->name);
663   while (fixp)
664     {
665       symbolS *s = fixp->fx_addsy;
666
667       fprintf (stream, "  %08lx: type %d ", (unsigned long) fixp,
668                (int) fixp->fx_r_type);
669       if (s == NULL)
670         fprintf (stream, "no sym\n");
671       else
672         {
673           print_symbol_value_1 (stream, s);
674           fprintf (stream, "\n");
675         }
676       fixp = fixp->fx_next;
677     }
678 }
679 #else
680 #define dump_section_relocs(ABFD,SEC,STREAM)    ((void) 0)
681 #endif
682
683 #ifndef EMIT_SECTION_SYMBOLS
684 #define EMIT_SECTION_SYMBOLS 1
685 #endif
686
687 static void
688 adjust_reloc_syms (abfd, sec, xxx)
689      bfd *abfd ATTRIBUTE_UNUSED;
690      asection *sec;
691      PTR xxx ATTRIBUTE_UNUSED;
692 {
693   segment_info_type *seginfo = seg_info (sec);
694   fixS *fixp;
695
696   if (seginfo == NULL)
697     return;
698
699   dump_section_relocs (abfd, sec, stderr);
700
701   for (fixp = seginfo->fix_root; fixp; fixp = fixp->fx_next)
702     if (fixp->fx_done)
703       /* ignore it */;
704     else if (fixp->fx_addsy)
705       {
706         symbolS *sym;
707         asection *symsec;
708
709 #ifdef DEBUG5
710         fprintf (stderr, "\n\nadjusting fixup:\n");
711         print_fixup (fixp);
712 #endif
713
714         sym = fixp->fx_addsy;
715
716         /* All symbols should have already been resolved at this
717            point.  It is possible to see unresolved expression
718            symbols, though, since they are not in the regular symbol
719            table.  */
720         if (sym != NULL)
721           resolve_symbol_value (sym, 1);
722         
723         if (fixp->fx_subsy != NULL)
724           resolve_symbol_value (fixp->fx_subsy, 1);
725
726         /* If this symbol is equated to an undefined symbol, convert
727            the fixup to being against that symbol.  */
728         if (sym != NULL && symbol_equated_p (sym)
729             && (! S_IS_DEFINED (sym) || S_IS_COMMON (sym)))
730           {
731             fixp->fx_offset += symbol_get_value_expression (sym)->X_add_number;
732             sym = symbol_get_value_expression (sym)->X_add_symbol;
733             fixp->fx_addsy = sym;
734           }
735
736         if (sym != NULL && symbol_mri_common_p (sym))
737           {
738             /* These symbols are handled specially in fixup_segment.  */
739             goto done;
740           }
741
742         symsec = S_GET_SEGMENT (sym);
743
744         if (symsec == NULL)
745           abort ();
746         
747         if (bfd_is_abs_section (symsec))
748           {
749             /* The fixup_segment routine will not use this symbol in a
750                relocation unless TC_FORCE_RELOCATION returns 1.  */
751             if (TC_FORCE_RELOCATION (fixp))
752               {
753                 symbol_mark_used_in_reloc (fixp->fx_addsy);
754 #ifdef UNDEFINED_DIFFERENCE_OK
755                 if (fixp->fx_subsy != NULL)
756                   symbol_mark_used_in_reloc (fixp->fx_subsy);
757 #endif
758               }
759             goto done;
760           }
761
762         /* If it's one of these sections, assume the symbol is
763            definitely going to be output.  The code in
764            md_estimate_size_before_relax in tc-mips.c uses this test
765            as well, so if you change this code you should look at that
766            code.  */
767         if (bfd_is_und_section (symsec)
768             || bfd_is_com_section (symsec))
769           {
770             symbol_mark_used_in_reloc (fixp->fx_addsy);
771 #ifdef UNDEFINED_DIFFERENCE_OK
772             /* We have the difference of an undefined symbol and some
773                other symbol.  Make sure to mark the other symbol as used
774                in a relocation so that it will always be output.  */
775             if (fixp->fx_subsy)
776               symbol_mark_used_in_reloc (fixp->fx_subsy);
777 #endif
778             goto done;
779           }
780
781         /* Don't try to reduce relocs which refer to non-local symbols
782            in .linkonce sections.  It can lead to confusion when a
783            debugging section refers to a .linkonce section.  I hope
784            this will always be correct.  */
785         if (symsec != sec && ! S_IS_LOCAL (sym))
786           {
787             boolean linkonce;
788
789             linkonce = false;
790 #ifdef BFD_ASSEMBLER
791             if ((bfd_get_section_flags (stdoutput, symsec) & SEC_LINK_ONCE)
792                 != 0)
793               linkonce = true;
794 #endif
795 #ifdef OBJ_ELF
796             /* The GNU toolchain uses an extension for ELF: a section
797                beginning with the magic string .gnu.linkonce is a
798                linkonce section.  */
799             if (strncmp (segment_name (symsec), ".gnu.linkonce",
800                          sizeof ".gnu.linkonce" - 1) == 0)
801               linkonce = true;
802 #endif
803
804             if (linkonce)
805               {
806                 symbol_mark_used_in_reloc (fixp->fx_addsy);
807 #ifdef UNDEFINED_DIFFERENCE_OK
808                 if (fixp->fx_subsy != NULL)
809                   symbol_mark_used_in_reloc (fixp->fx_subsy);
810 #endif
811                 goto done;
812               }
813           }
814
815         /* Since we're reducing to section symbols, don't attempt to reduce
816            anything that's already using one.  */
817         if (symbol_section_p (sym))
818           {
819             symbol_mark_used_in_reloc (fixp->fx_addsy);
820             goto done;
821           }
822
823 #ifdef BFD_ASSEMBLER
824         /* We can never adjust a reloc against a weak symbol.  If we
825            did, and the weak symbol was overridden by a real symbol
826            somewhere else, then our relocation would be pointing at
827            the wrong area of memory.  */
828         if (S_IS_WEAK (sym))
829           {
830             symbol_mark_used_in_reloc (fixp->fx_addsy);
831             goto done;
832           }
833 #endif
834
835         /* Is there some other reason we can't adjust this one?  (E.g.,
836            call/bal links in i960-bout symbols.)  */
837 #ifdef obj_fix_adjustable
838         if (! obj_fix_adjustable (fixp))
839           {
840             symbol_mark_used_in_reloc (fixp->fx_addsy);
841             goto done;
842           }
843 #endif
844
845         /* Is there some other (target cpu dependent) reason we can't adjust
846            this one?  (E.g. relocations involving function addresses on
847            the PA.  */
848 #ifdef tc_fix_adjustable
849         if (! tc_fix_adjustable (fixp))
850           {
851             symbol_mark_used_in_reloc (fixp->fx_addsy);
852             goto done;
853           }
854 #endif
855
856         /* If the section symbol isn't going to be output, the relocs
857            at least should still work.  If not, figure out what to do
858            when we run into that case.
859
860            We refetch the segment when calling section_symbol, rather
861            than using symsec, because S_GET_VALUE may wind up changing
862            the section when it calls resolve_symbol_value. */
863         fixp->fx_offset += S_GET_VALUE (sym);
864         fixp->fx_addsy = section_symbol (S_GET_SEGMENT (sym));
865         symbol_mark_used_in_reloc (fixp->fx_addsy);
866 #ifdef DEBUG5
867         fprintf (stderr, "\nadjusted fixup:\n");
868         print_fixup (fixp);
869 #endif
870
871       done:
872         ;
873       }
874 #if 1/*def RELOC_REQUIRES_SYMBOL*/
875     else
876       {
877         /* There was no symbol required by this relocation.  However,
878            BFD doesn't really handle relocations without symbols well.
879            (At least, the COFF support doesn't.)  So for now we fake up
880            a local symbol in the absolute section.  */
881
882         fixp->fx_addsy = section_symbol (absolute_section);
883 /*      fixp->fx_addsy->sy_used_in_reloc = 1; */
884       }
885 #endif
886
887   dump_section_relocs (abfd, sec, stderr);
888 }
889
890 static void
891 write_relocs (abfd, sec, xxx)
892      bfd *abfd;
893      asection *sec;
894      PTR xxx ATTRIBUTE_UNUSED;
895 {
896   segment_info_type *seginfo = seg_info (sec);
897   int i;
898   unsigned int n;
899   arelent **relocs;
900   fixS *fixp;
901   char *err;
902
903   /* If seginfo is NULL, we did not create this section; don't do
904      anything with it.  */
905   if (seginfo == NULL)
906     return;
907
908   fixup_segment (seginfo->fix_root, sec);
909
910   n = 0;
911   for (fixp = seginfo->fix_root; fixp; fixp = fixp->fx_next)
912     n++;
913
914 #ifndef RELOC_EXPANSION_POSSIBLE
915   /* Set up reloc information as well.  */
916   relocs = (arelent **) xmalloc (n * sizeof (arelent *));
917   memset ((char*)relocs, 0, n * sizeof (arelent*));
918
919   i = 0;
920   for (fixp = seginfo->fix_root; fixp != (fixS *) NULL; fixp = fixp->fx_next)
921     {
922       arelent *reloc;
923       bfd_reloc_status_type s;
924       symbolS *sym;
925
926       if (fixp->fx_done)
927         {
928           n--;
929           continue;
930         }
931
932       /* If this is an undefined symbol which was equated to another
933          symbol, then use generate the reloc against the latter symbol
934          rather than the former.  */
935       sym = fixp->fx_addsy;
936       while (symbol_equated_p (sym)
937              && (! S_IS_DEFINED (sym) || S_IS_COMMON (sym)))
938         {
939           symbolS *n;
940
941           /* We must avoid looping, as that can occur with a badly
942              written program.  */
943           n = symbol_get_value_expression (sym)->X_add_symbol;
944           if (n == sym)
945             break;
946           fixp->fx_offset += symbol_get_value_expression (sym)->X_add_number;
947           sym = n;
948         }
949       fixp->fx_addsy = sym;
950
951       reloc = tc_gen_reloc (sec, fixp);
952       if (!reloc)
953         {
954           n--;
955           continue;
956         }
957
958 #if 0
959       /* This test is triggered inappropriately for the SH.  */
960       if (fixp->fx_where + fixp->fx_size
961           > fixp->fx_frag->fr_fix + fixp->fx_frag->fr_offset)
962         abort ();
963 #endif
964
965       s = bfd_install_relocation (stdoutput, reloc,
966                                   fixp->fx_frag->fr_literal,
967                                   fixp->fx_frag->fr_address,
968                                   sec, &err);
969       switch (s)
970         {
971         case bfd_reloc_ok:
972           break;
973         case bfd_reloc_overflow:
974           as_bad_where (fixp->fx_file, fixp->fx_line, _("relocation overflow"));
975           break;
976         case bfd_reloc_outofrange:
977           as_bad_where (fixp->fx_file, fixp->fx_line, _("relocation out of range"));
978           break;
979         default:
980           as_fatal (_("%s:%u: bad return from bfd_install_relocation: %x"),
981                     fixp->fx_file, fixp->fx_line, s);
982         }
983       relocs[i++] = reloc;
984     }
985 #else
986   n = n * MAX_RELOC_EXPANSION;
987   /* Set up reloc information as well.  */
988   relocs = (arelent **) xmalloc (n * sizeof (arelent *));
989
990   i = 0;
991   for (fixp = seginfo->fix_root; fixp != (fixS *) NULL; fixp = fixp->fx_next)
992     {
993       arelent **reloc;
994       char *data;
995       bfd_reloc_status_type s;
996       symbolS *sym;
997       int j;
998
999       if (fixp->fx_done)
1000         {
1001           n--;
1002           continue;
1003         }
1004
1005       /* If this is an undefined symbol which was equated to another
1006          symbol, then use generate the reloc against the latter symbol
1007          rather than the former.  */
1008       sym = fixp->fx_addsy;
1009       while (symbol_equated_p (sym)
1010              && (! S_IS_DEFINED (sym) || S_IS_COMMON (sym)))
1011         sym = symbol_get_value_expression (sym)->X_add_symbol;
1012       fixp->fx_addsy = sym;
1013
1014       reloc = tc_gen_reloc (sec, fixp);
1015
1016       for (j = 0; reloc[j]; j++)
1017         {
1018           relocs[i++] = reloc[j];
1019           assert(i <= n);
1020         }
1021       data = fixp->fx_frag->fr_literal + fixp->fx_where;
1022       if (fixp->fx_where + fixp->fx_size
1023           > fixp->fx_frag->fr_fix + fixp->fx_frag->fr_offset)
1024         as_bad_where (fixp->fx_file, fixp->fx_line,
1025                       _("internal error: fixup not contained within frag"));
1026       for (j = 0; reloc[j]; j++)
1027         {
1028           s = bfd_install_relocation (stdoutput, reloc[j],
1029                                       fixp->fx_frag->fr_literal,
1030                                       fixp->fx_frag->fr_address,
1031                                       sec, &err);
1032           switch (s)
1033             {
1034             case bfd_reloc_ok:
1035               break;
1036             case bfd_reloc_overflow:
1037               as_bad_where (fixp->fx_file, fixp->fx_line,
1038                             _("relocation overflow"));
1039               break;
1040             default:
1041               as_fatal (_("%s:%u: bad return from bfd_install_relocation"),
1042                         fixp->fx_file, fixp->fx_line);
1043             }
1044         }
1045     }
1046   n = i;
1047 #endif
1048
1049 #ifdef DEBUG4
1050   {
1051     int i, j, nsyms;
1052     asymbol **sympp;
1053     sympp = bfd_get_outsymbols (stdoutput);
1054     nsyms = bfd_get_symcount (stdoutput);
1055     for (i = 0; i < n; i++)
1056       if (((*relocs[i]->sym_ptr_ptr)->flags & BSF_SECTION_SYM) == 0)
1057         {
1058           for (j = 0; j < nsyms; j++)
1059             if (sympp[j] == *relocs[i]->sym_ptr_ptr)
1060               break;
1061           if (j == nsyms)
1062             abort ();
1063         }
1064   }
1065 #endif
1066
1067   if (n)
1068     bfd_set_reloc (stdoutput, sec, relocs, n);
1069   else
1070     bfd_set_section_flags (abfd, sec,
1071                            (bfd_get_section_flags (abfd, sec)
1072                             & (flagword) ~SEC_RELOC));
1073
1074 #ifdef SET_SECTION_RELOCS
1075   SET_SECTION_RELOCS (sec, relocs, n);
1076 #endif
1077
1078 #ifdef DEBUG3
1079   {
1080     int i;
1081     arelent *r;
1082     asymbol *s;
1083     fprintf (stderr, "relocs for sec %s\n", sec->name);
1084     for (i = 0; i < n; i++)
1085       {
1086         r = relocs[i];
1087         s = *r->sym_ptr_ptr;
1088         fprintf (stderr, "  reloc %2d @%08x off %4x : sym %-10s addend %x\n",
1089                  i, r, r->address, s->name, r->addend);
1090       }
1091   }
1092 #endif
1093 }
1094
1095 static void
1096 write_contents (abfd, sec, xxx)
1097      bfd *abfd ATTRIBUTE_UNUSED;
1098      asection *sec;
1099      PTR xxx ATTRIBUTE_UNUSED;
1100 {
1101   segment_info_type *seginfo = seg_info (sec);
1102   unsigned long offset = 0;
1103   fragS *f;
1104
1105   /* Write out the frags.  */
1106   if (seginfo == NULL
1107       || ! (bfd_get_section_flags (abfd, sec) & SEC_HAS_CONTENTS))
1108     return;
1109
1110   for (f = seginfo->frchainP->frch_root;
1111        f;
1112        f = f->fr_next)
1113     {
1114       int x;
1115       unsigned long fill_size;
1116       char *fill_literal;
1117       long count;
1118
1119       assert (f->fr_type == rs_fill);
1120       if (f->fr_fix)
1121         {
1122           x = bfd_set_section_contents (stdoutput, sec,
1123                                         f->fr_literal, (file_ptr) offset,
1124                                         (bfd_size_type) f->fr_fix);
1125           if (x == false)
1126             {
1127               bfd_perror (stdoutput->filename);
1128               as_perror (_("FATAL: Can't write %s"), stdoutput->filename);
1129               exit (EXIT_FAILURE);
1130             }
1131           offset += f->fr_fix;
1132         }
1133       fill_literal = f->fr_literal + f->fr_fix;
1134       fill_size = f->fr_var;
1135       count = f->fr_offset;
1136       assert (count >= 0);
1137       if (fill_size && count)
1138         {
1139           char buf[256];
1140           if (fill_size > sizeof(buf))
1141             {
1142               /* Do it the old way. Can this ever happen? */
1143               while (count--)
1144                 {
1145                   x = bfd_set_section_contents (stdoutput, sec,
1146                                                 fill_literal,
1147                                                 (file_ptr) offset,
1148                                                 (bfd_size_type) fill_size);
1149                   if (x == false)
1150                     {
1151                       bfd_perror (stdoutput->filename);
1152                       as_perror (_("FATAL: Can't write %s"), stdoutput->filename);
1153                       exit (EXIT_FAILURE);
1154                     }
1155                   offset += fill_size;
1156                 }
1157             }
1158           else
1159             {
1160               /* Build a buffer full of fill objects and output it as
1161                  often as necessary. This saves on the overhead of
1162                  potentially lots of bfd_set_section_contents calls.  */
1163               int n_per_buf, i;
1164               if (fill_size == 1)
1165                 {
1166                   n_per_buf = sizeof (buf);
1167                   memset (buf, *fill_literal, n_per_buf);
1168                 }
1169               else
1170                 {
1171                   char *bufp;
1172                   n_per_buf = sizeof(buf)/fill_size;
1173                   for (i = n_per_buf, bufp = buf; i; i--, bufp += fill_size)
1174                     memcpy(bufp, fill_literal, fill_size);
1175                 }
1176               for (; count > 0; count -= n_per_buf)
1177                 {
1178                   n_per_buf = n_per_buf > count ? count : n_per_buf;
1179                   x = bfd_set_section_contents (stdoutput, sec,
1180                                                 buf, (file_ptr) offset,
1181                                                 (bfd_size_type) n_per_buf * fill_size);
1182                   if (x != true)
1183                     as_fatal (_("Cannot write to output file."));
1184                   offset += n_per_buf * fill_size;
1185                 }
1186             }
1187         }
1188     }
1189 }
1190 #endif
1191
1192 #if defined(BFD_ASSEMBLER) || (!defined (BFD) && !defined(OBJ_AOUT))
1193 static void
1194 merge_data_into_text ()
1195 {
1196 #if defined(BFD_ASSEMBLER) || defined(MANY_SEGMENTS)
1197   seg_info (text_section)->frchainP->frch_last->fr_next =
1198     seg_info (data_section)->frchainP->frch_root;
1199   seg_info (text_section)->frchainP->frch_last =
1200     seg_info (data_section)->frchainP->frch_last;
1201   seg_info (data_section)->frchainP = 0;
1202 #else
1203   fixS *tmp;
1204
1205   text_last_frag->fr_next = data_frag_root;
1206   text_last_frag = data_last_frag;
1207   data_last_frag = NULL;
1208   data_frag_root = NULL;
1209   if (text_fix_root)
1210     {
1211       for (tmp = text_fix_root; tmp->fx_next; tmp = tmp->fx_next);;
1212       tmp->fx_next = data_fix_root;
1213       text_fix_tail = data_fix_tail;
1214     }
1215   else
1216     text_fix_root = data_fix_root;
1217   data_fix_root = NULL;
1218 #endif
1219 }
1220 #endif /* BFD_ASSEMBLER || (! BFD && ! OBJ_AOUT) */
1221
1222 #if !defined (BFD_ASSEMBLER) && !defined (BFD)
1223 static void
1224 relax_and_size_all_segments ()
1225 {
1226   fragS *fragP;
1227
1228   relax_segment (text_frag_root, SEG_TEXT);
1229   relax_segment (data_frag_root, SEG_DATA);
1230   relax_segment (bss_frag_root, SEG_BSS);
1231   /*
1232    * Now the addresses of frags are correct within the segment.
1233    */
1234
1235   know (text_last_frag->fr_type == rs_fill && text_last_frag->fr_offset == 0);
1236   H_SET_TEXT_SIZE (&headers, text_last_frag->fr_address);
1237   text_last_frag->fr_address = H_GET_TEXT_SIZE (&headers);
1238
1239   /*
1240    * Join the 2 segments into 1 huge segment.
1241    * To do this, re-compute every rn_address in the SEG_DATA frags.
1242    * Then join the data frags after the text frags.
1243    *
1244    * Determine a_data [length of data segment].
1245    */
1246   if (data_frag_root)
1247     {
1248       register relax_addressT slide;
1249
1250       know ((text_last_frag->fr_type == rs_fill) && (text_last_frag->fr_offset == 0));
1251
1252       H_SET_DATA_SIZE (&headers, data_last_frag->fr_address);
1253       data_last_frag->fr_address = H_GET_DATA_SIZE (&headers);
1254       slide = H_GET_TEXT_SIZE (&headers);       /* & in file of the data segment. */
1255 #ifdef OBJ_BOUT
1256 #define RoundUp(N,S) (((N)+(S)-1)&-(S))
1257       /* For b.out: If the data section has a strict alignment
1258          requirement, its load address in the .o file will be
1259          rounded up from the size of the text section.  These
1260          two values are *not* the same!  Similarly for the bss
1261          section....  */
1262       slide = RoundUp (slide, 1 << section_alignment[SEG_DATA]);
1263 #endif
1264
1265       for (fragP = data_frag_root; fragP; fragP = fragP->fr_next)
1266         {
1267           fragP->fr_address += slide;
1268         }                       /* for each data frag */
1269
1270       know (text_last_frag != 0);
1271       text_last_frag->fr_next = data_frag_root;
1272     }
1273   else
1274     {
1275       H_SET_DATA_SIZE (&headers, 0);
1276     }
1277
1278 #ifdef OBJ_BOUT
1279   /* See above comments on b.out data section address.  */
1280   {
1281     long bss_vma;
1282     if (data_last_frag == 0)
1283       bss_vma = H_GET_TEXT_SIZE (&headers);
1284     else
1285       bss_vma = data_last_frag->fr_address;
1286     bss_vma = RoundUp (bss_vma, 1 << section_alignment[SEG_BSS]);
1287     bss_address_frag.fr_address = bss_vma;
1288   }
1289 #else /* ! OBJ_BOUT */
1290   bss_address_frag.fr_address = (H_GET_TEXT_SIZE (&headers) +
1291                                  H_GET_DATA_SIZE (&headers));
1292
1293 #endif /* ! OBJ_BOUT */
1294
1295   /* Slide all the frags */
1296   if (bss_frag_root)
1297     {
1298       relax_addressT slide = bss_address_frag.fr_address;
1299
1300       for (fragP = bss_frag_root; fragP; fragP = fragP->fr_next)
1301         {
1302           fragP->fr_address += slide;
1303         }                       /* for each bss frag */
1304     }
1305
1306   if (bss_last_frag)
1307     H_SET_BSS_SIZE (&headers,
1308                     bss_last_frag->fr_address - bss_frag_root->fr_address);
1309   else
1310     H_SET_BSS_SIZE (&headers, 0);
1311 }
1312 #endif /* ! BFD_ASSEMBLER && ! BFD */
1313
1314 #if defined (BFD_ASSEMBLER) || !defined (BFD)
1315
1316 #ifdef BFD_ASSEMBLER
1317 static void
1318 set_symtab ()
1319 {
1320   int nsyms;
1321   asymbol **asympp;
1322   symbolS *symp;
1323   boolean result;
1324   extern PTR bfd_alloc PARAMS ((bfd *, size_t));
1325
1326   /* Count symbols.  We can't rely on a count made by the loop in
1327      write_object_file, because *_frob_file may add a new symbol or
1328      two.  */
1329   nsyms = 0;
1330   for (symp = symbol_rootP; symp; symp = symbol_next (symp))
1331     nsyms++;
1332
1333   if (nsyms)
1334     {
1335       int i;
1336
1337       asympp = (asymbol **) bfd_alloc (stdoutput,
1338                                        nsyms * sizeof (asymbol *));
1339       symp = symbol_rootP;
1340       for (i = 0; i < nsyms; i++, symp = symbol_next (symp))
1341         {
1342           asympp[i] = symbol_get_bfdsym (symp);
1343           symbol_mark_written (symp);
1344         }
1345     }
1346   else
1347     asympp = 0;
1348   result = bfd_set_symtab (stdoutput, asympp, nsyms);
1349   assert (result == true);
1350   symbol_table_frozen = 1;
1351 }
1352 #endif
1353
1354 #if defined (BFD_ASSEMBLER) && defined (OBJ_COFF) && defined (TE_GO32)
1355 static void
1356 set_segment_vma (abfd, sec, xxx)
1357      bfd *abfd;
1358      asection *sec;
1359      PTR xxx ATTRIBUTE_UNUSED;
1360 {
1361   static bfd_vma addr = 0;
1362   
1363   bfd_set_section_vma (abfd, sec, addr);
1364   addr += bfd_section_size (abfd, sec);
1365 }
1366 #endif /* BFD_ASSEMBLER && OBJ_COFF && !TE_PE */
1367
1368 /* Finish the subsegments.  After every sub-segment, we fake an
1369    ".align ...".  This conforms to BSD4.2 brane-damage.  We then fake
1370    ".fill 0" because that is the kind of frag that requires least
1371    thought.  ".align" frags like to have a following frag since that
1372    makes calculating their intended length trivial.  */
1373
1374 #ifndef SUB_SEGMENT_ALIGN
1375 #ifdef BFD_ASSEMBLER
1376 #define SUB_SEGMENT_ALIGN(SEG) (0)
1377 #else
1378 #define SUB_SEGMENT_ALIGN(SEG) (2)
1379 #endif
1380 #endif
1381
1382 void
1383 subsegs_finish ()
1384 {
1385   struct frchain *frchainP;
1386
1387   for (frchainP = frchain_root; frchainP; frchainP = frchainP->frch_next)
1388     {
1389       subseg_set (frchainP->frch_seg, frchainP->frch_subseg);
1390
1391       /* This now gets called even if we had errors.  In that case,
1392          any alignment is meaningless, and, moreover, will look weird
1393          if we are generating a listing.  */
1394       frag_align (had_errors () ? 0 : SUB_SEGMENT_ALIGN (now_seg),
1395                   subseg_text_p (now_seg) ? NOP_OPCODE : 0,
1396                   0);
1397
1398       /* frag_align will have left a new frag.
1399          Use this last frag for an empty ".fill".
1400
1401          For this segment ...
1402          Create a last frag. Do not leave a "being filled in frag".  */
1403
1404       frag_wane (frag_now);
1405       frag_now->fr_fix = 0;
1406       know (frag_now->fr_next == NULL);
1407     }
1408 }
1409
1410 /* Write the object file.  */
1411
1412 void
1413 write_object_file ()
1414 {
1415 #if ! defined (BFD_ASSEMBLER) || ! defined (WORKING_DOT_WORD)
1416   fragS *fragP;                 /* Track along all frags. */
1417 #endif
1418
1419   /* Do we really want to write it?  */
1420   {
1421     int n_warns, n_errs;
1422     n_warns = had_warnings ();
1423     n_errs = had_errors ();
1424     /* The -Z flag indicates that an object file should be generated,
1425        regardless of warnings and errors.  */
1426     if (flag_always_generate_output)
1427       {
1428         if (n_warns || n_errs)
1429           as_warn (_("%d error%s, %d warning%s, generating bad object file.\n"),
1430                    n_errs, n_errs == 1 ? "" : "s",
1431                    n_warns, n_warns == 1 ? "" : "s");
1432       }
1433     else
1434       {
1435         if (n_errs)
1436           as_fatal (_("%d error%s, %d warning%s, no object file generated.\n"),
1437                     n_errs, n_errs == 1 ? "" : "s",
1438                     n_warns, n_warns == 1 ? "" : "s");
1439       }
1440   }
1441
1442 #ifdef  OBJ_VMS
1443   /* Under VMS we try to be compatible with VAX-11 "C".  Thus, we call
1444      a routine to check for the definition of the procedure "_main",
1445      and if so -- fix it up so that it can be program entry point. */
1446   vms_check_for_main ();
1447 #endif /* OBJ_VMS */
1448
1449   /* From now on, we don't care about sub-segments.  Build one frag chain
1450      for each segment. Linked thru fr_next.  */
1451
1452 #ifdef BFD_ASSEMBLER
1453   /* Remove the sections created by gas for its own purposes.  */
1454   {
1455     asection **seclist, *sec;
1456     int i;
1457
1458     seclist = &stdoutput->sections;
1459     while (seclist && *seclist)
1460       {
1461         sec = *seclist;
1462         while (sec == reg_section || sec == expr_section)
1463           {
1464             sec = sec->next;
1465             *seclist = sec;
1466             stdoutput->section_count--;
1467             if (!sec)
1468               break;
1469           }
1470         if (*seclist)
1471           seclist = &(*seclist)->next;
1472       }
1473     i = 0;
1474     bfd_map_over_sections (stdoutput, renumber_sections, &i);
1475   }
1476
1477   bfd_map_over_sections (stdoutput, chain_frchains_together, (char *) 0);
1478 #else
1479   remove_subsegs (frchain_root, SEG_TEXT, &text_frag_root, &text_last_frag);
1480   remove_subsegs (data0_frchainP, SEG_DATA, &data_frag_root, &data_last_frag);
1481   remove_subsegs (bss0_frchainP, SEG_BSS, &bss_frag_root, &bss_last_frag);
1482 #endif
1483
1484   /* We have two segments. If user gave -R flag, then we must put the
1485      data frags into the text segment. Do this before relaxing so
1486      we know to take advantage of -R and make shorter addresses.  */
1487 #if !defined (OBJ_AOUT) || defined (BFD_ASSEMBLER)
1488   if (flag_readonly_data_in_text)
1489     {
1490       merge_data_into_text ();
1491     }
1492 #endif
1493
1494 #ifdef BFD_ASSEMBLER
1495   bfd_map_over_sections (stdoutput, relax_and_size_seg, (char *) 0);
1496 #else
1497   relax_and_size_all_segments ();
1498 #endif /* BFD_ASSEMBLER */
1499
1500 #if defined (BFD_ASSEMBLER) && defined (OBJ_COFF) && defined (TE_GO32)
1501   /* Now that the segments have their final sizes, run through the
1502      sections and set their vma and lma. !BFD gas sets them, and BFD gas
1503      should too. Currently, only DJGPP uses this code, but other
1504      COFF targets may need to execute this too.  */
1505   bfd_map_over_sections (stdoutput, set_segment_vma, (char *) 0);
1506 #endif
1507
1508 #ifndef BFD_ASSEMBLER
1509   /*
1510    *
1511    * Crawl the symbol chain.
1512    *
1513    * For each symbol whose value depends on a frag, take the address of
1514    * that frag and subsume it into the value of the symbol.
1515    * After this, there is just one way to lookup a symbol value.
1516    * Values are left in their final state for object file emission.
1517    * We adjust the values of 'L' local symbols, even if we do
1518    * not intend to emit them to the object file, because their values
1519    * are needed for fix-ups.
1520    *
1521    * Unless we saw a -L flag, remove all symbols that begin with 'L'
1522    * from the symbol chain.  (They are still pointed to by the fixes.)
1523    *
1524    * Count the remaining symbols.
1525    * Assign a symbol number to each symbol.
1526    * Count the number of string-table chars we will emit.
1527    * Put this info into the headers as appropriate.
1528    *
1529    */
1530   know (zero_address_frag.fr_address == 0);
1531   string_byte_count = sizeof (string_byte_count);
1532
1533   obj_crawl_symbol_chain (&headers);
1534
1535   if (string_byte_count == sizeof (string_byte_count))
1536     string_byte_count = 0;
1537
1538   H_SET_STRING_SIZE (&headers, string_byte_count);
1539
1540   /*
1541    * Addresses of frags now reflect addresses we use in the object file.
1542    * Symbol values are correct.
1543    * Scan the frags, converting any ".org"s and ".align"s to ".fill"s.
1544    * Also converting any machine-dependent frags using md_convert_frag();
1545    */
1546   subseg_change (SEG_TEXT, 0);
1547
1548   for (fragP = text_frag_root; fragP; fragP = fragP->fr_next)
1549     {
1550       /* At this point we have linked all the frags into a single
1551          chain.  However, cvt_frag_to_fill may call md_convert_frag
1552          which may call fix_new.  We need to ensure that fix_new adds
1553          the fixup to the right section.  */
1554       if (fragP == data_frag_root)
1555         subseg_change (SEG_DATA, 0);
1556
1557       cvt_frag_to_fill (&headers, SEG_TEXT, fragP);
1558
1559       /* Some assert macros don't work with # directives mixed in.  */
1560 #ifndef NDEBUG
1561       if (!(fragP->fr_next == NULL
1562 #ifdef OBJ_BOUT
1563             || fragP->fr_next == data_frag_root
1564 #endif
1565             || ((fragP->fr_next->fr_address - fragP->fr_address)
1566                 == (fragP->fr_fix + fragP->fr_offset * fragP->fr_var))))
1567         abort ();
1568 #endif
1569     }
1570 #endif /* ! BFD_ASSEMBLER */
1571
1572 #ifndef WORKING_DOT_WORD
1573   {
1574     struct broken_word *lie;
1575     struct broken_word **prevP;
1576
1577     prevP = &broken_words;
1578     for (lie = broken_words; lie; lie = lie->next_broken_word)
1579       if (!lie->added)
1580         {
1581           expressionS exp;
1582
1583           subseg_change (lie->seg, lie->subseg);
1584           exp.X_op = O_subtract;
1585           exp.X_add_symbol = lie->add;
1586           exp.X_op_symbol = lie->sub;
1587           exp.X_add_number = lie->addnum;
1588 #ifdef BFD_ASSEMBLER
1589 #ifdef TC_CONS_FIX_NEW
1590           TC_CONS_FIX_NEW (lie->frag,
1591                        lie->word_goes_here - lie->frag->fr_literal,
1592                        2, &exp);
1593 #else
1594           fix_new_exp (lie->frag,
1595                        lie->word_goes_here - lie->frag->fr_literal,
1596                        2, &exp, 0, BFD_RELOC_16);
1597 #endif
1598 #else
1599 #if defined(TC_SPARC) || defined(TC_A29K) || defined(NEED_FX_R_TYPE)
1600           fix_new_exp (lie->frag,
1601                        lie->word_goes_here - lie->frag->fr_literal,
1602                        2, &exp, 0, NO_RELOC);
1603 #else
1604 #ifdef TC_NS32K
1605           fix_new_ns32k_exp (lie->frag,
1606                              lie->word_goes_here - lie->frag->fr_literal,
1607                              2, &exp, 0, 0, 2, 0, 0);
1608 #else
1609           fix_new_exp (lie->frag,
1610                        lie->word_goes_here - lie->frag->fr_literal,
1611                        2, &exp, 0, 0);
1612 #endif /* TC_NS32K */
1613 #endif /* TC_SPARC|TC_A29K|NEED_FX_R_TYPE */
1614 #endif /* BFD_ASSEMBLER */
1615           *prevP = lie->next_broken_word;
1616         }
1617       else
1618         prevP = &(lie->next_broken_word);
1619
1620     for (lie = broken_words; lie;)
1621       {
1622         struct broken_word *untruth;
1623         char *table_ptr;
1624         addressT table_addr;
1625         addressT from_addr, to_addr;
1626         int n, m;
1627
1628         subseg_change (lie->seg, lie->subseg);
1629         fragP = lie->dispfrag;
1630
1631         /* Find out how many broken_words go here.  */
1632         n = 0;
1633         for (untruth = lie; untruth && untruth->dispfrag == fragP; untruth = untruth->next_broken_word)
1634           if (untruth->added == 1)
1635             n++;
1636
1637         table_ptr = lie->dispfrag->fr_opcode;
1638         table_addr = lie->dispfrag->fr_address + (table_ptr - lie->dispfrag->fr_literal);
1639         /* Create the jump around the long jumps.  This is a short
1640            jump from table_ptr+0 to table_ptr+n*long_jump_size.  */
1641         from_addr = table_addr;
1642         to_addr = table_addr + md_short_jump_size + n * md_long_jump_size;
1643         md_create_short_jump (table_ptr, from_addr, to_addr, lie->dispfrag, lie->add);
1644         table_ptr += md_short_jump_size;
1645         table_addr += md_short_jump_size;
1646
1647         for (m = 0; lie && lie->dispfrag == fragP; m++, lie = lie->next_broken_word)
1648           {
1649             if (lie->added == 2)
1650               continue;
1651             /* Patch the jump table */
1652             /* This is the offset from ??? to table_ptr+0 */
1653             to_addr = table_addr - S_GET_VALUE (lie->sub);
1654 #ifdef BFD_ASSEMBLER
1655             to_addr -= symbol_get_frag (lie->sub)->fr_address;
1656 #endif
1657 #ifdef TC_CHECK_ADJUSTED_BROKEN_DOT_WORD
1658             TC_CHECK_ADJUSTED_BROKEN_DOT_WORD (to_addr, lie);
1659 #endif
1660             md_number_to_chars (lie->word_goes_here, to_addr, 2);
1661             for (untruth = lie->next_broken_word; untruth && untruth->dispfrag == fragP; untruth = untruth->next_broken_word)
1662               {
1663                 if (untruth->use_jump == lie)
1664                   md_number_to_chars (untruth->word_goes_here, to_addr, 2);
1665               }
1666
1667             /* Install the long jump */
1668             /* this is a long jump from table_ptr+0 to the final target */
1669             from_addr = table_addr;
1670             to_addr = S_GET_VALUE (lie->add) + lie->addnum;
1671 #ifdef BFD_ASSEMBLER
1672             to_addr += symbol_get_frag (lie->add)->fr_address;
1673 #endif
1674             md_create_long_jump (table_ptr, from_addr, to_addr, lie->dispfrag, lie->add);
1675             table_ptr += md_long_jump_size;
1676             table_addr += md_long_jump_size;
1677           }
1678       }
1679   }
1680 #endif /* not WORKING_DOT_WORD */
1681
1682 #ifndef BFD_ASSEMBLER
1683 #ifndef OBJ_VMS
1684   {                             /* not vms */
1685     char *the_object_file;
1686     long object_file_size;
1687     /*
1688      * Scan every FixS performing fixups. We had to wait until now to do
1689      * this because md_convert_frag() may have made some fixSs.
1690      */
1691     int trsize, drsize;
1692
1693     subseg_change (SEG_TEXT, 0);
1694     trsize = md_reloc_size * fixup_segment (text_fix_root, SEG_TEXT);
1695     subseg_change (SEG_DATA, 0);
1696     drsize = md_reloc_size * fixup_segment (data_fix_root, SEG_DATA);
1697     H_SET_RELOCATION_SIZE (&headers, trsize, drsize);
1698
1699     /* FIXME move this stuff into the pre-write-hook */
1700     H_SET_MAGIC_NUMBER (&headers, magic_number_for_object_file);
1701     H_SET_ENTRY_POINT (&headers, 0);
1702
1703     obj_pre_write_hook (&headers);      /* extra coff stuff */
1704
1705     object_file_size = H_GET_FILE_SIZE (&headers);
1706     next_object_file_charP = the_object_file = xmalloc (object_file_size);
1707
1708     output_file_create (out_file_name);
1709
1710     obj_header_append (&next_object_file_charP, &headers);
1711
1712     know ((next_object_file_charP - the_object_file) == H_GET_HEADER_SIZE (&headers));
1713
1714     /*
1715      * Emit code.
1716      */
1717     for (fragP = text_frag_root; fragP; fragP = fragP->fr_next)
1718       {
1719         register long count;
1720         register char *fill_literal;
1721         register long fill_size;
1722
1723         PROGRESS (1);
1724         know (fragP->fr_type == rs_fill);
1725         append (&next_object_file_charP, fragP->fr_literal, (unsigned long) fragP->fr_fix);
1726         fill_literal = fragP->fr_literal + fragP->fr_fix;
1727         fill_size = fragP->fr_var;
1728         know (fragP->fr_offset >= 0);
1729
1730         for (count = fragP->fr_offset; count; count--)
1731           {
1732             append (&next_object_file_charP, fill_literal, (unsigned long) fill_size);
1733           }                     /* for each  */
1734
1735       }                         /* for each code frag. */
1736
1737     know ((next_object_file_charP - the_object_file) == (H_GET_HEADER_SIZE (&headers) + H_GET_TEXT_SIZE (&headers) + H_GET_DATA_SIZE (&headers)));
1738
1739     /*
1740      * Emit relocations.
1741      */
1742     obj_emit_relocations (&next_object_file_charP, text_fix_root, (relax_addressT) 0);
1743     know ((next_object_file_charP - the_object_file) == (H_GET_HEADER_SIZE (&headers) + H_GET_TEXT_SIZE (&headers) + H_GET_DATA_SIZE (&headers) + H_GET_TEXT_RELOCATION_SIZE (&headers)));
1744 #ifdef TC_I960
1745     /* Make addresses in data relocation directives relative to beginning of
1746      * first data fragment, not end of last text fragment:  alignment of the
1747      * start of the data segment may place a gap between the segments.
1748      */
1749     obj_emit_relocations (&next_object_file_charP, data_fix_root, data0_frchainP->frch_root->fr_address);
1750 #else /* TC_I960 */
1751     obj_emit_relocations (&next_object_file_charP, data_fix_root, text_last_frag->fr_address);
1752 #endif /* TC_I960 */
1753
1754     know ((next_object_file_charP - the_object_file) == (H_GET_HEADER_SIZE (&headers) + H_GET_TEXT_SIZE (&headers) + H_GET_DATA_SIZE (&headers) + H_GET_TEXT_RELOCATION_SIZE (&headers) + H_GET_DATA_RELOCATION_SIZE (&headers)));
1755
1756     /*
1757      * Emit line number entries.
1758      */
1759     OBJ_EMIT_LINENO (&next_object_file_charP, lineno_rootP, the_object_file);
1760     know ((next_object_file_charP - the_object_file) == (H_GET_HEADER_SIZE (&headers) + H_GET_TEXT_SIZE (&headers) + H_GET_DATA_SIZE (&headers) + H_GET_TEXT_RELOCATION_SIZE (&headers) + H_GET_DATA_RELOCATION_SIZE (&headers) + H_GET_LINENO_SIZE (&headers)));
1761
1762     /*
1763      * Emit symbols.
1764      */
1765     obj_emit_symbols (&next_object_file_charP, symbol_rootP);
1766     know ((next_object_file_charP - the_object_file) == (H_GET_HEADER_SIZE (&headers) + H_GET_TEXT_SIZE (&headers) + H_GET_DATA_SIZE (&headers) + H_GET_TEXT_RELOCATION_SIZE (&headers) + H_GET_DATA_RELOCATION_SIZE (&headers) + H_GET_LINENO_SIZE (&headers) + H_GET_SYMBOL_TABLE_SIZE (&headers)));
1767
1768     /*
1769      * Emit strings.
1770      */
1771
1772     if (string_byte_count > 0)
1773       {
1774         obj_emit_strings (&next_object_file_charP);
1775       }                         /* only if we have a string table */
1776
1777 #ifdef BFD_HEADERS
1778     bfd_seek (stdoutput, 0, 0);
1779     bfd_write (the_object_file, 1, object_file_size, stdoutput);
1780 #else
1781
1782     /* Write the data to the file */
1783     output_file_append (the_object_file, object_file_size, out_file_name);
1784     free (the_object_file);
1785 #endif
1786   }                             /* non vms output */
1787 #else /* OBJ_VMS */
1788   /*
1789    *    Now do the VMS-dependent part of writing the object file
1790    */
1791   vms_write_object_file (H_GET_TEXT_SIZE (&headers),
1792                          H_GET_DATA_SIZE (&headers),
1793                          H_GET_BSS_SIZE (&headers),
1794                          text_frag_root, data_frag_root);
1795 #endif /* OBJ_VMS */
1796 #else /* BFD_ASSEMBLER */
1797
1798   /* Resolve symbol values.  This needs to be done before processing
1799      the relocations.  */
1800   if (symbol_rootP)
1801     {
1802       symbolS *symp;
1803
1804       for (symp = symbol_rootP; symp; symp = symbol_next (symp))
1805         resolve_symbol_value (symp, 1);
1806     }
1807   resolve_local_symbol_values ();
1808
1809   PROGRESS (1);
1810
1811 #ifdef tc_frob_file_before_adjust
1812   tc_frob_file_before_adjust ();
1813 #endif
1814 #ifdef obj_frob_file_before_adjust
1815   obj_frob_file_before_adjust ();
1816 #endif
1817
1818   bfd_map_over_sections (stdoutput, adjust_reloc_syms, (char *)0);
1819
1820   /* Set up symbol table, and write it out.  */
1821   if (symbol_rootP)
1822     {
1823       symbolS *symp;
1824
1825       for (symp = symbol_rootP; symp; symp = symbol_next (symp))
1826         {
1827           int punt = 0;
1828           const char *name;
1829
1830           if (symbol_mri_common_p (symp))
1831             {
1832               if (S_IS_EXTERNAL (symp))
1833                 as_bad (_("%s: global symbols not supported in common sections"),
1834                         S_GET_NAME (symp));
1835               symbol_remove (symp, &symbol_rootP, &symbol_lastP);
1836               continue;
1837             }
1838
1839           name = S_GET_NAME (symp);
1840           if (name)
1841             {
1842               const char *name2 = decode_local_label_name ((char *)S_GET_NAME (symp));
1843               /* They only differ if `name' is a fb or dollar local
1844                  label name.  */
1845               if (name2 != name && ! S_IS_DEFINED (symp))
1846                 as_bad (_("local label %s is not defined"), name2);
1847             }
1848
1849           /* Do it again, because adjust_reloc_syms might introduce
1850              more symbols.  They'll probably only be section symbols,
1851              but they'll still need to have the values computed.  */
1852           resolve_symbol_value (symp, 1);
1853
1854           /* Skip symbols which were equated to undefined or common
1855              symbols.  */
1856           if (symbol_equated_p (symp)
1857               && (! S_IS_DEFINED (symp) || S_IS_COMMON (symp)))
1858             {
1859               symbol_remove (symp, &symbol_rootP, &symbol_lastP);
1860               continue;
1861             }
1862
1863           /* So far, common symbols have been treated like undefined symbols.
1864              Put them in the common section now.  */
1865           if (S_IS_DEFINED (symp) == 0
1866               && S_GET_VALUE (symp) != 0)
1867             S_SET_SEGMENT (symp, bfd_com_section_ptr);
1868 #if 0
1869           printf ("symbol `%s'\n\t@%x: value=%d flags=%x seg=%s\n",
1870                   S_GET_NAME (symp), symp,
1871                   S_GET_VALUE (symp),
1872                   symbol_get_bfdsym (symp)->flags,
1873                   segment_name (S_GET_SEGMENT (symp)));
1874 #endif
1875
1876 #ifdef obj_frob_symbol
1877           obj_frob_symbol (symp, punt);
1878 #endif
1879 #ifdef tc_frob_symbol
1880           if (! punt || symbol_used_in_reloc_p (symp))
1881             tc_frob_symbol (symp, punt);
1882 #endif
1883
1884           /* If we don't want to keep this symbol, splice it out of
1885              the chain now.  If EMIT_SECTION_SYMBOLS is 0, we never
1886              want section symbols.  Otherwise, we skip local symbols
1887              and symbols that the frob_symbol macros told us to punt,
1888              but we keep such symbols if they are used in relocs.  */
1889           if ((! EMIT_SECTION_SYMBOLS
1890                && symbol_section_p (symp))
1891               /* Note that S_IS_EXTERN and S_IS_LOCAL are not always
1892                  opposites.  Sometimes the former checks flags and the
1893                  latter examines the name...  */
1894               || (!S_IS_EXTERN (symp)
1895                   && (S_IS_LOCAL (symp) || punt)
1896                   && ! symbol_used_in_reloc_p (symp)))
1897             {
1898               symbol_remove (symp, &symbol_rootP, &symbol_lastP);
1899               /* After symbol_remove, symbol_next(symp) still returns
1900                  the one that came after it in the chain.  So we don't
1901                  need to do any extra cleanup work here.  */
1902
1903               continue;
1904             }
1905
1906           /* Make sure we really got a value for the symbol.  */
1907           if (! symbol_resolved_p (symp))
1908             {
1909               as_bad (_("can't resolve value for symbol \"%s\""),
1910                       S_GET_NAME (symp));
1911               symbol_mark_resolved (symp);
1912             }
1913
1914           /* Set the value into the BFD symbol.  Up til now the value
1915              has only been kept in the gas symbolS struct.  */
1916           symbol_get_bfdsym (symp)->value = S_GET_VALUE (symp);
1917         }
1918     }
1919
1920   PROGRESS (1);
1921
1922   /* Now do any format-specific adjustments to the symbol table, such
1923      as adding file symbols.  */
1924 #ifdef tc_adjust_symtab
1925   tc_adjust_symtab ();
1926 #endif
1927 #ifdef obj_adjust_symtab
1928   obj_adjust_symtab ();
1929 #endif
1930
1931   /* Now that all the sizes are known, and contents correct, we can
1932      start writing to the file.  */
1933   set_symtab ();
1934
1935   /* If *_frob_file changes the symbol value at this point, it is
1936      responsible for moving the changed value into symp->bsym->value
1937      as well.  Hopefully all symbol value changing can be done in
1938      *_frob_symbol.  */
1939 #ifdef tc_frob_file
1940   tc_frob_file ();
1941 #endif
1942 #ifdef obj_frob_file
1943   obj_frob_file ();
1944 #endif
1945
1946   bfd_map_over_sections (stdoutput, write_relocs, (char *) 0);
1947
1948 #ifdef tc_frob_file_after_relocs
1949   tc_frob_file_after_relocs ();
1950 #endif
1951 #ifdef obj_frob_file_after_relocs
1952   obj_frob_file_after_relocs ();
1953 #endif
1954
1955   bfd_map_over_sections (stdoutput, write_contents, (char *) 0);
1956 #endif /* BFD_ASSEMBLER */
1957 }
1958 #endif /* ! BFD */
1959
1960 /*
1961  *                      relax_segment()
1962  *
1963  * Now we have a segment, not a crowd of sub-segments, we can make fr_address
1964  * values.
1965  *
1966  * Relax the frags.
1967  *
1968  * After this, all frags in this segment have addresses that are correct
1969  * within the segment. Since segments live in different file addresses,
1970  * these frag addresses may not be the same as final object-file addresses.
1971  */
1972
1973 #ifdef TC_GENERIC_RELAX_TABLE
1974
1975 static int is_dnrange PARAMS ((fragS *, fragS *));
1976
1977 /* Subroutines of relax_segment.  */
1978 static int
1979 is_dnrange (f1, f2)
1980      fragS *f1;
1981      fragS *f2;
1982 {
1983   for (; f1; f1 = f1->fr_next)
1984     if (f1->fr_next == f2)
1985       return 1;
1986   return 0;
1987 }
1988
1989 /* Relax a fragment by scanning TC_GENERIC_RELAX_TABLE.  */
1990
1991 long
1992 relax_frag (fragP, stretch)
1993      fragS *fragP;
1994      long stretch;
1995 {
1996   const relax_typeS *this_type;
1997   const relax_typeS *start_type;
1998   relax_substateT next_state;
1999   relax_substateT this_state;
2000   long aim, target, growth;
2001   symbolS *symbolP = fragP->fr_symbol;
2002   long offset = fragP->fr_offset;
2003   /* Recompute was_address by undoing "+= stretch" done by relax_segment.  */
2004   unsigned long was_address = fragP->fr_address - stretch;
2005   unsigned long address = fragP->fr_address;
2006   const relax_typeS *table = TC_GENERIC_RELAX_TABLE;
2007
2008   this_state = fragP->fr_subtype;
2009   start_type = this_type = table + this_state;
2010   target = offset;
2011
2012   if (symbolP)
2013     {
2014 #ifndef DIFF_EXPR_OK
2015 #if !defined (MANY_SEGMENTS) && !defined (BFD_ASSEMBLER)
2016       know ((S_GET_SEGMENT (symbolP) == SEG_ABSOLUTE)
2017             || (S_GET_SEGMENT (symbolP) == SEG_DATA)
2018             || (S_GET_SEGMENT (symbolP) == SEG_BSS)
2019             || (S_GET_SEGMENT (symbolP) == SEG_TEXT));
2020 #endif
2021       know (symbolP->sy_frag);
2022 #endif
2023       know (!(S_GET_SEGMENT (symbolP) == absolute_section)
2024             || symbolP->sy_frag == &zero_address_frag);
2025       target += S_GET_VALUE (symbolP) + symbol_get_frag (symbolP)->fr_address;
2026
2027       /* If frag has yet to be reached on this pass,
2028          assume it will move by STRETCH just as we did.
2029          If this is not so, it will be because some frag
2030          between grows, and that will force another pass.
2031
2032          Beware zero-length frags.
2033
2034          There should be a faster way to do this.  */
2035
2036       if (symbol_get_frag (symbolP)->fr_address >= was_address
2037           && is_dnrange (fragP, symbol_get_frag (symbolP)))
2038         {
2039           target += stretch;
2040         }
2041     }
2042
2043   aim = target - address - fragP->fr_fix;
2044 #ifdef TC_PCREL_ADJUST
2045   /* Currently only the ns32k family needs this */
2046   aim += TC_PCREL_ADJUST(fragP);
2047 /*#else*/
2048   /* This machine doesn't want to use pcrel_adjust.
2049      In that case, pcrel_adjust should be zero.  */
2050 /*  assert (fragP->fr_targ.ns32k.pcrel_adjust == 0);*/
2051 #endif
2052 #ifdef md_prepare_relax_scan /* formerly called M68K_AIM_KLUDGE */
2053   md_prepare_relax_scan (fragP, address, aim, this_state, this_type);
2054 #endif
2055
2056   if (aim < 0)
2057     {
2058       /* Look backwards. */
2059       for (next_state = this_type->rlx_more; next_state;)
2060         if (aim >= this_type->rlx_backward)
2061           next_state = 0;
2062         else
2063           {
2064             /* Grow to next state. */
2065             this_state = next_state;
2066             this_type = table + this_state;
2067             next_state = this_type->rlx_more;
2068           }
2069     }
2070   else
2071     {
2072       /* Look forwards. */
2073       for (next_state = this_type->rlx_more; next_state;)
2074         if (aim <= this_type->rlx_forward)
2075           next_state = 0;
2076         else
2077           {
2078             /* Grow to next state. */
2079             this_state = next_state;
2080             this_type = table + this_state;
2081             next_state = this_type->rlx_more;
2082           }
2083     }
2084
2085   growth = this_type->rlx_length - start_type->rlx_length;
2086   if (growth != 0)
2087     fragP->fr_subtype = this_state;
2088   return growth;
2089 }
2090
2091 #endif /* defined (TC_GENERIC_RELAX_TABLE) */
2092
2093 /* Relax_align. Advance location counter to next address that has 'alignment'
2094    lowest order bits all 0s, return size of adjustment made.  */
2095 static relax_addressT
2096 relax_align (address, alignment)
2097      register relax_addressT address;   /* Address now. */
2098      register int alignment;    /* Alignment (binary). */
2099 {
2100   relax_addressT mask;
2101   relax_addressT new_address;
2102
2103   mask = ~((~0) << alignment);
2104   new_address = (address + mask) & (~mask);
2105 #ifdef LINKER_RELAXING_SHRINKS_ONLY
2106   if (linkrelax)
2107     /* We must provide lots of padding, so the linker can discard it
2108        when needed.  The linker will not add extra space, ever.  */
2109     new_address += (1 << alignment);
2110 #endif
2111   return (new_address - address);
2112 }
2113
2114 void
2115 relax_segment (segment_frag_root, segment)
2116      struct frag *segment_frag_root;
2117      segT segment;
2118 {
2119   register struct frag *fragP;
2120   register relax_addressT address;
2121 #if !defined (MANY_SEGMENTS) && !defined (BFD_ASSEMBLER)
2122   know (segment == SEG_DATA || segment == SEG_TEXT || segment == SEG_BSS);
2123 #endif
2124   /* In case md_estimate_size_before_relax() wants to make fixSs. */
2125   subseg_change (segment, 0);
2126
2127   /* For each frag in segment: count and store  (a 1st guess of)
2128      fr_address.  */
2129   address = 0;
2130   for (fragP = segment_frag_root; fragP; fragP = fragP->fr_next)
2131     {
2132       fragP->fr_address = address;
2133       address += fragP->fr_fix;
2134
2135       switch (fragP->fr_type)
2136         {
2137         case rs_fill:
2138           address += fragP->fr_offset * fragP->fr_var;
2139           break;
2140
2141         case rs_align:
2142         case rs_align_code:
2143           {
2144             addressT offset = relax_align (address, (int) fragP->fr_offset);
2145
2146             if (fragP->fr_subtype != 0 && offset > fragP->fr_subtype)
2147               offset = 0;
2148
2149             if (offset % fragP->fr_var != 0)
2150               {
2151                 as_bad (_("alignment padding (%lu bytes) not a multiple of %ld"),
2152                         (unsigned long) offset, (long) fragP->fr_var);
2153                 offset -= (offset % fragP->fr_var);
2154               }
2155
2156             address += offset;
2157           }
2158           break;
2159
2160         case rs_org:
2161         case rs_space:
2162           /* Assume .org is nugatory. It will grow with 1st relax.  */
2163           break;
2164
2165         case rs_machine_dependent:
2166           address += md_estimate_size_before_relax (fragP, segment);
2167           break;
2168
2169 #ifndef WORKING_DOT_WORD
2170           /* Broken words don't concern us yet */
2171         case rs_broken_word:
2172           break;
2173 #endif
2174
2175         case rs_leb128:
2176           /* Initial guess is always 1; doing otherwise can result in 
2177              stable solutions that are larger than the minimum.  */
2178           address += fragP->fr_offset = 1;
2179           break;
2180
2181         case rs_cfa:
2182           address += eh_frame_estimate_size_before_relax (fragP);
2183           break;
2184
2185         default:
2186           BAD_CASE (fragP->fr_type);
2187           break;
2188         }                       /* switch(fr_type) */
2189     }                           /* for each frag in the segment */
2190
2191   /* Do relax().  */
2192   {
2193     long stretch;       /* May be any size, 0 or negative. */
2194     /* Cumulative number of addresses we have */
2195     /* relaxed this pass. */
2196     /* We may have relaxed more than one address. */
2197     long stretched;     /* Have we stretched on this pass? */
2198     /* This is 'cuz stretch may be zero, when, in fact some piece of code
2199        grew, and another shrank.  If a branch instruction doesn't fit anymore,
2200        we could be scrod.  */
2201
2202     do
2203       {
2204         stretch = stretched = 0;
2205         for (fragP = segment_frag_root; fragP; fragP = fragP->fr_next)
2206           {
2207             long growth = 0;
2208             addressT was_address;
2209             offsetT offset;
2210             symbolS *symbolP;
2211
2212             was_address = fragP->fr_address;
2213             address = fragP->fr_address += stretch;
2214             symbolP = fragP->fr_symbol;
2215             offset = fragP->fr_offset;
2216
2217             switch (fragP->fr_type)
2218               {
2219               case rs_fill:     /* .fill never relaxes. */
2220                 growth = 0;
2221                 break;
2222
2223 #ifndef WORKING_DOT_WORD
2224                 /* JF:  This is RMS's idea.  I do *NOT* want to be blamed
2225                    for it I do not want to write it.  I do not want to have
2226                    anything to do with it.  This is not the proper way to
2227                    implement this misfeature.  */
2228               case rs_broken_word:
2229                 {
2230                   struct broken_word *lie;
2231                   struct broken_word *untruth;
2232
2233                   /* Yes this is ugly (storing the broken_word pointer
2234                      in the symbol slot).  Still, this whole chunk of
2235                      code is ugly, and I don't feel like doing anything
2236                      about it.  Think of it as stubbornness in action.  */
2237                   growth = 0;
2238                   for (lie = (struct broken_word *) (fragP->fr_symbol);
2239                        lie && lie->dispfrag == fragP;
2240                        lie = lie->next_broken_word)
2241                     {
2242
2243                       if (lie->added)
2244                         continue;
2245
2246                       offset = (symbol_get_frag (lie->add)->fr_address
2247                                 + S_GET_VALUE (lie->add)
2248                                 + lie->addnum
2249                                 - (symbol_get_frag (lie->sub)->fr_address
2250                                    + S_GET_VALUE (lie->sub)));
2251                       if (offset <= -32768 || offset >= 32767)
2252                         {
2253                           if (flag_warn_displacement)
2254                             {
2255                               char buf[50];
2256                               sprint_value (buf, (addressT) lie->addnum);
2257                               as_warn (_(".word %s-%s+%s didn't fit"),
2258                                        S_GET_NAME (lie->add),
2259                                        S_GET_NAME (lie->sub),
2260                                        buf);
2261                             }
2262                           lie->added = 1;
2263                           if (fragP->fr_subtype == 0)
2264                             {
2265                               fragP->fr_subtype++;
2266                               growth += md_short_jump_size;
2267                             }
2268                           for (untruth = lie->next_broken_word;
2269                                untruth && untruth->dispfrag == lie->dispfrag;
2270                                untruth = untruth->next_broken_word)
2271                             if ((symbol_get_frag (untruth->add)
2272                                  == symbol_get_frag (lie->add))
2273                                 && (S_GET_VALUE (untruth->add)
2274                                     == S_GET_VALUE (lie->add)))
2275                               {
2276                                 untruth->added = 2;
2277                                 untruth->use_jump = lie;
2278                               }
2279                           growth += md_long_jump_size;
2280                         }
2281                     }
2282
2283                   break;
2284                 }               /* case rs_broken_word */
2285 #endif
2286               case rs_align:
2287               case rs_align_code:
2288                 {
2289                   addressT oldoff, newoff;
2290
2291                   oldoff = relax_align (was_address + fragP->fr_fix,
2292                                         (int) offset);
2293                   newoff = relax_align (address + fragP->fr_fix,
2294                                         (int) offset);
2295
2296                   if (fragP->fr_subtype != 0)
2297                     {
2298                       if (oldoff > fragP->fr_subtype)
2299                         oldoff = 0;
2300                       if (newoff > fragP->fr_subtype)
2301                         newoff = 0;
2302                     }
2303
2304                   growth = newoff - oldoff;
2305                 }
2306                 break;
2307
2308               case rs_org:
2309                 {
2310                   long target = offset;
2311                   long after;
2312
2313                   if (symbolP)
2314                     {
2315 #if !defined (MANY_SEGMENTS) && !defined (BFD_ASSEMBLER)
2316                       know ((S_GET_SEGMENT (symbolP) == SEG_ABSOLUTE)
2317                             || (S_GET_SEGMENT (symbolP) == SEG_DATA)
2318                             || (S_GET_SEGMENT (symbolP) == SEG_TEXT)
2319                             || S_GET_SEGMENT (symbolP) == SEG_BSS);
2320                       know (symbolP->sy_frag);
2321                       know (!(S_GET_SEGMENT (symbolP) == SEG_ABSOLUTE)
2322                             || (symbolP->sy_frag == &zero_address_frag));
2323 #endif
2324                       target += (S_GET_VALUE (symbolP)
2325                                  + symbol_get_frag (symbolP)->fr_address);
2326                     }           /* if we have a symbol */
2327
2328                   know (fragP->fr_next);
2329                   after = fragP->fr_next->fr_address;
2330                   growth = target - after;
2331                   if (growth < 0)
2332                     {
2333                       /* Growth may be negative, but variable part of frag
2334                          cannot have fewer than 0 chars.  That is, we can't
2335                          .org backwards. */
2336                       as_bad_where (fragP->fr_file, fragP->fr_line,
2337                                     _("attempt to .org backwards ignored"));
2338
2339                       /* We've issued an error message.  Change the
2340                          frag to avoid cascading errors.  */
2341                       fragP->fr_type = rs_align;
2342                       fragP->fr_subtype = 0;
2343                       fragP->fr_offset = 0;
2344                       fragP->fr_fix = after - address;
2345                       growth = stretch;
2346                     }
2347
2348                   growth -= stretch;    /* This is an absolute growth factor */
2349                   break;
2350                 }
2351
2352               case rs_space:
2353                 if (symbolP)
2354                   {
2355                     growth = S_GET_VALUE (symbolP);
2356                     if (symbol_get_frag (symbolP) != &zero_address_frag
2357                         || S_IS_COMMON (symbolP)
2358                         || ! S_IS_DEFINED (symbolP))
2359                       as_bad_where (fragP->fr_file, fragP->fr_line,
2360                                     _(".space specifies non-absolute value"));
2361                     fragP->fr_symbol = 0;
2362                     if (growth < 0)
2363                       {
2364                         as_warn (_(".space or .fill with negative value, ignored"));
2365                         growth = 0;
2366                       }
2367                   }
2368                 else
2369                   growth = 0;
2370                 break;
2371
2372               case rs_machine_dependent:
2373 #ifdef md_relax_frag
2374                 growth = md_relax_frag (fragP, stretch);
2375 #else
2376 #ifdef TC_GENERIC_RELAX_TABLE
2377                 /* The default way to relax a frag is to look through
2378                    TC_GENERIC_RELAX_TABLE.  */
2379                 growth = relax_frag (fragP, stretch);
2380 #endif /* TC_GENERIC_RELAX_TABLE */
2381 #endif
2382                 break;
2383
2384               case rs_leb128:
2385                 {
2386                   valueT value;
2387                   int size;
2388
2389                   value = resolve_symbol_value (fragP->fr_symbol, 0);
2390                   size = sizeof_leb128 (value, fragP->fr_subtype);
2391                   growth = size - fragP->fr_offset;
2392                   fragP->fr_offset = size;
2393                 }
2394                 break;
2395
2396               case rs_cfa:
2397                 growth = eh_frame_relax_frag (fragP);
2398                 break;
2399
2400               default:
2401                 BAD_CASE (fragP->fr_type);
2402                 break;
2403               }
2404             if (growth)
2405               {
2406                 stretch += growth;
2407                 stretched++;
2408               }
2409           }                     /* For each frag in the segment. */
2410       }
2411     while (stretched);          /* Until nothing further to relax. */
2412   }                             /* do_relax */
2413
2414   /*
2415    * We now have valid fr_address'es for each frag.
2416    */
2417
2418   /*
2419    * All fr_address's are correct, relative to their own segment.
2420    * We have made all the fixS we will ever make.
2421    */
2422 }                               /* relax_segment() */
2423
2424 #if defined (BFD_ASSEMBLER) || (!defined (BFD) && !defined (OBJ_VMS))
2425
2426 #ifndef TC_RELOC_RTSYM_LOC_FIXUP
2427 #define TC_RELOC_RTSYM_LOC_FIXUP(X) (1)
2428 #endif
2429
2430 /* fixup_segment()
2431
2432    Go through all the fixS's in a segment and see which ones can be
2433    handled now.  (These consist of fixS where we have since discovered
2434    the value of a symbol, or the address of the frag involved.)
2435    For each one, call md_apply_fix to put the fix into the frag data.
2436
2437    Result is a count of how many relocation structs will be needed to
2438    handle the remaining fixS's that we couldn't completely handle here.
2439    These will be output later by emit_relocations().  */
2440
2441 static long
2442 fixup_segment (fixP, this_segment_type)
2443      register fixS *fixP;
2444      segT this_segment_type;    /* N_TYPE bits for segment. */
2445 {
2446   long seg_reloc_count = 0;
2447   symbolS *add_symbolP;
2448   symbolS *sub_symbolP;
2449   valueT add_number;
2450   int size;
2451   char *place;
2452   long where;
2453   int pcrel, plt;
2454   fragS *fragP;
2455   segT add_symbol_segment = absolute_section;
2456
2457   /* If the linker is doing the relaxing, we must not do any fixups.
2458
2459      Well, strictly speaking that's not true -- we could do any that are
2460      PC-relative and don't cross regions that could change size.  And for the
2461      i960 (the only machine for which we've got a relaxing linker right now),
2462      we might be able to turn callx/callj into bal anyways in cases where we
2463      know the maximum displacement.  */
2464   if (linkrelax)
2465     {
2466       for (; fixP; fixP = fixP->fx_next)
2467         seg_reloc_count++;
2468       TC_ADJUST_RELOC_COUNT (fixP, seg_reloc_count);
2469       return seg_reloc_count;
2470     }
2471
2472   for (; fixP; fixP = fixP->fx_next)
2473     {
2474
2475 #ifdef DEBUG5
2476       fprintf (stderr, "\nprocessing fixup:\n");
2477       print_fixup (fixP);
2478 #endif
2479
2480
2481       fragP = fixP->fx_frag;
2482       know (fragP);
2483       where = fixP->fx_where;
2484       place = fragP->fr_literal + where;
2485       size = fixP->fx_size;
2486       add_symbolP = fixP->fx_addsy;
2487 #ifdef TC_VALIDATE_FIX
2488       TC_VALIDATE_FIX (fixP, this_segment_type, skip);
2489 #endif
2490       sub_symbolP = fixP->fx_subsy;
2491       add_number = fixP->fx_offset;
2492       pcrel = fixP->fx_pcrel;
2493       plt = fixP->fx_plt;
2494
2495       if (add_symbolP != NULL
2496           && symbol_mri_common_p (add_symbolP))
2497         {
2498           know (add_symbolP->sy_value.X_op == O_symbol);
2499           add_number += S_GET_VALUE (add_symbolP);
2500           fixP->fx_offset = add_number;
2501           add_symbolP = fixP->fx_addsy =
2502             symbol_get_value_expression (add_symbolP)->X_add_symbol;
2503         }
2504
2505       if (add_symbolP)
2506         add_symbol_segment = S_GET_SEGMENT (add_symbolP);
2507
2508       if (sub_symbolP)
2509         {
2510           resolve_symbol_value (sub_symbolP, 1);
2511           if (add_symbolP == NULL || add_symbol_segment == absolute_section)
2512             {
2513               if (add_symbolP != NULL)
2514                 {
2515                   add_number += S_GET_VALUE (add_symbolP);
2516                   add_symbolP = NULL;
2517                   fixP->fx_addsy = NULL;
2518                 }
2519
2520               /* It's just -sym */
2521               if (S_GET_SEGMENT (sub_symbolP) == absolute_section)
2522                 {
2523                   add_number -= S_GET_VALUE (sub_symbolP);
2524                   fixP->fx_subsy = NULL;
2525                 }
2526               else if (pcrel
2527                        && S_GET_SEGMENT (sub_symbolP) == this_segment_type)
2528                 {
2529                   /* Should try converting to a constant.  */
2530                   goto bad_sub_reloc;
2531                 }
2532               else
2533               bad_sub_reloc:
2534                 as_bad_where (fixP->fx_file, fixP->fx_line,
2535                               _("Negative of non-absolute symbol %s"),
2536                               S_GET_NAME (sub_symbolP));
2537             }
2538           else if (S_GET_SEGMENT (sub_symbolP) == add_symbol_segment
2539                    && SEG_NORMAL (add_symbol_segment))
2540             {
2541               /* Difference of 2 symbols from same segment.
2542                  Can't make difference of 2 undefineds: 'value' means
2543                  something different for N_UNDF. */
2544 #ifdef TC_I960
2545               /* Makes no sense to use the difference of 2 arbitrary symbols
2546                  as the target of a call instruction.  */
2547               if (fixP->fx_tcbit)
2548                 as_bad_where (fixP->fx_file, fixP->fx_line,
2549                               _("callj to difference of 2 symbols"));
2550 #endif /* TC_I960 */
2551               add_number += S_GET_VALUE (add_symbolP) -
2552                 S_GET_VALUE (sub_symbolP);
2553
2554               add_symbolP = NULL;
2555               pcrel = 0;        /* No further pcrel processing. */
2556
2557               /* Let the target machine make the final determination
2558                  as to whether or not a relocation will be needed to
2559                  handle this fixup.  */
2560               if (!TC_FORCE_RELOCATION_SECTION (fixP, this_segment_type))
2561                 {
2562                   fixP->fx_pcrel = 0;
2563                   fixP->fx_addsy = NULL;
2564                   fixP->fx_subsy = NULL;
2565                 }
2566             }
2567           else
2568             {
2569               /* Different segments in subtraction. */
2570               know (!(S_IS_EXTERNAL (sub_symbolP)
2571                       && (S_GET_SEGMENT (sub_symbolP) == absolute_section)));
2572
2573               if ((S_GET_SEGMENT (sub_symbolP) == absolute_section))
2574                 add_number -= S_GET_VALUE (sub_symbolP);
2575
2576 #ifdef DIFF_EXPR_OK
2577               else if (S_GET_SEGMENT (sub_symbolP) == this_segment_type
2578 #if 0 /* Do this even if it's already described as pc-relative.  For example,
2579          on the m68k, an operand of "pc@(foo-.-2)" should address "foo" in a
2580          pc-relative mode.  */
2581                        && pcrel
2582 #endif
2583                        )
2584                 {
2585                   /* Make it pc-relative.  */
2586                   add_number += (MD_PCREL_FROM_SECTION (fixP, this_segment_type)
2587                                  - S_GET_VALUE (sub_symbolP));
2588                   pcrel = 1;
2589                   fixP->fx_pcrel = 1;
2590                   sub_symbolP = 0;
2591                   fixP->fx_subsy = 0;
2592                 }
2593 #endif
2594 #ifdef UNDEFINED_DIFFERENCE_OK
2595               /* The PA needs this for PIC code generation.  We basically
2596                  don't want to do anything if we have the difference of two
2597                  symbols at this point.  */
2598               else if (1)
2599                 {
2600                   /* Leave it alone.  */
2601                 }
2602 #endif
2603 #ifdef BFD_ASSEMBLER
2604               else if (fixP->fx_r_type == BFD_RELOC_GPREL32
2605                        || fixP->fx_r_type == BFD_RELOC_GPREL16)
2606                 {
2607                   /* Leave it alone.  */
2608                 }
2609 #endif
2610               else
2611                 {
2612                   char buf[50];
2613                   sprint_value (buf, fragP->fr_address + where);
2614                   as_bad_where (fixP->fx_file, fixP->fx_line,
2615                                 _("Subtraction of two symbols in different sections \"%s\" {%s section} - \"%s\" {%s section} at file address %s."),
2616                                 S_GET_NAME (add_symbolP),
2617                                 segment_name (S_GET_SEGMENT (add_symbolP)),
2618                                 S_GET_NAME (sub_symbolP),
2619                                 segment_name (S_GET_SEGMENT (sub_symbolP)),
2620                                 buf);
2621                 }
2622             }
2623         }
2624
2625       if (add_symbolP)
2626         {
2627           if (add_symbol_segment == this_segment_type && pcrel && !plt
2628               && TC_RELOC_RTSYM_LOC_FIXUP (fixP))
2629             {
2630               /*
2631                * This fixup was made when the symbol's segment was
2632                * SEG_UNKNOWN, but it is now in the local segment.
2633                * So we know how to do the address without relocation.
2634                */
2635 #ifdef TC_I960
2636               /* reloc_callj() may replace a 'call' with a 'calls' or a
2637                  'bal', in which cases it modifies *fixP as appropriate.
2638                  In the case of a 'calls', no further work is required,
2639                  and *fixP has been set up to make the rest of the code
2640                  below a no-op. */
2641               reloc_callj (fixP);
2642 #endif /* TC_I960 */
2643
2644               add_number += S_GET_VALUE (add_symbolP);
2645               add_number -= MD_PCREL_FROM_SECTION (fixP, this_segment_type);
2646               pcrel = 0;        /* Lie. Don't want further pcrel processing. */
2647
2648               /* Let the target machine make the final determination
2649                  as to whether or not a relocation will be needed to
2650                  handle this fixup.  */
2651               if (!TC_FORCE_RELOCATION (fixP))
2652                 {
2653                   fixP->fx_pcrel = 0;
2654                   fixP->fx_addsy = NULL;
2655                 }
2656             }
2657           else
2658             {
2659               if (add_symbol_segment == absolute_section
2660                   && ! pcrel)
2661                 {
2662 #ifdef TC_I960
2663                   /* See comment about reloc_callj() above.  */
2664                   reloc_callj (fixP);
2665 #endif /* TC_I960 */
2666                   add_number += S_GET_VALUE (add_symbolP);
2667
2668                   /* Let the target machine make the final determination
2669                      as to whether or not a relocation will be needed to
2670                      handle this fixup.  */
2671
2672                   if (!TC_FORCE_RELOCATION (fixP))
2673                     {
2674                       fixP->fx_addsy = NULL;
2675                       add_symbolP = NULL;
2676                     }
2677                 }
2678               else if (add_symbol_segment == undefined_section
2679 #ifdef BFD_ASSEMBLER
2680                        || bfd_is_com_section (add_symbol_segment)
2681 #endif
2682                        )
2683                 {
2684 #ifdef TC_I960
2685                   if ((int) fixP->fx_bit_fixP == 13)
2686                     {
2687                       /* This is a COBR instruction.  They have only a
2688                        * 13-bit displacement and are only to be used
2689                        * for local branches: flag as error, don't generate
2690                        * relocation.
2691                        */
2692                       as_bad_where (fixP->fx_file, fixP->fx_line,
2693                                     _("can't use COBR format with external label"));
2694                       fixP->fx_addsy = NULL;
2695                       fixP->fx_done = 1;
2696                       continue;
2697                     }           /* COBR */
2698 #endif /* TC_I960 */
2699
2700 #ifdef OBJ_COFF
2701 #ifdef TE_I386AIX
2702                   if (S_IS_COMMON (add_symbolP))
2703                     add_number += S_GET_VALUE (add_symbolP);
2704 #endif /* TE_I386AIX */
2705 #endif /* OBJ_COFF */
2706                   ++seg_reloc_count;
2707                 }
2708               else
2709                 {
2710                   seg_reloc_count++;
2711 #if !(defined (TC_V850) && defined (OBJ_ELF))
2712 #if !(defined (TC_M68K) && defined (OBJ_ELF))
2713 #if !(defined (TC_ARM)  && defined (OBJ_ELF))
2714 #if !(defined (TC_I960) && defined (OBJ_ELF))
2715 #if !defined (TC_I386) || !(defined (OBJ_ELF) || defined (OBJ_COFF)) || defined (TE_PE)
2716                   add_number += S_GET_VALUE (add_symbolP);
2717 #endif
2718 #endif
2719 #endif
2720 #endif
2721 #endif
2722                 }
2723             }
2724         }
2725
2726       if (pcrel)
2727         {
2728           add_number -= MD_PCREL_FROM_SECTION (fixP, this_segment_type);
2729           if (add_symbolP == 0)
2730             {
2731 #ifndef BFD_ASSEMBLER
2732               fixP->fx_addsy = &abs_symbol;
2733 #else
2734               fixP->fx_addsy = section_symbol (absolute_section);
2735 #endif
2736               symbol_mark_used_in_reloc (fixP->fx_addsy);
2737               ++seg_reloc_count;
2738             }
2739         }
2740
2741       if (!fixP->fx_done)
2742         {
2743 #ifdef MD_APPLY_FIX3
2744           md_apply_fix3 (fixP, &add_number, this_segment_type);
2745 #else
2746 #ifdef BFD_ASSEMBLER
2747           md_apply_fix (fixP, &add_number);
2748 #else
2749           md_apply_fix (fixP, add_number);
2750 #endif
2751 #endif
2752
2753 #ifndef TC_HANDLES_FX_DONE
2754           /* If the tc-* files haven't been converted, assume it's handling
2755              it the old way, where a null fx_addsy means that the fix has
2756              been applied completely, and no further work is needed.  */
2757           if (fixP->fx_addsy == 0 && fixP->fx_pcrel == 0)
2758             fixP->fx_done = 1;
2759 #endif
2760         }
2761
2762       if (!fixP->fx_bit_fixP && !fixP->fx_no_overflow && size > 0)
2763         {
2764           if ((size_t) size < sizeof (valueT))
2765             {
2766               valueT mask;
2767
2768               mask = 0;
2769               mask--;           /* set all bits to one */
2770               mask <<= size * 8 - (fixP->fx_signed ? 1 : 0);
2771               if ((add_number & mask) != 0 && (add_number & mask) != mask)
2772                 {
2773                   char buf[50], buf2[50];
2774                   sprint_value (buf, fragP->fr_address + where);
2775                   if (add_number > 1000)
2776                     sprint_value (buf2, add_number);
2777                   else
2778                     sprintf (buf2, "%ld", (long) add_number);
2779                   as_bad_where (fixP->fx_file, fixP->fx_line,
2780                                 _("Value of %s too large for field of %d bytes at %s"),
2781                                 buf2, size, buf);
2782                 } /* generic error checking */
2783             }
2784 #ifdef WARN_SIGNED_OVERFLOW_WORD
2785           /* Warn if a .word value is too large when treated as a signed
2786              number.  We already know it is not too negative.  This is to
2787              catch over-large switches generated by gcc on the 68k.  */
2788           if (!flag_signed_overflow_ok
2789               && size == 2
2790               && add_number > 0x7fff)
2791             as_bad_where (fixP->fx_file, fixP->fx_line,
2792                           _("Signed .word overflow; switch may be too large; %ld at 0x%lx"),
2793                           (long) add_number,
2794                           (unsigned long) (fragP->fr_address + where));
2795 #endif
2796         }                       /* not a bit fix */
2797
2798 #ifdef TC_VALIDATE_FIX
2799     skip:  ATTRIBUTE_UNUSED_LABEL
2800       ;
2801 #endif
2802 #ifdef DEBUG5
2803       fprintf (stderr, "result:\n");
2804       print_fixup (fixP);
2805 #endif
2806     }                           /* For each fixS in this segment. */
2807
2808   TC_ADJUST_RELOC_COUNT (fixP, seg_reloc_count);
2809   return seg_reloc_count;
2810 }
2811
2812 #endif /* defined (BFD_ASSEMBLER) || (!defined (BFD) && !defined (OBJ_VMS)) */
2813
2814 void
2815 number_to_chars_bigendian (buf, val, n)
2816      char *buf;
2817      valueT val;
2818      int n;
2819 {
2820   if ((size_t) n > sizeof (val) || n <= 0)
2821     abort ();
2822   while (n--)
2823     {
2824       buf[n] = val & 0xff;
2825       val >>= 8;
2826     }
2827 }
2828
2829 void
2830 number_to_chars_littleendian (buf, val, n)
2831      char *buf;
2832      valueT val;
2833      int n;
2834 {
2835   if ((size_t) n > sizeof (val) || n <= 0)
2836     abort ();
2837   while (n--)
2838     {
2839       *buf++ = val & 0xff;
2840       val >>= 8;
2841     }
2842 }
2843
2844 void
2845 write_print_statistics (file)
2846      FILE *file;
2847 {
2848   fprintf (file, "fixups: %d\n", n_fixups);
2849 }
2850
2851 /* for debugging */
2852 extern int indent_level;
2853
2854 void
2855 print_fixup (fixp)
2856      fixS *fixp;
2857 {
2858   indent_level = 1;
2859   fprintf (stderr, "fix %lx %s:%d", (long) fixp, fixp->fx_file, fixp->fx_line);
2860   if (fixp->fx_pcrel)
2861     fprintf (stderr, " pcrel");
2862   if (fixp->fx_pcrel_adjust)
2863     fprintf (stderr, " pcrel_adjust=%d", fixp->fx_pcrel_adjust);
2864   if (fixp->fx_im_disp)
2865     {
2866 #ifdef TC_NS32K
2867       fprintf (stderr, " im_disp=%d", fixp->fx_im_disp);
2868 #else
2869       fprintf (stderr, " im_disp");
2870 #endif
2871     }
2872   if (fixp->fx_tcbit)
2873     fprintf (stderr, " tcbit");
2874   if (fixp->fx_done)
2875     fprintf (stderr, " done");
2876   fprintf (stderr, "\n    size=%d frag=%lx where=%ld offset=%lx addnumber=%lx",
2877            fixp->fx_size, (long) fixp->fx_frag, (long) fixp->fx_where,
2878            (long) fixp->fx_offset, (long) fixp->fx_addnumber);
2879 #ifdef BFD_ASSEMBLER
2880   fprintf (stderr, "\n    %s (%d)", bfd_get_reloc_code_name (fixp->fx_r_type),
2881            fixp->fx_r_type);
2882 #else
2883 #ifdef NEED_FX_R_TYPE
2884   fprintf (stderr, " r_type=%d", fixp->fx_r_type);
2885 #endif
2886 #endif
2887   if (fixp->fx_addsy)
2888     {
2889       fprintf (stderr, "\n   +<");
2890       print_symbol_value_1 (stderr, fixp->fx_addsy);
2891       fprintf (stderr, ">");
2892     }
2893   if (fixp->fx_subsy)
2894     {
2895       fprintf (stderr, "\n   -<");
2896       print_symbol_value_1 (stderr, fixp->fx_subsy);
2897       fprintf (stderr, ">");
2898     }
2899   fprintf (stderr, "\n");
2900 #ifdef TC_FIX_DATA_PRINT
2901   TC_FIX_DATA_PRINT (stderr, fixp);
2902 #endif
2903 }
2904
2905 /* end of write.c */