force all files to end in "/* end of filename"
[platform/upstream/binutils.git] / gas / write.c
1
2 /* write.c - emit .o file
3    Copyright (C) 1986, 1987, 1990, 1991 Free Software Foundation, Inc.
4    
5    This file is part of GAS, the GNU Assembler.
6    
7    GAS is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2, or (at your option)
10    any later version.
11    
12    GAS is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16    
17    You should have received a copy of the GNU General Public License
18    along with GAS; see the file COPYING.  If not, write to
19    the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */
20
21 /* 
22   
23   This thing should be set up to do byteordering correctly.  But...
24   
25   In order to cross-assemble the target machine must have an a.out header
26   similar to the one in a.out.h on THIS machine.  Byteorder doesn't matter,
27   we take special care of it, but the numbers must be the same SIZE (# of
28   bytes) and in the same PLACE.  If this is not true, you will have some
29   trouble.
30   */
31
32 #include "as.h"
33 #include "subsegs.h"
34 #include "obstack.h"
35 #include "output-file.h"
36
37 #ifndef MANY_SEGMENTS
38 static struct frag *text_frag_root;
39 static struct frag *data_frag_root;
40
41 static struct frag *text_last_frag;     /* Last frag in segment. */
42 static struct frag *data_last_frag;     /* Last frag in segment. */
43 #endif
44
45 static object_headers headers;
46
47 long string_byte_count;
48
49 static char *the_object_file;
50
51 char *next_object_file_charP;   /* Tracks object file bytes. */
52
53 int magic_number_for_object_file = DEFAULT_MAGIC_NUMBER_FOR_OBJECT_FILE;
54
55 /* static long          length; JF unused */    /* String length, including trailing '\0'. */
56
57
58 #ifdef __STDC__
59
60 static int is_dnrange(struct frag *f1, struct frag *f2);
61 static long fixup_segment(fixS *fixP, segT this_segment_type);
62 static relax_addressT relax_align(relax_addressT address, long alignment);
63 void relax_segment(struct frag *segment_frag_root, segT segment_type);
64
65 #else
66
67 static int is_dnrange();
68 static long fixup_segment();
69 static relax_addressT relax_align();
70 void relax_segment();
71
72 #endif /* __STDC__ */
73
74 /*
75  *                      fix_new()
76  *
77  * Create a fixS in obstack 'notes'.
78  */
79 fixS *fix_new(frag, where, size, add_symbol, sub_symbol, offset, pcrel, r_type)
80 fragS *frag;            /* Which frag? */
81 int where;              /* Where in that frag? */
82 short int size;         /* 1, 2  or 4 usually. */
83 symbolS *add_symbol;    /* X_add_symbol. */
84 symbolS *sub_symbol;    /* X_subtract_symbol. */
85 long offset;            /* X_add_number. */
86 int pcrel;              /* TRUE if PC-relative relocation. */
87 enum reloc_type r_type; /* Relocation type */
88 {
89         register fixS * fixP;
90         
91         fixP = (fixS *)obstack_alloc(&notes,sizeof(fixS));
92         
93         fixP->fx_frag   = frag;
94         fixP->fx_where  = where;
95         fixP->fx_size   = size;
96         fixP->fx_addsy  = add_symbol;
97         fixP->fx_subsy  = sub_symbol;
98         fixP->fx_offset = offset;
99         fixP->fx_pcrel  = pcrel;
100         fixP->fx_r_type = r_type;
101         
102         /* JF these 'cuz of the NS32K stuff */
103         fixP->fx_im_disp        = 0;
104         fixP->fx_pcrel_adjust = 0;
105         fixP->fx_bsr    = 0;
106         fixP->fx_bit_fixP       = 0;
107         
108         /* usually, we want relocs sorted numerically, but while
109            comparing to older versions of gas that have relocs
110            reverse sorted, it is convenient to have this compile
111            time option.  xoxorich. */
112         
113 #ifdef REVERSE_SORT_RELOCS
114         
115         fixP->fx_next = *seg_fix_rootP;
116         *seg_fix_rootP = fixP;
117         
118 #else /* REVERSE_SORT_RELOCS */
119         
120         fixP->fx_next   = NULL;
121         
122         if (*seg_fix_tailP)
123             (*seg_fix_tailP)->fx_next = fixP;
124         else
125             *seg_fix_rootP = fixP;
126         *seg_fix_tailP = fixP;
127         
128 #endif /* REVERSE_SORT_RELOCS */
129         
130         fixP->fx_callj = 0;
131         return fixP;
132 }
133 #ifndef BFD
134 void write_object_file() 
135 {
136         register struct frchain *       frchainP; /* Track along all frchains. */
137         register fragS *                fragP;  /* Track along all frags. */
138         register struct frchain *       next_frchainP;
139         register fragS * *              prev_fragPP;
140         /*  register char *             name; */
141         /*  symbolS *symbolP; */
142         /*  register symbolS **         symbolPP; */
143         /* register fixS *              fixP; JF unused */
144         unsigned int data_siz;
145         
146 #ifdef DONTDEF
147         void gdb_emit();
148         void gdb_end();
149 #endif
150         long object_file_size;
151         
152 #ifdef  VMS
153         /*
154          *      Under VMS we try to be compatible with VAX-11 "C".  Thus, we
155          *      call a routine to check for the definition of the procedure
156          *      "_main", and if so -- fix it up so that it can be program
157          *      entry point.
158          */
159         VMS_Check_For_Main();
160 #endif /* VMS */
161         /*
162          * After every sub-segment, we fake an ".align ...". This conforms to BSD4.2
163          * brane-damage. We then fake ".fill 0" because that is the kind of frag
164          * that requires least thought. ".align" frags like to have a following
165          * frag since that makes calculating their intended length trivial.
166          */
167 #define SUB_SEGMENT_ALIGN (2)
168         for (frchainP = frchain_root; frchainP; frchainP = frchainP->frch_next) {
169 #ifdef  VMS
170                 /*
171                  *      Under VAX/VMS, the linker (and PSECT specifications)
172                  *      take care of correctly aligning the segments.
173                  *      Doing the alignment here (on initialized data) can
174                  *      mess up the calculation of global data PSECT sizes.
175                  */
176 #undef  SUB_SEGMENT_ALIGN
177 #define SUB_SEGMENT_ALIGN ((frchainP->frch_seg != SEG_DATA) ? 2 : 0)
178 #endif  /* VMS */
179                 subseg_new (frchainP->frch_seg, frchainP->frch_subseg);
180                 frag_align (SUB_SEGMENT_ALIGN, 0);
181                 /* frag_align will have left a new frag. */
182                 /* Use this last frag for an empty ".fill". */
183                 /*
184                  * For this segment ...
185                  * Create a last frag. Do not leave a "being filled in frag".
186                  */
187                 frag_wane (frag_now);
188                 frag_now->fr_fix        = 0;
189                 know( frag_now->fr_next == NULL );
190                 /* know( frags . obstack_c_base == frags . obstack_c_next_free ); */
191                 /* Above shows we haven't left a half-completed object on obstack. */
192         } /* walk the frag chain */
193         
194         /*
195          * From now on, we don't care about sub-segments.
196          * Build one frag chain for each segment. Linked thru fr_next.
197          * We know that there is at least 1 text frchain & at least 1 data frchain.
198          */
199         prev_fragPP = &text_frag_root;
200         for (frchainP = frchain_root; frchainP; frchainP = next_frchainP) {
201                 know( frchainP->frch_root );
202                 * prev_fragPP = frchainP->frch_root;
203                 prev_fragPP = & frchainP->frch_last->fr_next;
204                 
205                 if (((next_frchainP = frchainP->frch_next) == NULL)
206                     || next_frchainP == data0_frchainP) {
207                         prev_fragPP = & data_frag_root;
208                         if (next_frchainP) {
209                                 text_last_frag = frchainP->frch_last;
210                         } else {
211                                 data_last_frag = frchainP->frch_last;
212                         }
213                 }
214         } /* walk the frag chain */
215         
216         /*
217          * We have two segments. If user gave -R flag, then we must put the
218          * data frags into the text segment. Do this before relaxing so
219          * we know to take advantage of -R and make shorter addresses.
220          */
221         if (flagseen[ 'R' ]) {
222                 fixS *tmp;
223                 
224                 text_last_frag->fr_next = data_frag_root;
225                 text_last_frag = data_last_frag;
226                 data_last_frag = NULL;
227                 data_frag_root = NULL;
228                 if (text_fix_root) {
229                         for (tmp = text_fix_root; tmp->fx_next; tmp = tmp->fx_next) ;;
230                         tmp->fx_next=data_fix_root;
231                 } else
232                     text_fix_root=data_fix_root;
233                 data_fix_root=NULL;
234         }
235         
236         relax_segment(text_frag_root, SEG_TEXT);
237         relax_segment(data_frag_root, SEG_DATA);
238         /*
239          * Now the addresses of frags are correct within the segment.
240          */
241         
242         know(text_last_frag->fr_type == rs_fill && text_last_frag->fr_offset == 0);
243         H_SET_TEXT_SIZE(&headers, text_last_frag->fr_address);
244         text_last_frag->fr_address = H_GET_TEXT_SIZE(&headers);
245         
246         /*
247          * Join the 2 segments into 1 huge segment.
248          * To do this, re-compute every rn_address in the SEG_DATA frags.
249          * Then join the data frags after the text frags.
250          *
251          * Determine a_data [length of data segment].
252          */
253         if (data_frag_root) {
254                 register relax_addressT slide;
255                 
256                 know((text_last_frag->fr_type == rs_fill) && (text_last_frag->fr_offset == 0));
257                 
258                 H_SET_DATA_SIZE(&headers, data_last_frag->fr_address);
259                 data_last_frag->fr_address = H_GET_DATA_SIZE(&headers);
260                 slide = H_GET_TEXT_SIZE(&headers); /* & in file of the data segment. */
261                 
262                 for (fragP = data_frag_root; fragP; fragP = fragP->fr_next) {
263                         fragP->fr_address += slide;
264                 } /* for each data frag */
265                 
266                 know(text_last_frag != 0);
267                 text_last_frag->fr_next = data_frag_root;
268         } else {
269                 H_SET_DATA_SIZE(&headers,0);
270                 data_siz = 0;
271         }
272         
273         bss_address_frag.fr_address = H_GET_TEXT_SIZE(&headers) + 
274             H_GET_DATA_SIZE(&headers);
275         
276         H_SET_BSS_SIZE(&headers,local_bss_counter);
277         
278         /*
279          *
280          * Crawl the symbol chain.
281          *
282          * For each symbol whose value depends on a frag, take the address of
283          * that frag and subsume it into the value of the symbol.
284          * After this, there is just one way to lookup a symbol value.
285          * Values are left in their final state for object file emission.
286          * We adjust the values of 'L' local symbols, even if we do
287          * not intend to emit them to the object file, because their values
288          * are needed for fix-ups.
289          *
290          * Unless we saw a -L flag, remove all symbols that begin with 'L'
291          * from the symbol chain.  (They are still pointed to by the fixes.)
292          *
293          * Count the remaining symbols.
294          * Assign a symbol number to each symbol.
295          * Count the number of string-table chars we will emit.
296          * Put this info into the headers as appropriate.
297          *
298          */
299         know(zero_address_frag.fr_address == 0);
300         string_byte_count = sizeof(string_byte_count);
301         
302         obj_crawl_symbol_chain(&headers);
303         
304         if (string_byte_count == sizeof(string_byte_count)) {
305                 string_byte_count = 0;
306         } /* if no strings, then no count. */
307         
308         H_SET_STRING_SIZE(&headers, string_byte_count);
309         
310         /*
311          * Addresses of frags now reflect addresses we use in the object file.
312          * Symbol values are correct.
313          * Scan the frags, converting any ".org"s and ".align"s to ".fill"s.
314          * Also converting any machine-dependent frags using md_convert_frag();
315          */
316         subseg_change(SEG_TEXT, 0);
317         
318         for (fragP = text_frag_root;  fragP;  fragP = fragP->fr_next) {
319                 switch (fragP->fr_type) {
320                 case rs_align:
321                 case rs_org:
322                         fragP->fr_type = rs_fill;
323                         know(fragP->fr_var == 1);
324                         know(fragP->fr_next != NULL);
325                         
326                         fragP->fr_offset = (fragP->fr_next->fr_address
327                                             - fragP->fr_address
328                                             - fragP->fr_fix);
329                         break;
330                         
331                 case rs_fill:
332                         break;
333                         
334                 case rs_machine_dependent:
335                         md_convert_frag(&headers, fragP);
336                         
337                         know((fragP->fr_next == NULL) || ((fragP->fr_next->fr_address - fragP->fr_address) == fragP->fr_fix));
338                         
339                         /*
340                          * After md_convert_frag, we make the frag into a ".space 0".
341                          * Md_convert_frag() should set up any fixSs and constants
342                          * required.
343                          */
344                         frag_wane(fragP);
345                         break;
346                         
347 #ifndef WORKING_DOT_WORD
348                 case rs_broken_word: {
349                         struct broken_word *lie;
350                         extern md_short_jump_size;
351                         extern md_long_jump_size;
352                         
353                         if (fragP->fr_subtype) {
354                                 fragP->fr_fix+=md_short_jump_size;
355                                 for (lie=(struct broken_word *)(fragP->fr_symbol);lie && lie->dispfrag==fragP;lie=lie->next_broken_word)
356                                     if (lie->added==1)
357                                         fragP->fr_fix+=md_long_jump_size;
358                         }
359                         frag_wane(fragP);
360                 }
361                         break;
362 #endif
363                         
364                 default:
365                         BAD_CASE( fragP->fr_type );
366                         break;
367                 } /* switch (fr_type) */
368                 
369                 know((fragP->fr_next == NULL) || ((fragP->fr_next->fr_address - fragP->fr_address) == (fragP->fr_fix + (fragP->fr_offset * fragP->fr_var))));
370         } /* for each frag. */
371         
372 #ifndef WORKING_DOT_WORD
373         {
374                 struct broken_word *lie;
375                 struct broken_word **prevP;
376                 
377                 prevP= &broken_words;
378                 for (lie=broken_words; lie; lie=lie->next_broken_word)
379                     if (!lie->added) {
380 #ifdef TC_NS32K
381                             fix_new_ns32k(lie->frag,
382                                           lie->word_goes_here - lie->frag->fr_literal,
383                                           2,
384                                           lie->add,
385                                           lie->sub,
386                                           lie->addnum,
387                                           0, 0, 2, 0, 0);
388 #else /* TC_NS32K */
389                             fix_new(    lie->frag,  lie->word_goes_here - lie->frag->fr_literal,
390                                     2,  lie->add,
391                                     lie->sub,  lie->addnum,
392                                     0,  NO_RELOC);
393 #endif /* TC_NS32K */
394                             /* md_number_to_chars(lie->word_goes_here,
395                                S_GET_VALUE(lie->add)
396                                + lie->addnum
397                                - S_GET_VALUE(lie->sub),
398                                2); */
399                             *prevP=lie->next_broken_word;
400                     } else
401                         prevP= &(lie->next_broken_word);
402                 
403                 for (lie=broken_words;lie;) {
404                         struct broken_word *untruth;
405                         char    *table_ptr;
406                         long    table_addr;
407                         long    from_addr,
408                         to_addr;
409                         int     n,
410                         m;
411                         
412                         extern md_short_jump_size;
413                         extern md_long_jump_size;
414                         
415                         fragP=lie->dispfrag;
416                         
417                         /* Find out how many broken_words go here */
418                         n=0;
419                         for (untruth=lie;untruth && untruth->dispfrag==fragP;untruth=untruth->next_broken_word)
420                             if (untruth->added==1)
421                                 n++;
422                         
423                         table_ptr=lie->dispfrag->fr_opcode;
424                         table_addr=lie->dispfrag->fr_address+(table_ptr - lie->dispfrag->fr_literal);
425                         /* Create the jump around the long jumps */
426                         /* This is a short jump from table_ptr+0 to table_ptr+n*long_jump_size */
427                         from_addr=table_addr;
428                         to_addr = table_addr + md_short_jump_size + n * md_long_jump_size;
429                         md_create_short_jump(table_ptr, from_addr, to_addr, lie->dispfrag, lie->add);
430                         table_ptr+=md_short_jump_size;
431                         table_addr+=md_short_jump_size;
432                         
433                         for (m=0;lie && lie->dispfrag==fragP;m++,lie=lie->next_broken_word) {
434                                 if (lie->added==2)
435                                     continue;
436                                 /* Patch the jump table */
437                                 /* This is the offset from ??? to table_ptr+0 */
438                                 to_addr =   table_addr
439                                     - S_GET_VALUE(lie->sub);
440                                 md_number_to_chars(lie->word_goes_here,to_addr,2);
441                                 for (untruth=lie->next_broken_word;untruth && untruth->dispfrag==fragP;untruth=untruth->next_broken_word) {
442                                         if (untruth->use_jump==lie)
443                                             md_number_to_chars(untruth->word_goes_here,to_addr,2);
444                                 }
445                                 
446                                 /* Install the long jump */
447                                 /* this is a long jump from table_ptr+0 to the final target */
448                                 from_addr=table_addr;
449                                 to_addr=S_GET_VALUE(lie->add) + lie->addnum;
450                                 md_create_long_jump(table_ptr,from_addr,to_addr,lie->dispfrag,lie->add);
451                                 table_ptr+=md_long_jump_size;
452                                 table_addr+=md_long_jump_size;
453                         }
454                 }
455         }
456 #endif /* not WORKING_DOT_WORD */
457         
458 #ifndef VMS
459         { /* not vms */
460                 /*
461                  * Scan every FixS performing fixups. We had to wait until now to do
462                  * this because md_convert_frag() may have made some fixSs.
463                  */
464                 
465                 H_SET_RELOCATION_SIZE(&headers,
466                                       md_reloc_size * fixup_segment(text_fix_root, SEG_TEXT),
467                                       md_reloc_size * fixup_segment(data_fix_root, SEG_DATA));
468                 
469                 
470                 /* FIXME move this stuff into the pre-write-hook */
471                 H_SET_MAGIC_NUMBER(&headers, magic_number_for_object_file);
472                 H_SET_ENTRY_POINT(&headers, 0);
473                 
474                 obj_pre_write_hook(&headers); /* extra coff stuff */
475                 if ((had_warnings() && flagseen['Z'])
476                     || had_errors() > 0) {
477                         if (flagseen['Z']) {
478                                 as_warn("%d error%s, %d warning%s, generating bad object file.\n",
479                                         had_errors(), had_errors() == 1 ? "" : "s",
480                                         had_warnings(), had_warnings() == 1 ? "" : "s");
481                         } else {
482                                 as_fatal("%d error%s, %d warning%s, no object file generated.\n",
483                                          had_errors(), had_errors() == 1 ? "" : "s",
484                                          had_warnings(), had_warnings() == 1 ? "" : "s");
485                         } /* on want output */
486                 } /* on error condition */
487                 
488                 object_file_size = H_GET_FILE_SIZE(&headers);
489                 next_object_file_charP = the_object_file = xmalloc(object_file_size);
490                 
491                 output_file_create(out_file_name);
492                 
493                 obj_header_append(&next_object_file_charP, &headers);
494                 
495                 know((next_object_file_charP - the_object_file) == H_GET_HEADER_SIZE(&headers));
496                 
497                 /*
498                  * Emit code.
499                  */
500                 for (fragP = text_frag_root;  fragP;  fragP = fragP->fr_next) {
501                         register long count;
502                         register char *fill_literal;
503                         register long fill_size;
504                         
505                         know(fragP->fr_type == rs_fill);
506                         append(&next_object_file_charP, fragP->fr_literal, (unsigned long) fragP->fr_fix);
507                         fill_literal = fragP->fr_literal + fragP->fr_fix;
508                         fill_size = fragP->fr_var;
509                         know(fragP->fr_offset >= 0);
510                         
511                         for (count = fragP->fr_offset; count; count--) {
512                                 append(&next_object_file_charP, fill_literal, (unsigned long) fill_size);
513                         } /* for each  */
514                         
515                 } /* for each code frag. */
516                 
517                 know((next_object_file_charP - the_object_file) == (H_GET_HEADER_SIZE(&headers) + H_GET_TEXT_SIZE(&headers) + H_GET_DATA_SIZE(&headers)));
518                 
519                 /*
520                  * Emit relocations.
521                  */
522                 obj_emit_relocations(&next_object_file_charP, text_fix_root, (relax_addressT)0);
523                 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)));
524 #ifdef TC_I960
525                 /* Make addresses in data relocation directives relative to beginning of
526                  * first data fragment, not end of last text fragment:  alignment of the
527                  * start of the data segment may place a gap between the segments.
528                  */
529                 obj_emit_relocations(&next_object_file_charP, data_fix_root, data0_frchainP->frch_root->fr_address);
530 #else /* TC_I960 */
531                 obj_emit_relocations(&next_object_file_charP, data_fix_root, text_last_frag->fr_address);
532 #endif /* TC_I960 */
533                 
534                 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)));
535                 
536                 /*
537                  * Emit line number entries.
538                  */
539                 OBJ_EMIT_LINENO(&next_object_file_charP, lineno_rootP, the_object_file);
540                 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)));
541                 
542                 /*
543                  * Emit symbols.
544                  */
545                 obj_emit_symbols(&next_object_file_charP, symbol_rootP);
546                 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)));
547                 
548                 /*
549                  * Emit strings.
550                  */
551                 
552                 if (string_byte_count > 0) {
553                         obj_emit_strings(&next_object_file_charP);
554                 } /* only if we have a string table */
555                 
556                 /*        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) + H_GET_STRING_SIZE(&headers)));
557                  */
558                 /*        know(next_object_file_charP == the_object_file + object_file_size);*/
559                 
560 #ifdef BFD_HEADERS
561                 bfd_seek(stdoutput, 0, 0);
562                 bfd_write(the_object_file, 1, object_file_size,  stdoutput);
563 #else
564                 
565                 /* Write the data to the file */
566                 output_file_append(the_object_file,object_file_size,out_file_name);
567 #endif
568                 
569 #ifdef DONTDEF
570                 if (flagseen['G'])              /* GDB symbol file to be appended? */
571                     {
572                             gdb_emit (out_file_name);
573                             gdb_end ();
574                     }
575 #endif /* DONTDEF */
576                 
577                 output_file_close(out_file_name);
578         } /* non vms output */
579 #else   /* VMS */
580         /*
581          *      Now do the VMS-dependent part of writing the object file
582          */
583         VMS_write_object_file(text_siz, data_siz, text_frag_root, data_frag_root);
584 #endif  /* VMS */
585 } /* write_object_file() */
586 #else
587 #endif
588
589 /*
590  *                      relax_segment()
591  *
592  * Now we have a segment, not a crowd of sub-segments, we can make fr_address
593  * values.
594  *
595  * Relax the frags.
596  *
597  * After this, all frags in this segment have addresses that are correct
598  * within the segment. Since segments live in different file addresses,
599  * these frag addresses may not be the same as final object-file addresses.
600  */
601
602
603
604 void relax_segment(segment_frag_root, segment)
605 struct frag *   segment_frag_root;
606 segT            segment; /* SEG_DATA or SEG_TEXT */
607 {
608         register struct frag *  fragP;
609         register relax_addressT address;
610         /* register relax_addressT      old_address; JF unused */
611         /* register relax_addressT      new_address; JF unused */
612 #ifndef MANY_SEGMENTS   
613         know( segment == SEG_DATA || segment == SEG_TEXT );
614 #endif
615         /* In case md_estimate_size_before_relax() wants to make fixSs. */
616         subseg_change(segment, 0);
617         
618         /*
619          * For each frag in segment: count and store  (a 1st guess of) fr_address.
620          */
621         address = 0;
622         for (fragP = segment_frag_root; fragP; fragP = fragP->fr_next) {
623                 fragP->fr_address = address;
624                 address += fragP->fr_fix;
625                 
626                 switch (fragP->fr_type) {
627                 case rs_fill:
628                         address += fragP->fr_offset * fragP->fr_var ;
629                         break;
630                         
631                 case rs_align:
632                         address += relax_align(address, fragP->fr_offset);
633                         break;
634                         
635                 case rs_org:
636                         /*
637                          * Assume .org is nugatory. It will grow with 1st relax.
638                          */
639                         break;
640                         
641                 case rs_machine_dependent:
642                         address += md_estimate_size_before_relax(fragP, segment);
643                         break;
644                         
645 #ifndef WORKING_DOT_WORD
646                         /* Broken words don't concern us yet */
647                 case rs_broken_word:
648                         break;
649 #endif
650                         
651                 default:
652                         BAD_CASE(fragP->fr_type);
653                         break;
654                 } /* switch(fr_type) */
655         } /* for each frag in the segment */
656         
657         /*
658          * Do relax().
659          */
660         {
661                 register long   stretch; /* May be any size, 0 or negative. */
662                 /* Cumulative number of addresses we have */
663                 /* relaxed this pass. */
664                 /* We may have relaxed more than one address. */
665                 register long stretched;  /* Have we stretched on this pass? */
666                 /* This is 'cuz stretch may be zero, when,
667                    in fact some piece of code grew, and
668                    another shrank.  If a branch instruction
669                    doesn't fit anymore, we could be scrod */
670                 
671                 do {
672                         stretch = stretched = 0;
673                         for (fragP = segment_frag_root;  fragP;  fragP = fragP->fr_next) {
674                                 register long growth = 0;
675                                 register unsigned long was_address;
676                                 /* register long var; */
677                                 register long offset;
678                                 register symbolS *symbolP;
679                                 register long target;
680                                 register long after;
681                                 register long aim;
682                                 
683                                 was_address = fragP->fr_address;
684                                 address = fragP->fr_address += stretch;
685                                 symbolP = fragP->fr_symbol;
686                                 offset = fragP->fr_offset;
687                                 /* var = fragP->fr_var; */
688                                 
689                                 switch (fragP->fr_type) {
690                                 case rs_fill:   /* .fill never relaxes. */
691                                         growth = 0;
692                                         break;
693                                         
694 #ifndef WORKING_DOT_WORD
695                                         /* JF:  This is RMS's idea.  I do *NOT* want to be blamed
696                                            for it I do not want to write it.  I do not want to have
697                                            anything to do with it.  This is not the proper way to
698                                            implement this misfeature. */
699                                 case rs_broken_word: {
700                                         struct broken_word *lie;
701                                         struct broken_word *untruth;
702                                         extern int md_short_jump_size;
703                                         extern int md_long_jump_size;
704                                         
705                                         /* Yes this is ugly (storing the broken_word pointer
706                                            in the symbol slot).  Still, this whole chunk of
707                                            code is ugly, and I don't feel like doing anything
708                                            about it.  Think of it as stubbornness in action */
709                                         growth=0;
710                                         for (lie=(struct broken_word *)(fragP->fr_symbol);
711                                              lie && lie->dispfrag==fragP;
712                                              lie=lie->next_broken_word) {
713                                                 
714                                                 if (lie->added)
715                                                     continue;
716                                                 
717                                                 offset=  lie->add->sy_frag->fr_address+ S_GET_VALUE(lie->add) + lie->addnum -
718                                                     (lie->sub->sy_frag->fr_address+ S_GET_VALUE(lie->sub));
719                                                 if (offset<=-32768 || offset>=32767) {
720                                                         if (flagseen['k'])
721                                                             as_warn(".word %s-%s+%ld didn't fit",
722                                                                     S_GET_NAME(lie->add),
723                                                                     S_GET_NAME(lie->sub),
724                                                                     lie->addnum);
725                                                         lie->added=1;
726                                                         if (fragP->fr_subtype==0) {
727                                                                 fragP->fr_subtype++;
728                                                                 growth+=md_short_jump_size;
729                                                         }
730                                                         for (untruth=lie->next_broken_word;untruth && untruth->dispfrag==lie->dispfrag;untruth=untruth->next_broken_word)
731                                                             if ((untruth->add->sy_frag == lie->add->sy_frag)
732                                                                 && S_GET_VALUE(untruth->add) == S_GET_VALUE(lie->add)) {
733                                                                     untruth->added=2;
734                                                                     untruth->use_jump=lie;
735                                                             }
736                                                         growth+=md_long_jump_size;
737                                                 }
738                                         }
739                                         
740                                         break;
741                                 } /* case rs_broken_word */
742 #endif
743                                 case rs_align:
744                                         growth = relax_align((relax_addressT) (address + fragP->fr_fix), offset)
745                                             - relax_align((relax_addressT) (was_address + fragP->fr_fix), offset);
746                                         break;
747                                         
748                                 case rs_org:
749                                         target = offset;
750                                         
751                                         if (symbolP) {
752 #ifdef MANY_SEGMENTS
753 #else
754                                                 know((S_GET_SEGMENT(symbolP) == SEG_ABSOLUTE) || (S_GET_SEGMENT(symbolP) == SEG_DATA) || (S_GET_SEGMENT(symbolP) == SEG_TEXT));
755                                                 know(symbolP->sy_frag);
756                                                 know(!(S_GET_SEGMENT(symbolP) == SEG_ABSOLUTE) || (symbolP->sy_frag == &zero_address_frag));
757 #endif
758                                                 target += S_GET_VALUE(symbolP)
759                                                     + symbolP->sy_frag->fr_address;
760                                         } /* if we have a symbol */
761                                         
762                                         know(fragP->fr_next);
763                                         after = fragP->fr_next->fr_address;
764                                         growth = ((target - after ) > 0) ? (target - after) : 0;
765                                         /* Growth may be -ve, but variable part */
766                                         /* of frag cannot have < 0 chars. */
767                                         /* That is, we can't .org backwards. */
768                                         
769                                         growth -= stretch;      /* This is an absolute growth factor */
770                                         break;
771                                         
772                                 case rs_machine_dependent: {
773                                         register const relax_typeS *    this_type;
774                                         register const relax_typeS *    start_type;
775                                         register relax_substateT        next_state;
776                                         register relax_substateT        this_state;
777                                         
778                                         start_type = this_type = md_relax_table + (this_state = fragP->fr_subtype);
779                                         target = offset;
780                                         
781                                         if (symbolP) {
782 #ifndef MANY_SEGMENTS
783                                                 know((S_GET_SEGMENT(symbolP) == SEG_ABSOLUTE) || (S_GET_SEGMENT(symbolP) == SEG_DATA) || (S_GET_SEGMENT(symbolP) == SEG_TEXT));
784 #endif
785                                                 know(symbolP->sy_frag);
786                                                 know(!(S_GET_SEGMENT(symbolP) == SEG_ABSOLUTE) || symbolP->sy_frag==&zero_address_frag );
787                                                 target +=
788                                                     S_GET_VALUE(symbolP)
789                                                         + symbolP->sy_frag->fr_address;
790                                                 
791                                                 /* If frag has yet to be reached on this pass,
792                                                    assume it will move by STRETCH just as we did.
793                                                    If this is not so, it will be because some frag
794                                                    between grows, and that will force another pass.  */
795                                                 
796                                                 /* JF was just address */
797                                                 /* JF also added is_dnrange hack */
798                                                 /* There's gotta be a better/faster/etc way
799                                                    to do this. . . */
800                                                 /* gnu@cygnus.com:  I changed this from > to >=
801                                                    because I ran into a zero-length frag (fr_fix=0)
802                                                    which was created when the obstack needed a new
803                                                    chunk JUST AFTER the opcode of a branch.  Since
804                                                    fr_fix is zero, fr_address of this frag is the same
805                                                    as fr_address of the next frag.  This
806                                                    zero-length frag was variable and jumped to .+2
807                                                    (in the next frag), but since the > comparison
808                                                    below failed (the two were =, not >), "stretch"
809                                                    was not added to the target.  Stretch was 178, so
810                                                    the offset appeared to be .-176 instead, which did
811                                                    not fit into a byte branch, so the assembler
812                                                    relaxed the branch to a word.  This didn't compare
813                                                    with what happened when the same source file was
814                                                    assembled on other machines, which is how I found it.
815                                                    You might want to think about what other places have
816                                                    trouble with zero length frags... */
817                                                 
818                                                 if (symbolP->sy_frag->fr_address >= was_address
819                                                     && is_dnrange(fragP,symbolP->sy_frag)) {
820                                                         target += stretch;
821                                                 } /*  */
822                                                 
823                                         } /* if there's a symbol attached */
824                                         
825                                         aim = target - address - fragP->fr_fix;
826                                         /* The displacement is affected by the instruction size
827                                          * for the 32k architecture. I think we ought to be able
828                                          * to add fragP->fr_pcrel_adjust in all cases (it should be
829                                          * zero if not used), but just in case it breaks something
830                                          * else we'll put this inside #ifdef NS32K ... #endif
831                                          */
832 #ifdef TC_NS32K
833                                         aim += fragP->fr_pcrel_adjust;
834 #endif /* TC_NS32K */
835                                         
836                                         if (aim < 0) {
837                                                 /* Look backwards. */
838                                                 for (next_state = this_type->rlx_more; next_state; ) {
839                                                         if (aim >= this_type->rlx_backward) {
840                                                                 next_state = 0;
841                                                         } else { /* Grow to next state. */
842                                                                 this_type = md_relax_table + (this_state = next_state);
843                                                                 next_state = this_type->rlx_more;
844                                                         }
845                                                 }
846                                         } else {
847 #ifdef DONTDEF
848                                                 /* JF these next few lines of code are for the mc68020 which can't handle short
849                                                    offsets of zero in branch instructions.  What a kludge! */
850                                                 if (aim==0 && this_state==(1<<2+0)) { /* FOO hard encoded from m.c */
851                                                         aim=this_type->rlx_forward+1; /* Force relaxation into word mode */
852                                                 }
853 #endif
854 #ifdef M68K_AIM_KLUDGE
855                                                 M68K_AIM_KLUDGE(aim, this_state, this_type);
856 #endif
857                                                 /* JF end of 68020 code */
858                                                 /* Look forwards. */
859                                                 for (next_state = this_type->rlx_more; next_state; ) {
860                                                         if (aim <= this_type->rlx_forward) {
861                                                                 next_state = 0;
862                                                         } else { /* Grow to next state. */
863                                                                 this_type = md_relax_table + (this_state = next_state);
864                                                                 next_state = this_type->rlx_more;
865                                                         }
866                                                 }
867                                         }
868                                         
869                                         if ((growth = this_type->rlx_length - start_type->rlx_length) != 0)
870                                             fragP->fr_subtype = this_state;
871                                         
872                                         break;
873                                 } /* case rs_machine_dependent */
874                                         
875                                 default:
876                                         BAD_CASE( fragP->fr_type );
877                                         break;
878                                 }
879                                 if (growth) {
880                                         stretch += growth;
881                                         stretched++;
882                                 }
883                         } /* For each frag in the segment. */
884                 } while (stretched);    /* Until nothing further to relax. */
885         } /* do_relax */
886         
887         /*
888          * We now have valid fr_address'es for each frag.
889          */
890         
891         /*
892          * All fr_address's are correct, relative to their own segment.
893          * We have made all the fixS we will ever make.
894          */
895 } /* relax_segment() */
896
897 /*
898  * Relax_align. Advance location counter to next address that has 'alignment'
899  * lowest order bits all 0s.
900  */
901
902 /* How many addresses does the .align take? */
903 static relax_addressT relax_align(address, alignment)
904 register relax_addressT address; /* Address now. */
905 register long alignment; /* Alignment (binary). */
906 {
907         relax_addressT  mask;
908         relax_addressT  new_address;
909         
910         mask = ~ ( (~0) << alignment );
911         new_address = (address + mask) & (~ mask);
912         return (new_address - address);
913 } /* relax_align() */
914
915 /* fixup_segment()
916    
917    Go through all the fixS's in a segment and see which ones can be
918    handled now.  (These consist of fixS where we have since discovered
919    the value of a symbol, or the address of the frag involved.)
920    For each one, call md_apply_fix to put the fix into the frag data.
921    
922    Result is a count of how many relocation structs will be needed to
923    handle the remaining fixS's that we couldn't completely handle here.
924    These will be output later by emit_relocations().  */
925
926 static long fixup_segment(fixP, this_segment_type)
927 register fixS * fixP;
928 segT            this_segment_type; /* N_TYPE bits for segment. */
929 {
930         register long seg_reloc_count;
931         register symbolS *add_symbolP;
932         register symbolS *sub_symbolP;
933         register long add_number;
934         register int size;
935         register char *place;
936         register long where;
937         register char pcrel;
938         register fragS *fragP;
939         register segT add_symbol_segment = SEG_ABSOLUTE;
940         
941         /* FIXME: remove this line */ /*        fixS *orig = fixP; */
942         seg_reloc_count = 0;
943         
944         for ( ;  fixP;  fixP = fixP->fx_next) {
945                 fragP       = fixP->fx_frag;
946                 know(fragP);
947                 where     = fixP->fx_where;
948                 place       = fragP->fr_literal + where;
949                 size      = fixP->fx_size;
950                 add_symbolP = fixP->fx_addsy;
951 #ifdef TC_I960
952                 if (fixP->fx_callj && TC_S_IS_CALLNAME(add_symbolP)) {
953                         /* Relocation should be done via the
954                            associated 'bal' entry point
955                            symbol. */
956                         
957                         if (!TC_S_IS_BALNAME(tc_get_bal_of_call(add_symbolP))) {
958                                 as_bad("No 'bal' entry point for leafproc %s",
959                                        S_GET_NAME(add_symbolP));
960                                 continue;
961                         }
962                         fixP->fx_addsy = add_symbolP = tc_get_bal_of_call(add_symbolP);
963                 }       /* callj relocation */
964 #endif
965                 sub_symbolP = fixP->fx_subsy;
966                 add_number  = fixP->fx_offset;
967                 pcrel     = fixP->fx_pcrel;
968                 
969                 if (add_symbolP) {
970                         add_symbol_segment = S_GET_SEGMENT(add_symbolP);
971                 }       /* if there is an addend */
972                 
973                 if (sub_symbolP) {
974                         if (!add_symbolP) {
975                                 /* Its just -sym */
976                                 if (S_GET_SEGMENT(sub_symbolP) != SEG_ABSOLUTE) {
977                                         as_bad("Negative of non-absolute symbol %s", S_GET_NAME(sub_symbolP));
978                                 } /* not absolute */
979                                 
980                                 add_number -= S_GET_VALUE(sub_symbolP);
981                                 
982                                 /* if sub_symbol is in the same segment that add_symbol
983                                    and add_symbol is either in DATA, TEXT, BSS or ABSOLUTE */
984                         } else if ((S_GET_SEGMENT(sub_symbolP) == add_symbol_segment)
985                                    && (SEG_NORMAL(add_symbol_segment)
986                                        || (add_symbol_segment == SEG_ABSOLUTE))) {
987                                 /* Difference of 2 symbols from same segment. */
988                                 /* Can't make difference of 2 undefineds: 'value' means */
989                                 /* something different for N_UNDF. */
990 #ifdef TC_I960
991                                 /* Makes no sense to use the difference of 2 arbitrary symbols
992                                  * as the target of a call instruction.
993                                  */
994                                 if (fixP->fx_callj) {
995                                         as_bad("callj to difference of 2 symbols");
996                                 }
997 #endif  /* TC_I960 */
998                                 add_number += S_GET_VALUE(add_symbolP) - 
999                                     S_GET_VALUE(sub_symbolP);
1000                                 
1001                                 add_symbolP = NULL;
1002                                 fixP->fx_addsy = NULL;
1003                         } else {
1004                                 /* Different segments in subtraction. */
1005                                 know(!(S_IS_EXTERNAL(sub_symbolP) && (S_GET_SEGMENT(sub_symbolP) == SEG_ABSOLUTE)));
1006                                 
1007                                 if ((S_GET_SEGMENT(sub_symbolP) == SEG_ABSOLUTE)) {
1008                                         add_number -= S_GET_VALUE(sub_symbolP);
1009                                 } else {
1010                                         as_bad("Can't emit reloc {- %s-seg symbol \"%s\"} @ file address %d.",
1011                                                segment_name(S_GET_SEGMENT(sub_symbolP)),
1012                                                S_GET_NAME(sub_symbolP), fragP->fr_address + where);
1013                                 } /* if absolute */
1014                         }
1015                 } /* if sub_symbolP */
1016                 
1017                 if (add_symbolP) {
1018                         if (add_symbol_segment == this_segment_type && pcrel) {
1019                                 /*
1020                                  * This fixup was made when the symbol's segment was
1021                                  * SEG_UNKNOWN, but it is now in the local segment.
1022                                  * So we know how to do the address without relocation.
1023                                  */
1024 #ifdef TC_I960
1025                                 /* reloc_callj() may replace a 'call' with a 'calls' or a 'bal',
1026                                  * in which cases it modifies *fixP as appropriate.  In the case
1027                                  * of a 'calls', no further work is required, and *fixP has been
1028                                  * set up to make the rest of the code below a no-op.
1029                                  */
1030                                 reloc_callj(fixP);
1031 #endif /* TC_I960 */
1032                                 
1033                                 add_number += S_GET_VALUE(add_symbolP);
1034                                 add_number -= md_pcrel_from (fixP);
1035                                 pcrel = 0;      /* Lie. Don't want further pcrel processing. */
1036                                 fixP->fx_addsy = NULL; /* No relocations please. */
1037                         } else {
1038                                 switch (add_symbol_segment) {
1039                                 case SEG_ABSOLUTE:
1040 #ifdef TC_I960
1041                                         reloc_callj(fixP); /* See comment about reloc_callj() above*/
1042 #endif /* TC_I960 */
1043                                         add_number += S_GET_VALUE(add_symbolP);
1044                                         fixP->fx_addsy = NULL;
1045                                         add_symbolP = NULL;
1046                                         break;
1047                                 default:
1048                                         seg_reloc_count ++;
1049                                         add_number += S_GET_VALUE(add_symbolP);
1050                                         break;
1051                                         
1052                                 case SEG_UNKNOWN:
1053 #ifdef TC_I960
1054                                         if ((int)fixP->fx_bit_fixP == 13) {
1055                                                 /* This is a COBR instruction.  They have only a
1056                                                  * 13-bit displacement and are only to be used
1057                                                  * for local branches: flag as error, don't generate
1058                                                  * relocation.
1059                                                  */
1060                                                 as_bad("can't use COBR format with external label");
1061                                                 fixP->fx_addsy = NULL;  /* No relocations please. */
1062                                                 continue;
1063                                         } /* COBR */
1064 #endif /* TC_I960 */
1065                                         /* FIXME-SOON: I think this is trash, but I'm not sure.  xoxorich. */
1066 #ifdef comment
1067 #ifdef OBJ_COFF
1068                                         if (S_IS_COMMON(add_symbolP))
1069                                             add_number += S_GET_VALUE(add_symbolP);
1070 #endif /* OBJ_COFF */
1071 #endif /* comment */
1072                                         
1073                                         ++seg_reloc_count;
1074                                         
1075                                         break;
1076                                         
1077                                         
1078                                 } /* switch on symbol seg */
1079                         } /* if not in local seg */
1080                 } /* if there was a + symbol */
1081                 
1082                 if (pcrel) {
1083                         add_number -= md_pcrel_from(fixP);
1084                         if (add_symbolP == 0) {
1085                                 fixP->fx_addsy = & abs_symbol;
1086                                 ++seg_reloc_count;
1087                         } /* if there's an add_symbol */
1088                 } /* if pcrel */
1089                 
1090                 if (!fixP->fx_bit_fixP) {
1091                         if ((size==1 &&
1092                              (add_number& ~0xFF)   && (add_number&~0xFF!=(-1&~0xFF))) ||
1093                             (size==2 &&
1094                              (add_number& ~0xFFFF) && (add_number&~0xFFFF!=(-1&~0xFFFF)))) {
1095                                 as_bad("Value of %d too large for field of %d bytes at 0x%x",
1096                                        add_number, size, fragP->fr_address + where);
1097                         } /* generic error checking */
1098                 } /* not a bit fix */
1099                 
1100                 md_apply_fix(fixP, add_number);
1101         } /* For each fixS in this segment. */
1102         
1103 #ifdef OBJ_COFF
1104 #ifdef TC_I960
1105         {
1106                 fixS *topP = fixP;
1107                 
1108                 /* two relocs per callj under coff. */
1109                 for (fixP = topP; fixP; fixP = fixP->fx_next) {
1110                         if (fixP->fx_callj && fixP->fx_addsy != 0) {
1111                                 ++seg_reloc_count;
1112                         } /* if callj and not already fixed. */
1113                 } /* for each fix */
1114         }
1115 #endif /* TC_I960 */
1116         
1117 #endif /* OBJ_COFF */
1118         return(seg_reloc_count);
1119 } /* fixup_segment() */
1120
1121
1122 static int is_dnrange(f1,f2)
1123 struct frag *f1;
1124 struct frag *f2;
1125 {
1126         while (f1) {
1127                 if (f1->fr_next==f2)
1128                     return 1;
1129                 f1=f1->fr_next;
1130         }
1131         return 0;
1132 } /* is_dnrange() */
1133
1134 /* Append a string onto another string, bumping the pointer along.  */
1135 void
1136     append (charPP, fromP, length)
1137 char    **charPP;
1138 char    *fromP;
1139 unsigned long length;
1140 {
1141         if (length) {           /* Don't trust bcopy() of 0 chars. */
1142                 bcopy(fromP, *charPP, (int) length);
1143                 *charPP += length;
1144         }
1145 }
1146
1147 int section_alignment[SEG_MAXIMUM_ORDINAL];
1148
1149 /*
1150  * This routine records the largest alignment seen for each segment.
1151  * If the beginning of the segment is aligned on the worst-case
1152  * boundary, all of the other alignments within it will work.  At
1153  * least one object format really uses this info.
1154  */
1155 void record_alignment(seg, align)
1156 segT seg;       /* Segment to which alignment pertains */
1157 int align;      /* Alignment, as a power of 2
1158                  *      (e.g., 1 => 2-byte boundary, 2 => 4-byte boundary, etc.)
1159                  */
1160 {
1161         
1162         if ( align > section_alignment[(int) seg] ){
1163                 section_alignment[(int) seg] = align;
1164         } /* if highest yet */
1165         
1166         return;
1167 } /* record_alignment() */
1168
1169 /*
1170  * Local Variables:
1171  * comment-column: 0
1172  * fill-column: 131
1173  * End:
1174  */
1175
1176 /* end of write.c */