* write.c (write_contents): Compute the relocs before writing out
[external/binutils.git] / gas / write.c
1 /* write.c - emit .o file
2    Copyright (C) 1986, 1987, 1990, 1991, 1992, 1993 Free Software Foundation, Inc.
3
4    This file is part of GAS, the GNU Assembler.
5
6    GAS is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 2, or (at your option)
9    any later version.
10
11    GAS is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with GAS; see the file COPYING.  If not, write to
18    the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */
19
20 /* This thing should be set up to do byteordering correctly.  But... */
21
22 #include "as.h"
23 #include "subsegs.h"
24 #include "obstack.h"
25 #include "output-file.h"
26
27 /* The NOP_OPCODE is for the alignment fill value.  Fill it with a nop
28    instruction so that the disassembler does not choke on it.  */
29 #ifndef NOP_OPCODE
30 #define NOP_OPCODE 0x00
31 #endif
32
33 #ifndef WORKING_DOT_WORD
34 extern CONST int md_short_jump_size;
35 extern CONST int md_long_jump_size;
36 #endif
37
38 #ifndef BFD_ASSEMBLER
39
40 #ifndef MANY_SEGMENTS
41 struct frag *text_frag_root;
42 struct frag *data_frag_root;
43 struct frag *bss_frag_root;
44
45 struct frag *text_last_frag;    /* Last frag in segment. */
46 struct frag *data_last_frag;    /* Last frag in segment. */
47 static struct frag *bss_last_frag;      /* Last frag in segment. */
48 #endif
49
50 static object_headers headers;
51
52 long string_byte_count;
53
54 static char *the_object_file;
55
56 char *next_object_file_charP;   /* Tracks object file bytes. */
57
58 #ifndef OBJ_VMS
59 int magic_number_for_object_file = DEFAULT_MAGIC_NUMBER_FOR_OBJECT_FILE;
60 #endif
61
62 #endif /* BFD_ASSEMBLER */
63
64 static long fixup_segment PARAMS ((fixS * fixP, segT this_segment_type));
65 static relax_addressT relax_align PARAMS ((relax_addressT addr, long align));
66 void relax_segment PARAMS ((struct frag * seg_frag_root, segT seg_type));
67
68 /*
69  *                      fix_new()
70  *
71  * Create a fixS in obstack 'notes'.
72  */
73 fixS *
74 fix_new (frag, where, size, add_symbol, sub_symbol, offset, pcrel, r_type)
75      fragS *frag;               /* Which frag? */
76      int where;                 /* Where in that frag? */
77      short int size;            /* 1, 2, or 4 usually. */
78      symbolS *add_symbol;       /* X_add_symbol. */
79      symbolS *sub_symbol;       /* X_subtract_symbol. */
80      long offset;               /* X_add_number. */
81      int pcrel;                 /* TRUE if PC-relative relocation. */
82 #ifdef BFD_ASSEMBLER
83      bfd_reloc_code_real_type r_type; /* Relocation type */
84 #else
85      int r_type;                /* Relocation type */
86 #endif
87 {
88   fixS *fixP;
89
90   fixP = (fixS *) obstack_alloc (&notes, sizeof (fixS));
91
92   fixP->fx_frag = frag;
93   fixP->fx_where = where;
94   fixP->fx_size = size;
95   fixP->fx_addsy = add_symbol;
96   fixP->fx_subsy = sub_symbol;
97   fixP->fx_offset = offset;
98   fixP->fx_pcrel = pcrel;
99 #if defined(NEED_FX_R_TYPE) || defined (BFD_ASSEMBLER)
100   fixP->fx_r_type = r_type;
101 #endif
102   fixP->fx_im_disp = 0;
103   fixP->fx_pcrel_adjust = 0;
104   fixP->fx_bit_fixP = 0;
105   fixP->fx_addnumber = 0;
106
107 #ifdef TC_something
108   fixP->fx_bsr = 0;
109 #endif
110 #ifdef TC_I960
111   fixP->fx_callj = 0;
112 #endif
113
114   /* Usually, we want relocs sorted numerically, but while
115      comparing to older versions of gas that have relocs
116      reverse sorted, it is convenient to have this compile
117      time option.  xoxorich. */
118
119   {
120
121 #ifdef BFD_ASSEMBLER
122     fixS **seg_fix_rootP = & (seg_info (now_seg)->fix_root);
123     fixS **seg_fix_tailP = & (seg_info (now_seg)->fix_tail);
124 #endif
125
126 #ifdef REVERSE_SORT_RELOCS
127
128     fixP->fx_next = *seg_fix_rootP;
129     *seg_fix_rootP = fixP;
130
131 #else /* REVERSE_SORT_RELOCS */
132
133     fixP->fx_next = NULL;
134
135     if (*seg_fix_tailP)
136       (*seg_fix_tailP)->fx_next = fixP;
137     else
138       *seg_fix_rootP = fixP;
139     *seg_fix_tailP = fixP;
140
141 #endif /* REVERSE_SORT_RELOCS */
142
143   }
144
145   return fixP;
146 }
147
148 /* Append a string onto another string, bumping the pointer along.  */
149 void
150 append (charPP, fromP, length)
151      char **charPP;
152      char *fromP;
153      unsigned long length;
154 {
155   /* Don't trust memcpy() of 0 chars. */
156   if (length == 0)
157     return;
158
159   memcpy (*charPP, fromP, (int) length);
160   *charPP += length;
161 }
162
163 #ifndef BFD_ASSEMBLER 
164 int section_alignment[SEG_MAXIMUM_ORDINAL];
165 #endif
166
167 /*
168  * This routine records the largest alignment seen for each segment.
169  * If the beginning of the segment is aligned on the worst-case
170  * boundary, all of the other alignments within it will work.  At
171  * least one object format really uses this info.
172  */
173 void 
174 record_alignment (seg, align)
175      /* Segment to which alignment pertains */
176      segT seg;
177      /* Alignment, as a power of 2 (e.g., 1 => 2-byte boundary, 2 => 4-byte
178         boundary, etc.)  */
179      int align;
180 {
181 #ifdef BFD_ASSEMBLER
182   if (align > bfd_get_section_alignment (stdoutput, seg))
183     bfd_set_section_alignment (stdoutput, seg, align);
184 #else
185   if (align > section_alignment[(int) seg])
186     section_alignment[(int) seg] = align;
187 #endif
188 }
189
190 #if defined (BFD_ASSEMBLER) || ! defined (BFD)
191
192 static fragS *
193 chain_frchains_together_1 (section, frchp)
194      segT section;
195      struct frchain *frchp;
196 {
197   fragS dummy, *prev_frag = &dummy;
198   for (; frchp && frchp->frch_seg == section; frchp = frchp->frch_next)
199     {
200       prev_frag->fr_next = frchp->frch_root;
201       prev_frag = frchp->frch_last;
202     }
203   prev_frag->fr_next = 0;
204   return prev_frag;
205 }
206
207 #endif
208
209 #ifdef BFD_ASSEMBLER
210
211 static void
212 chain_frchains_together (abfd, section, xxx)
213      bfd *abfd;                 /* unused */
214      segT section;
215      char *xxx;                 /* unused */
216 {
217   segment_info_type *info;
218
219   /* BFD may have introduced its own sections without using
220      subseg_new, so it is possible that seg_info is NULL.  */
221   info = seg_info (section);
222   if (info != (segment_info_type *) NULL)
223     chain_frchains_together_1 (section, info->frchainP);
224 }
225
226 #endif
227
228 #ifndef BFD
229
230 void 
231 remove_subsegs (head, seg, root, last)
232      frchainS *head;
233      int seg;
234      fragS **root;
235      fragS **last;
236 {
237   *root = head->frch_root;
238   *last = chain_frchains_together_1 (seg, head);
239 }
240
241 #endif /* BFD */
242
243 #ifndef BFD
244
245 static void
246 cvt_frag_to_fill (x, fragP)
247 #ifdef BFD_ASSEMBLER
248      segT x;
249 #else
250      object_headers *x;
251 #endif
252      fragS *fragP;
253 {
254 #ifdef BFD_ASSEMBLER
255   segT sec = x;
256 #else
257   object_headers *headers = x;
258 #endif
259
260   switch (fragP->fr_type)
261     {
262     case rs_align:
263     case rs_org:
264 #ifdef HANDLE_ALIGN
265       HANDLE_ALIGN (fragP);
266 #endif
267       fragP->fr_type = rs_fill;
268       know (fragP->fr_var == 1);
269       know (fragP->fr_next != NULL);
270
271       fragP->fr_offset = (fragP->fr_next->fr_address
272                           - fragP->fr_address
273                           - fragP->fr_fix);
274       break;
275
276     case rs_fill:
277       break;
278
279     case rs_machine_dependent:
280 #ifdef BFD_ASSEMBLER
281       md_convert_frag (stdoutput, sec, fragP);
282 #else
283       md_convert_frag (headers, fragP);
284 #endif
285
286       assert (fragP->fr_next == NULL \
287               || (fragP->fr_next->fr_address - fragP->fr_address \
288                   == fragP->fr_fix));
289
290       /*
291        * After md_convert_frag, we make the frag into a ".space 0".
292        * Md_convert_frag() should set up any fixSs and constants
293        * required.
294        */
295       frag_wane (fragP);
296       break;
297
298 #ifndef WORKING_DOT_WORD
299     case rs_broken_word:
300       {
301         struct broken_word *lie;
302
303         if (fragP->fr_subtype)
304           {
305             fragP->fr_fix += md_short_jump_size;
306             for (lie = (struct broken_word *) (fragP->fr_symbol);
307                  lie && lie->dispfrag == fragP;
308                  lie = lie->next_broken_word)
309               if (lie->added == 1)
310                 fragP->fr_fix += md_long_jump_size;
311           }
312         frag_wane (fragP);
313       }
314       break;
315 #endif
316
317     default:
318       BAD_CASE (fragP->fr_type);
319       break;
320     }
321 }
322
323 #ifdef BFD_ASSEMBLER
324 static void
325 relax_and_size_seg (abfd, sec, xxx)
326      bfd *abfd;
327      asection *sec;
328      char *xxx;
329 {
330   flagword flags;
331
332   flags = bfd_get_section_flags (abfd, sec);
333
334   if (flags & SEC_ALLOC)
335     {
336       fragS *fragp;
337       segment_info_type *seginfo;
338       int x;
339       unsigned long size, newsize;
340
341       seginfo = (segment_info_type *) bfd_get_section_userdata (abfd, sec);
342       relax_segment (seginfo->frchainP->frch_root, sec);
343       for (fragp = seginfo->frchainP->frch_root; fragp; fragp = fragp->fr_next)
344         cvt_frag_to_fill (sec, fragp);
345       for (fragp = seginfo->frchainP->frch_root;
346            fragp->fr_next;
347            fragp = fragp->fr_next)
348         /* walk to last elt */;
349       size = fragp->fr_address;
350       if (size > 0)
351         {
352           flags |= SEC_HAS_CONTENTS;
353           /* @@ This is just an approximation.  */
354           if (seginfo->fix_root)
355             flags |= SEC_RELOC;
356           x = bfd_set_section_flags (abfd, sec, flags);
357           assert (x == true);
358         }
359       size = md_section_align (sec, size);
360       x = bfd_set_section_size (abfd, sec, size);
361       assert (x == true);
362
363       /* If the size had to be rounded up, add some padding in the last
364          non-empty frag.  */
365       newsize = bfd_get_section_size_before_reloc (sec);
366       assert (newsize >= size);
367       if (size != newsize)
368         {
369           fragS *last = seginfo->frchainP->frch_last;
370           fragp = seginfo->frchainP->frch_root;
371           while (fragp->fr_next != last)
372             fragp = fragp->fr_next;
373           last->fr_address = size;
374           fragp->fr_offset += newsize - size;
375         }
376     }
377 #ifdef tc_frob_section
378   tc_frob_section (sec);
379 #endif
380 #ifdef obj_frob_section
381   obj_frob_section (sec);
382 #endif
383 }
384
385 static void
386 write_contents (abfd, sec, xxx)
387      bfd *abfd;
388      asection *sec;
389      char *xxx;
390 {
391   segment_info_type *seginfo = seg_info (sec);
392   unsigned long offset = 0;
393   fragS *frags;
394   int i, n;
395   arelent **relocs;
396   fixS *fixp;
397
398   if (! (bfd_get_section_flags (abfd, sec) & SEC_LOAD))
399     return;
400
401   fixup_segment (seginfo->fix_root, sec);
402
403   n = 0;
404   for (i = 0, fixp = seginfo->fix_root; fixp; fixp = fixp->fx_next)
405     {
406       n++;
407       if (fixp->fx_addsy)
408         {
409           symbolS *sym = fixp->fx_addsy;
410           asection *sec = sym->bsym->section;
411           if (sec == &bfd_und_section
412               || sec == &bfd_abs_section
413               || sec == &bfd_com_section)
414             continue;
415           if (sym->bsym == sec->symbol)
416             continue;
417           /* If the section symbol isn't going to be output, the relocs
418              at least should still work.  If not, figure out what to do
419              when we run into that case.  */
420           fixp->fx_offset += S_GET_VALUE (sym);
421           fixp->fx_addsy = symbol_find (sec->name);
422           if (!fixp->fx_addsy)
423             {
424               fixp->fx_addsy = symbol_make (sec->name);
425               fixp->fx_addsy->bsym = sec->symbol;
426             }
427         }
428     }
429
430   /* Force calculations (size, vma) to get done.  */
431   bfd_set_section_contents (stdoutput, sec, "", 0, 0);
432
433   /* Set up reloc information as well.  */
434   relocs = (arelent **) bfd_alloc_by_size_t (stdoutput,
435                                              n * sizeof (arelent *));
436
437   i = 0;
438   for (fixp = seginfo->fix_root; fixp != (fixS *) NULL; fixp = fixp->fx_next)
439     {
440       arelent *reloc;
441       extern arelent *tc_gen_reloc ();
442       char *data;
443       bfd_reloc_status_type s;
444
445       if (fixp->fx_addsy == 0)
446         {
447           /* @@ Need some other flag to indicate which have already
448              been performed...  */
449           n--;
450           continue;
451         }
452       reloc = tc_gen_reloc (sec, fixp);
453       if (!reloc)
454         {
455           n--;
456           continue;
457         }
458       data = fixp->fx_frag->fr_literal + fixp->fx_where;
459       if (fixp->fx_where + 4
460           > fixp->fx_frag->fr_fix + fixp->fx_frag->fr_offset)
461         abort ();
462       s = bfd_perform_relocation (stdoutput, reloc, data - reloc->address,
463                                   sec, stdoutput);
464       switch (s)
465         {
466         case bfd_reloc_ok:
467           break;
468         default:
469           as_fatal ("bad return from bfd_perform_relocation");
470         }
471       relocs[i++] = reloc;
472     }
473       
474   if (n)
475     bfd_set_reloc (stdoutput, sec, relocs, n);
476
477   /* Write out the frags.  */
478   for (frags = seginfo->frchainP->frch_root;
479        frags;
480        frags = frags->fr_next)
481     {
482       int x;
483       unsigned long fill_size;
484       char *fill_literal;
485       long count;
486
487       assert (frags->fr_type == rs_fill);
488       if (frags->fr_fix)
489         {
490           x = bfd_set_section_contents (stdoutput, sec,
491                                         frags->fr_literal, offset,
492                                         frags->fr_fix);
493           assert (x == true);
494           offset += frags->fr_fix;
495         }
496       fill_literal = frags->fr_literal + frags->fr_fix;
497       fill_size = frags->fr_var;
498       count = frags->fr_offset;
499       assert (count >= 0);
500       if (fill_size && count)
501         while (count--)
502           {
503             x = bfd_set_section_contents (stdoutput, sec,
504                                           fill_literal, offset, fill_size);
505             assert (x == true);
506             offset += fill_size;
507           }
508     }
509 }
510 #endif
511
512 void 
513 write_object_file ()
514 {
515   register struct frchain *frchainP;    /* Track along all frchains. */
516   register fragS *fragP;        /* Track along all frags. */
517   register struct frchain *next_frchainP;
518   register fragS **prev_fragPP;
519
520   long object_file_size;
521
522   /* Do we really want to write it?  */
523   {
524     int n_warns, n_errs;
525     n_warns = had_warnings ();
526     n_errs = had_errors ();
527     /* The -Z flag indicates that an object file should be generated,
528        regardless of warnings and errors.  */
529     if (flagseen['Z'])
530       {
531         if (n_warns || n_errs)
532           as_warn ("%d error%s, %d warning%s, generating bad object file.\n",
533                    n_errs, n_errs == 1 ? "" : "s",
534                    n_warns, n_warns == 1 ? "" : "s");
535       }
536     else
537       {
538         if (n_errs)
539           as_fatal ("%d error%s, %d warning%s, no object file generated.\n",
540                     n_errs, n_errs == 1 ? "" : "s",
541                     n_warns, n_warns == 1 ? "" : "s");
542       }
543   }
544
545 #ifdef  OBJ_VMS
546   /*
547    *    Under VMS we try to be compatible with VAX-11 "C".  Thus, we
548    *    call a routine to check for the definition of the procedure
549    *    "_main", and if so -- fix it up so that it can be program
550    *    entry point.
551    */
552   VMS_Check_For_Main ();
553 #endif /* VMS */
554
555   /* After every sub-segment, we fake an ".align ...". This conforms to
556      BSD4.2 brane-damage. We then fake ".fill 0" because that is the kind of
557      frag that requires least thought. ".align" frags like to have a
558      following frag since that makes calculating their intended length
559      trivial.
560
561      @@ Is this really necessary??  */
562 #ifndef SUB_SEGMENT_ALIGN
563 #ifdef BFD_ASSEMBLER
564 #define SUB_SEGMENT_ALIGN(SEG) (0)
565 #else
566 #define SUB_SEGMENT_ALIGN(SEG) (2)
567 #endif
568 #endif
569   for (frchainP = frchain_root; frchainP; frchainP = frchainP->frch_next)
570     {
571 #ifdef BFD_ASSEMBLER
572       subseg_set (frchainP->frch_seg, frchainP->frch_subseg);
573 #else
574       subseg_new (frchainP->frch_seg, frchainP->frch_subseg);
575 #endif
576       frag_align (SUB_SEGMENT_ALIGN (now_seg), NOP_OPCODE);
577       /* frag_align will have left a new frag.
578          Use this last frag for an empty ".fill".
579
580          For this segment ...
581          Create a last frag. Do not leave a "being filled in frag".  */
582       frag_wane (frag_now);
583       frag_now->fr_fix = 0;
584       know (frag_now->fr_next == NULL);
585       /* know( frags . obstack_c_base == frags . obstack_c_next_free ); */
586       /* Above shows we haven't left a half-completed object on obstack. */
587     }
588
589   /* From now on, we don't care about sub-segments.  Build one frag chain
590      for each segment. Linked thru fr_next.  */
591
592 #ifdef BFD_ASSEMBLER
593   /* Remove the sections created by gas for its own purposes.  */
594   {
595     asection **seclist, *sec;
596     seclist = &stdoutput->sections;
597     while (seclist && *seclist)
598       {
599         sec = *seclist;
600         while (sec == big_section
601                || sec == reg_section
602                || sec == pass1_section
603                || sec == diff_section
604                || sec == absent_section)
605           {
606             sec = sec->next;
607             *seclist = sec;
608             stdoutput->section_count--;
609             if (!sec)
610               break;
611           }
612         if (*seclist)
613           seclist = &(*seclist)->next;
614       }
615   }
616
617   bfd_map_over_sections (stdoutput, chain_frchains_together, (char *) 0);
618 #else
619   remove_subsegs (frchain_root, SEG_TEXT, &text_frag_root, &text_last_frag);
620   remove_subsegs (data0_frchainP, SEG_DATA, &data_frag_root, &data_last_frag);
621   remove_subsegs (bss0_frchainP, SEG_BSS, &bss_frag_root, &bss_last_frag);
622 #endif
623
624   /* We have two segments. If user gave -R flag, then we must put the
625      data frags into the text segment. Do this before relaxing so
626      we know to take advantage of -R and make shorter addresses.  */
627 #if !defined (OBJ_AOUT) || defined (BFD_ASSEMBLER)
628   if (flagseen['R'])
629     {
630 #ifdef BFD_ASSEMBLER
631       seg_info (text_section)->frchainP->frch_last->fr_next =
632         seg_info (data_section)->frchainP->frch_root;
633       seg_info (text_section)->frchainP->frch_last =
634         seg_info (data_section)->frchainP->frch_last;
635       seg_info (data_section)->frchainP = 0;
636 #else
637       fixS *tmp;
638
639       text_last_frag->fr_next = data_frag_root;
640       text_last_frag = data_last_frag;
641       data_last_frag = NULL;
642       data_frag_root = NULL;
643       if (text_fix_root)
644         {
645           for (tmp = text_fix_root; tmp->fx_next; tmp = tmp->fx_next);;
646           tmp->fx_next = data_fix_root;
647           text_fix_tail = data_fix_tail;
648         }
649       else
650         text_fix_root = data_fix_root;
651       data_fix_root = NULL;
652 #endif
653     }
654 #endif
655
656 #ifdef BFD_ASSEMBLER
657   bfd_map_over_sections (stdoutput, relax_and_size_seg, (char *) 0);
658 #else
659   relax_segment (text_frag_root, SEG_TEXT);
660   relax_segment (data_frag_root, SEG_DATA);
661   relax_segment (bss_frag_root, SEG_BSS);
662   /*
663    * Now the addresses of frags are correct within the segment.
664    */
665
666   know (text_last_frag->fr_type == rs_fill && text_last_frag->fr_offset == 0);
667   H_SET_TEXT_SIZE (&headers, text_last_frag->fr_address);
668   text_last_frag->fr_address = H_GET_TEXT_SIZE (&headers);
669
670   /*
671    * Join the 2 segments into 1 huge segment.
672    * To do this, re-compute every rn_address in the SEG_DATA frags.
673    * Then join the data frags after the text frags.
674    *
675    * Determine a_data [length of data segment].
676    */
677   if (data_frag_root)
678     {
679       register relax_addressT slide;
680
681       know ((text_last_frag->fr_type == rs_fill) && (text_last_frag->fr_offset == 0));
682
683       H_SET_DATA_SIZE (&headers, data_last_frag->fr_address);
684       data_last_frag->fr_address = H_GET_DATA_SIZE (&headers);
685       slide = H_GET_TEXT_SIZE (&headers);       /* & in file of the data segment. */
686 #ifdef OBJ_BOUT
687 #define RoundUp(N,S) (((N)+(S)-1)&-(S))
688       /* For b.out: If the data section has a strict alignment
689          requirement, its load address in the .o file will be
690          rounded up from the size of the text section.  These
691          two values are *not* the same!  Similarly for the bss
692          section....  */
693       slide = RoundUp (slide, 1 << section_alignment[SEG_DATA]);
694 #endif
695
696       for (fragP = data_frag_root; fragP; fragP = fragP->fr_next)
697         {
698           fragP->fr_address += slide;
699         }                       /* for each data frag */
700
701       know (text_last_frag != 0);
702       text_last_frag->fr_next = data_frag_root;
703     }
704   else
705     {
706       H_SET_DATA_SIZE (&headers, 0);
707     }
708
709 #ifdef OBJ_BOUT
710   /* See above comments on b.out data section address.  */
711   {
712     long bss_vma;
713     if (data_last_frag == 0)
714       bss_vma = H_GET_TEXT_SIZE (&headers);
715     else
716       bss_vma = data_last_frag->fr_address;
717     bss_vma = RoundUp (bss_vma, 1 << section_alignment[SEG_BSS]);
718     bss_address_frag.fr_address = bss_vma;
719   }
720 #else /* ! OBJ_BOUT */
721   bss_address_frag.fr_address = (H_GET_TEXT_SIZE (&headers) +
722                                  H_GET_DATA_SIZE (&headers));
723
724
725   /* Slide all the frags */
726   if (bss_frag_root)
727     {
728       relax_addressT slide = bss_address_frag.fr_address;
729
730       for (fragP = bss_frag_root; fragP; fragP = fragP->fr_next)
731         {
732           fragP->fr_address += slide;
733         }                       /* for each bss frag */
734     }
735
736 #endif /* ! OBJ_BOUT */
737
738   if (bss_last_frag)
739     H_SET_BSS_SIZE (&headers,
740                     bss_last_frag->fr_address - bss_frag_root->fr_address);
741   else
742     H_SET_BSS_SIZE (&headers, 0);
743 #endif /* BFD_ASSEMBLER */
744
745 #ifndef BFD_ASSEMBLER
746   /*
747    *
748    * Crawl the symbol chain.
749    *
750    * For each symbol whose value depends on a frag, take the address of
751    * that frag and subsume it into the value of the symbol.
752    * After this, there is just one way to lookup a symbol value.
753    * Values are left in their final state for object file emission.
754    * We adjust the values of 'L' local symbols, even if we do
755    * not intend to emit them to the object file, because their values
756    * are needed for fix-ups.
757    *
758    * Unless we saw a -L flag, remove all symbols that begin with 'L'
759    * from the symbol chain.  (They are still pointed to by the fixes.)
760    *
761    * Count the remaining symbols.
762    * Assign a symbol number to each symbol.
763    * Count the number of string-table chars we will emit.
764    * Put this info into the headers as appropriate.
765    *
766    */
767   know (zero_address_frag.fr_address == 0);
768   string_byte_count = sizeof (string_byte_count);
769
770   obj_crawl_symbol_chain (&headers);
771
772   if (string_byte_count == sizeof (string_byte_count))
773     string_byte_count = 0;
774
775   H_SET_STRING_SIZE (&headers, string_byte_count);
776
777   /*
778    * Addresses of frags now reflect addresses we use in the object file.
779    * Symbol values are correct.
780    * Scan the frags, converting any ".org"s and ".align"s to ".fill"s.
781    * Also converting any machine-dependent frags using md_convert_frag();
782    */
783   subseg_change (SEG_TEXT, 0);
784
785   for (fragP = text_frag_root; fragP; fragP = fragP->fr_next)
786     {
787       cvt_frag_to_fill (&headers, fragP);
788
789       /* Some assert macros don't work with # directives mixed in.  */
790 #ifndef NDEBUG
791       if (!(fragP->fr_next == NULL
792 #ifdef OBJ_BOUT
793             || fragP->fr_next == data_frag_root
794 #endif
795             || ((fragP->fr_next->fr_address - fragP->fr_address)
796                 == (fragP->fr_fix + fragP->fr_offset * fragP->fr_var))))
797         abort ();
798 #endif
799     }
800 #endif /* ! BFD_ASSEMBLER */
801
802 #ifndef WORKING_DOT_WORD
803   {
804     struct broken_word *lie;
805     struct broken_word **prevP;
806
807     prevP = &broken_words;
808     for (lie = broken_words; lie; lie = lie->next_broken_word)
809       if (!lie->added)
810         {
811 #ifdef BFD_ASSEMBLER
812           fix_new (lie->frag, lie->word_goes_here - lie->frag->fr_literal,
813                    2, lie->add, lie->sub, lie->addnum, 0, BFD_RELOC_NONE);
814 #else
815 #if defined(TC_SPARC) || defined(TC_A29K) || defined(NEED_FX_R_TYPE)
816           fix_new (lie->frag, lie->word_goes_here - lie->frag->fr_literal,
817                    2, lie->add,
818                    lie->sub, lie->addnum,
819                    0, NO_RELOC);
820 #else
821 #ifdef TC_NS32K
822           fix_new_ns32k (lie->frag,
823                          lie->word_goes_here - lie->frag->fr_literal,
824                          2,
825                          lie->add,
826                          lie->sub,
827                          lie->addnum,
828                          0, 0, 2, 0, 0);
829 #else
830           fix_new (lie->frag, lie->word_goes_here - lie->frag->fr_literal,
831                    2, lie->add,
832                    lie->sub, lie->addnum,
833                    0, 0);
834 #endif /* TC_NS32K */
835 #endif /* TC_SPARC|TC_A29K|NEED_FX_R_TYPE */
836 #endif /* BFD_ASSEMBLER */
837           *prevP = lie->next_broken_word;
838         }
839       else
840         prevP = &(lie->next_broken_word);
841
842     for (lie = broken_words; lie;)
843       {
844         struct broken_word *untruth;
845         char *table_ptr;
846         long table_addr;
847         long from_addr, to_addr;
848         int n, m;
849
850         fragP = lie->dispfrag;
851
852         /* Find out how many broken_words go here.  */
853         n = 0;
854         for (untruth = lie; untruth && untruth->dispfrag == fragP; untruth = untruth->next_broken_word)
855           if (untruth->added == 1)
856             n++;
857
858         table_ptr = lie->dispfrag->fr_opcode;
859         table_addr = lie->dispfrag->fr_address + (table_ptr - lie->dispfrag->fr_literal);
860         /* Create the jump around the long jumps.  This is a short
861            jump from table_ptr+0 to table_ptr+n*long_jump_size.  */
862         from_addr = table_addr;
863         to_addr = table_addr + md_short_jump_size + n * md_long_jump_size;
864         md_create_short_jump (table_ptr, from_addr, to_addr, lie->dispfrag, lie->add);
865         table_ptr += md_short_jump_size;
866         table_addr += md_short_jump_size;
867
868         for (m = 0; lie && lie->dispfrag == fragP; m++, lie = lie->next_broken_word)
869           {
870             if (lie->added == 2)
871               continue;
872             /* Patch the jump table */
873             /* This is the offset from ??? to table_ptr+0 */
874             to_addr = table_addr
875               - S_GET_VALUE (lie->sub);
876             md_number_to_chars (lie->word_goes_here, to_addr, 2);
877             for (untruth = lie->next_broken_word; untruth && untruth->dispfrag == fragP; untruth = untruth->next_broken_word)
878               {
879                 if (untruth->use_jump == lie)
880                   md_number_to_chars (untruth->word_goes_here, to_addr, 2);
881               }
882
883             /* Install the long jump */
884             /* this is a long jump from table_ptr+0 to the final target */
885             from_addr = table_addr;
886             to_addr = S_GET_VALUE (lie->add) + lie->addnum;
887             md_create_long_jump (table_ptr, from_addr, to_addr, lie->dispfrag, lie->add);
888             table_ptr += md_long_jump_size;
889             table_addr += md_long_jump_size;
890           }
891       }
892   }
893 #endif /* not WORKING_DOT_WORD */
894
895 #ifndef BFD_ASSEMBLER
896 #ifndef OBJ_VMS
897   {                             /* not vms */
898     /*
899      * Scan every FixS performing fixups. We had to wait until now to do
900      * this because md_convert_frag() may have made some fixSs.
901      */
902     int trsize, drsize;
903
904     subseg_change (SEG_TEXT, 0);
905     trsize = md_reloc_size * fixup_segment (text_fix_root,
906                                             SEG_TEXT);
907     subseg_change (SEG_DATA, 0);
908     drsize = md_reloc_size * fixup_segment (data_fix_root,
909                                             SEG_DATA);
910     H_SET_RELOCATION_SIZE (&headers, trsize, drsize);
911
912     /* FIXME move this stuff into the pre-write-hook */
913     H_SET_MAGIC_NUMBER (&headers, magic_number_for_object_file);
914     H_SET_ENTRY_POINT (&headers, 0);
915
916     obj_pre_write_hook (&headers);      /* extra coff stuff */
917
918     object_file_size = H_GET_FILE_SIZE (&headers);
919     next_object_file_charP = the_object_file = xmalloc (object_file_size);
920
921     output_file_create (out_file_name);
922
923     obj_header_append (&next_object_file_charP, &headers);
924
925     know ((next_object_file_charP - the_object_file) == H_GET_HEADER_SIZE (&headers));
926
927     /*
928      * Emit code.
929      */
930     for (fragP = text_frag_root; fragP; fragP = fragP->fr_next)
931       {
932         register long count;
933         register char *fill_literal;
934         register long fill_size;
935
936         know (fragP->fr_type == rs_fill);
937         append (&next_object_file_charP, fragP->fr_literal, (unsigned long) fragP->fr_fix);
938         fill_literal = fragP->fr_literal + fragP->fr_fix;
939         fill_size = fragP->fr_var;
940         know (fragP->fr_offset >= 0);
941
942         for (count = fragP->fr_offset; count; count--)
943           {
944             append (&next_object_file_charP, fill_literal, (unsigned long) fill_size);
945           }                     /* for each  */
946
947       }                         /* for each code frag. */
948
949     know ((next_object_file_charP - the_object_file) == (H_GET_HEADER_SIZE (&headers) + H_GET_TEXT_SIZE (&headers) + H_GET_DATA_SIZE (&headers)));
950
951     /*
952      * Emit relocations.
953      */
954     obj_emit_relocations (&next_object_file_charP, text_fix_root, (relax_addressT) 0);
955     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)));
956 #ifdef TC_I960
957     /* Make addresses in data relocation directives relative to beginning of
958      * first data fragment, not end of last text fragment:  alignment of the
959      * start of the data segment may place a gap between the segments.
960      */
961     obj_emit_relocations (&next_object_file_charP, data_fix_root, data0_frchainP->frch_root->fr_address);
962 #else /* TC_I960 */
963     obj_emit_relocations (&next_object_file_charP, data_fix_root, text_last_frag->fr_address);
964 #endif /* TC_I960 */
965
966     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)));
967
968     /*
969      * Emit line number entries.
970      */
971     OBJ_EMIT_LINENO (&next_object_file_charP, lineno_rootP, the_object_file);
972     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)));
973
974     /*
975      * Emit symbols.
976      */
977     obj_emit_symbols (&next_object_file_charP, symbol_rootP);
978     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)));
979
980     /*
981      * Emit strings.
982      */
983
984     if (string_byte_count > 0)
985       {
986         obj_emit_strings (&next_object_file_charP);
987       }                         /* only if we have a string table */
988
989 #ifdef BFD_HEADERS
990     bfd_seek (stdoutput, 0, 0);
991     bfd_write (the_object_file, 1, object_file_size, stdoutput);
992 #else
993
994     /* Write the data to the file */
995     output_file_append (the_object_file, object_file_size, out_file_name);
996 #endif
997
998     output_file_close (out_file_name);
999   }                             /* non vms output */
1000 #else /* VMS */
1001   /*
1002    *    Now do the VMS-dependent part of writing the object file
1003    */
1004   VMS_write_object_file (H_GET_TEXT_SIZE (&headers),
1005                          H_GET_DATA_SIZE (&headers),
1006                          H_GET_BSS_SIZE (&headers),
1007                          text_frag_root, data_frag_root);
1008 #endif /* VMS */
1009 #else /* BFD_ASSEMBLER */
1010
1011   /* Set up symbol table, and write it out.  */
1012   if (symbol_rootP)
1013     {
1014       int i = 0, n;
1015       symbolS *symp;
1016
1017       for (symp = symbol_rootP; symp; symp = symbol_next (symp))
1018         {
1019           S_SET_VALUE (symp, S_GET_VALUE (symp) + symp->sy_frag->fr_address);
1020           /* So far, common symbols have been treated like undefined symbols.
1021              Put them in the common section now.  */
1022           if (S_IS_DEFINED (symp) == 0
1023               && S_GET_VALUE (symp) != 0)
1024             S_SET_SEGMENT (symp, &bfd_com_section);
1025 #if 0
1026           printf ("symbol `%s'\n\t@%x: value=%d type=%d forward=%x seg=%s\n",
1027                   S_GET_NAME (symp), symp,
1028                   S_GET_VALUE (symp),
1029                   S_GET_DATA_TYPE (symp),
1030                   symp->sy_forward,
1031                   segment_name (symp->bsym->section));
1032 #endif
1033           {
1034             int punt = 0;
1035 #ifdef obj_frob_symbol
1036             obj_frob_symbol (symp, punt);
1037             if (punt)
1038               goto punt_it;
1039 #endif
1040 #ifdef tc_frob_symbol
1041             tc_frob_symbol (symp, punt);
1042             if (punt)
1043               goto punt_it;
1044 #endif
1045           }
1046           /* If we don't want to keep this symbol, splice it out of the
1047              chain now.  */
1048           if (S_IS_LOCAL (symp))
1049             {
1050               symbolS *prev, *next;
1051             punt_it:
1052               prev = symbol_previous (symp);
1053               next = symbol_next (symp);
1054 #ifdef DEBUG
1055               /* debugging: verify consistency */
1056               {
1057                 symbolS *p = symp, *n = symp;
1058                 while (symbol_previous (p))
1059                   p = symbol_previous (p);
1060                 while (symbol_next (n))
1061                   n = symbol_next (n);
1062                 verify_symbol_chain (p, n);
1063               }
1064 #endif
1065               if (prev)
1066                 {
1067                   symbol_next (prev) = next;
1068                   symp = prev;
1069                 }
1070               else
1071                 abort ();
1072               if (next)
1073                 symbol_previous (next) = prev;
1074               else
1075                 symbol_lastP = prev;
1076 #ifdef DEBUG
1077               /* debugging: verify consistency */
1078               {
1079                 symbolS *p = symp, *n = symp;
1080                 while (symbol_previous (p))
1081                   p = symbol_previous (p);
1082                 while (symbol_next (n))
1083                   n = symbol_next (n);
1084                 verify_symbol_chain (p, n);
1085               }
1086 #endif
1087               continue;
1088             }
1089           i++;
1090         }
1091       n = i;
1092       if (n)
1093         {
1094           asymbol **asympp;
1095           boolean result;
1096
1097           asympp = (asymbol **) bfd_alloc (stdoutput, n * sizeof (asymbol *));
1098           symp = symbol_rootP;
1099           for (i = 0; i < n; i++, symp = symbol_next (symp))
1100             {
1101               asympp[i] = symp->bsym;
1102               symp->written = 1;
1103             }
1104           result = bfd_set_symtab (stdoutput, asympp, n);
1105           assert (result == true);
1106         }
1107     }
1108
1109 #ifdef obj_frob_file
1110   obj_frob_file ();
1111 #endif
1112
1113   /* Now that all the sizes are known, and contents correct, we can
1114      start writing the file.  */
1115   bfd_map_over_sections (stdoutput, write_contents, (char *) 0);
1116
1117   output_file_close (out_file_name);
1118 #endif /* BFD_ASSEMBLER */
1119 }
1120 #endif /* BFD */
1121
1122 /*
1123  *                      relax_segment()
1124  *
1125  * Now we have a segment, not a crowd of sub-segments, we can make fr_address
1126  * values.
1127  *
1128  * Relax the frags.
1129  *
1130  * After this, all frags in this segment have addresses that are correct
1131  * within the segment. Since segments live in different file addresses,
1132  * these frag addresses may not be the same as final object-file addresses.
1133  */
1134
1135
1136 static int 
1137 is_dnrange (f1, f2)
1138      struct frag *f1;
1139      struct frag *f2;
1140 {
1141   for (; f1; f1 = f1->fr_next)
1142     if (f1->fr_next == f2)
1143       return 1;
1144   return 0;
1145 }
1146
1147 /* Relax_align. Advance location counter to next address that has 'alignment'
1148    lowest order bits all 0s.  */
1149
1150 /* How many addresses does the .align take? */
1151 static relax_addressT
1152 relax_align (address, alignment)
1153      register relax_addressT address;   /* Address now. */
1154      register long alignment;   /* Alignment (binary). */
1155 {
1156   relax_addressT mask;
1157   relax_addressT new_address;
1158
1159   mask = ~((~0) << alignment);
1160   new_address = (address + mask) & (~mask);
1161   if (linkrelax)
1162     /* We must provide lots of padding, so the linker can discard it
1163        when needed.  The linker will not add extra space, ever.  */
1164     new_address += (1 << alignment);
1165   return (new_address - address);
1166 }
1167
1168 void 
1169 relax_segment (segment_frag_root, segment)
1170      struct frag *segment_frag_root;
1171      segT segment;
1172 {
1173   register struct frag *fragP;
1174   register relax_addressT address;
1175 #if !defined (MANY_SEGMENTS) && !defined (BFD_ASSEMBLER)
1176   know (segment == SEG_DATA || segment == SEG_TEXT || segment == SEG_BSS);
1177 #endif
1178   /* In case md_estimate_size_before_relax() wants to make fixSs. */
1179   subseg_change (segment, 0);
1180
1181   /* For each frag in segment: count and store  (a 1st guess of)
1182      fr_address.  */
1183   address = 0;
1184   for (fragP = segment_frag_root; fragP; fragP = fragP->fr_next)
1185     {
1186       fragP->fr_address = address;
1187       address += fragP->fr_fix;
1188
1189       switch (fragP->fr_type)
1190         {
1191         case rs_fill:
1192           address += fragP->fr_offset * fragP->fr_var;
1193           break;
1194
1195         case rs_align:
1196           address += relax_align (address, fragP->fr_offset);
1197           break;
1198
1199         case rs_org:
1200           /* Assume .org is nugatory. It will grow with 1st relax.  */
1201           break;
1202
1203         case rs_machine_dependent:
1204           address += md_estimate_size_before_relax (fragP, segment);
1205           break;
1206
1207 #ifndef WORKING_DOT_WORD
1208           /* Broken words don't concern us yet */
1209         case rs_broken_word:
1210           break;
1211 #endif
1212
1213         default:
1214           BAD_CASE (fragP->fr_type);
1215           break;
1216         }                       /* switch(fr_type) */
1217     }                           /* for each frag in the segment */
1218
1219   /* Do relax().  */
1220   {
1221     long stretch;       /* May be any size, 0 or negative. */
1222     /* Cumulative number of addresses we have */
1223     /* relaxed this pass. */
1224     /* We may have relaxed more than one address. */
1225     long stretched;     /* Have we stretched on this pass? */
1226     /* This is 'cuz stretch may be zero, when, in fact some piece of code
1227        grew, and another shrank.  If a branch instruction doesn't fit anymore,
1228        we could be scrod.  */
1229
1230     do
1231       {
1232         stretch = stretched = 0;
1233         for (fragP = segment_frag_root; fragP; fragP = fragP->fr_next)
1234           {
1235             long growth = 0;
1236             unsigned long was_address;
1237             long offset;
1238             symbolS *symbolP;
1239             long target;
1240             long after;
1241             long aim;
1242
1243             was_address = fragP->fr_address;
1244             address = fragP->fr_address += stretch;
1245             symbolP = fragP->fr_symbol;
1246             offset = fragP->fr_offset;
1247
1248             switch (fragP->fr_type)
1249               {
1250               case rs_fill:     /* .fill never relaxes. */
1251                 growth = 0;
1252                 break;
1253
1254 #ifndef WORKING_DOT_WORD
1255                 /* JF:  This is RMS's idea.  I do *NOT* want to be blamed
1256                    for it I do not want to write it.  I do not want to have
1257                    anything to do with it.  This is not the proper way to
1258                    implement this misfeature.  */
1259               case rs_broken_word:
1260                 {
1261                   struct broken_word *lie;
1262                   struct broken_word *untruth;
1263
1264                   /* Yes this is ugly (storing the broken_word pointer
1265                      in the symbol slot).  Still, this whole chunk of
1266                      code is ugly, and I don't feel like doing anything
1267                      about it.  Think of it as stubbornness in action.  */
1268                   growth = 0;
1269                   for (lie = (struct broken_word *) (fragP->fr_symbol);
1270                        lie && lie->dispfrag == fragP;
1271                        lie = lie->next_broken_word)
1272                     {
1273
1274                       if (lie->added)
1275                         continue;
1276
1277                       offset = (lie->add->sy_frag->fr_address
1278                                 + S_GET_VALUE (lie->add)
1279                                 + lie->addnum
1280                                 - (lie->sub->sy_frag->fr_address
1281                                    + S_GET_VALUE (lie->sub)));
1282                       if (offset <= -32768 || offset >= 32767)
1283                         {
1284                           if (flagseen['K'])
1285                             as_warn (".word %s-%s+%ld didn't fit",
1286                                      S_GET_NAME (lie->add),
1287                                      S_GET_NAME (lie->sub),
1288                                      lie->addnum);
1289                           lie->added = 1;
1290                           if (fragP->fr_subtype == 0)
1291                             {
1292                               fragP->fr_subtype++;
1293                               growth += md_short_jump_size;
1294                             }
1295                           for (untruth = lie->next_broken_word;
1296                                untruth && untruth->dispfrag == lie->dispfrag;
1297                                untruth = untruth->next_broken_word)
1298                             if ((untruth->add->sy_frag == lie->add->sy_frag)
1299                                 && S_GET_VALUE (untruth->add) == S_GET_VALUE (lie->add))
1300                               {
1301                                 untruth->added = 2;
1302                                 untruth->use_jump = lie;
1303                               }
1304                           growth += md_long_jump_size;
1305                         }
1306                     }
1307
1308                   break;
1309                 }               /* case rs_broken_word */
1310 #endif
1311               case rs_align:
1312                 growth = (relax_align ((relax_addressT) (address
1313                                                          + fragP->fr_fix),
1314                                        offset)
1315                           - relax_align ((relax_addressT) (was_address
1316                                                            + fragP->fr_fix),
1317                                          offset));
1318                 break;
1319
1320               case rs_org:
1321                 target = offset;
1322
1323                 if (symbolP)
1324                   {
1325 #if !defined (MANY_SEGMENTS) && !defined (BFD_ASSEMBLER)
1326                     know ((S_GET_SEGMENT (symbolP) == SEG_ABSOLUTE)
1327                           || (S_GET_SEGMENT (symbolP) == SEG_DATA)
1328                           || (S_GET_SEGMENT (symbolP) == SEG_TEXT)
1329                           || S_GET_SEGMENT (symbolP) == SEG_BSS);
1330                     know (symbolP->sy_frag);
1331                     know (!(S_GET_SEGMENT (symbolP) == SEG_ABSOLUTE)
1332                           || (symbolP->sy_frag == &zero_address_frag));
1333 #endif
1334                     target += S_GET_VALUE (symbolP)
1335                       + symbolP->sy_frag->fr_address;
1336                   }             /* if we have a symbol */
1337
1338                 know (fragP->fr_next);
1339                 after = fragP->fr_next->fr_address;
1340                 growth = ((target - after) > 0) ? (target - after) : 0;
1341                 /* Growth may be negative, but variable part of frag
1342                    cannot have fewer than 0 chars.  That is, we can't
1343                    .org backwards. */
1344
1345                 growth -= stretch;      /* This is an absolute growth factor */
1346                 break;
1347
1348               case rs_machine_dependent:
1349                 {
1350                   const relax_typeS *this_type;
1351                   const relax_typeS *start_type;
1352                   relax_substateT next_state;
1353                   relax_substateT this_state;
1354
1355                   this_state = fragP->fr_subtype;
1356                   start_type = this_type = md_relax_table + this_state;
1357                   target = offset;
1358
1359                   if (symbolP)
1360                     {
1361 #if !defined (MANY_SEGMENTS) && !defined (BFD_ASSEMBLER)
1362                       know ((S_GET_SEGMENT (symbolP) == SEG_ABSOLUTE)
1363                             || (S_GET_SEGMENT (symbolP) == SEG_DATA)
1364                             || (S_GET_SEGMENT (symbolP) == SEG_BSS)
1365                             || (S_GET_SEGMENT (symbolP) == SEG_TEXT));
1366 #endif
1367                       know (symbolP->sy_frag);
1368                       know (!(S_GET_SEGMENT (symbolP) == absolute_section)
1369                             || symbolP->sy_frag == &zero_address_frag);
1370                       target +=
1371                         S_GET_VALUE (symbolP)
1372                         + symbolP->sy_frag->fr_address;
1373
1374                       /* If frag has yet to be reached on this pass,
1375                          assume it will move by STRETCH just as we did.
1376                          If this is not so, it will be because some frag
1377                          between grows, and that will force another pass.  */
1378
1379                       /* JF was just address */
1380                       /* JF also added is_dnrange hack */
1381                       /* There's gotta be a better/faster/etc way
1382                          to do this. . . */
1383                       /* gnu@cygnus.com:  I changed this from > to >=
1384                          because I ran into a zero-length frag (fr_fix=0)
1385                          which was created when the obstack needed a new
1386                          chunk JUST AFTER the opcode of a branch.  Since
1387                          fr_fix is zero, fr_address of this frag is the same
1388                          as fr_address of the next frag.  This
1389                          zero-length frag was variable and jumped to .+2
1390                          (in the next frag), but since the > comparison
1391                          below failed (the two were =, not >), "stretch"
1392                          was not added to the target.  Stretch was 178, so
1393                          the offset appeared to be .-176 instead, which did
1394                          not fit into a byte branch, so the assembler
1395                          relaxed the branch to a word.  This didn't compare
1396                          with what happened when the same source file was
1397                          assembled on other machines, which is how I found it.
1398                          You might want to think about what other places have
1399                          trouble with zero length frags... */
1400
1401                       if (symbolP->sy_frag->fr_address >= was_address
1402                           && is_dnrange (fragP, symbolP->sy_frag))
1403                         {
1404                           target += stretch;
1405                         }
1406                     }           /* if there's a symbol attached */
1407
1408                   aim = target - address - fragP->fr_fix;
1409                   /* The displacement is affected by the instruction size
1410                      for the 32k architecture. I think we ought to be able
1411                      to add fragP->fr_pcrel_adjust in all cases (it should be
1412                      zero if not used), but just in case it breaks something
1413                      else we'll put this inside #ifdef NS32K ... #endif  */
1414 #ifdef TC_NS32K
1415                   aim += fragP->fr_pcrel_adjust;
1416 #endif /* TC_NS32K */
1417
1418                   if (aim < 0)
1419                     {
1420                       /* Look backwards. */
1421                       for (next_state = this_type->rlx_more; next_state;)
1422                         if (aim >= this_type->rlx_backward)
1423                           next_state = 0;
1424                         else
1425                           {
1426                             /* Grow to next state. */
1427                             this_state = next_state;
1428                             this_type = md_relax_table + this_state;
1429                             next_state = this_type->rlx_more;
1430                           }
1431                     }
1432                   else
1433                     {
1434 #ifdef M68K_AIM_KLUDGE
1435                       M68K_AIM_KLUDGE (aim, this_state, this_type);
1436 #endif
1437                       /* Look forwards. */
1438                       for (next_state = this_type->rlx_more; next_state;)
1439                         if (aim <= this_type->rlx_forward)
1440                           next_state = 0;
1441                         else
1442                           {
1443                             /* Grow to next state. */
1444                             this_state = next_state;
1445                             this_type = md_relax_table + this_state;
1446                             next_state = this_type->rlx_more;
1447                           }
1448                     }
1449
1450                   growth = this_type->rlx_length - start_type->rlx_length;
1451                   if (growth != 0)
1452                     fragP->fr_subtype = this_state;
1453                 }
1454                 break;
1455
1456               default:
1457                 BAD_CASE (fragP->fr_type);
1458                 break;
1459               }
1460             if (growth)
1461               {
1462                 stretch += growth;
1463                 stretched++;
1464               }
1465           }                     /* For each frag in the segment. */
1466       }
1467     while (stretched);          /* Until nothing further to relax. */
1468   }                             /* do_relax */
1469
1470   /*
1471    * We now have valid fr_address'es for each frag.
1472    */
1473
1474   /*
1475    * All fr_address's are correct, relative to their own segment.
1476    * We have made all the fixS we will ever make.
1477    */
1478 }                               /* relax_segment() */
1479
1480 /* fixup_segment()
1481
1482    Go through all the fixS's in a segment and see which ones can be
1483    handled now.  (These consist of fixS where we have since discovered
1484    the value of a symbol, or the address of the frag involved.)
1485    For each one, call md_apply_fix to put the fix into the frag data.
1486
1487    Result is a count of how many relocation structs will be needed to
1488    handle the remaining fixS's that we couldn't completely handle here.
1489    These will be output later by emit_relocations().  */
1490
1491 static long
1492 fixup_segment (fixP, this_segment_type)
1493      register fixS *fixP;
1494      segT this_segment_type;    /* N_TYPE bits for segment. */
1495 {
1496   register long seg_reloc_count;
1497   register symbolS *add_symbolP;
1498   register symbolS *sub_symbolP;
1499   long add_number;
1500   register int size;
1501   register char *place;
1502   register long where;
1503   register char pcrel;
1504   register fragS *fragP;
1505   register segT add_symbol_segment = absolute_section;
1506
1507   seg_reloc_count = 0;
1508   /* If the linker is doing the relaxing, we must not do any fixups */
1509   if (linkrelax)
1510     for (; fixP; fixP = fixP->fx_next)
1511       seg_reloc_count++;
1512   else
1513     for (; fixP; fixP = fixP->fx_next)
1514       {
1515         fragP = fixP->fx_frag;
1516         know (fragP);
1517         where = fixP->fx_where;
1518         place = fragP->fr_literal + where;
1519         size = fixP->fx_size;
1520         add_symbolP = fixP->fx_addsy;
1521 #ifdef TC_I960
1522         if (fixP->fx_callj && TC_S_IS_CALLNAME (add_symbolP))
1523           {
1524             /* Relocation should be done via the associated 'bal'
1525                entry point symbol. */
1526
1527             if (!TC_S_IS_BALNAME (tc_get_bal_of_call (add_symbolP)))
1528               {
1529                 as_bad ("No 'bal' entry point for leafproc %s",
1530                         S_GET_NAME (add_symbolP));
1531                 continue;
1532               }
1533             fixP->fx_addsy = add_symbolP = tc_get_bal_of_call (add_symbolP);
1534           }
1535 #endif
1536         sub_symbolP = fixP->fx_subsy;
1537         add_number = fixP->fx_offset;
1538         pcrel = fixP->fx_pcrel;
1539
1540         if (add_symbolP)
1541           add_symbol_segment = S_GET_SEGMENT (add_symbolP);
1542
1543         if (sub_symbolP)
1544           {
1545             if (!add_symbolP)
1546               {
1547                 /* Its just -sym */
1548                 if (S_GET_SEGMENT (sub_symbolP) != absolute_section)
1549                   as_bad ("Negative of non-absolute symbol %s",
1550                           S_GET_NAME (sub_symbolP));
1551
1552                 add_number -= S_GET_VALUE (sub_symbolP);
1553               }
1554             else if ((S_GET_SEGMENT (sub_symbolP) == add_symbol_segment)
1555                      && (SEG_NORMAL (add_symbol_segment)
1556                          || (add_symbol_segment == absolute_section)))
1557               {
1558                 /* Difference of 2 symbols from same segment.
1559                    Can't make difference of 2 undefineds: 'value' means
1560                    something different for N_UNDF. */
1561 #ifdef TC_I960
1562                 /* Makes no sense to use the difference of 2 arbitrary symbols
1563                    as the target of a call instruction.  */
1564                 if (fixP->fx_callj)
1565                   {
1566                     as_bad ("callj to difference of 2 symbols");
1567                   }
1568 #endif /* TC_I960 */
1569                 add_number += S_GET_VALUE (add_symbolP) -
1570                   S_GET_VALUE (sub_symbolP);
1571
1572                 add_symbolP = NULL;
1573                 fixP->fx_addsy = NULL;
1574               }
1575             else
1576               {
1577                 /* Different segments in subtraction. */
1578                 know (!(S_IS_EXTERNAL (sub_symbolP)
1579                         && (S_GET_SEGMENT (sub_symbolP) == absolute_section)));
1580
1581                 if ((S_GET_SEGMENT (sub_symbolP) == absolute_section))
1582                   {
1583                     add_number -= S_GET_VALUE (sub_symbolP);
1584                   }
1585                 else
1586                   {
1587                     as_bad ("Can't emit reloc {- %s-seg symbol \"%s\"} @ file address %d.",
1588                             segment_name (S_GET_SEGMENT (sub_symbolP)),
1589                        S_GET_NAME (sub_symbolP), fragP->fr_address + where);
1590                   }             /* if absolute */
1591               }
1592           }                     /* if sub_symbolP */
1593
1594         if (add_symbolP)
1595           {
1596             if (add_symbol_segment == this_segment_type && pcrel)
1597               {
1598                 /*
1599                  * This fixup was made when the symbol's segment was
1600                  * SEG_UNKNOWN, but it is now in the local segment.
1601                  * So we know how to do the address without relocation.
1602                  */
1603 #ifdef TC_I960
1604                 /* reloc_callj() may replace a 'call' with a 'calls' or a
1605                    'bal', in which cases it modifies *fixP as appropriate.
1606                    In the case of a 'calls', no further work is required,
1607                    and *fixP has been set up to make the rest of the code
1608                    below a no-op. */
1609                 reloc_callj (fixP);
1610 #endif /* TC_I960 */
1611
1612                 add_number += S_GET_VALUE (add_symbolP);
1613                 add_number -= md_pcrel_from (fixP);
1614                 pcrel = 0;      /* Lie. Don't want further pcrel processing. */
1615                 fixP->fx_addsy = NULL;  /* No relocations please. */
1616               }
1617             else
1618               {
1619                 if (add_symbol_segment == absolute_section)
1620                   {
1621 #ifdef TC_I960
1622                     /* See comment about reloc_callj() above.  */
1623                     reloc_callj (fixP);
1624 #endif /* TC_I960 */
1625                     add_number += S_GET_VALUE (add_symbolP);
1626                     fixP->fx_addsy = NULL;
1627                     add_symbolP = NULL;
1628                   }
1629                 else if (add_symbol_segment == undefined_section
1630 #ifdef BFD_ASSEMBLER
1631                          || add_symbol_segment == &bfd_com_section
1632 #endif
1633                          )
1634                   {
1635 #ifdef TC_I960
1636                     if ((int) fixP->fx_bit_fixP == 13)
1637                       {
1638                         /* This is a COBR instruction.  They have only a
1639                          * 13-bit displacement and are only to be used
1640                          * for local branches: flag as error, don't generate
1641                          * relocation.
1642                          */
1643                         as_bad ("can't use COBR format with external label");
1644                         fixP->fx_addsy = NULL;  /* No relocations please. */
1645                         continue;
1646                       }         /* COBR */
1647 #endif /* TC_I960 */
1648
1649 #ifdef OBJ_COFF
1650 #ifdef TE_I386AIX
1651                     if (S_IS_COMMON (add_symbolP))
1652                       add_number += S_GET_VALUE (add_symbolP);
1653 #endif /* TE_I386AIX */
1654 #endif /* OBJ_COFF */
1655                     ++seg_reloc_count;
1656                   }
1657                 else
1658                   {
1659                     seg_reloc_count++;
1660                     add_number += S_GET_VALUE (add_symbolP);
1661                   }
1662               }                 /* if not in local seg */
1663           }                     /* if there was a + symbol */
1664
1665         if (pcrel)
1666           {
1667             add_number -= md_pcrel_from (fixP);
1668             if (add_symbolP == 0)
1669               {
1670                 fixP->fx_addsy = &abs_symbol;
1671                 ++seg_reloc_count;
1672               }                 /* if there's an add_symbol */
1673           }                     /* if pcrel */
1674
1675         if (!fixP->fx_bit_fixP)
1676           {
1677             if ((size == 1 &&
1678                  (add_number & ~0xFF)
1679                  && ((add_number & ~0xFF) != (-1 & ~0xFF)))
1680                 || (size == 2
1681                     && (add_number & ~0xFFFF)
1682                     && ((add_number & ~0xFFFF) != (-1 & ~0xFFFF))))
1683               {
1684                 as_bad ("Value of %d too large for field of %d bytes at 0x%x",
1685                         add_number, size, fragP->fr_address + where);
1686               }                 /* generic error checking */
1687 #ifdef WARN_SIGNED_OVERFLOW_WORD
1688             /* Warn if a .word value is too large when treated as a signed
1689                number.  We already know it is not too negative.  This is to
1690                catch over-large switches generated by gcc on the 68k.  */
1691             if (!flagseen['J']
1692                 && size == 2
1693                 && add_number > 0x7fff)
1694               as_bad ("Signed .word overflow; switch may be too large; %d at 0x%x",
1695                       add_number, fragP->fr_address + where);
1696 #endif
1697           }                     /* not a bit fix */
1698
1699 #ifdef BFD_ASSEMBLER
1700         md_apply_fix (fixP, &add_number);
1701 #else
1702         md_apply_fix (fixP, add_number);
1703 #endif
1704       }                         /* For each fixS in this segment. */
1705
1706 #ifdef OBJ_COFF
1707 #ifdef TC_I960
1708   {
1709     fixS *topP = fixP;
1710
1711     /* two relocs per callj under coff. */
1712     for (fixP = topP; fixP; fixP = fixP->fx_next)
1713       {
1714         if (fixP->fx_callj && fixP->fx_addsy != 0)
1715           {
1716             ++seg_reloc_count;
1717           }                     /* if callj and not already fixed. */
1718       }                         /* for each fix */
1719   }
1720 #endif /* TC_I960 */
1721
1722 #endif /* OBJ_COFF */
1723   return (seg_reloc_count);
1724 }                               /* fixup_segment() */
1725
1726 /* end of write.c */