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