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