* Makefile.am (GAS_CFILES): Remove bignum-copy.c.
[external/binutils.git] / gas / config / obj-coff.c
1 /* coff object file format
2    Copyright 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998,
3    1999, 2000, 2001, 2002, 2003, 2004, 2005
4    Free Software Foundation, Inc.
5
6    This file is part of GAS.
7
8    GAS is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 2, or (at your option)
11    any later version.
12
13    GAS is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with GAS; see the file COPYING.  If not, write to the Free
20    Software Foundation, 59 Temple Place - Suite 330, Boston, MA
21    02111-1307, USA.  */
22
23 #define OBJ_HEADER "obj-coff.h"
24
25 #include "as.h"
26 #include "obstack.h"
27 #include "subsegs.h"
28
29 #ifdef TE_PE
30 #include "coff/pe.h"
31 #endif
32
33 #define streq(a,b)     (strcmp ((a), (b)) == 0)
34 #define strneq(a,b,n)  (strncmp ((a), (b), (n)) == 0)
35
36 /* I think this is probably always correct.  */
37 #ifndef KEEP_RELOC_INFO
38 #define KEEP_RELOC_INFO
39 #endif
40
41 /* The BFD_ASSEMBLER version of obj_coff_section will use this macro to set
42    a new section's attributes when a directive has no valid flags or the
43    "w" flag is used. This default should be appropriate for most.  */
44 #ifndef TC_COFF_SECTION_DEFAULT_ATTRIBUTES
45 #define TC_COFF_SECTION_DEFAULT_ATTRIBUTES (SEC_LOAD | SEC_DATA)
46 #endif
47
48 /* This is used to hold the symbol built by a sequence of pseudo-ops
49    from .def and .endef.  */
50 static symbolS *def_symbol_in_progress;
51 #ifdef TE_PE
52 /* PE weak alternate symbols begin with this string.  */
53 static const char weak_altprefix[] = ".weak.";
54 #endif /* TE_PE */
55
56 typedef struct
57   {
58     unsigned long chunk_size;
59     unsigned long element_size;
60     unsigned long size;
61     char *data;
62     unsigned long pointer;
63   }
64 stack;
65
66 \f
67 /* Stack stuff.  */
68
69 static stack *
70 stack_init (unsigned long chunk_size,
71             unsigned long element_size)
72 {
73   stack *st;
74
75   st = malloc (sizeof (* st));
76   if (!st)
77     return NULL;
78   st->data = malloc (chunk_size);
79   if (!st->data)
80     {
81       free (st);
82       return NULL;
83     }
84   st->pointer = 0;
85   st->size = chunk_size;
86   st->chunk_size = chunk_size;
87   st->element_size = element_size;
88   return st;
89 }
90
91 static char *
92 stack_push (stack *st, char *element)
93 {
94   if (st->pointer + st->element_size >= st->size)
95     {
96       st->size += st->chunk_size;
97       if ((st->data = xrealloc (st->data, st->size)) == NULL)
98         return NULL;
99     }
100   memcpy (st->data + st->pointer, element, st->element_size);
101   st->pointer += st->element_size;
102   return st->data + st->pointer;
103 }
104
105 static char *
106 stack_pop (stack *st)
107 {
108   if (st->pointer < st->element_size)
109     {
110       st->pointer = 0;
111       return NULL;
112     }
113   st->pointer -= st->element_size;
114   return st->data + st->pointer;
115 }
116 \f
117 /* Maintain a list of the tagnames of the structures.  */
118
119 static struct hash_control *tag_hash;
120
121 static void
122 tag_init (void)
123 {
124   tag_hash = hash_new ();
125 }
126
127 static void
128 tag_insert (const char *name, symbolS *symbolP)
129 {
130   const char *error_string;
131
132   if ((error_string = hash_jam (tag_hash, name, (char *) symbolP)))
133     as_fatal (_("Inserting \"%s\" into structure table failed: %s"),
134               name, error_string);
135 }
136
137 static symbolS *
138 tag_find (char *name)
139 {
140   return (symbolS *) hash_find (tag_hash, name);
141 }
142
143 static symbolS *
144 tag_find_or_make (char *name)
145 {
146   symbolS *symbolP;
147
148   if ((symbolP = tag_find (name)) == NULL)
149     {
150       symbolP = symbol_new (name, undefined_section,
151                             0, &zero_address_frag);
152
153       tag_insert (S_GET_NAME (symbolP), symbolP);
154 #ifdef BFD_ASSEMBLER
155       symbol_table_insert (symbolP);
156 #endif
157     }
158
159   return symbolP;
160 }
161
162 /* We accept the .bss directive to set the section for backward
163    compatibility with earlier versions of gas.  */
164
165 static void
166 obj_coff_bss (int ignore ATTRIBUTE_UNUSED)
167 {
168   if (*input_line_pointer == '\n')
169     subseg_new (".bss", get_absolute_expression ());
170   else
171     s_lcomm (0);
172 }
173
174 #ifdef BFD_ASSEMBLER
175
176 #define GET_FILENAME_STRING(X) \
177   ((char *) (&((X)->sy_symbol.ost_auxent->x_file.x_n.x_offset))[1])
178
179 /* @@ Ick.  */
180 static segT
181 fetch_coff_debug_section (void)
182 {
183   static segT debug_section;
184
185   if (!debug_section)
186     {
187       const asymbol *s;
188
189       s = bfd_make_debug_symbol (stdoutput, NULL, 0);
190       assert (s != 0);
191       debug_section = s->section;
192     }
193   return debug_section;
194 }
195
196 void
197 SA_SET_SYM_ENDNDX (symbolS *sym, symbolS *val)
198 {
199   combined_entry_type *entry, *p;
200
201   entry = &coffsymbol (symbol_get_bfdsym (sym))->native[1];
202   p = coffsymbol (symbol_get_bfdsym (val))->native;
203   entry->u.auxent.x_sym.x_fcnary.x_fcn.x_endndx.p = p;
204   entry->fix_end = 1;
205 }
206
207 static void
208 SA_SET_SYM_TAGNDX (symbolS *sym, symbolS *val)
209 {
210   combined_entry_type *entry, *p;
211
212   entry = &coffsymbol (symbol_get_bfdsym (sym))->native[1];
213   p = coffsymbol (symbol_get_bfdsym (val))->native;
214   entry->u.auxent.x_sym.x_tagndx.p = p;
215   entry->fix_tag = 1;
216 }
217
218 static int
219 S_GET_DATA_TYPE (symbolS *sym)
220 {
221   return coffsymbol (symbol_get_bfdsym (sym))->native->u.syment.n_type;
222 }
223
224 int
225 S_SET_DATA_TYPE (symbolS *sym, int val)
226 {
227   coffsymbol (symbol_get_bfdsym (sym))->native->u.syment.n_type = val;
228   return val;
229 }
230
231 int
232 S_GET_STORAGE_CLASS (symbolS *sym)
233 {
234   return coffsymbol (symbol_get_bfdsym (sym))->native->u.syment.n_sclass;
235 }
236
237 int
238 S_SET_STORAGE_CLASS (symbolS *sym, int val)
239 {
240   coffsymbol (symbol_get_bfdsym (sym))->native->u.syment.n_sclass = val;
241   return val;
242 }
243
244 /* Merge a debug symbol containing debug information into a normal symbol.  */
245
246 static void
247 c_symbol_merge (symbolS *debug, symbolS *normal)
248 {
249   S_SET_DATA_TYPE (normal, S_GET_DATA_TYPE (debug));
250   S_SET_STORAGE_CLASS (normal, S_GET_STORAGE_CLASS (debug));
251
252   if (S_GET_NUMBER_AUXILIARY (debug) > S_GET_NUMBER_AUXILIARY (normal))
253     /* Take the most we have.  */
254     S_SET_NUMBER_AUXILIARY (normal, S_GET_NUMBER_AUXILIARY (debug));
255
256   if (S_GET_NUMBER_AUXILIARY (debug) > 0)
257     /* Move all the auxiliary information.  */
258     memcpy (SYM_AUXINFO (normal), SYM_AUXINFO (debug),
259             (S_GET_NUMBER_AUXILIARY (debug)
260              * sizeof (*SYM_AUXINFO (debug))));
261
262   /* Move the debug flags.  */
263   SF_SET_DEBUG_FIELD (normal, SF_GET_DEBUG_FIELD (debug));
264 }
265
266 void
267 c_dot_file_symbol (const char *filename, int appfile ATTRIBUTE_UNUSED)
268 {
269   symbolS *symbolP;
270
271   /* BFD converts filename to a .file symbol with an aux entry.  It
272      also handles chaining.  */
273   symbolP = symbol_new (filename, bfd_abs_section_ptr, 0, &zero_address_frag);
274
275   S_SET_STORAGE_CLASS (symbolP, C_FILE);
276   S_SET_NUMBER_AUXILIARY (symbolP, 1);
277
278   symbol_get_bfdsym (symbolP)->flags = BSF_DEBUGGING;
279
280 #ifndef NO_LISTING
281   {
282     extern int listing;
283
284     if (listing)
285       listing_source_file (filename);
286   }
287 #endif
288
289   /* Make sure that the symbol is first on the symbol chain.  */
290   if (symbol_rootP != symbolP)
291     {
292       symbol_remove (symbolP, &symbol_rootP, &symbol_lastP);
293       symbol_insert (symbolP, symbol_rootP, &symbol_rootP, &symbol_lastP);
294     }
295 }
296
297 /* Line number handling.  */
298
299 struct line_no
300 {
301   struct line_no *next;
302   fragS *frag;
303   alent l;
304 };
305
306 int coff_line_base;
307
308 /* Symbol of last function, which we should hang line#s off of.  */
309 static symbolS *line_fsym;
310
311 #define in_function()           (line_fsym != 0)
312 #define clear_function()        (line_fsym = 0)
313 #define set_function(F)         (line_fsym = (F), coff_add_linesym (F))
314
315 \f
316 void
317 coff_obj_symbol_new_hook (symbolS *symbolP)
318 {
319   long   sz = (OBJ_COFF_MAX_AUXENTRIES + 1) * sizeof (combined_entry_type);
320   char * s  = xmalloc (sz);
321
322   memset (s, 0, sz);
323   coffsymbol (symbol_get_bfdsym (symbolP))->native = (combined_entry_type *) s;
324
325   S_SET_DATA_TYPE (symbolP, T_NULL);
326   S_SET_STORAGE_CLASS (symbolP, 0);
327   S_SET_NUMBER_AUXILIARY (symbolP, 0);
328
329   if (S_IS_STRING (symbolP))
330     SF_SET_STRING (symbolP);
331
332   if (S_IS_LOCAL (symbolP))
333     SF_SET_LOCAL (symbolP);
334 }
335
336 \f
337 /* Handle .ln directives.  */
338
339 static symbolS *current_lineno_sym;
340 static struct line_no *line_nos;
341 /* FIXME:  Blindly assume all .ln directives will be in the .text section.  */
342 int coff_n_line_nos;
343
344 static void
345 add_lineno (fragS * frag, addressT offset, int num)
346 {
347   struct line_no * new_line = xmalloc (sizeof (* new_line));
348
349   if (!current_lineno_sym)
350     abort ();
351
352 #ifndef OBJ_XCOFF
353   /* The native aix assembler accepts negative line number.  */
354
355   if (num <= 0)
356     {
357       /* Zero is used as an end marker in the file.  */
358       as_warn (_("Line numbers must be positive integers\n"));
359       num = 1;
360     }
361 #endif /* OBJ_XCOFF */
362   new_line->next = line_nos;
363   new_line->frag = frag;
364   new_line->l.line_number = num;
365   new_line->l.u.offset = offset;
366   line_nos = new_line;
367   coff_n_line_nos++;
368 }
369
370 void
371 coff_add_linesym (symbolS *sym)
372 {
373   if (line_nos)
374     {
375       coffsymbol (symbol_get_bfdsym (current_lineno_sym))->lineno =
376         (alent *) line_nos;
377       coff_n_line_nos++;
378       line_nos = 0;
379     }
380   current_lineno_sym = sym;
381 }
382
383 static void
384 obj_coff_ln (int appline)
385 {
386   int l;
387
388   if (! appline && def_symbol_in_progress != NULL)
389     {
390       as_warn (_(".ln pseudo-op inside .def/.endef: ignored."));
391       demand_empty_rest_of_line ();
392       return;
393     }
394
395   l = get_absolute_expression ();
396
397   /* If there is no lineno symbol, treat a .ln
398      directive as if it were a .appline directive.  */
399   if (appline || current_lineno_sym == NULL)
400     new_logical_line ((char *) NULL, l - 1);
401   else
402     add_lineno (frag_now, frag_now_fix (), l);
403
404 #ifndef NO_LISTING
405   {
406     extern int listing;
407
408     if (listing)
409       {
410         if (! appline)
411           l += coff_line_base - 1;
412         listing_source_line (l);
413       }
414   }
415 #endif
416
417   demand_empty_rest_of_line ();
418 }
419
420 /* .loc is essentially the same as .ln; parse it for assembler
421    compatibility.  */
422
423 static void
424 obj_coff_loc (int ignore ATTRIBUTE_UNUSED)
425 {
426   int lineno;
427
428   /* FIXME: Why do we need this check?  We need it for ECOFF, but why
429      do we need it for COFF?  */
430   if (now_seg != text_section)
431     {
432       as_warn (_(".loc outside of .text"));
433       demand_empty_rest_of_line ();
434       return;
435     }
436
437   if (def_symbol_in_progress != NULL)
438     {
439       as_warn (_(".loc pseudo-op inside .def/.endef: ignored."));
440       demand_empty_rest_of_line ();
441       return;
442     }
443
444   /* Skip the file number.  */
445   SKIP_WHITESPACE ();
446   get_absolute_expression ();
447   SKIP_WHITESPACE ();
448
449   lineno = get_absolute_expression ();
450
451 #ifndef NO_LISTING
452   {
453     extern int listing;
454
455     if (listing)
456       {
457         lineno += coff_line_base - 1;
458         listing_source_line (lineno);
459       }
460   }
461 #endif
462
463   demand_empty_rest_of_line ();
464
465   add_lineno (frag_now, frag_now_fix (), lineno);
466 }
467
468 /* Handle the .ident pseudo-op.  */
469
470 static void
471 obj_coff_ident (int ignore ATTRIBUTE_UNUSED)
472 {
473   segT current_seg = now_seg;
474   subsegT current_subseg = now_subseg;
475
476 #ifdef TE_PE
477   {
478     segT sec;
479
480     /* We could put it in .comment, but that creates an extra section
481        that shouldn't be loaded into memory, which requires linker
482        changes...  For now, until proven otherwise, use .rdata.  */
483     sec = subseg_new (".rdata$zzz", 0);
484     bfd_set_section_flags (stdoutput, sec,
485                            ((SEC_ALLOC | SEC_LOAD | SEC_READONLY | SEC_DATA)
486                             & bfd_applicable_section_flags (stdoutput)));
487   }
488 #else
489   subseg_new (".comment", 0);
490 #endif
491
492   stringer (1);
493   subseg_set (current_seg, current_subseg);
494 }
495
496 /* Handle .def directives.
497
498    One might ask : why can't we symbol_new if the symbol does not
499    already exist and fill it with debug information.  Because of
500    the C_EFCN special symbol. It would clobber the value of the
501    function symbol before we have a chance to notice that it is
502    a C_EFCN. And a second reason is that the code is more clear this
503    way. (at least I think it is :-).  */
504
505 #define SKIP_SEMI_COLON()       while (*input_line_pointer++ != ';')
506 #define SKIP_WHITESPACES()      while (*input_line_pointer == ' ' || \
507                                        *input_line_pointer == '\t')  \
508                                   input_line_pointer++;
509
510 static void
511 obj_coff_def (int what ATTRIBUTE_UNUSED)
512 {
513   char name_end;                /* Char after the end of name.  */
514   char *symbol_name;            /* Name of the debug symbol.  */
515   char *symbol_name_copy;       /* Temporary copy of the name.  */
516   unsigned int symbol_name_length;
517
518   if (def_symbol_in_progress != NULL)
519     {
520       as_warn (_(".def pseudo-op used inside of .def/.endef: ignored."));
521       demand_empty_rest_of_line ();
522       return;
523     }
524
525   SKIP_WHITESPACES ();
526
527   symbol_name = input_line_pointer;
528   name_end = get_symbol_end ();
529   symbol_name_length = strlen (symbol_name);
530   symbol_name_copy = xmalloc (symbol_name_length + 1);
531   strcpy (symbol_name_copy, symbol_name);
532 #ifdef tc_canonicalize_symbol_name
533   symbol_name_copy = tc_canonicalize_symbol_name (symbol_name_copy);
534 #endif
535
536   /* Initialize the new symbol.  */
537   def_symbol_in_progress = symbol_make (symbol_name_copy);
538   symbol_set_frag (def_symbol_in_progress, &zero_address_frag);
539   S_SET_VALUE (def_symbol_in_progress, 0);
540
541   if (S_IS_STRING (def_symbol_in_progress))
542     SF_SET_STRING (def_symbol_in_progress);
543
544   *input_line_pointer = name_end;
545
546   demand_empty_rest_of_line ();
547 }
548
549 unsigned int dim_index;
550
551 static void
552 obj_coff_endef (int ignore ATTRIBUTE_UNUSED)
553 {
554   symbolS *symbolP = NULL;
555
556   dim_index = 0;
557   if (def_symbol_in_progress == NULL)
558     {
559       as_warn (_(".endef pseudo-op used outside of .def/.endef: ignored."));
560       demand_empty_rest_of_line ();
561       return;
562     }
563
564   /* Set the section number according to storage class.  */
565   switch (S_GET_STORAGE_CLASS (def_symbol_in_progress))
566     {
567     case C_STRTAG:
568     case C_ENTAG:
569     case C_UNTAG:
570       SF_SET_TAG (def_symbol_in_progress);
571       /* Fall through.  */
572     case C_FILE:
573     case C_TPDEF:
574       SF_SET_DEBUG (def_symbol_in_progress);
575       S_SET_SEGMENT (def_symbol_in_progress, fetch_coff_debug_section ());
576       break;
577
578     case C_EFCN:
579       SF_SET_LOCAL (def_symbol_in_progress);    /* Do not emit this symbol.  */
580       /* Fall through.  */
581     case C_BLOCK:
582       SF_SET_PROCESS (def_symbol_in_progress);  /* Will need processing before writing.  */
583       /* Fall through.  */
584     case C_FCN:
585       {
586         const char *name;
587
588         S_SET_SEGMENT (def_symbol_in_progress, text_section);
589
590         name = S_GET_NAME (def_symbol_in_progress);
591         if (name[0] == '.' && name[2] == 'f' && name[3] == '\0')
592           {
593             switch (name[1])
594               {
595               case 'b':
596                 /* .bf */
597                 if (! in_function ())
598                   as_warn (_("`%s' symbol without preceding function"), name);
599                 /* Will need relocating.  */
600                 SF_SET_PROCESS (def_symbol_in_progress);
601                 clear_function ();
602                 break;
603 #ifdef TE_PE
604               case 'e':
605                 /* .ef */
606                 /* The MS compilers output the actual endline, not the
607                    function-relative one... we want to match without
608                    changing the assembler input.  */
609                 SA_SET_SYM_LNNO (def_symbol_in_progress,
610                                  (SA_GET_SYM_LNNO (def_symbol_in_progress)
611                                   + coff_line_base));
612                 break;
613 #endif
614               }
615           }
616       }
617       break;
618
619 #ifdef C_AUTOARG
620     case C_AUTOARG:
621 #endif /* C_AUTOARG */
622     case C_AUTO:
623     case C_REG:
624     case C_ARG:
625     case C_REGPARM:
626     case C_FIELD:
627
628     /* According to the COFF documentation:
629
630        http://osr5doc.sco.com:1996/topics/COFF_SectNumFld.html
631
632        A special section number (-2) marks symbolic debugging symbols,
633        including structure/union/enumeration tag names, typedefs, and
634        the name of the file. A section number of -1 indicates that the
635        symbol has a value but is not relocatable. Examples of
636        absolute-valued symbols include automatic and register variables,
637        function arguments, and .eos symbols.
638
639        But from Ian Lance Taylor:
640
641        http://sources.redhat.com/ml/binutils/2000-08/msg00202.html
642
643        the actual tools all marked them as section -1. So the GNU COFF
644        assembler follows historical COFF assemblers.
645
646        However, it causes problems for djgpp
647
648        http://sources.redhat.com/ml/binutils/2000-08/msg00210.html
649
650        By defining STRICTCOFF, a COFF port can make the assembler to
651        follow the documented behavior.  */
652 #ifdef STRICTCOFF
653     case C_MOS:
654     case C_MOE:
655     case C_MOU:
656     case C_EOS:
657 #endif
658       SF_SET_DEBUG (def_symbol_in_progress);
659       S_SET_SEGMENT (def_symbol_in_progress, absolute_section);
660       break;
661
662 #ifndef STRICTCOFF
663     case C_MOS:
664     case C_MOE:
665     case C_MOU:
666     case C_EOS:
667       S_SET_SEGMENT (def_symbol_in_progress, absolute_section);
668       break;
669 #endif
670
671     case C_EXT:
672     case C_WEAKEXT:
673 #ifdef TE_PE
674     case C_NT_WEAK:
675 #endif
676     case C_STAT:
677     case C_LABEL:
678       /* Valid but set somewhere else (s_comm, s_lcomm, colon).  */
679       break;
680
681     default:
682     case C_USTATIC:
683     case C_EXTDEF:
684     case C_ULABEL:
685       as_warn (_("unexpected storage class %d"),
686                S_GET_STORAGE_CLASS (def_symbol_in_progress));
687       break;
688     }
689
690   /* Now that we have built a debug symbol, try to find if we should
691      merge with an existing symbol or not.  If a symbol is C_EFCN or
692      absolute_section or untagged SEG_DEBUG it never merges.  We also
693      don't merge labels, which are in a different namespace, nor
694      symbols which have not yet been defined since they are typically
695      unique, nor do we merge tags with non-tags.  */
696
697   /* Two cases for functions.  Either debug followed by definition or
698      definition followed by debug.  For definition first, we will
699      merge the debug symbol into the definition.  For debug first, the
700      lineno entry MUST point to the definition function or else it
701      will point off into space when obj_crawl_symbol_chain() merges
702      the debug symbol into the real symbol.  Therefor, let's presume
703      the debug symbol is a real function reference.  */
704
705   /* FIXME-SOON If for some reason the definition label/symbol is
706      never seen, this will probably leave an undefined symbol at link
707      time.  */
708
709   if (S_GET_STORAGE_CLASS (def_symbol_in_progress) == C_EFCN
710       || S_GET_STORAGE_CLASS (def_symbol_in_progress) == C_LABEL
711       || (streq (bfd_get_section_name (stdoutput,
712                                        S_GET_SEGMENT (def_symbol_in_progress)),
713                  "*DEBUG*")
714           && !SF_GET_TAG (def_symbol_in_progress))
715       || S_GET_SEGMENT (def_symbol_in_progress) == absolute_section
716       || ! symbol_constant_p (def_symbol_in_progress)
717       || (symbolP = symbol_find (S_GET_NAME (def_symbol_in_progress))) == NULL
718       || SF_GET_TAG (def_symbol_in_progress) != SF_GET_TAG (symbolP))
719     {
720       /* If it already is at the end of the symbol list, do nothing */
721       if (def_symbol_in_progress != symbol_lastP)
722         {
723           symbol_remove (def_symbol_in_progress, &symbol_rootP, &symbol_lastP);
724           symbol_append (def_symbol_in_progress, symbol_lastP, &symbol_rootP,
725                          &symbol_lastP);
726         }
727     }
728   else
729     {
730       /* This symbol already exists, merge the newly created symbol
731          into the old one.  This is not mandatory. The linker can
732          handle duplicate symbols correctly. But I guess that it save
733          a *lot* of space if the assembly file defines a lot of
734          symbols. [loic]  */
735
736       /* The debug entry (def_symbol_in_progress) is merged into the
737          previous definition.  */
738
739       c_symbol_merge (def_symbol_in_progress, symbolP);
740       symbol_remove (def_symbol_in_progress, &symbol_rootP, &symbol_lastP);
741
742       def_symbol_in_progress = symbolP;
743
744       if (SF_GET_FUNCTION (def_symbol_in_progress)
745           || SF_GET_TAG (def_symbol_in_progress)
746           || S_GET_STORAGE_CLASS (def_symbol_in_progress) == C_STAT)
747         {
748           /* For functions, and tags, and static symbols, the symbol
749              *must* be where the debug symbol appears.  Move the
750              existing symbol to the current place.  */
751           /* If it already is at the end of the symbol list, do nothing.  */
752           if (def_symbol_in_progress != symbol_lastP)
753             {
754               symbol_remove (def_symbol_in_progress, &symbol_rootP, &symbol_lastP);
755               symbol_append (def_symbol_in_progress, symbol_lastP, &symbol_rootP, &symbol_lastP);
756             }
757         }
758     }
759
760   if (SF_GET_TAG (def_symbol_in_progress))
761     {
762       symbolS *oldtag;
763
764       oldtag = symbol_find (S_GET_NAME (def_symbol_in_progress));
765       if (oldtag == NULL || ! SF_GET_TAG (oldtag))
766         tag_insert (S_GET_NAME (def_symbol_in_progress),
767                     def_symbol_in_progress);
768     }
769
770   if (SF_GET_FUNCTION (def_symbol_in_progress))
771     {
772       know (sizeof (def_symbol_in_progress) <= sizeof (long));
773       set_function (def_symbol_in_progress);
774       SF_SET_PROCESS (def_symbol_in_progress);
775
776       if (symbolP == NULL)
777         /* That is, if this is the first time we've seen the
778            function.  */
779         symbol_table_insert (def_symbol_in_progress);
780
781     }
782
783   def_symbol_in_progress = NULL;
784   demand_empty_rest_of_line ();
785 }
786
787 static void
788 obj_coff_dim (int ignore ATTRIBUTE_UNUSED)
789 {
790   int dim_index;
791
792   if (def_symbol_in_progress == NULL)
793     {
794       as_warn (_(".dim pseudo-op used outside of .def/.endef: ignored."));
795       demand_empty_rest_of_line ();
796       return;
797     }
798
799   S_SET_NUMBER_AUXILIARY (def_symbol_in_progress, 1);
800
801   for (dim_index = 0; dim_index < DIMNUM; dim_index++)
802     {
803       SKIP_WHITESPACES ();
804       SA_SET_SYM_DIMEN (def_symbol_in_progress, dim_index,
805                         get_absolute_expression ());
806
807       switch (*input_line_pointer)
808         {
809         case ',':
810           input_line_pointer++;
811           break;
812
813         default:
814           as_warn (_("badly formed .dim directive ignored"));
815           /* Fall through.  */
816         case '\n':
817         case ';':
818           dim_index = DIMNUM;
819           break;
820         }
821     }
822
823   demand_empty_rest_of_line ();
824 }
825
826 static void
827 obj_coff_line (int ignore ATTRIBUTE_UNUSED)
828 {
829   int this_base;
830
831   if (def_symbol_in_progress == NULL)
832     {
833       /* Probably stabs-style line?  */
834       obj_coff_ln (0);
835       return;
836     }
837
838   this_base = get_absolute_expression ();
839   if (streq (".bf", S_GET_NAME (def_symbol_in_progress)))
840     coff_line_base = this_base;
841
842   S_SET_NUMBER_AUXILIARY (def_symbol_in_progress, 1);
843   SA_SET_SYM_LNNO (def_symbol_in_progress, this_base);
844
845   demand_empty_rest_of_line ();
846
847 #ifndef NO_LISTING
848   if (streq (".bf", S_GET_NAME (def_symbol_in_progress)))
849     {
850       extern int listing;
851
852       if (listing)
853         listing_source_line ((unsigned int) this_base);
854     }
855 #endif
856 }
857
858 static void
859 obj_coff_size (int ignore ATTRIBUTE_UNUSED)
860 {
861   if (def_symbol_in_progress == NULL)
862     {
863       as_warn (_(".size pseudo-op used outside of .def/.endef ignored."));
864       demand_empty_rest_of_line ();
865       return;
866     }
867
868   S_SET_NUMBER_AUXILIARY (def_symbol_in_progress, 1);
869   SA_SET_SYM_SIZE (def_symbol_in_progress, get_absolute_expression ());
870   demand_empty_rest_of_line ();
871 }
872
873 static void
874 obj_coff_scl (int ignore ATTRIBUTE_UNUSED)
875 {
876   if (def_symbol_in_progress == NULL)
877     {
878       as_warn (_(".scl pseudo-op used outside of .def/.endef ignored."));
879       demand_empty_rest_of_line ();
880       return;
881     }
882
883   S_SET_STORAGE_CLASS (def_symbol_in_progress, get_absolute_expression ());
884   demand_empty_rest_of_line ();
885 }
886
887 static void
888 obj_coff_tag (int ignore ATTRIBUTE_UNUSED)
889 {
890   char *symbol_name;
891   char name_end;
892
893   if (def_symbol_in_progress == NULL)
894     {
895       as_warn (_(".tag pseudo-op used outside of .def/.endef ignored."));
896       demand_empty_rest_of_line ();
897       return;
898     }
899
900   S_SET_NUMBER_AUXILIARY (def_symbol_in_progress, 1);
901   symbol_name = input_line_pointer;
902   name_end = get_symbol_end ();
903
904 #ifdef tc_canonicalize_symbol_name
905   symbol_name = tc_canonicalize_symbol_name (symbol_name);
906 #endif
907
908   /* Assume that the symbol referred to by .tag is always defined.
909      This was a bad assumption.  I've added find_or_make. xoxorich.  */
910   SA_SET_SYM_TAGNDX (def_symbol_in_progress,
911                      tag_find_or_make (symbol_name));
912   if (SA_GET_SYM_TAGNDX (def_symbol_in_progress) == 0L)
913     as_warn (_("tag not found for .tag %s"), symbol_name);
914
915   SF_SET_TAGGED (def_symbol_in_progress);
916   *input_line_pointer = name_end;
917
918   demand_empty_rest_of_line ();
919 }
920
921 static void
922 obj_coff_type (int ignore ATTRIBUTE_UNUSED)
923 {
924   if (def_symbol_in_progress == NULL)
925     {
926       as_warn (_(".type pseudo-op used outside of .def/.endef ignored."));
927       demand_empty_rest_of_line ();
928       return;
929     }
930
931   S_SET_DATA_TYPE (def_symbol_in_progress, get_absolute_expression ());
932
933   if (ISFCN (S_GET_DATA_TYPE (def_symbol_in_progress)) &&
934       S_GET_STORAGE_CLASS (def_symbol_in_progress) != C_TPDEF)
935     SF_SET_FUNCTION (def_symbol_in_progress);
936
937   demand_empty_rest_of_line ();
938 }
939
940 static void
941 obj_coff_val (int ignore ATTRIBUTE_UNUSED)
942 {
943   if (def_symbol_in_progress == NULL)
944     {
945       as_warn (_(".val pseudo-op used outside of .def/.endef ignored."));
946       demand_empty_rest_of_line ();
947       return;
948     }
949
950   if (is_name_beginner (*input_line_pointer))
951     {
952       char *symbol_name = input_line_pointer;
953       char name_end = get_symbol_end ();
954
955 #ifdef tc_canonicalize_symbol_name
956   symbol_name = tc_canonicalize_symbol_name (symbol_name);
957 #endif
958       if (streq (symbol_name, "."))
959         {
960           /* If the .val is != from the .def (e.g. statics).  */
961           symbol_set_frag (def_symbol_in_progress, frag_now);
962           S_SET_VALUE (def_symbol_in_progress, (valueT) frag_now_fix ());
963         }
964       else if (! streq (S_GET_NAME (def_symbol_in_progress), symbol_name))
965         {
966           expressionS exp;
967
968           exp.X_op = O_symbol;
969           exp.X_add_symbol = symbol_find_or_make (symbol_name);
970           exp.X_op_symbol = NULL;
971           exp.X_add_number = 0;
972           symbol_set_value_expression (def_symbol_in_progress, &exp);
973
974           /* If the segment is undefined when the forward reference is
975              resolved, then copy the segment id from the forward
976              symbol.  */
977           SF_SET_GET_SEGMENT (def_symbol_in_progress);
978
979           /* FIXME: gcc can generate address expressions here in
980              unusual cases (search for "obscure" in sdbout.c).  We
981              just ignore the offset here, thus generating incorrect
982              debugging information.  We ignore the rest of the line
983              just below.  */
984         }
985       /* Otherwise, it is the name of a non debug symbol and its value
986          will be calculated later.  */
987       *input_line_pointer = name_end;
988     }
989   else
990     {
991       S_SET_VALUE (def_symbol_in_progress, get_absolute_expression ());
992     }
993
994   demand_empty_rest_of_line ();
995 }
996
997 #ifdef TE_PE
998
999 /* Return nonzero if name begins with weak alternate symbol prefix.  */
1000
1001 static int
1002 weak_is_altname (const char * name)
1003 {
1004   return strneq (name, weak_altprefix, sizeof (weak_altprefix) - 1);
1005 }
1006
1007 /* Return the name of the alternate symbol
1008    name corresponding to a weak symbol's name.  */
1009
1010 static const char *
1011 weak_name2altname (const char * name)
1012 {
1013   char *alt_name;
1014
1015   alt_name = xmalloc (sizeof (weak_altprefix) + strlen (name));
1016   strcpy (alt_name, weak_altprefix);
1017   return strcat (alt_name, name);
1018 }
1019
1020 /* Return the name of the weak symbol corresponding to an
1021    alterate symbol.  */
1022
1023 static const char *
1024 weak_altname2name (const char * name)
1025 {
1026   char * weak_name;
1027   char * dot;
1028
1029   assert (weak_is_altname (name));
1030
1031   weak_name = xstrdup (name + 6);
1032   if ((dot = strchr (weak_name, '.')))
1033     *dot = 0;
1034   return weak_name;
1035 }
1036
1037 /* Make a weak symbol name unique by
1038    appending the name of an external symbol.  */
1039
1040 static const char *
1041 weak_uniquify (const char * name)
1042 {
1043   char *ret;
1044   const char * unique = "";
1045
1046 #ifdef USE_UNIQUE
1047   if (an_external_name != NULL)
1048     unique = an_external_name;
1049 #endif
1050   assert (weak_is_altname (name));
1051
1052   if (strchr (name + sizeof (weak_altprefix), '.'))
1053     return name;
1054
1055   ret = xmalloc (strlen (name) + strlen (unique) + 2);
1056   strcpy (ret, name);
1057   strcat (ret, ".");
1058   strcat (ret, unique);
1059   return ret;
1060 }
1061
1062 #endif  /* TE_PE */
1063
1064 /* Handle .weak.  This is a GNU extension in formats other than PE. */
1065
1066 static void
1067 obj_coff_weak (int ignore ATTRIBUTE_UNUSED)
1068 {
1069   char *name;
1070   int c;
1071   symbolS *symbolP;
1072 #ifdef TE_PE
1073   symbolS *alternateP;
1074 #endif
1075
1076   do
1077     {
1078       name = input_line_pointer;
1079       c = get_symbol_end ();
1080       if (*name == 0)
1081         {
1082           as_warn (_("badly formed .weak directive ignored"));
1083           ignore_rest_of_line ();
1084           return;
1085         }
1086       c = 0;
1087       symbolP = symbol_find_or_make (name);
1088       *input_line_pointer = c;
1089       SKIP_WHITESPACE ();
1090
1091 #if defined BFD_ASSEMBLER || defined S_SET_WEAK
1092       S_SET_WEAK (symbolP);
1093 #endif
1094
1095 #ifdef TE_PE
1096       /* See _Microsoft Portable Executable and Common Object
1097          File Format Specification_, section 5.5.3.
1098          Create a symbol representing the alternate value.
1099          coff_frob_symbol will set the value of this symbol from
1100          the value of the weak symbol itself.  */
1101       S_SET_STORAGE_CLASS (symbolP, C_NT_WEAK);
1102       S_SET_NUMBER_AUXILIARY (symbolP, 1);
1103       SA_SET_SYM_FSIZE (symbolP, IMAGE_WEAK_EXTERN_SEARCH_LIBRARY);
1104
1105       alternateP = symbol_find_or_make (weak_name2altname (name));
1106       S_SET_EXTERNAL (alternateP);
1107       S_SET_STORAGE_CLASS (alternateP, C_NT_WEAK);
1108
1109       SA_SET_SYM_TAGNDX (symbolP, alternateP);
1110 #endif
1111
1112       if (c == ',')
1113         {
1114           input_line_pointer++;
1115           SKIP_WHITESPACE ();
1116           if (*input_line_pointer == '\n')
1117             c = '\n';
1118         }
1119
1120     }
1121   while (c == ',');
1122
1123   demand_empty_rest_of_line ();
1124 }
1125
1126 void
1127 coff_obj_read_begin_hook (void)
1128 {
1129   /* These had better be the same.  Usually 18 bytes.  */
1130 #ifndef BFD_HEADERS
1131   know (sizeof (SYMENT) == sizeof (AUXENT));
1132   know (SYMESZ == AUXESZ);
1133 #endif
1134   tag_init ();
1135 }
1136
1137 symbolS *coff_last_function;
1138 #ifndef OBJ_XCOFF
1139 static symbolS *coff_last_bf;
1140 #endif
1141
1142 void
1143 coff_frob_symbol (symbolS *symp, int *punt)
1144 {
1145   static symbolS *last_tagP;
1146   static stack *block_stack;
1147   static symbolS *set_end;
1148   symbolS *next_set_end = NULL;
1149
1150   if (symp == &abs_symbol)
1151     {
1152       *punt = 1;
1153       return;
1154     }
1155
1156   if (current_lineno_sym)
1157     coff_add_linesym (NULL);
1158
1159   if (!block_stack)
1160     block_stack = stack_init (512, sizeof (symbolS*));
1161
1162 #ifdef TE_PE
1163   if (S_GET_STORAGE_CLASS (symp) == C_NT_WEAK
1164       && ! S_IS_WEAK (symp)
1165       && weak_is_altname (S_GET_NAME (symp)))
1166     {
1167       /* This is a weak alternate symbol.  All processing of
1168          PECOFFweak symbols is done here, through the alternate.  */
1169       symbolS *weakp = symbol_find (weak_altname2name (S_GET_NAME (symp)));
1170
1171       assert (weakp);
1172       assert (S_GET_NUMBER_AUXILIARY (weakp) == 1);
1173
1174       if (symbol_equated_p (weakp))
1175         {
1176           /* The weak symbol has an alternate specified; symp is unneeded.  */
1177           S_SET_STORAGE_CLASS (weakp, C_NT_WEAK);
1178           SA_SET_SYM_TAGNDX (weakp,
1179             symbol_get_value_expression (weakp)->X_add_symbol);
1180
1181           S_CLEAR_EXTERNAL (symp);
1182           *punt = 1;
1183           return;
1184         }
1185       else
1186         {
1187           /* The weak symbol has been assigned an alternate value.
1188              Copy this value to symp, and set symp as weakp's alternate.  */
1189           if (S_GET_STORAGE_CLASS (weakp) != C_NT_WEAK)
1190             {
1191               S_SET_STORAGE_CLASS (symp, S_GET_STORAGE_CLASS (weakp));
1192               S_SET_STORAGE_CLASS (weakp, C_NT_WEAK);
1193             }
1194
1195           if (S_IS_DEFINED (weakp))
1196             {
1197               /* This is a defined weak symbol.  Copy value information
1198                  from the weak symbol itself to the alternate symbol.  */
1199               symbol_set_value_expression (symp,
1200                                            symbol_get_value_expression (weakp));
1201               symbol_set_frag (symp, symbol_get_frag (weakp));
1202               S_SET_SEGMENT (symp, S_GET_SEGMENT (weakp));
1203             }
1204           else
1205             {
1206               /* This is an undefined weak symbol.
1207                  Define the alternate symbol to zero.  */
1208               S_SET_VALUE (symp, 0);
1209               S_SET_SEGMENT (symp, absolute_section);
1210             }
1211
1212           S_SET_NAME (symp, weak_uniquify (S_GET_NAME (symp)));
1213           S_SET_STORAGE_CLASS (symp, C_EXT);
1214
1215           S_SET_VALUE (weakp, 0);
1216           S_SET_SEGMENT (weakp, undefined_section);
1217         }
1218     }
1219 #else /* TE_PE */
1220   if (S_IS_WEAK (symp))
1221     S_SET_STORAGE_CLASS (symp, C_WEAKEXT);
1222 #endif /* TE_PE */
1223
1224   if (!S_IS_DEFINED (symp)
1225       && !S_IS_WEAK (symp)
1226       && S_GET_STORAGE_CLASS (symp) != C_STAT)
1227     S_SET_STORAGE_CLASS (symp, C_EXT);
1228
1229   if (!SF_GET_DEBUG (symp))
1230     {
1231       symbolS * real;
1232
1233       if (!SF_GET_LOCAL (symp)
1234           && !SF_GET_STATICS (symp)
1235           && S_GET_STORAGE_CLASS (symp) != C_LABEL
1236           && symbol_constant_p (symp)
1237           && (real = symbol_find (S_GET_NAME (symp)))
1238           && S_GET_STORAGE_CLASS (real) == C_NULL
1239           && real != symp)
1240         {
1241           c_symbol_merge (symp, real);
1242           *punt = 1;
1243           return;
1244         }
1245
1246       if (!S_IS_DEFINED (symp) && !SF_GET_LOCAL (symp))
1247         {
1248           assert (S_GET_VALUE (symp) == 0);
1249           S_SET_EXTERNAL (symp);
1250         }
1251       else if (S_GET_STORAGE_CLASS (symp) == C_NULL)
1252         {
1253           if (S_GET_SEGMENT (symp) == text_section
1254               && symp != seg_info (text_section)->sym)
1255             S_SET_STORAGE_CLASS (symp, C_LABEL);
1256           else
1257             S_SET_STORAGE_CLASS (symp, C_STAT);
1258         }
1259
1260       if (SF_GET_PROCESS (symp))
1261         {
1262           if (S_GET_STORAGE_CLASS (symp) == C_BLOCK)
1263             {
1264               if (streq (S_GET_NAME (symp), ".bb"))
1265                 stack_push (block_stack, (char *) &symp);
1266               else
1267                 {
1268                   symbolS *begin;
1269
1270                   begin = *(symbolS **) stack_pop (block_stack);
1271                   if (begin == 0)
1272                     as_warn (_("mismatched .eb"));
1273                   else
1274                     next_set_end = begin;
1275                 }
1276             }
1277
1278           if (coff_last_function == 0 && SF_GET_FUNCTION (symp))
1279             {
1280               union internal_auxent *auxp;
1281
1282               coff_last_function = symp;
1283               if (S_GET_NUMBER_AUXILIARY (symp) < 1)
1284                 S_SET_NUMBER_AUXILIARY (symp, 1);
1285               auxp = SYM_AUXENT (symp);
1286               memset (auxp->x_sym.x_fcnary.x_ary.x_dimen, 0,
1287                       sizeof (auxp->x_sym.x_fcnary.x_ary.x_dimen));
1288             }
1289
1290           if (S_GET_STORAGE_CLASS (symp) == C_EFCN)
1291             {
1292               if (coff_last_function == 0)
1293                 as_fatal (_("C_EFCN symbol for %s out of scope"),
1294                           S_GET_NAME (symp));
1295               SA_SET_SYM_FSIZE (coff_last_function,
1296                                 (long) (S_GET_VALUE (symp)
1297                                         - S_GET_VALUE (coff_last_function)));
1298               next_set_end = coff_last_function;
1299               coff_last_function = 0;
1300             }
1301         }
1302
1303       if (S_IS_EXTERNAL (symp))
1304         S_SET_STORAGE_CLASS (symp, C_EXT);
1305       else if (SF_GET_LOCAL (symp))
1306         *punt = 1;
1307
1308       if (SF_GET_FUNCTION (symp))
1309         symbol_get_bfdsym (symp)->flags |= BSF_FUNCTION;
1310     }
1311
1312   /* Double check weak symbols.  */
1313   if (S_IS_WEAK (symp) && S_IS_COMMON (symp))
1314     as_bad (_("Symbol `%s' can not be both weak and common"),
1315             S_GET_NAME (symp));
1316
1317   if (SF_GET_TAG (symp))
1318     last_tagP = symp;
1319   else if (S_GET_STORAGE_CLASS (symp) == C_EOS)
1320     next_set_end = last_tagP;
1321
1322 #ifdef OBJ_XCOFF
1323   /* This is pretty horrible, but we have to set *punt correctly in
1324      order to call SA_SET_SYM_ENDNDX correctly.  */
1325   if (! symbol_used_in_reloc_p (symp)
1326       && ((symbol_get_bfdsym (symp)->flags & BSF_SECTION_SYM) != 0
1327           || (! (S_IS_EXTERNAL (symp) || S_IS_WEAK (symp))
1328               && ! symbol_get_tc (symp)->output
1329               && S_GET_STORAGE_CLASS (symp) != C_FILE)))
1330     *punt = 1;
1331 #endif
1332
1333   if (set_end != (symbolS *) NULL
1334       && ! *punt
1335       && ((symbol_get_bfdsym (symp)->flags & BSF_NOT_AT_END) != 0
1336           || (S_IS_DEFINED (symp)
1337               && ! S_IS_COMMON (symp)
1338               && (! S_IS_EXTERNAL (symp) || SF_GET_FUNCTION (symp)))))
1339     {
1340       SA_SET_SYM_ENDNDX (set_end, symp);
1341       set_end = NULL;
1342     }
1343
1344   if (next_set_end != NULL)
1345     {
1346       if (set_end != NULL)
1347         as_warn ("Warning: internal error: forgetting to set endndx of %s",
1348                  S_GET_NAME (set_end));
1349       set_end = next_set_end;
1350     }
1351
1352 #ifndef OBJ_XCOFF
1353   if (! *punt
1354       && S_GET_STORAGE_CLASS (symp) == C_FCN
1355       && streq (S_GET_NAME (symp), ".bf"))
1356     {
1357       if (coff_last_bf != NULL)
1358         SA_SET_SYM_ENDNDX (coff_last_bf, symp);
1359       coff_last_bf = symp;
1360     }
1361 #endif
1362   if (coffsymbol (symbol_get_bfdsym (symp))->lineno)
1363     {
1364       int i;
1365       struct line_no *lptr;
1366       alent *l;
1367
1368       lptr = (struct line_no *) coffsymbol (symbol_get_bfdsym (symp))->lineno;
1369       for (i = 0; lptr; lptr = lptr->next)
1370         i++;
1371       lptr = (struct line_no *) coffsymbol (symbol_get_bfdsym (symp))->lineno;
1372
1373       /* We need i entries for line numbers, plus 1 for the first
1374          entry which BFD will override, plus 1 for the last zero
1375          entry (a marker for BFD).  */
1376       l = xmalloc ((i + 2) * sizeof (* l));
1377       coffsymbol (symbol_get_bfdsym (symp))->lineno = l;
1378       l[i + 1].line_number = 0;
1379       l[i + 1].u.sym = NULL;
1380       for (; i > 0; i--)
1381         {
1382           if (lptr->frag)
1383             lptr->l.u.offset += lptr->frag->fr_address / OCTETS_PER_BYTE;
1384           l[i] = lptr->l;
1385           lptr = lptr->next;
1386         }
1387     }
1388 }
1389
1390 void
1391 coff_adjust_section_syms (bfd *abfd ATTRIBUTE_UNUSED,
1392                           asection *sec,
1393                           void * x ATTRIBUTE_UNUSED)
1394 {
1395   symbolS *secsym;
1396   segment_info_type *seginfo = seg_info (sec);
1397   int nlnno, nrelocs = 0;
1398
1399   /* RS/6000 gas creates a .debug section manually in ppc_frob_file in
1400      tc-ppc.c.  Do not get confused by it.  */
1401   if (seginfo == NULL)
1402     return;
1403
1404   if (streq (sec->name, ".text"))
1405     nlnno = coff_n_line_nos;
1406   else
1407     nlnno = 0;
1408   {
1409     /* @@ Hope that none of the fixups expand to more than one reloc
1410        entry...  */
1411     fixS *fixp = seginfo->fix_root;
1412     while (fixp)
1413       {
1414         if (! fixp->fx_done)
1415           nrelocs++;
1416         fixp = fixp->fx_next;
1417       }
1418   }
1419   if (bfd_get_section_size (sec) == 0
1420       && nrelocs == 0
1421       && nlnno == 0
1422       && sec != text_section
1423       && sec != data_section
1424       && sec != bss_section)
1425     return;
1426
1427   secsym = section_symbol (sec);
1428   /* This is an estimate; we'll plug in the real value using
1429      SET_SECTION_RELOCS later */
1430   SA_SET_SCN_NRELOC (secsym, nrelocs);
1431   SA_SET_SCN_NLINNO (secsym, nlnno);
1432 }
1433
1434 void
1435 coff_frob_file_after_relocs (void)
1436 {
1437   bfd_map_over_sections (stdoutput, coff_adjust_section_syms, NULL);
1438 }
1439
1440 /* Implement the .section pseudo op:
1441         .section name {, "flags"}
1442                   ^         ^
1443                   |         +--- optional flags: 'b' for bss
1444                   |                              'i' for info
1445                   +-- section name               'l' for lib
1446                                                  'n' for noload
1447                                                  'o' for over
1448                                                  'w' for data
1449                                                  'd' (apparently m88k for data)
1450                                                  'x' for text
1451                                                  'r' for read-only data
1452                                                  's' for shared data (PE)
1453    But if the argument is not a quoted string, treat it as a
1454    subsegment number.
1455
1456    Note the 'a' flag is silently ignored.  This allows the same
1457    .section directive to be parsed in both ELF and COFF formats.  */
1458
1459 void
1460 obj_coff_section (int ignore ATTRIBUTE_UNUSED)
1461 {
1462   /* Strip out the section name.  */
1463   char *section_name;
1464   char c;
1465   char *name;
1466   unsigned int exp;
1467   flagword flags, oldflags;
1468   asection *sec;
1469
1470   if (flag_mri)
1471     {
1472       char type;
1473
1474       s_mri_sect (&type);
1475       return;
1476     }
1477
1478   section_name = input_line_pointer;
1479   c = get_symbol_end ();
1480
1481   name = xmalloc (input_line_pointer - section_name + 1);
1482   strcpy (name, section_name);
1483
1484   *input_line_pointer = c;
1485
1486   SKIP_WHITESPACE ();
1487
1488   exp = 0;
1489   flags = SEC_NO_FLAGS;
1490
1491   if (*input_line_pointer == ',')
1492     {
1493       ++input_line_pointer;
1494       SKIP_WHITESPACE ();
1495       if (*input_line_pointer != '"')
1496         exp = get_absolute_expression ();
1497       else
1498         {
1499           ++input_line_pointer;
1500           while (*input_line_pointer != '"'
1501                  && ! is_end_of_line[(unsigned char) *input_line_pointer])
1502             {
1503               switch (*input_line_pointer)
1504                 {
1505                 case 'b': flags |= SEC_ALLOC; flags &=~ SEC_LOAD; break;
1506                 case 'n': flags &=~ SEC_LOAD; flags |= SEC_NEVER_LOAD; break;
1507
1508                 case 's': flags |= SEC_COFF_SHARED; /* Fall through.  */
1509                 case 'd': flags |= SEC_DATA | SEC_LOAD; /* Fall through.  */
1510                 case 'w': flags &=~ SEC_READONLY; break;
1511
1512                 case 'a': break; /* For compatibility with ELF.  */
1513                 case 'x': flags |= SEC_CODE | SEC_LOAD; break;
1514                 case 'r': flags |= SEC_DATA | SEC_LOAD | SEC_READONLY; break;
1515
1516                 case 'i': /* STYP_INFO */
1517                 case 'l': /* STYP_LIB */
1518                 case 'o': /* STYP_OVER */
1519                   as_warn (_("unsupported section attribute '%c'"),
1520                            *input_line_pointer);
1521                   break;
1522
1523                 default:
1524                   as_warn (_("unknown section attribute '%c'"),
1525                            *input_line_pointer);
1526                   break;
1527                 }
1528               ++input_line_pointer;
1529             }
1530           if (*input_line_pointer == '"')
1531             ++input_line_pointer;
1532         }
1533     }
1534
1535   sec = subseg_new (name, (subsegT) exp);
1536
1537   oldflags = bfd_get_section_flags (stdoutput, sec);
1538   if (oldflags == SEC_NO_FLAGS)
1539     {
1540       /* Set section flags for a new section just created by subseg_new.
1541          Provide a default if no flags were parsed.  */
1542       if (flags == SEC_NO_FLAGS)
1543         flags = TC_COFF_SECTION_DEFAULT_ATTRIBUTES;
1544
1545 #ifdef COFF_LONG_SECTION_NAMES
1546       /* Add SEC_LINK_ONCE and SEC_LINK_DUPLICATES_DISCARD to .gnu.linkonce
1547          sections so adjust_reloc_syms in write.c will correctly handle
1548          relocs which refer to non-local symbols in these sections.  */
1549       if (strneq (name, ".gnu.linkonce", sizeof (".gnu.linkonce") - 1))
1550         flags |= SEC_LINK_ONCE | SEC_LINK_DUPLICATES_DISCARD;
1551 #endif
1552
1553       if (! bfd_set_section_flags (stdoutput, sec, flags))
1554         as_warn (_("error setting flags for \"%s\": %s"),
1555                  bfd_section_name (stdoutput, sec),
1556                  bfd_errmsg (bfd_get_error ()));
1557     }
1558   else if (flags != SEC_NO_FLAGS)
1559     {
1560       /* This section's attributes have already been set.  Warn if the
1561          attributes don't match.  */
1562       flagword matchflags = (SEC_ALLOC | SEC_LOAD | SEC_READONLY | SEC_CODE
1563                              | SEC_DATA | SEC_COFF_SHARED | SEC_NEVER_LOAD);
1564       if ((flags ^ oldflags) & matchflags)
1565         as_warn (_("Ignoring changed section attributes for %s"), name);
1566     }
1567
1568   demand_empty_rest_of_line ();
1569 }
1570
1571 void
1572 coff_adjust_symtab (void)
1573 {
1574   if (symbol_rootP == NULL
1575       || S_GET_STORAGE_CLASS (symbol_rootP) != C_FILE)
1576     c_dot_file_symbol ("fake", 0);
1577 }
1578
1579 void
1580 coff_frob_section (segT sec)
1581 {
1582   segT strsec;
1583   char *p;
1584   fragS *fragp;
1585   bfd_vma size, n_entries, mask;
1586   bfd_vma align_power = (bfd_vma)sec->alignment_power + OCTETS_PER_BYTE_POWER;
1587
1588   /* The COFF back end in BFD requires that all section sizes be
1589      rounded up to multiples of the corresponding section alignments,
1590      supposedly because standard COFF has no other way of encoding alignment
1591      for sections.  If your COFF flavor has a different way of encoding
1592      section alignment, then skip this step, as TICOFF does.  */
1593   size = bfd_get_section_size (sec);
1594   mask = ((bfd_vma) 1 << align_power) - 1;
1595 #if !defined(TICOFF)
1596   if (size & mask)
1597     {
1598       bfd_vma new_size;
1599       fragS *last;
1600
1601       new_size = (size + mask) & ~mask;
1602       bfd_set_section_size (stdoutput, sec, new_size);
1603
1604       /* If the size had to be rounded up, add some padding in
1605          the last non-empty frag.  */
1606       fragp = seg_info (sec)->frchainP->frch_root;
1607       last = seg_info (sec)->frchainP->frch_last;
1608       while (fragp->fr_next != last)
1609         fragp = fragp->fr_next;
1610       last->fr_address = size;
1611       fragp->fr_offset += new_size - size;
1612     }
1613 #endif
1614
1615   /* If the section size is non-zero, the section symbol needs an aux
1616      entry associated with it, indicating the size.  We don't know
1617      all the values yet; coff_frob_symbol will fill them in later.  */
1618 #ifndef TICOFF
1619   if (size != 0
1620       || sec == text_section
1621       || sec == data_section
1622       || sec == bss_section)
1623 #endif
1624     {
1625       symbolS *secsym = section_symbol (sec);
1626
1627       S_SET_STORAGE_CLASS (secsym, C_STAT);
1628       S_SET_NUMBER_AUXILIARY (secsym, 1);
1629       SF_SET_STATICS (secsym);
1630       SA_SET_SCN_SCNLEN (secsym, size);
1631     }
1632
1633   /* FIXME: These should be in a "stabs.h" file, or maybe as.h.  */
1634 #ifndef STAB_SECTION_NAME
1635 #define STAB_SECTION_NAME ".stab"
1636 #endif
1637 #ifndef STAB_STRING_SECTION_NAME
1638 #define STAB_STRING_SECTION_NAME ".stabstr"
1639 #endif
1640   if (! streq (STAB_STRING_SECTION_NAME, sec->name))
1641     return;
1642
1643   strsec = sec;
1644   sec = subseg_get (STAB_SECTION_NAME, 0);
1645   /* size is already rounded up, since other section will be listed first */
1646   size = bfd_get_section_size (strsec);
1647
1648   n_entries = bfd_get_section_size (sec) / 12 - 1;
1649
1650   /* Find first non-empty frag.  It should be large enough.  */
1651   fragp = seg_info (sec)->frchainP->frch_root;
1652   while (fragp && fragp->fr_fix == 0)
1653     fragp = fragp->fr_next;
1654   assert (fragp != 0 && fragp->fr_fix >= 12);
1655
1656   /* Store the values.  */
1657   p = fragp->fr_literal;
1658   bfd_h_put_16 (stdoutput, n_entries, (bfd_byte *) p + 6);
1659   bfd_h_put_32 (stdoutput, size, (bfd_byte *) p + 8);
1660 }
1661
1662 void
1663 obj_coff_init_stab_section (segT seg)
1664 {
1665   char *file;
1666   char *p;
1667   char *stabstr_name;
1668   unsigned int stroff;
1669
1670   /* Make space for this first symbol.  */
1671   p = frag_more (12);
1672   /* Zero it out.  */
1673   memset (p, 0, 12);
1674   as_where (&file, (unsigned int *) NULL);
1675   stabstr_name = xmalloc (strlen (seg->name) + 4);
1676   strcpy (stabstr_name, seg->name);
1677   strcat (stabstr_name, "str");
1678   stroff = get_stab_string_offset (file, stabstr_name);
1679   know (stroff == 1);
1680   md_number_to_chars (p, stroff, 4);
1681 }
1682
1683 #ifdef DEBUG
1684 const char *
1685 s_get_name (symbolS *s)
1686 {
1687   return ((s == NULL) ? "(NULL)" : S_GET_NAME (s));
1688 }
1689
1690 void
1691 symbol_dump (void)
1692 {
1693   symbolS *symbolP;
1694
1695   for (symbolP = symbol_rootP; symbolP; symbolP = symbol_next (symbolP))
1696     printf (_("0x%lx: \"%s\" type = %ld, class = %d, segment = %d\n"),
1697             (unsigned long) symbolP,
1698             S_GET_NAME (symbolP),
1699             (long) S_GET_DATA_TYPE (symbolP),
1700             S_GET_STORAGE_CLASS (symbolP),
1701             (int) S_GET_SEGMENT (symbolP));
1702 }
1703
1704 #endif /* DEBUG */
1705
1706 #else /* not BFD_ASSEMBLER */
1707
1708 #include "frags.h"
1709 /* This is needed because we include internal bfd things.  */
1710 #include <time.h>
1711
1712 #include "libbfd.h"
1713 #include "libcoff.h"
1714
1715 /* The NOP_OPCODE is for the alignment fill value.  Fill with nop so
1716    that we can stick sections together without causing trouble.  */
1717 #ifndef NOP_OPCODE
1718 #define NOP_OPCODE 0x00
1719 #endif
1720
1721 /* The zeroes if symbol name is longer than 8 chars */
1722 #define S_SET_ZEROES(s,v)               ((s)->sy_symbol.ost_entry.n_zeroes = (v))
1723
1724 #define MIN(a,b) ((a) < (b)? (a) : (b))
1725
1726 /* This vector is used to turn a gas internal segment number into a
1727    section number suitable for insertion into a coff symbol table.
1728    This must correspond to seg_info_off_by_4.  */
1729
1730 const short seg_N_TYPE[] =
1731 {                               /* in: segT   out: N_TYPE bits */
1732   C_ABS_SECTION,
1733   1,    2,  3,   4,    5,   6,   7,   8,   9,  10,
1734   11,  12,  13,  14,  15,  16,  17,  18,  19,  20,
1735   21,  22,  23,  24,  25,  26,  27,  28,  29,  30,
1736   31,  32,  33,  34,  35,  36,  37,  38,  39,  40,
1737   C_UNDEF_SECTION,              /* SEG_UNKNOWN */
1738   C_UNDEF_SECTION,              /* SEG_GOOF */
1739   C_UNDEF_SECTION,              /* SEG_EXPR */
1740   C_DEBUG_SECTION,              /* SEG_DEBUG */
1741   C_NTV_SECTION,                /* SEG_NTV */
1742   C_PTV_SECTION,                /* SEG_PTV */
1743   C_REGISTER_SECTION,           /* SEG_REGISTER */
1744 };
1745
1746 int function_lineoff = -1;      /* Offset in line#s where the last function
1747                                    started (the odd entry for line #0) */
1748
1749 /* Structure used to keep the filenames which
1750    are too long around so that we can stick them
1751    into the string table.  */
1752 struct filename_list
1753 {
1754   const char *filename;
1755   struct filename_list *next;
1756 };
1757
1758 static struct filename_list *filename_list_head;
1759 static struct filename_list *filename_list_tail;
1760
1761 static symbolS *last_line_symbol;
1762
1763 /* Add 4 to the real value to get the index and compensate the
1764    negatives. This vector is used by S_GET_SEGMENT to turn a coff
1765    section number into a segment number.  */
1766
1767 bfd *abfd;
1768 static symbolS *previous_file_symbol;
1769 static int line_base;
1770
1771 /* When not using BFD_ASSEMBLER, we permit up to 40 sections.
1772
1773    This array maps a COFF section number into a gas section number.
1774    Because COFF uses negative section numbers, you must add 4 to the
1775    COFF section number when indexing into this array; this is done via
1776    the SEG_INFO_FROM_SECTION_NUMBER macro.  This must correspond to
1777    seg_N_TYPE.  */
1778
1779 static const segT seg_info_off_by_4[] =
1780 {
1781  SEG_PTV,
1782  SEG_NTV,
1783  SEG_DEBUG,
1784  SEG_ABSOLUTE,
1785  SEG_UNKNOWN,
1786  SEG_E0,  SEG_E1,  SEG_E2,  SEG_E3,  SEG_E4,
1787  SEG_E5,  SEG_E6,  SEG_E7,  SEG_E8,  SEG_E9,
1788  SEG_E10, SEG_E11, SEG_E12, SEG_E13, SEG_E14,
1789  SEG_E15, SEG_E16, SEG_E17, SEG_E18, SEG_E19,
1790  SEG_E20, SEG_E21, SEG_E22, SEG_E23, SEG_E24,
1791  SEG_E25, SEG_E26, SEG_E27, SEG_E28, SEG_E29,
1792  SEG_E30, SEG_E31, SEG_E32, SEG_E33, SEG_E34,
1793  SEG_E35, SEG_E36, SEG_E37, SEG_E38, SEG_E39,
1794  (segT) 40,
1795  (segT) 41,
1796  (segT) 42,
1797  (segT) 43,
1798  (segT) 44,
1799  (segT) 45,
1800  (segT) 0,
1801  (segT) 0,
1802  (segT) 0,
1803  SEG_REGISTER
1804 };
1805
1806 #define SEG_INFO_FROM_SECTION_NUMBER(x) (seg_info_off_by_4[(x)+4])
1807
1808 static relax_addressT
1809 relax_align (relax_addressT address, long alignment)
1810 {
1811   relax_addressT mask;
1812   relax_addressT new_address;
1813
1814   mask = ~((~0) << alignment);
1815   new_address = (address + mask) & (~mask);
1816
1817   return new_address - address;
1818 }
1819
1820 segT
1821 s_get_segment (symbolS * x)
1822 {
1823   return SEG_INFO_FROM_SECTION_NUMBER (x->sy_symbol.ost_entry.n_scnum);
1824 }
1825
1826 /* Calculate the size of the frag chain and fill in the section header
1827    to contain all of it, also fill in the addr of the sections.  */
1828
1829 static unsigned int
1830 size_section (bfd *abfd ATTRIBUTE_UNUSED, unsigned int idx)
1831 {
1832   unsigned int size = 0;
1833   fragS *frag = segment_info[idx].frchainP->frch_root;
1834
1835   while (frag)
1836     {
1837       size = frag->fr_address;
1838       if (frag->fr_address != size)
1839         {
1840           fprintf (stderr, _("Out of step\n"));
1841           size = frag->fr_address;
1842         }
1843
1844       switch (frag->fr_type)
1845         {
1846 #ifdef TC_COFF_SIZEMACHDEP
1847         case rs_machine_dependent:
1848           size += TC_COFF_SIZEMACHDEP (frag);
1849           break;
1850 #endif
1851         case rs_space:
1852         case rs_fill:
1853         case rs_org:
1854           size += frag->fr_fix;
1855           size += frag->fr_offset * frag->fr_var;
1856           break;
1857         case rs_align:
1858         case rs_align_code:
1859         case rs_align_test:
1860           {
1861             addressT off;
1862
1863             size += frag->fr_fix;
1864             off = relax_align (size, frag->fr_offset);
1865             if (frag->fr_subtype != 0 && off > frag->fr_subtype)
1866               off = 0;
1867             size += off;
1868           }
1869           break;
1870         default:
1871           BAD_CASE (frag->fr_type);
1872           break;
1873         }
1874       frag = frag->fr_next;
1875     }
1876   segment_info[idx].scnhdr.s_size = size;
1877   return size;
1878 }
1879
1880 static unsigned int
1881 count_entries_in_chain (unsigned int idx)
1882 {
1883   unsigned int nrelocs;
1884   fixS *fixup_ptr;
1885
1886   /* Count the relocations.  */
1887   fixup_ptr = segment_info[idx].fix_root;
1888   nrelocs = 0;
1889   while (fixup_ptr != (fixS *) NULL)
1890     {
1891       if (fixup_ptr->fx_done == 0 && TC_COUNT_RELOC (fixup_ptr))
1892         {
1893 #if defined(TC_A29K) || defined(TC_OR32)
1894           if (fixup_ptr->fx_r_type == RELOC_CONSTH)
1895             nrelocs += 2;
1896           else
1897             nrelocs++;
1898 #else
1899           nrelocs++;
1900 #endif
1901         }
1902
1903       fixup_ptr = fixup_ptr->fx_next;
1904     }
1905   return nrelocs;
1906 }
1907
1908 #ifdef TE_AUX
1909
1910 /* AUX's ld expects relocations to be sorted.  */
1911
1912 static int
1913 compare_external_relocs (const void * x, const void * y)
1914 {
1915   struct external_reloc *a = (struct external_reloc *) x;
1916   struct external_reloc *b = (struct external_reloc *) y;
1917   bfd_vma aadr = bfd_getb32 (a->r_vaddr);
1918   bfd_vma badr = bfd_getb32 (b->r_vaddr);
1919
1920   return (aadr < badr ? -1 : badr < aadr ? 1 : 0);
1921 }
1922
1923 #endif
1924
1925 /* Output all the relocations for a section.  */
1926
1927 static void
1928 do_relocs_for (bfd * abfd, object_headers * h, unsigned long *file_cursor)
1929 {
1930   unsigned int nrelocs;
1931   unsigned int idx;
1932   unsigned long reloc_start = *file_cursor;
1933
1934   for (idx = SEG_E0; idx < SEG_LAST; idx++)
1935     {
1936       if (segment_info[idx].scnhdr.s_name[0])
1937         {
1938           struct external_reloc *ext_ptr;
1939           struct external_reloc *external_reloc_vec;
1940           unsigned int external_reloc_size;
1941           unsigned int base = segment_info[idx].scnhdr.s_paddr;
1942           fixS *fix_ptr = segment_info[idx].fix_root;
1943
1944           nrelocs = count_entries_in_chain (idx);
1945
1946           if (nrelocs)
1947             /* Bypass this stuff if no relocs.  This also incidentally
1948                avoids a SCO bug, where free(malloc(0)) tends to crash.  */
1949             {
1950               external_reloc_size = nrelocs * RELSZ;
1951               external_reloc_vec = malloc (external_reloc_size);
1952
1953               ext_ptr = external_reloc_vec;
1954
1955               /* Fill in the internal coff style reloc struct from the
1956                  internal fix list.  */
1957               while (fix_ptr)
1958                 {
1959                   struct internal_reloc intr;
1960
1961                   /* Only output some of the relocations.  */
1962                   if (fix_ptr->fx_done == 0 && TC_COUNT_RELOC (fix_ptr))
1963                     {
1964 #ifdef TC_RELOC_MANGLE
1965                       TC_RELOC_MANGLE (&segment_info[idx], fix_ptr, &intr,
1966                                        base);
1967 #else
1968                       symbolS *dot;
1969                       symbolS *symbol_ptr = fix_ptr->fx_addsy;
1970
1971                       intr.r_type = TC_COFF_FIX2RTYPE (fix_ptr);
1972                       intr.r_vaddr =
1973                         base + fix_ptr->fx_frag->fr_address + fix_ptr->fx_where;
1974
1975 #ifdef TC_KEEP_FX_OFFSET
1976                       intr.r_offset = fix_ptr->fx_offset;
1977 #else
1978                       intr.r_offset = 0;
1979 #endif
1980
1981                       while (symbol_ptr->sy_value.X_op == O_symbol
1982                              && (! S_IS_DEFINED (symbol_ptr)
1983                                  || S_IS_COMMON (symbol_ptr)))
1984                         {
1985                           symbolS *n;
1986
1987                           /* We must avoid looping, as that can occur
1988                              with a badly written program.  */
1989                           n = symbol_ptr->sy_value.X_add_symbol;
1990                           if (n == symbol_ptr)
1991                             break;
1992                           symbol_ptr = n;
1993                         }
1994
1995                       /* Turn the segment of the symbol into an offset.  */
1996                       if (symbol_ptr)
1997                         {
1998                           resolve_symbol_value (symbol_ptr);
1999                           if (! symbol_ptr->sy_resolved)
2000                             {
2001                               char *file;
2002                               unsigned int line;
2003
2004                               if (expr_symbol_where (symbol_ptr, &file, &line))
2005                                 as_bad_where (file, line,
2006                                               _("unresolved relocation"));
2007                               else
2008                                 as_bad (_("bad relocation: symbol `%s' not in symbol table"),
2009                                         S_GET_NAME (symbol_ptr));
2010                             }
2011
2012                           dot = segment_info[S_GET_SEGMENT (symbol_ptr)].dot;
2013                           if (dot)
2014                             intr.r_symndx = dot->sy_number;
2015                           else
2016                             intr.r_symndx = symbol_ptr->sy_number;
2017                         }
2018                       else
2019                         intr.r_symndx = -1;
2020 #endif
2021                       (void) bfd_coff_swap_reloc_out (abfd, &intr, ext_ptr);
2022                       ext_ptr++;
2023 #if defined(TC_A29K)
2024                       /* The 29k has a special kludge for the high 16 bit
2025                          reloc.  Two relocations are emitted, R_IHIHALF,
2026                          and R_IHCONST. The second one doesn't contain a
2027                          symbol, but uses the value for offset.  */
2028                       if (intr.r_type == R_IHIHALF)
2029                         {
2030                           /* Now emit the second bit.  */
2031                           intr.r_type = R_IHCONST;
2032                           intr.r_symndx = fix_ptr->fx_addnumber;
2033                           (void) bfd_coff_swap_reloc_out (abfd, &intr, ext_ptr);
2034                           ext_ptr++;
2035                         }
2036 #endif
2037 #if defined(TC_OR32)
2038                       /* The or32 has a special kludge for the high 16 bit
2039                          reloc.  Two relocations are emitted, R_IHIHALF,
2040                          and R_IHCONST. The second one doesn't contain a
2041                          symbol, but uses the value for offset.  */
2042                       if (intr.r_type == R_IHIHALF)
2043                         {
2044                           /* Now emit the second bit.  */
2045                           intr.r_type = R_IHCONST;
2046                           intr.r_symndx = fix_ptr->fx_addnumber;
2047                           (void) bfd_coff_swap_reloc_out (abfd, & intr, ext_ptr);
2048                           ext_ptr ++;
2049                         }
2050 #endif
2051                     }
2052
2053                   fix_ptr = fix_ptr->fx_next;
2054                 }
2055 #ifdef TE_AUX
2056               /* Sort the reloc table.  */
2057               qsort ((void *) external_reloc_vec, nrelocs,
2058                      sizeof (struct external_reloc), compare_external_relocs);
2059 #endif
2060               /* Write out the reloc table.  */
2061               bfd_bwrite ((void *) external_reloc_vec,
2062                           (bfd_size_type) external_reloc_size, abfd);
2063               free (external_reloc_vec);
2064
2065               /* Fill in section header info.  */
2066               segment_info[idx].scnhdr.s_relptr = *file_cursor;
2067               *file_cursor += external_reloc_size;
2068               segment_info[idx].scnhdr.s_nreloc = nrelocs;
2069             }
2070           else
2071             {
2072               /* No relocs.  */
2073               segment_info[idx].scnhdr.s_relptr = 0;
2074             }
2075         }
2076     }
2077
2078   /* Set relocation_size field in file headers.  */
2079   H_SET_RELOCATION_SIZE (h, *file_cursor - reloc_start, 0);
2080 }
2081
2082 /* Run through a frag chain and write out the data to go with it, fill
2083    in the scnhdrs with the info on the file positions.  */
2084
2085 static void
2086 fill_section (bfd * abfd,
2087               object_headers *h ATTRIBUTE_UNUSED,
2088               unsigned long *file_cursor)
2089 {
2090   unsigned int i;
2091   unsigned int paddr = 0;
2092
2093   for (i = SEG_E0; i < SEG_UNKNOWN; i++)
2094     {
2095       unsigned int offset = 0;
2096       struct internal_scnhdr *s = &(segment_info[i].scnhdr);
2097
2098       PROGRESS (1);
2099
2100       if (s->s_name[0])
2101         {
2102           fragS *frag = segment_info[i].frchainP->frch_root;
2103           char *buffer = NULL;
2104
2105           if (s->s_size == 0)
2106             s->s_scnptr = 0;
2107           else
2108             {
2109               buffer = xmalloc (s->s_size);
2110               s->s_scnptr = *file_cursor;
2111             }
2112           know (s->s_paddr == paddr);
2113
2114           if (streq (s->s_name, ".text"))
2115             s->s_flags |= STYP_TEXT;
2116           else if (streq (s->s_name, ".data"))
2117             s->s_flags |= STYP_DATA;
2118           else if (streq (s->s_name, ".bss"))
2119             {
2120               s->s_scnptr = 0;
2121               s->s_flags |= STYP_BSS;
2122
2123               /* @@ Should make the i386 and a29k coff targets define
2124                  COFF_NOLOAD_PROBLEM, and have only one test here.  */
2125 #ifndef TC_I386
2126 #ifndef TC_A29K
2127 #ifndef TC_OR32
2128 #ifndef COFF_NOLOAD_PROBLEM
2129               /* Apparently the SVR3 linker (and exec syscall) and UDI
2130                  mondfe progrem are confused by noload sections.  */
2131               s->s_flags |= STYP_NOLOAD;
2132 #endif
2133 #endif
2134 #endif
2135 #endif
2136             }
2137           else if (streq (s->s_name, ".lit"))
2138             s->s_flags = STYP_LIT | STYP_TEXT;
2139           else if (streq (s->s_name, ".init"))
2140             s->s_flags |= STYP_TEXT;
2141           else if (streq (s->s_name, ".fini"))
2142             s->s_flags |= STYP_TEXT;
2143           else if (strneq (s->s_name, ".comment", 8))
2144             s->s_flags |= STYP_INFO;
2145
2146           while (frag)
2147             {
2148               unsigned int fill_size;
2149
2150               switch (frag->fr_type)
2151                 {
2152                 case rs_machine_dependent:
2153                   if (frag->fr_fix)
2154                     {
2155                       memcpy (buffer + frag->fr_address,
2156                               frag->fr_literal,
2157                               (unsigned int) frag->fr_fix);
2158                       offset += frag->fr_fix;
2159                     }
2160
2161                   break;
2162                 case rs_space:
2163                 case rs_fill:
2164                 case rs_align:
2165                 case rs_align_code:
2166                 case rs_align_test:
2167                 case rs_org:
2168                   if (frag->fr_fix)
2169                     {
2170                       memcpy (buffer + frag->fr_address,
2171                               frag->fr_literal,
2172                               (unsigned int) frag->fr_fix);
2173                       offset += frag->fr_fix;
2174                     }
2175
2176                   fill_size = frag->fr_var;
2177                   if (fill_size && frag->fr_offset > 0)
2178                     {
2179                       unsigned int count;
2180                       unsigned int off = frag->fr_fix;
2181
2182                       for (count = frag->fr_offset; count; count--)
2183                         {
2184                           if (fill_size + frag->fr_address + off <= s->s_size)
2185                             {
2186                               memcpy (buffer + frag->fr_address + off,
2187                                       frag->fr_literal + frag->fr_fix,
2188                                       fill_size);
2189                               off += fill_size;
2190                               offset += fill_size;
2191                             }
2192                         }
2193                     }
2194                   break;
2195                 case rs_broken_word:
2196                   break;
2197                 default:
2198                   abort ();
2199                 }
2200               frag = frag->fr_next;
2201             }
2202
2203           if (s->s_size != 0)
2204             {
2205               if (s->s_scnptr != 0)
2206                 {
2207                   bfd_bwrite (buffer, s->s_size, abfd);
2208                   *file_cursor += s->s_size;
2209                 }
2210               free (buffer);
2211             }
2212           paddr += s->s_size;
2213         }
2214     }
2215 }
2216
2217 /* Coff file generation & utilities.  */
2218
2219 static void
2220 coff_header_append (bfd * abfd, object_headers * h)
2221 {
2222   unsigned int i;
2223   char buffer[1000];
2224   char buffero[1000];
2225 #ifdef COFF_LONG_SECTION_NAMES
2226   unsigned long string_size = 4;
2227 #endif
2228
2229   bfd_seek (abfd, 0, 0);
2230
2231 #ifndef OBJ_COFF_OMIT_OPTIONAL_HEADER
2232   H_SET_MAGIC_NUMBER (h, COFF_MAGIC);
2233   H_SET_VERSION_STAMP (h, 0);
2234   H_SET_ENTRY_POINT (h, 0);
2235   H_SET_TEXT_START (h, segment_info[SEG_E0].frchainP->frch_root->fr_address);
2236   H_SET_DATA_START (h, segment_info[SEG_E1].frchainP->frch_root->fr_address);
2237   H_SET_SIZEOF_OPTIONAL_HEADER (h, bfd_coff_swap_aouthdr_out (abfd, &h->aouthdr,
2238                                                               buffero));
2239 #else /* defined (OBJ_COFF_OMIT_OPTIONAL_HEADER) */
2240   H_SET_SIZEOF_OPTIONAL_HEADER (h, 0);
2241 #endif /* defined (OBJ_COFF_OMIT_OPTIONAL_HEADER) */
2242
2243   i = bfd_coff_swap_filehdr_out (abfd, &h->filehdr, buffer);
2244
2245   bfd_bwrite (buffer, (bfd_size_type) i, abfd);
2246   bfd_bwrite (buffero, (bfd_size_type) H_GET_SIZEOF_OPTIONAL_HEADER (h), abfd);
2247
2248   for (i = SEG_E0; i < SEG_LAST; i++)
2249     {
2250       if (segment_info[i].scnhdr.s_name[0])
2251         {
2252           unsigned int size;
2253
2254 #ifdef COFF_LONG_SECTION_NAMES
2255           /* Support long section names as found in PE.  This code
2256              must coordinate with that in write_object_file and
2257              w_strings.  */
2258           if (strlen (segment_info[i].name) > SCNNMLEN)
2259             {
2260               memset (segment_info[i].scnhdr.s_name, 0, SCNNMLEN);
2261               sprintf (segment_info[i].scnhdr.s_name, "/%lu", string_size);
2262               string_size += strlen (segment_info[i].name) + 1;
2263             }
2264 #endif
2265           size = bfd_coff_swap_scnhdr_out (abfd,
2266                                            &(segment_info[i].scnhdr),
2267                                            buffer);
2268           if (size == 0)
2269             as_bad (_("bfd_coff_swap_scnhdr_out failed"));
2270           bfd_bwrite (buffer, (bfd_size_type) size, abfd);
2271         }
2272     }
2273 }
2274
2275 static char *
2276 symbol_to_chars (bfd * abfd, char * where, symbolS * symbolP)
2277 {
2278   unsigned int numaux = symbolP->sy_symbol.ost_entry.n_numaux;
2279   unsigned int i;
2280   valueT val;
2281
2282   /* Turn any symbols with register attributes into abs symbols.  */
2283   if (S_GET_SEGMENT (symbolP) == reg_section)
2284     S_SET_SEGMENT (symbolP, absolute_section);
2285
2286   /* At the same time, relocate all symbols to their output value.  */
2287 #ifndef TE_PE
2288   val = (segment_info[S_GET_SEGMENT (symbolP)].scnhdr.s_paddr
2289          + S_GET_VALUE (symbolP));
2290 #else
2291   val = S_GET_VALUE (symbolP);
2292 #endif
2293
2294   S_SET_VALUE (symbolP, val);
2295
2296   symbolP->sy_symbol.ost_entry.n_value = val;
2297
2298   where += bfd_coff_swap_sym_out (abfd, &symbolP->sy_symbol.ost_entry,
2299                                   where);
2300
2301   for (i = 0; i < numaux; i++)
2302     {
2303       where += bfd_coff_swap_aux_out (abfd,
2304                                       &symbolP->sy_symbol.ost_auxent[i],
2305                                       S_GET_DATA_TYPE (symbolP),
2306                                       S_GET_STORAGE_CLASS (symbolP),
2307                                       i, numaux, where);
2308     }
2309
2310   return where;
2311 }
2312
2313 void
2314 coff_obj_symbol_new_hook (symbolS *symbolP)
2315 {
2316   char underscore = 0;          /* Symbol has leading _  */
2317
2318   /* Effective symbol.  */
2319   /* Store the pointer in the offset.  */
2320   S_SET_ZEROES (symbolP, 0L);
2321   S_SET_DATA_TYPE (symbolP, T_NULL);
2322   S_SET_STORAGE_CLASS (symbolP, 0);
2323   S_SET_NUMBER_AUXILIARY (symbolP, 0);
2324   /* Additional information.  */
2325   symbolP->sy_symbol.ost_flags = 0;
2326   /* Auxiliary entries.  */
2327   memset ((char *) &symbolP->sy_symbol.ost_auxent[0], 0, AUXESZ);
2328
2329   if (S_IS_STRING (symbolP))
2330     SF_SET_STRING (symbolP);
2331   if (!underscore && S_IS_LOCAL (symbolP))
2332     SF_SET_LOCAL (symbolP);
2333 }
2334
2335 static int
2336 c_line_new (symbolS * symbol, long paddr, int line_number, fragS * frag)
2337 {
2338   struct lineno_list *new_line = xmalloc (sizeof (* new_line));
2339
2340   segment_info_type *s = segment_info + now_seg;
2341   new_line->line.l_lnno = line_number;
2342
2343   if (line_number == 0)
2344     {
2345       last_line_symbol = symbol;
2346       new_line->line.l_addr.l_symndx = (long) symbol;
2347     }
2348   else
2349     {
2350       new_line->line.l_addr.l_paddr = paddr;
2351     }
2352
2353   new_line->frag = (char *) frag;
2354   new_line->next = NULL;
2355
2356   if (s->lineno_list_head == NULL)
2357     s->lineno_list_head = new_line;
2358   else
2359     s->lineno_list_tail->next = new_line;
2360
2361   s->lineno_list_tail = new_line;
2362   return LINESZ * s->scnhdr.s_nlnno++;
2363 }
2364
2365 /* Handle .ln directives.  */
2366
2367 static void
2368 obj_coff_ln (int appline)
2369 {
2370   int l;
2371
2372   if (! appline && def_symbol_in_progress != NULL)
2373     {
2374       /* Wrong context.  */
2375       as_warn (_(".ln pseudo-op inside .def/.endef: ignored."));
2376       demand_empty_rest_of_line ();
2377       return;
2378     }
2379
2380   l = get_absolute_expression ();
2381   c_line_new (0, frag_now_fix (), l, frag_now);
2382
2383   if (appline)
2384     new_logical_line ((char *) NULL, l - 1);
2385
2386 #ifndef NO_LISTING
2387   {
2388     extern int listing;
2389
2390     if (listing)
2391       {
2392         if (! appline)
2393           l += line_base - 1;
2394         listing_source_line ((unsigned int) l);
2395       }
2396   }
2397 #endif
2398   demand_empty_rest_of_line ();
2399 }
2400
2401 /* Handle .def directives.
2402
2403   One might ask : why can't we symbol_new if the symbol does not
2404   already exist and fill it with debug information.  Because of
2405   the C_EFCN special symbol. It would clobber the value of the
2406   function symbol before we have a chance to notice that it is
2407   a C_EFCN. And a second reason is that the code is more clear this
2408   way. (at least I think it is :-).  */
2409
2410 #define SKIP_SEMI_COLON()       while (*input_line_pointer++ != ';')
2411 #define SKIP_WHITESPACES()      while (*input_line_pointer == ' ' || \
2412                                        *input_line_pointer == '\t')  \
2413                                   input_line_pointer++;
2414
2415 static void
2416 obj_coff_def (int what ATTRIBUTE_UNUSED)
2417 {
2418   char name_end;                /* Char after the end of name.  */
2419   char *symbol_name;            /* Name of the debug symbol.  */
2420   char *symbol_name_copy;       /* Temporary copy of the name.  */
2421   unsigned int symbol_name_length;
2422
2423   if (def_symbol_in_progress != NULL)
2424     {
2425       as_warn (_(".def pseudo-op used inside of .def/.endef: ignored."));
2426       demand_empty_rest_of_line ();
2427       return;
2428     }
2429
2430   SKIP_WHITESPACES ();
2431
2432   def_symbol_in_progress = obstack_alloc (&notes, sizeof (*def_symbol_in_progress));
2433   memset (def_symbol_in_progress, 0, sizeof (*def_symbol_in_progress));
2434
2435   symbol_name = input_line_pointer;
2436   name_end = get_symbol_end ();
2437   symbol_name_length = strlen (symbol_name);
2438   symbol_name_copy = xmalloc (symbol_name_length + 1);
2439   strcpy (symbol_name_copy, symbol_name);
2440 #ifdef tc_canonicalize_symbol_name
2441   symbol_name_copy = tc_canonicalize_symbol_name (symbol_name_copy);
2442 #endif
2443
2444   /* Initialize the new symbol.  */
2445   S_SET_NAME (def_symbol_in_progress, symbol_name_copy);
2446   /* free(symbol_name_copy); */
2447   def_symbol_in_progress->sy_name_offset = (unsigned long) ~0;
2448   def_symbol_in_progress->sy_number = ~0;
2449   def_symbol_in_progress->sy_frag = &zero_address_frag;
2450   S_SET_VALUE (def_symbol_in_progress, 0);
2451
2452   if (S_IS_STRING (def_symbol_in_progress))
2453     SF_SET_STRING (def_symbol_in_progress);
2454
2455   *input_line_pointer = name_end;
2456
2457   demand_empty_rest_of_line ();
2458 }
2459
2460 static void
2461 c_symbol_merge (symbolS *debug, symbolS *normal)
2462 {
2463   S_SET_DATA_TYPE (normal, S_GET_DATA_TYPE (debug));
2464   S_SET_STORAGE_CLASS (normal, S_GET_STORAGE_CLASS (debug));
2465
2466   if (S_GET_NUMBER_AUXILIARY (debug) > S_GET_NUMBER_AUXILIARY (normal))
2467     S_SET_NUMBER_AUXILIARY (normal, S_GET_NUMBER_AUXILIARY (debug));
2468
2469   if (S_GET_NUMBER_AUXILIARY (debug) > 0)
2470     memcpy ((char *) &normal->sy_symbol.ost_auxent[0],
2471             (char *) &debug->sy_symbol.ost_auxent[0],
2472             (unsigned int) (S_GET_NUMBER_AUXILIARY (debug) * AUXESZ));
2473
2474   /* Move the debug flags.  */
2475   SF_SET_DEBUG_FIELD (normal, SF_GET_DEBUG_FIELD (debug));
2476 }
2477
2478 static unsigned int dim_index;
2479
2480 static void
2481 obj_coff_endef (int ignore ATTRIBUTE_UNUSED)
2482 {
2483   symbolS *symbolP = 0;
2484
2485   dim_index = 0;
2486   if (def_symbol_in_progress == NULL)
2487     {
2488       as_warn (_(".endef pseudo-op used outside of .def/.endef: ignored."));
2489       demand_empty_rest_of_line ();
2490       return;
2491     }
2492
2493   /* Set the section number according to storage class.  */
2494   switch (S_GET_STORAGE_CLASS (def_symbol_in_progress))
2495     {
2496     case C_STRTAG:
2497     case C_ENTAG:
2498     case C_UNTAG:
2499       SF_SET_TAG (def_symbol_in_progress);
2500       /* Fall through.  */
2501
2502     case C_FILE:
2503     case C_TPDEF:
2504       SF_SET_DEBUG (def_symbol_in_progress);
2505       S_SET_SEGMENT (def_symbol_in_progress, SEG_DEBUG);
2506       break;
2507
2508     case C_EFCN:
2509       /* Do not emit this symbol.  */
2510       SF_SET_LOCAL (def_symbol_in_progress);
2511       /* Fall through.  */
2512
2513     case C_BLOCK:
2514       /* Will need processing before writing.  */
2515       SF_SET_PROCESS (def_symbol_in_progress);
2516       /* Fall through.  */
2517
2518     case C_FCN:
2519       S_SET_SEGMENT (def_symbol_in_progress, SEG_E0);
2520
2521       if (streq (S_GET_NAME (def_symbol_in_progress), ".bf"))
2522         {
2523           if (function_lineoff < 0)
2524             fprintf (stderr, _("`.bf' symbol without preceding function\n"));
2525
2526           SA_GET_SYM_LNNOPTR (last_line_symbol) = function_lineoff;
2527
2528           SF_SET_PROCESS (last_line_symbol);
2529           SF_SET_ADJ_LNNOPTR (last_line_symbol);
2530           SF_SET_PROCESS (def_symbol_in_progress);
2531           function_lineoff = -1;
2532         }
2533
2534       /* Value is always set to .  */
2535       def_symbol_in_progress->sy_frag = frag_now;
2536       S_SET_VALUE (def_symbol_in_progress, (valueT) frag_now_fix ());
2537       break;
2538
2539 #ifdef C_AUTOARG
2540     case C_AUTOARG:
2541 #endif /* C_AUTOARG */
2542     case C_AUTO:
2543     case C_REG:
2544     case C_MOS:
2545     case C_MOE:
2546     case C_MOU:
2547     case C_ARG:
2548     case C_REGPARM:
2549     case C_FIELD:
2550     case C_EOS:
2551       SF_SET_DEBUG (def_symbol_in_progress);
2552       S_SET_SEGMENT (def_symbol_in_progress, absolute_section);
2553       break;
2554
2555     case C_EXT:
2556     case C_WEAKEXT:
2557 #ifdef TE_PE
2558     case C_NT_WEAK:
2559 #endif
2560     case C_STAT:
2561     case C_LABEL:
2562       /* Valid but set somewhere else (s_comm, s_lcomm, colon).  */
2563       break;
2564
2565     case C_USTATIC:
2566     case C_EXTDEF:
2567     case C_ULABEL:
2568       as_warn (_("unexpected storage class %d"), S_GET_STORAGE_CLASS (def_symbol_in_progress));
2569       break;
2570     }
2571
2572   /* Now that we have built a debug symbol, try to find if we should
2573      merge with an existing symbol or not.  If a symbol is C_EFCN or
2574      absolute_section or untagged SEG_DEBUG it never merges.  We also
2575      don't merge labels, which are in a different namespace, nor
2576      symbols which have not yet been defined since they are typically
2577      unique, nor do we merge tags with non-tags.  */
2578
2579   /* Two cases for functions.  Either debug followed by definition or
2580      definition followed by debug.  For definition first, we will
2581      merge the debug symbol into the definition.  For debug first, the
2582      lineno entry MUST point to the definition function or else it
2583      will point off into space when crawl_symbols() merges the debug
2584      symbol into the real symbol.  Therefor, let's presume the debug
2585      symbol is a real function reference.  */
2586
2587   /* FIXME-SOON If for some reason the definition label/symbol is
2588      never seen, this will probably leave an undefined symbol at link
2589      time.  */
2590
2591   if (S_GET_STORAGE_CLASS (def_symbol_in_progress) == C_EFCN
2592       || S_GET_STORAGE_CLASS (def_symbol_in_progress) == C_LABEL
2593       || (S_GET_SEGMENT (def_symbol_in_progress) == SEG_DEBUG
2594           && !SF_GET_TAG (def_symbol_in_progress))
2595       || S_GET_SEGMENT (def_symbol_in_progress) == absolute_section
2596       || def_symbol_in_progress->sy_value.X_op != O_constant
2597       || (symbolP = symbol_find (S_GET_NAME (def_symbol_in_progress))) == NULL
2598       || (SF_GET_TAG (def_symbol_in_progress) != SF_GET_TAG (symbolP)))
2599     {
2600       symbol_append (def_symbol_in_progress, symbol_lastP, &symbol_rootP,
2601                      &symbol_lastP);
2602     }
2603   else
2604     {
2605       /* This symbol already exists, merge the newly created symbol
2606          into the old one.  This is not mandatory. The linker can
2607          handle duplicate symbols correctly. But I guess that it save
2608          a *lot* of space if the assembly file defines a lot of
2609          symbols. [loic] */
2610
2611       /* The debug entry (def_symbol_in_progress) is merged into the
2612          previous definition.  */
2613
2614       c_symbol_merge (def_symbol_in_progress, symbolP);
2615       /* FIXME-SOON Should *def_symbol_in_progress be free'd? xoxorich.  */
2616       def_symbol_in_progress = symbolP;
2617
2618       if (SF_GET_FUNCTION (def_symbol_in_progress)
2619           || SF_GET_TAG (def_symbol_in_progress)
2620           || S_GET_STORAGE_CLASS (def_symbol_in_progress) == C_STAT)
2621         {
2622           /* For functions, and tags, and static symbols, the symbol
2623              *must* be where the debug symbol appears.  Move the
2624              existing symbol to the current place.  */
2625           /* If it already is at the end of the symbol list, do nothing.  */
2626           if (def_symbol_in_progress != symbol_lastP)
2627             {
2628               symbol_remove (def_symbol_in_progress, &symbol_rootP,
2629                              &symbol_lastP);
2630               symbol_append (def_symbol_in_progress, symbol_lastP,
2631                              &symbol_rootP, &symbol_lastP);
2632             }
2633         }
2634     }
2635
2636   if (SF_GET_TAG (def_symbol_in_progress))
2637     {
2638       symbolS *oldtag;
2639
2640       oldtag = symbol_find (S_GET_NAME (def_symbol_in_progress));
2641       if (oldtag == NULL || ! SF_GET_TAG (oldtag))
2642         tag_insert (S_GET_NAME (def_symbol_in_progress),
2643                     def_symbol_in_progress);
2644     }
2645
2646   if (SF_GET_FUNCTION (def_symbol_in_progress))
2647     {
2648       know (sizeof (def_symbol_in_progress) <= sizeof (long));
2649       function_lineoff
2650         = c_line_new (def_symbol_in_progress, 0, 0, &zero_address_frag);
2651
2652       SF_SET_PROCESS (def_symbol_in_progress);
2653
2654       if (symbolP == NULL)
2655         /* That is, if this is the first time we've seen the function.  */
2656         symbol_table_insert (def_symbol_in_progress);
2657     }
2658
2659   def_symbol_in_progress = NULL;
2660   demand_empty_rest_of_line ();
2661 }
2662
2663 static void
2664 obj_coff_dim (int ignore ATTRIBUTE_UNUSED)
2665 {
2666   int dim_index;
2667
2668   if (def_symbol_in_progress == NULL)
2669     {
2670       as_warn (_(".dim pseudo-op used outside of .def/.endef: ignored."));
2671       demand_empty_rest_of_line ();
2672       return;
2673     }
2674
2675   S_SET_NUMBER_AUXILIARY (def_symbol_in_progress, 1);
2676
2677   for (dim_index = 0; dim_index < DIMNUM; dim_index++)
2678     {
2679       SKIP_WHITESPACES ();
2680       SA_SET_SYM_DIMEN (def_symbol_in_progress, dim_index,
2681                         get_absolute_expression ());
2682
2683       switch (*input_line_pointer)
2684         {
2685         case ',':
2686           input_line_pointer++;
2687           break;
2688
2689         default:
2690           as_warn (_("badly formed .dim directive ignored"));
2691           /* Fall through.  */
2692
2693         case '\n':
2694         case ';':
2695           dim_index = DIMNUM;
2696           break;
2697         }
2698     }
2699
2700   demand_empty_rest_of_line ();
2701 }
2702
2703 static void
2704 obj_coff_line (int ignore ATTRIBUTE_UNUSED)
2705 {
2706   int this_base;
2707   const char *name;
2708
2709   if (def_symbol_in_progress == NULL)
2710     {
2711       obj_coff_ln (0);
2712       return;
2713     }
2714
2715   name = S_GET_NAME (def_symbol_in_progress);
2716   this_base = get_absolute_expression ();
2717
2718   /* Only .bf symbols indicate the use of a new base line number; the
2719      line numbers associated with .ef, .bb, .eb are relative to the
2720      start of the containing function.  */
2721   if (streq (".bf", name))
2722     {
2723         line_base = this_base;
2724
2725 #ifndef NO_LISTING
2726       {
2727         extern int listing;
2728         if (listing)
2729           listing_source_line ((unsigned int) line_base);
2730       }
2731 #endif
2732     }
2733
2734   S_SET_NUMBER_AUXILIARY (def_symbol_in_progress, 1);
2735   SA_SET_SYM_LNNO (def_symbol_in_progress, this_base);
2736
2737   demand_empty_rest_of_line ();
2738 }
2739
2740 static void
2741 obj_coff_size (int ignore ATTRIBUTE_UNUSED)
2742 {
2743   if (def_symbol_in_progress == NULL)
2744     {
2745       as_warn (_(".size pseudo-op used outside of .def/.endef ignored."));
2746       demand_empty_rest_of_line ();
2747       return;
2748     }
2749
2750   S_SET_NUMBER_AUXILIARY (def_symbol_in_progress, 1);
2751   SA_SET_SYM_SIZE (def_symbol_in_progress, get_absolute_expression ());
2752   demand_empty_rest_of_line ();
2753 }
2754
2755 static void
2756 obj_coff_scl (int ignore ATTRIBUTE_UNUSED)
2757 {
2758   if (def_symbol_in_progress == NULL)
2759     {
2760       as_warn (_(".scl pseudo-op used outside of .def/.endef ignored."));
2761       demand_empty_rest_of_line ();
2762       return;
2763     }
2764
2765   S_SET_STORAGE_CLASS (def_symbol_in_progress, get_absolute_expression ());
2766   demand_empty_rest_of_line ();
2767 }
2768
2769 static void
2770 obj_coff_tag (int ignore ATTRIBUTE_UNUSED)
2771 {
2772   char *symbol_name;
2773   char name_end;
2774
2775   if (def_symbol_in_progress == NULL)
2776     {
2777       as_warn (_(".tag pseudo-op used outside of .def/.endef ignored."));
2778       demand_empty_rest_of_line ();
2779       return;
2780     }
2781
2782   S_SET_NUMBER_AUXILIARY (def_symbol_in_progress, 1);
2783   symbol_name = input_line_pointer;
2784   name_end = get_symbol_end ();
2785 #ifdef tc_canonicalize_symbol_name
2786   symbol_name = tc_canonicalize_symbol_name (symbol_name);
2787 #endif
2788
2789   /* Assume that the symbol referred to by .tag is always defined.
2790      This was a bad assumption.  I've added find_or_make. xoxorich.  */
2791   SA_SET_SYM_TAGNDX (def_symbol_in_progress,
2792                      (long) tag_find_or_make (symbol_name));
2793   if (SA_GET_SYM_TAGNDX (def_symbol_in_progress) == 0L)
2794     as_warn (_("tag not found for .tag %s"), symbol_name);
2795
2796   SF_SET_TAGGED (def_symbol_in_progress);
2797   *input_line_pointer = name_end;
2798
2799   demand_empty_rest_of_line ();
2800 }
2801
2802 static void
2803 obj_coff_type (int ignore ATTRIBUTE_UNUSED)
2804 {
2805   if (def_symbol_in_progress == NULL)
2806     {
2807       as_warn (_(".type pseudo-op used outside of .def/.endef ignored."));
2808       demand_empty_rest_of_line ();
2809       return;
2810     }
2811
2812   S_SET_DATA_TYPE (def_symbol_in_progress, get_absolute_expression ());
2813
2814   if (ISFCN (S_GET_DATA_TYPE (def_symbol_in_progress)) &&
2815       S_GET_STORAGE_CLASS (def_symbol_in_progress) != C_TPDEF)
2816     SF_SET_FUNCTION (def_symbol_in_progress);
2817
2818   demand_empty_rest_of_line ();
2819 }
2820
2821 static void
2822 obj_coff_val (int ignore ATTRIBUTE_UNUSED)
2823 {
2824   if (def_symbol_in_progress == NULL)
2825     {
2826       as_warn (_(".val pseudo-op used outside of .def/.endef ignored."));
2827       demand_empty_rest_of_line ();
2828       return;
2829     }
2830
2831   if (is_name_beginner (*input_line_pointer))
2832     {
2833       char *symbol_name = input_line_pointer;
2834       char name_end = get_symbol_end ();
2835
2836 #ifdef tc_canonicalize_symbol_name
2837   symbol_name = tc_canonicalize_symbol_name (symbol_name);
2838 #endif
2839
2840       if (streq (symbol_name, "."))
2841         {
2842           def_symbol_in_progress->sy_frag = frag_now;
2843           S_SET_VALUE (def_symbol_in_progress, (valueT) frag_now_fix ());
2844           /* If the .val is != from the .def (e.g. statics).  */
2845         }
2846       else if (! streq (S_GET_NAME (def_symbol_in_progress), symbol_name))
2847         {
2848           def_symbol_in_progress->sy_value.X_op = O_symbol;
2849           def_symbol_in_progress->sy_value.X_add_symbol =
2850             symbol_find_or_make (symbol_name);
2851           def_symbol_in_progress->sy_value.X_op_symbol = NULL;
2852           def_symbol_in_progress->sy_value.X_add_number = 0;
2853
2854           /* If the segment is undefined when the forward reference is
2855              resolved, then copy the segment id from the forward
2856              symbol.  */
2857           SF_SET_GET_SEGMENT (def_symbol_in_progress);
2858
2859           /* FIXME: gcc can generate address expressions here in
2860              unusual cases (search for "obscure" in sdbout.c).  We
2861              just ignore the offset here, thus generating incorrect
2862              debugging information.  We ignore the rest of the line
2863              just below.  */
2864         }
2865       /* Otherwise, it is the name of a non debug symbol and
2866          its value will be calculated later.  */
2867       *input_line_pointer = name_end;
2868
2869       /* FIXME: this is to avoid an error message in the
2870          FIXME case mentioned just above.  */
2871       while (! is_end_of_line[(unsigned char) *input_line_pointer])
2872         ++input_line_pointer;
2873     }
2874   else
2875     {
2876       S_SET_VALUE (def_symbol_in_progress,
2877                    (valueT) get_absolute_expression ());
2878     }
2879
2880   demand_empty_rest_of_line ();
2881 }
2882
2883 #ifdef TE_PE
2884
2885 /* Handle the .linkonce pseudo-op.  This is parsed by s_linkonce in
2886    read.c, which then calls this object file format specific routine.  */
2887
2888 void
2889 obj_coff_pe_handle_link_once (enum linkonce_type type)
2890 {
2891   seg_info (now_seg)->scnhdr.s_flags |= IMAGE_SCN_LNK_COMDAT;
2892
2893   /* We store the type in the seg_info structure, and use it to set up
2894      the auxiliary entry for the section symbol in c_section_symbol.  */
2895   seg_info (now_seg)->linkonce = type;
2896 }
2897
2898 #endif /* TE_PE */
2899
2900 void
2901 coff_obj_read_begin_hook (void)
2902 {
2903   /* These had better be the same.  Usually 18 bytes.  */
2904 #ifndef BFD_HEADERS
2905   know (sizeof (SYMENT) == sizeof (AUXENT));
2906   know (SYMESZ == AUXESZ);
2907 #endif
2908   tag_init ();
2909 }
2910
2911 /* This function runs through the symbol table and puts all the
2912    externals onto another chain.  */
2913
2914 /* The chain of globals.  */
2915 symbolS *symbol_globalP;
2916 symbolS *symbol_global_lastP;
2917
2918 /* The chain of externals.  */
2919 symbolS *symbol_externP;
2920 symbolS *symbol_extern_lastP;
2921
2922 stack *block_stack;
2923 symbolS *last_functionP;
2924 static symbolS *last_bfP;
2925 symbolS *last_tagP;
2926
2927 static unsigned int
2928 yank_symbols (void)
2929 {
2930   symbolS *symbolP;
2931   unsigned int symbol_number = 0;
2932   unsigned int last_file_symno = 0;
2933   struct filename_list *filename_list_scan = filename_list_head;
2934
2935   for (symbolP = symbol_rootP;
2936        symbolP;
2937        symbolP = symbolP ? symbol_next (symbolP) : symbol_rootP)
2938     {
2939       if (symbolP->sy_mri_common)
2940         {
2941           if (S_GET_STORAGE_CLASS (symbolP) == C_EXT
2942 #ifdef TE_PE
2943               || S_GET_STORAGE_CLASS (symbolP) == C_NT_WEAK
2944 #endif
2945               || S_GET_STORAGE_CLASS (symbolP) == C_WEAKEXT)
2946             as_bad (_("%s: global symbols not supported in common sections"),
2947                     S_GET_NAME (symbolP));
2948           symbol_remove (symbolP, &symbol_rootP, &symbol_lastP);
2949           continue;
2950         }
2951
2952       if (!SF_GET_DEBUG (symbolP))
2953         {
2954           /* Debug symbols do not need all this rubbish.  */
2955           symbolS *real_symbolP;
2956
2957           /* L* and C_EFCN symbols never merge.  */
2958           if (!SF_GET_LOCAL (symbolP)
2959               && !SF_GET_STATICS (symbolP)
2960               && S_GET_STORAGE_CLASS (symbolP) != C_LABEL
2961               && symbolP->sy_value.X_op == O_constant
2962               && (real_symbolP = symbol_find (S_GET_NAME (symbolP)))
2963               && real_symbolP != symbolP)
2964             {
2965               /* FIXME-SOON: where do dups come from?
2966                  Maybe tag references before definitions? xoxorich.  */
2967               /* Move the debug data from the debug symbol to the
2968                  real symbol. Do NOT do the opposite (i.e. move from
2969                  real symbol to debug symbol and remove real symbol from the
2970                  list.) Because some pointers refer to the real symbol
2971                  whereas no pointers refer to the debug symbol.  */
2972               c_symbol_merge (symbolP, real_symbolP);
2973               /* Replace the current symbol by the real one.  */
2974               /* The symbols will never be the last or the first
2975                  because : 1st symbol is .file and 3 last symbols are
2976                  .text, .data, .bss.  */
2977               symbol_remove (real_symbolP, &symbol_rootP, &symbol_lastP);
2978               symbol_insert (real_symbolP, symbolP, &symbol_rootP, &symbol_lastP);
2979               symbol_remove (symbolP, &symbol_rootP, &symbol_lastP);
2980               symbolP = real_symbolP;
2981             }
2982
2983           if (flag_readonly_data_in_text && (S_GET_SEGMENT (symbolP) == SEG_E1))
2984             S_SET_SEGMENT (symbolP, SEG_E0);
2985
2986           resolve_symbol_value (symbolP);
2987
2988           if (S_GET_STORAGE_CLASS (symbolP) == C_NULL)
2989             {
2990               if (!S_IS_DEFINED (symbolP) && !SF_GET_LOCAL (symbolP))
2991                 S_SET_EXTERNAL (symbolP);
2992
2993               else if (S_GET_SEGMENT (symbolP) == SEG_E0)
2994                 S_SET_STORAGE_CLASS (symbolP, C_LABEL);
2995
2996               else
2997                 S_SET_STORAGE_CLASS (symbolP, C_STAT);
2998             }
2999
3000           /* Mainly to speed up if not -g.  */
3001           if (SF_GET_PROCESS (symbolP))
3002             {
3003               /* Handle the nested blocks auxiliary info.  */
3004               if (S_GET_STORAGE_CLASS (symbolP) == C_BLOCK)
3005                 {
3006                   if (streq (S_GET_NAME (symbolP), ".bb"))
3007                     stack_push (block_stack, (char *) &symbolP);
3008                   else
3009                     {
3010                       /* .eb */
3011                       symbolS *begin_symbolP;
3012
3013                       begin_symbolP = *(symbolS **) stack_pop (block_stack);
3014                       if (begin_symbolP == NULL)
3015                         as_warn (_("mismatched .eb"));
3016                       else
3017                         SA_SET_SYM_ENDNDX (begin_symbolP, symbol_number + 2);
3018                     }
3019                 }
3020
3021               /* If we are able to identify the type of a function, and we
3022                are out of a function (last_functionP == 0) then, the
3023                function symbol will be associated with an auxiliary
3024                entry.  */
3025               if (last_functionP == NULL && SF_GET_FUNCTION (symbolP))
3026                 {
3027                   last_functionP = symbolP;
3028
3029                   if (S_GET_NUMBER_AUXILIARY (symbolP) < 1)
3030                     S_SET_NUMBER_AUXILIARY (symbolP, 1);
3031                 }
3032
3033               if (S_GET_STORAGE_CLASS (symbolP) == C_FCN)
3034                 {
3035                   if (streq (S_GET_NAME (symbolP), ".bf"))
3036                     {
3037                       if (last_bfP != NULL)
3038                         SA_SET_SYM_ENDNDX (last_bfP, symbol_number);
3039                       last_bfP = symbolP;
3040                     }
3041                 }
3042               else if (S_GET_STORAGE_CLASS (symbolP) == C_EFCN)
3043                 {
3044                   /* I don't even know if this is needed for sdb. But
3045                      the standard assembler generates it, so...  */
3046                   if (last_functionP == NULL)
3047                     as_fatal (_("C_EFCN symbol out of scope"));
3048                   SA_SET_SYM_FSIZE (last_functionP,
3049                                     (long) (S_GET_VALUE (symbolP) -
3050                                             S_GET_VALUE (last_functionP)));
3051                   SA_SET_SYM_ENDNDX (last_functionP, symbol_number);
3052                  last_functionP = NULL;
3053                 }
3054             }
3055         }
3056       else if (SF_GET_TAG (symbolP))
3057         /* First descriptor of a structure must point to
3058            the first slot after the structure description.  */
3059         last_tagP = symbolP;
3060
3061       else if (S_GET_STORAGE_CLASS (symbolP) == C_EOS)
3062         /* +2 take in account the current symbol.  */
3063         SA_SET_SYM_ENDNDX (last_tagP, symbol_number + 2);
3064
3065       else if (S_GET_STORAGE_CLASS (symbolP) == C_FILE)
3066         {
3067           /* If the filename was too long to fit in the
3068              auxent, put it in the string table.  */
3069           if (SA_GET_FILE_FNAME_ZEROS (symbolP) == 0
3070               && SA_GET_FILE_FNAME_OFFSET (symbolP) != 0)
3071             {
3072               SA_SET_FILE_FNAME_OFFSET (symbolP, string_byte_count);
3073               string_byte_count += strlen (filename_list_scan->filename) + 1;
3074               filename_list_scan = filename_list_scan->next;
3075             }
3076           if (S_GET_VALUE (symbolP))
3077             {
3078               S_SET_VALUE (symbolP, last_file_symno);
3079               last_file_symno = symbol_number;
3080             }
3081         }
3082
3083 #ifdef tc_frob_coff_symbol
3084       tc_frob_coff_symbol (symbolP);
3085 #endif
3086
3087       /* We must put the external symbols apart. The loader
3088          does not bomb if we do not. But the references in
3089          the endndx field for a .bb symbol are not corrected
3090          if an external symbol is removed between .bb and .be.
3091          I.e in the following case :
3092          [20] .bb endndx = 22
3093          [21] foo external
3094          [22] .be
3095          ld will move the symbol 21 to the end of the list but
3096          endndx will still be 22 instead of 21.  */
3097
3098       if (SF_GET_LOCAL (symbolP))
3099         /* Remove C_EFCN and LOCAL (L...) symbols.  */
3100         /* Next pointer remains valid.  */
3101         symbol_remove (symbolP, &symbol_rootP, &symbol_lastP);
3102
3103       else if (symbolP->sy_value.X_op == O_symbol
3104                && (! S_IS_DEFINED (symbolP) || S_IS_COMMON (symbolP)))
3105         /* Skip symbols which were equated to undefined or common
3106            symbols.  */
3107         symbol_remove (symbolP, &symbol_rootP, &symbol_lastP);
3108
3109       else if (!S_IS_DEFINED (symbolP)
3110                && !S_IS_DEBUG (symbolP)
3111                && !SF_GET_STATICS (symbolP)
3112                && (S_GET_STORAGE_CLASS (symbolP) == C_EXT
3113 #ifdef TE_PE
3114                    || S_GET_STORAGE_CLASS (symbolP) == C_NT_WEAK
3115 #endif
3116                    || S_GET_STORAGE_CLASS (symbolP) == C_WEAKEXT))
3117         {
3118           /* If external, Remove from the list.  */
3119           symbolS *hold = symbol_previous (symbolP);
3120
3121           symbol_remove (symbolP, &symbol_rootP, &symbol_lastP);
3122           symbol_clear_list_pointers (symbolP);
3123           symbol_append (symbolP, symbol_extern_lastP, &symbol_externP, &symbol_extern_lastP);
3124           symbolP = hold;
3125         }
3126       else if (! S_IS_DEBUG (symbolP)
3127                && ! SF_GET_STATICS (symbolP)
3128                && ! SF_GET_FUNCTION (symbolP)
3129                && (S_GET_STORAGE_CLASS (symbolP) == C_EXT
3130 #ifdef TE_PE
3131                    || S_GET_STORAGE_CLASS (symbolP) == C_NT_WEAK
3132 #endif
3133                    || S_GET_STORAGE_CLASS (symbolP) == C_NT_WEAK))
3134         {
3135           symbolS *hold = symbol_previous (symbolP);
3136
3137           /* The O'Reilly COFF book says that defined global symbols
3138              come at the end of the symbol table, just before
3139              undefined global symbols.  */
3140           symbol_remove (symbolP, &symbol_rootP, &symbol_lastP);
3141           symbol_clear_list_pointers (symbolP);
3142           symbol_append (symbolP, symbol_global_lastP, &symbol_globalP,
3143                          &symbol_global_lastP);
3144           symbolP = hold;
3145         }
3146       else
3147         {
3148           if (SF_GET_STRING (symbolP))
3149             {
3150               symbolP->sy_name_offset = string_byte_count;
3151               string_byte_count += strlen (S_GET_NAME (symbolP)) + 1;
3152             }
3153           else
3154             symbolP->sy_name_offset = 0;
3155
3156           symbolP->sy_number = symbol_number;
3157           symbol_number += 1 + S_GET_NUMBER_AUXILIARY (symbolP);
3158         }
3159     }
3160
3161   return symbol_number;
3162 }
3163
3164 static unsigned int
3165 glue_symbols (symbolS **head, symbolS **tail)
3166 {
3167   unsigned int symbol_number = 0;
3168
3169   while (*head != NULL)
3170     {
3171       symbolS *tmp = *head;
3172
3173       /* Append.  */
3174       symbol_remove (tmp, head, tail);
3175       symbol_append (tmp, symbol_lastP, &symbol_rootP, &symbol_lastP);
3176
3177       /* Process.  */
3178       if (SF_GET_STRING (tmp))
3179         {
3180           tmp->sy_name_offset = string_byte_count;
3181           string_byte_count += strlen (S_GET_NAME (tmp)) + 1;
3182         }
3183       else
3184         /* Fix "long" names.  */
3185         tmp->sy_name_offset = 0;
3186
3187       tmp->sy_number = symbol_number;
3188       symbol_number += 1 + S_GET_NUMBER_AUXILIARY (tmp);
3189     }
3190
3191   return symbol_number;
3192 }
3193
3194 static unsigned int
3195 tie_tags (void)
3196 {
3197   unsigned int symbol_number = 0;
3198   symbolS *symbolP;
3199
3200   for (symbolP = symbol_rootP; symbolP; symbolP = symbol_next (symbolP))
3201     {
3202       symbolP->sy_number = symbol_number;
3203
3204       if (SF_GET_TAGGED (symbolP))
3205         {
3206           SA_SET_SYM_TAGNDX
3207             (symbolP,
3208              ((symbolS *) SA_GET_SYM_TAGNDX (symbolP))->sy_number);
3209         }
3210
3211       symbol_number += 1 + S_GET_NUMBER_AUXILIARY (symbolP);
3212     }
3213
3214   return symbol_number;
3215 }
3216
3217
3218 /* Build a 'section static' symbol.  */
3219
3220 static symbolS *
3221 c_section_symbol (char *name, int idx)
3222 {
3223   symbolS *symbolP;
3224
3225   symbolP = symbol_find (name);
3226   if (symbolP == NULL)
3227     symbolP = symbol_new (name, idx, 0, &zero_address_frag);
3228   else
3229     {
3230       /* Mmmm.  I just love violating interfaces.  Makes me feel...dirty.  */
3231       S_SET_SEGMENT (symbolP, idx);
3232       symbolP->sy_frag = &zero_address_frag;
3233     }
3234
3235   S_SET_STORAGE_CLASS (symbolP, C_STAT);
3236   S_SET_NUMBER_AUXILIARY (symbolP, 1);
3237
3238   SF_SET_STATICS (symbolP);
3239
3240 #ifdef TE_DELTA
3241   /* manfred@s-direktnet.de: section symbols *must* have the LOCAL bit cleared,
3242      which is set by the new definition of LOCAL_LABEL in tc-m68k.h.  */
3243   SF_CLEAR_LOCAL (symbolP);
3244 #endif
3245 #ifdef TE_PE
3246   /* If the .linkonce pseudo-op was used for this section, we must
3247      store the information in the auxiliary entry for the section
3248      symbol.  */
3249   if (segment_info[idx].linkonce != LINKONCE_UNSET)
3250     {
3251       int type;
3252
3253       switch (segment_info[idx].linkonce)
3254         {
3255         default:
3256           abort ();
3257         case LINKONCE_DISCARD:
3258           type = IMAGE_COMDAT_SELECT_ANY;
3259           break;
3260         case LINKONCE_ONE_ONLY:
3261           type = IMAGE_COMDAT_SELECT_NODUPLICATES;
3262           break;
3263         case LINKONCE_SAME_SIZE:
3264           type = IMAGE_COMDAT_SELECT_SAME_SIZE;
3265           break;
3266         case LINKONCE_SAME_CONTENTS:
3267           type = IMAGE_COMDAT_SELECT_EXACT_MATCH;
3268           break;
3269         }
3270
3271       SYM_AUXENT (symbolP)->x_scn.x_comdat = type;
3272     }
3273 #endif /* TE_PE */
3274
3275   return symbolP;
3276 }
3277
3278 static void
3279 crawl_symbols (object_headers *h, bfd *abfd ATTRIBUTE_UNUSED)
3280 {
3281   unsigned int i;
3282
3283   /* Initialize the stack used to keep track of the matching .bb .be.  */
3284   block_stack = stack_init (512, sizeof (symbolS *));
3285
3286   /* The symbol list should be ordered according to the following sequence
3287      order :
3288      . .file symbol
3289      . debug entries for functions
3290      . fake symbols for the sections, including .text .data and .bss
3291      . defined symbols
3292      . undefined symbols
3293      But this is not mandatory. The only important point is to put the
3294      undefined symbols at the end of the list.  */
3295
3296   /* Is there a .file symbol ? If not insert one at the beginning.  */
3297   if (symbol_rootP == NULL
3298       || S_GET_STORAGE_CLASS (symbol_rootP) != C_FILE)
3299     c_dot_file_symbol ("fake", 0);
3300
3301   /* Build up static symbols for the sections, they are filled in later.  */
3302   for (i = SEG_E0; i < SEG_LAST; i++)
3303     if (segment_info[i].scnhdr.s_name[0])
3304       segment_info[i].dot = c_section_symbol ((char *) segment_info[i].name,
3305                                               i - SEG_E0 + 1);
3306
3307   /* Take all the externals out and put them into another chain.  */
3308   H_SET_SYMBOL_TABLE_SIZE (h, yank_symbols ());
3309   /* Take the externals and glue them onto the end.  */
3310   H_SET_SYMBOL_TABLE_SIZE (h,
3311                            (H_GET_SYMBOL_COUNT (h)
3312                             + glue_symbols (&symbol_globalP,
3313                                             &symbol_global_lastP)
3314                             + glue_symbols (&symbol_externP,
3315                                             &symbol_extern_lastP)));
3316
3317   H_SET_SYMBOL_TABLE_SIZE (h, tie_tags ());
3318   know (symbol_globalP == NULL);
3319   know (symbol_global_lastP == NULL);
3320   know (symbol_externP == NULL);
3321   know (symbol_extern_lastP == NULL);
3322 }
3323
3324 /* Find strings by crawling along symbol table chain.  */
3325
3326 static void
3327 w_strings (char *where)
3328 {
3329   symbolS *symbolP;
3330   struct filename_list *filename_list_scan = filename_list_head;
3331
3332   /* Gotta do md_ byte-ordering stuff for string_byte_count first - KWK.  */
3333   md_number_to_chars (where, (valueT) string_byte_count, 4);
3334   where += 4;
3335
3336 #ifdef COFF_LONG_SECTION_NAMES
3337   /* Support long section names as found in PE.  This code must
3338      coordinate with that in coff_header_append and write_object_file.  */
3339   {
3340     unsigned int i;
3341
3342     for (i = SEG_E0; i < SEG_LAST; i++)
3343       {
3344         if (segment_info[i].scnhdr.s_name[0]
3345             && strlen (segment_info[i].name) > SCNNMLEN)
3346           {
3347             unsigned int size;
3348
3349             size = strlen (segment_info[i].name) + 1;
3350             memcpy (where, segment_info[i].name, size);
3351             where += size;
3352           }
3353       }
3354   }
3355 #endif /* COFF_LONG_SECTION_NAMES */
3356
3357   for (symbolP = symbol_rootP;
3358        symbolP;
3359        symbolP = symbol_next (symbolP))
3360     {
3361       unsigned int size;
3362
3363       if (SF_GET_STRING (symbolP))
3364         {
3365           size = strlen (S_GET_NAME (symbolP)) + 1;
3366           memcpy (where, S_GET_NAME (symbolP), size);
3367           where += size;
3368         }
3369       if (S_GET_STORAGE_CLASS (symbolP) == C_FILE
3370           && SA_GET_FILE_FNAME_ZEROS (symbolP) == 0
3371           && SA_GET_FILE_FNAME_OFFSET (symbolP) != 0)
3372         {
3373           size = strlen (filename_list_scan->filename) + 1;
3374           memcpy (where, filename_list_scan->filename, size);
3375           filename_list_scan = filename_list_scan ->next;
3376           where += size;
3377         }
3378     }
3379 }
3380
3381 static void
3382 do_linenos_for (bfd * abfd,
3383                 object_headers * h,
3384                 unsigned long *file_cursor)
3385 {
3386   unsigned int idx;
3387   unsigned long start = *file_cursor;
3388
3389   for (idx = SEG_E0; idx < SEG_LAST; idx++)
3390     {
3391       segment_info_type *s = segment_info + idx;
3392
3393       if (s->scnhdr.s_nlnno != 0)
3394         {
3395           struct lineno_list *line_ptr;
3396           struct external_lineno *buffer = xmalloc (s->scnhdr.s_nlnno * LINESZ);
3397           struct external_lineno *dst = buffer;
3398
3399           /* Run through the table we've built and turn it into its external
3400              form, take this chance to remove duplicates.  */
3401
3402           for (line_ptr = s->lineno_list_head;
3403                line_ptr != (struct lineno_list *) NULL;
3404                line_ptr = line_ptr->next)
3405             {
3406               if (line_ptr->line.l_lnno == 0)
3407                 {
3408                   /* Turn a pointer to a symbol into the symbols' index,
3409                      provided that it has been initialised.  */
3410                   if (line_ptr->line.l_addr.l_symndx)
3411                     line_ptr->line.l_addr.l_symndx =
3412                       ((symbolS *) line_ptr->line.l_addr.l_symndx)->sy_number;
3413                 }
3414               else
3415                 line_ptr->line.l_addr.l_paddr += ((struct frag *) (line_ptr->frag))->fr_address;
3416
3417               (void) bfd_coff_swap_lineno_out (abfd, &(line_ptr->line), dst);
3418               dst++;
3419             }
3420
3421           s->scnhdr.s_lnnoptr = *file_cursor;
3422
3423           bfd_bwrite (buffer, (bfd_size_type) s->scnhdr.s_nlnno * LINESZ, abfd);
3424           free (buffer);
3425
3426           *file_cursor += s->scnhdr.s_nlnno * LINESZ;
3427         }
3428     }
3429
3430   H_SET_LINENO_SIZE (h, *file_cursor - start);
3431 }
3432
3433 /* Now we run through the list of frag chains in a segment and
3434    make all the subsegment frags appear at the end of the
3435    list, as if the seg 0 was extra long.  */
3436
3437 static void
3438 remove_subsegs (void)
3439 {
3440   unsigned int i;
3441
3442   for (i = SEG_E0; i < SEG_UNKNOWN; i++)
3443     {
3444       frchainS *head = segment_info[i].frchainP;
3445       fragS dummy;
3446       fragS *prev_frag = &dummy;
3447
3448       while (head && head->frch_seg == i)
3449         {
3450           prev_frag->fr_next = head->frch_root;
3451           prev_frag = head->frch_last;
3452           head = head->frch_next;
3453         }
3454       prev_frag->fr_next = 0;
3455     }
3456 }
3457
3458 unsigned long machine;
3459 int coff_flags;
3460
3461 #ifndef SUB_SEGMENT_ALIGN
3462 #ifdef HANDLE_ALIGN
3463 /* The last subsegment gets an alignment corresponding to the alignment
3464    of the section.  This allows proper nop-filling at the end of
3465    code-bearing sections.  */
3466 #define SUB_SEGMENT_ALIGN(SEG, FRCHAIN)                                 \
3467   (!(FRCHAIN)->frch_next || (FRCHAIN)->frch_next->frch_seg != (SEG)     \
3468    ? get_recorded_alignment (SEG) : 0)
3469 #else
3470 #define SUB_SEGMENT_ALIGN(SEG, FRCHAIN) 1
3471 #endif
3472 #endif
3473
3474 static void
3475 w_symbols (bfd * abfd, char *where, symbolS * symbol_rootP)
3476 {
3477   symbolS *symbolP;
3478   unsigned int i;
3479
3480   /* First fill in those values we have only just worked out.  */
3481   for (i = SEG_E0; i < SEG_LAST; i++)
3482     {
3483       symbolP = segment_info[i].dot;
3484       if (symbolP)
3485         {
3486           SA_SET_SCN_SCNLEN (symbolP, segment_info[i].scnhdr.s_size);
3487           SA_SET_SCN_NRELOC (symbolP, segment_info[i].scnhdr.s_nreloc);
3488           SA_SET_SCN_NLINNO (symbolP, segment_info[i].scnhdr.s_nlnno);
3489         }
3490     }
3491
3492   /* Emit all symbols left in the symbol chain.  */
3493   for (symbolP = symbol_rootP; symbolP; symbolP = symbol_next (symbolP))
3494     {
3495       /* Used to save the offset of the name. It is used to point
3496          to the string in memory but must be a file offset.  */
3497       char *temp;
3498
3499       /* We can't fix the lnnoptr field in yank_symbols with the other
3500          adjustments, because we have to wait until we know where they
3501          go in the file.  */
3502       if (SF_GET_ADJ_LNNOPTR (symbolP))
3503         SA_GET_SYM_LNNOPTR (symbolP) +=
3504           segment_info[S_GET_SEGMENT (symbolP)].scnhdr.s_lnnoptr;
3505
3506       tc_coff_symbol_emit_hook (symbolP);
3507
3508       temp = S_GET_NAME (symbolP);
3509       if (SF_GET_STRING (symbolP))
3510         {
3511           S_SET_OFFSET (symbolP, symbolP->sy_name_offset);
3512           S_SET_ZEROES (symbolP, 0);
3513         }
3514       else
3515         {
3516           memset (symbolP->sy_symbol.ost_entry.n_name, 0, SYMNMLEN);
3517           strncpy (symbolP->sy_symbol.ost_entry.n_name, temp, SYMNMLEN);
3518         }
3519       where = symbol_to_chars (abfd, where, symbolP);
3520       S_SET_NAME (symbolP, temp);
3521     }
3522 }
3523
3524 static void
3525 fixup_mdeps (fragS *frags,
3526              object_headers *h ATTRIBUTE_UNUSED,
3527              segT this_segment)
3528 {
3529   subseg_change (this_segment, 0);
3530
3531   while (frags)
3532     {
3533       switch (frags->fr_type)
3534         {
3535         case rs_align:
3536         case rs_align_code:
3537         case rs_align_test:
3538         case rs_org:
3539 #ifdef HANDLE_ALIGN
3540           HANDLE_ALIGN (frags);
3541 #endif
3542           frags->fr_type = rs_fill;
3543           frags->fr_offset =
3544             ((frags->fr_next->fr_address - frags->fr_address - frags->fr_fix)
3545              / frags->fr_var);
3546           break;
3547         case rs_machine_dependent:
3548           md_convert_frag (h, this_segment, frags);
3549           frag_wane (frags);
3550           break;
3551         default:
3552           ;
3553         }
3554       frags = frags->fr_next;
3555     }
3556 }
3557
3558 #ifndef TC_FORCE_RELOCATION
3559 #define TC_FORCE_RELOCATION(fix) 0
3560 #endif
3561
3562 static void
3563 fixup_segment (segment_info_type * segP, segT this_segment_type)
3564 {
3565   fixS * fixP;
3566   symbolS *add_symbolP;
3567   symbolS *sub_symbolP;
3568   long add_number;
3569   int size;
3570   char *place;
3571   long where;
3572   char pcrel;
3573   fragS *fragP;
3574   segT add_symbol_segment = absolute_section;
3575
3576   for (fixP = segP->fix_root; fixP; fixP = fixP->fx_next)
3577     {
3578       fragP = fixP->fx_frag;
3579       know (fragP);
3580       where = fixP->fx_where;
3581       place = fragP->fr_literal + where;
3582       size = fixP->fx_size;
3583       add_symbolP = fixP->fx_addsy;
3584       sub_symbolP = fixP->fx_subsy;
3585       add_number = fixP->fx_offset;
3586       pcrel = fixP->fx_pcrel;
3587
3588       /* We want function-relative stabs to work on systems which
3589          may use a relaxing linker; thus we must handle the sym1-sym2
3590          fixups function-relative stabs generates.
3591
3592          Of course, if you actually enable relaxing in the linker, the
3593          line and block scoping information is going to be incorrect
3594          in some cases.  The only way to really fix this is to support
3595          a reloc involving the difference of two symbols.  */
3596       if (linkrelax
3597           && (!sub_symbolP || pcrel))
3598         continue;
3599
3600 #ifdef TC_I960
3601       if (fixP->fx_tcbit && SF_GET_CALLNAME (add_symbolP))
3602         {
3603           /* Relocation should be done via the associated 'bal' entry
3604              point symbol.  */
3605           if (!SF_GET_BALNAME (tc_get_bal_of_call (add_symbolP)))
3606             {
3607               as_bad_where (fixP->fx_file, fixP->fx_line,
3608                             _("No 'bal' entry point for leafproc %s"),
3609                             S_GET_NAME (add_symbolP));
3610               continue;
3611             }
3612           fixP->fx_addsy = add_symbolP = tc_get_bal_of_call (add_symbolP);
3613         }
3614 #endif
3615
3616       /* Make sure the symbols have been resolved; this may not have
3617          happened if these are expression symbols.  */
3618       if (add_symbolP != NULL && ! add_symbolP->sy_resolved)
3619         resolve_symbol_value (add_symbolP);
3620
3621       if (add_symbolP != NULL)
3622         {
3623           /* If this fixup is against a symbol which has been equated
3624              to another symbol, convert it to the other symbol.  */
3625           if (add_symbolP->sy_value.X_op == O_symbol
3626               && (! S_IS_DEFINED (add_symbolP)
3627                   || S_IS_COMMON (add_symbolP)))
3628             {
3629               while (add_symbolP->sy_value.X_op == O_symbol
3630                      && (! S_IS_DEFINED (add_symbolP)
3631                          || S_IS_COMMON (add_symbolP)))
3632                 {
3633                   symbolS *n;
3634
3635                   /* We must avoid looping, as that can occur with a
3636                      badly written program.  */
3637                   n = add_symbolP->sy_value.X_add_symbol;
3638                   if (n == add_symbolP)
3639                     break;
3640                   add_number += add_symbolP->sy_value.X_add_number;
3641                   add_symbolP = n;
3642                 }
3643               fixP->fx_addsy = add_symbolP;
3644               fixP->fx_offset = add_number;
3645             }
3646         }
3647
3648       if (sub_symbolP != NULL && ! sub_symbolP->sy_resolved)
3649         resolve_symbol_value (sub_symbolP);
3650
3651       if (add_symbolP != NULL
3652           && add_symbolP->sy_mri_common)
3653         {
3654           add_number += S_GET_VALUE (add_symbolP);
3655           fixP->fx_offset = add_number;
3656           add_symbolP = fixP->fx_addsy = add_symbolP->sy_value.X_add_symbol;
3657         }
3658
3659       if (add_symbolP)
3660         add_symbol_segment = S_GET_SEGMENT (add_symbolP);
3661
3662       if (sub_symbolP)
3663         {
3664           if (add_symbolP == NULL || add_symbol_segment == absolute_section)
3665             {
3666               if (add_symbolP != NULL)
3667                 {
3668                   add_number += S_GET_VALUE (add_symbolP);
3669                   add_symbolP = NULL;
3670                   fixP->fx_addsy = NULL;
3671                 }
3672
3673               /* It's just -sym.  */
3674               if (S_GET_SEGMENT (sub_symbolP) == absolute_section)
3675                 {
3676                   add_number -= S_GET_VALUE (sub_symbolP);
3677                   fixP->fx_subsy = 0;
3678                   fixP->fx_done = 1;
3679                 }
3680               else
3681                 {
3682 #ifndef TC_M68K
3683                   as_bad_where (fixP->fx_file, fixP->fx_line,
3684                                 _("Negative of non-absolute symbol %s"),
3685                                 S_GET_NAME (sub_symbolP));
3686 #endif
3687                   add_number -= S_GET_VALUE (sub_symbolP);
3688                 }               /* not absolute */
3689
3690               /* If sub_symbol is in the same segment that add_symbol
3691                  and add_symbol is either in DATA, TEXT, BSS or ABSOLUTE.  */
3692             }
3693           else if (S_GET_SEGMENT (sub_symbolP) == add_symbol_segment
3694                    && SEG_NORMAL (add_symbol_segment))
3695             {
3696               /* Difference of 2 symbols from same segment.  Can't
3697                  make difference of 2 undefineds: 'value' means
3698                  something different for N_UNDF.  */
3699 #ifdef TC_I960
3700               /* Makes no sense to use the difference of 2 arbitrary symbols
3701                  as the target of a call instruction.  */
3702               if (fixP->fx_tcbit)
3703                 as_bad_where (fixP->fx_file, fixP->fx_line,
3704                               _("callj to difference of 2 symbols"));
3705 #endif /* TC_I960 */
3706               add_number += S_GET_VALUE (add_symbolP) -
3707                 S_GET_VALUE (sub_symbolP);
3708               add_symbolP = NULL;
3709
3710               if (!TC_FORCE_RELOCATION (fixP))
3711                 {
3712                   fixP->fx_addsy = NULL;
3713                   fixP->fx_subsy = NULL;
3714                   fixP->fx_done = 1;
3715 #ifdef TC_M68K /* FIXME: Is this right?  */
3716                   pcrel = 0;
3717                   fixP->fx_pcrel = 0;
3718 #endif
3719                 }
3720             }
3721           else
3722             {
3723               /* Different segments in subtraction.  */
3724               know (!(S_IS_EXTERNAL (sub_symbolP) && (S_GET_SEGMENT (sub_symbolP) == absolute_section)));
3725
3726               if ((S_GET_SEGMENT (sub_symbolP) == absolute_section))
3727                 add_number -= S_GET_VALUE (sub_symbolP);
3728
3729 #ifdef DIFF_EXPR_OK
3730               else if (S_GET_SEGMENT (sub_symbolP) == this_segment_type)
3731                 {
3732                   /* Make it pc-relative.  */
3733                   add_number += (md_pcrel_from (fixP)
3734                                  - S_GET_VALUE (sub_symbolP));
3735                   pcrel = 1;
3736                   fixP->fx_pcrel = 1;
3737                   sub_symbolP = 0;
3738                   fixP->fx_subsy = 0;
3739                 }
3740 #endif
3741               else
3742                 {
3743                   as_bad_where (fixP->fx_file, fixP->fx_line,
3744                                 _("Can't emit reloc {- %s-seg symbol \"%s\"} @ file address %ld."),
3745                                 segment_name (S_GET_SEGMENT (sub_symbolP)),
3746                                 S_GET_NAME (sub_symbolP),
3747                                 (long) (fragP->fr_address + where));
3748                 }
3749             }
3750         }
3751
3752       if (add_symbolP)
3753         {
3754           if (add_symbol_segment == this_segment_type && pcrel)
3755             {
3756               /* This fixup was made when the symbol's segment was
3757                  SEG_UNKNOWN, but it is now in the local segment.
3758                  So we know how to do the address without relocation.  */
3759 #ifdef TC_I960
3760               /* reloc_callj() may replace a 'call' with a 'calls' or a 'bal',
3761                  in which cases it modifies *fixP as appropriate.  In the case
3762                  of a 'calls', no further work is required, and *fixP has been
3763                  set up to make the rest of the code below a no-op.  */
3764               reloc_callj (fixP);
3765 #endif
3766
3767               add_number += S_GET_VALUE (add_symbolP);
3768               add_number -= md_pcrel_from (fixP);
3769
3770               /* We used to do
3771                    add_number -= segP->scnhdr.s_vaddr;
3772                  if defined (TC_I386) || defined (TE_LYNX).  I now
3773                  think that was an error propagated from the case when
3774                  we are going to emit the relocation.  If we are not
3775                  going to emit the relocation, then we just want to
3776                  set add_number to the difference between the symbols.
3777                  This is a case that would only arise when there is a
3778                  PC relative reference from a section other than .text
3779                  to a symbol defined in the same section, and the
3780                  reference is not relaxed.  Since jump instructions on
3781                  the i386 are relaxed, this could only arise with a
3782                  call instruction.  */
3783
3784               /* Lie. Don't want further pcrel processing.  */
3785               pcrel = 0;
3786               if (!TC_FORCE_RELOCATION (fixP))
3787                 {
3788                   fixP->fx_addsy = NULL;
3789                   fixP->fx_done = 1;
3790                 }
3791             }
3792           else
3793             {
3794               switch (add_symbol_segment)
3795                 {
3796                 case absolute_section:
3797 #ifdef TC_I960
3798                   /* See comment about reloc_callj() above.  */
3799                   reloc_callj (fixP);
3800 #endif /* TC_I960 */
3801                   add_number += S_GET_VALUE (add_symbolP);
3802                   add_symbolP = NULL;
3803
3804                   if (!TC_FORCE_RELOCATION (fixP))
3805                     {
3806                       fixP->fx_addsy = NULL;
3807                       fixP->fx_done = 1;
3808                     }
3809                   break;
3810                 default:
3811
3812 #if defined(TC_A29K) || (defined(TE_PE) && defined(TC_I386)) || defined(TC_M88K) || defined(TC_OR32)
3813                   /* This really should be handled in the linker, but
3814                      backward compatibility forbids.  */
3815                   add_number += S_GET_VALUE (add_symbolP);
3816 #else
3817                   add_number += S_GET_VALUE (add_symbolP) +
3818                     segment_info[S_GET_SEGMENT (add_symbolP)].scnhdr.s_paddr;
3819 #endif
3820                   break;
3821
3822                 case SEG_UNKNOWN:
3823 #ifdef TC_I960
3824                   if ((int) fixP->fx_bit_fixP == 13)
3825                     {
3826                       /* This is a COBR instruction.  They have only a
3827                          13-bit displacement and are only to be used
3828                          for local branches: flag as error, don't generate
3829                          relocation.  */
3830                       as_bad_where (fixP->fx_file, fixP->fx_line,
3831                                     _("can't use COBR format with external label"));
3832                       fixP->fx_addsy = NULL;
3833                       fixP->fx_done = 1;
3834                       continue;
3835                     }
3836 #endif /* TC_I960 */
3837 #if ((defined (TC_I386) || defined (TE_LYNX) || defined (TE_AUX)) && !defined(TE_PE)) || defined (COFF_COMMON_ADDEND)
3838                   /* 386 COFF uses a peculiar format in which the
3839                      value of a common symbol is stored in the .text
3840                      segment (I've checked this on SVR3.2 and SCO
3841                      3.2.2) Ian Taylor <ian@cygnus.com>.  */
3842                   /* This is also true for 68k COFF on sysv machines
3843                      (Checked on Motorola sysv68 R3V6 and R3V7.1, and also on
3844                      UNIX System V/M68000, Release 1.0 from ATT/Bell Labs)
3845                      Philippe De Muyter <phdm@info.ucl.ac.be>.  */
3846                   if (S_IS_COMMON (add_symbolP))
3847                     add_number += S_GET_VALUE (add_symbolP);
3848 #endif
3849                   break;
3850
3851                 }
3852             }
3853         }
3854
3855       if (pcrel)
3856         {
3857 #if !defined(TC_M88K) && !(defined(TE_PE) && defined(TC_I386)) && !defined(TC_A29K) && !defined(TC_OR32)
3858           /* This adjustment is not correct on the m88k, for which the
3859              linker does all the computation.  */
3860           add_number -= md_pcrel_from (fixP);
3861 #endif
3862           if (add_symbolP == 0)
3863             fixP->fx_addsy = &abs_symbol;
3864 #if defined (TC_I386) || defined (TE_LYNX) || defined (TC_I960) || defined (TC_M68K)
3865           /* On the 386 we must adjust by the segment vaddr as well.
3866              Ian Taylor.
3867
3868              I changed the i960 to work this way as well.  This is
3869              compatible with the current GNU linker behaviour.  I do
3870              not know what other i960 COFF assemblers do.  This is not
3871              a common case: normally, only assembler code will contain
3872              a PC relative reloc, and only branches which do not
3873              originate in the .text section will have a non-zero
3874              address.
3875
3876              I changed the m68k to work this way as well.  This will
3877              break existing PC relative relocs from sections which do
3878              not start at address 0, but it will make ld -r work.
3879              Ian Taylor, 4 Oct 96.  */
3880
3881           add_number -= segP->scnhdr.s_vaddr;
3882 #endif
3883         }
3884
3885       md_apply_fix3 (fixP, (valueT *) & add_number, this_segment_type);
3886
3887       if (!fixP->fx_bit_fixP && ! fixP->fx_no_overflow)
3888         {
3889 #ifndef TC_M88K
3890           /* The m88k uses the offset field of the reloc to get around
3891              this problem.  */
3892           if ((size == 1
3893                && ((add_number & ~0xFF)
3894                    || (fixP->fx_signed && (add_number & 0x80)))
3895                && ((add_number & ~0xFF) != (-1 & ~0xFF)
3896                    || (add_number & 0x80) == 0))
3897               || (size == 2
3898                   && ((add_number & ~0xFFFF)
3899                       || (fixP->fx_signed && (add_number & 0x8000)))
3900                   && ((add_number & ~0xFFFF) != (-1 & ~0xFFFF)
3901                       || (add_number & 0x8000) == 0)))
3902             {
3903               as_bad_where (fixP->fx_file, fixP->fx_line,
3904                             _("Value of %ld too large for field of %d bytes at 0x%lx"),
3905                             (long) add_number, size,
3906                             (unsigned long) (fragP->fr_address + where));
3907             }
3908 #endif
3909 #ifdef WARN_SIGNED_OVERFLOW_WORD
3910           /* Warn if a .word value is too large when treated as a
3911              signed number.  We already know it is not too negative.
3912              This is to catch over-large switches generated by gcc on
3913              the 68k.  */
3914           if (!flag_signed_overflow_ok
3915               && size == 2
3916               && add_number > 0x7fff)
3917             as_bad_where (fixP->fx_file, fixP->fx_line,
3918                           _("Signed .word overflow; switch may be too large; %ld at 0x%lx"),
3919                           (long) add_number,
3920                           (unsigned long) (fragP->fr_address + where));
3921 #endif
3922         }
3923     }
3924 }
3925
3926 /* Fill in the counts in the first entry in a .stab section.  */
3927
3928 static void
3929 adjust_stab_section (bfd *abfd, segT seg)
3930 {
3931   segT stabstrseg = SEG_UNKNOWN;
3932   const char *secname, *name2;
3933   char *name;
3934   char *p = NULL;
3935   int i, strsz = 0, nsyms;
3936   fragS *frag = segment_info[seg].frchainP->frch_root;
3937
3938   /* Look for the associated string table section.  */
3939
3940   secname = segment_info[seg].name;
3941   name = alloca (strlen (secname) + 4);
3942   strcpy (name, secname);
3943   strcat (name, "str");
3944
3945   for (i = SEG_E0; i < SEG_UNKNOWN; i++)
3946     {
3947       name2 = segment_info[i].name;
3948       if (name2 != NULL && strneq (name2, name, 8))
3949         {
3950           stabstrseg = i;
3951           break;
3952         }
3953     }
3954
3955   /* If we found the section, get its size.  */
3956   if (stabstrseg != SEG_UNKNOWN)
3957     strsz = size_section (abfd, stabstrseg);
3958
3959   nsyms = size_section (abfd, seg) / 12 - 1;
3960
3961   /* Look for the first frag of sufficient size for the initial stab
3962      symbol, and collect a pointer to it.  */
3963   while (frag && frag->fr_fix < 12)
3964     frag = frag->fr_next;
3965   assert (frag != 0);
3966   p = frag->fr_literal;
3967   assert (p != 0);
3968
3969   /* Write in the number of stab symbols and the size of the string
3970      table.  */
3971   bfd_h_put_16 (abfd, (bfd_vma) nsyms, (bfd_byte *) p + 6);
3972   bfd_h_put_32 (abfd, (bfd_vma) strsz, (bfd_byte *) p + 8);
3973 }
3974
3975 void
3976 write_object_file (void)
3977 {
3978   int i;
3979   const char *name;
3980   struct frchain *frchain_ptr;
3981   object_headers headers;
3982   unsigned long file_cursor;
3983   bfd *abfd;
3984   unsigned int addr;
3985   abfd = bfd_openw (out_file_name, TARGET_FORMAT);
3986
3987   if (abfd == 0)
3988     {
3989       as_perror (_("FATAL: Can't create %s"), out_file_name);
3990       exit (EXIT_FAILURE);
3991     }
3992   bfd_set_format (abfd, bfd_object);
3993   bfd_set_arch_mach (abfd, BFD_ARCH, machine);
3994
3995   string_byte_count = 4;
3996
3997   /* Run through all the sub-segments and align them up.  Also
3998      close any open frags.  We tack a .fill onto the end of the
3999      frag chain so that any .align's size can be worked by looking
4000      at the next frag.  */
4001   for (frchain_ptr = frchain_root;
4002        frchain_ptr != (struct frchain *) NULL;
4003        frchain_ptr = frchain_ptr->frch_next)
4004     {
4005       int alignment;
4006
4007       subseg_set (frchain_ptr->frch_seg, frchain_ptr->frch_subseg);
4008
4009       alignment = SUB_SEGMENT_ALIGN (now_seg, frchain_ptr);
4010
4011 #ifdef md_do_align
4012       md_do_align (alignment, NULL, 0, 0, alignment_done);
4013 #endif
4014       if (subseg_text_p (now_seg))
4015         frag_align_code (alignment, 0);
4016       else
4017         frag_align (alignment, 0, 0);
4018
4019 #ifdef md_do_align
4020     alignment_done:
4021 #endif
4022
4023       frag_wane (frag_now);
4024       frag_now->fr_fix = 0;
4025       know (frag_now->fr_next == NULL);
4026     }
4027
4028   remove_subsegs ();
4029
4030   for (i = SEG_E0; i < SEG_UNKNOWN; i++)
4031     relax_segment (segment_info[i].frchainP->frch_root, i);
4032
4033   /* Relaxation has completed.  Freeze all syms.  */
4034   finalize_syms = 1;
4035
4036   H_SET_NUMBER_OF_SECTIONS (&headers, 0);
4037
4038   /* Find out how big the sections are, and set the addresses.  */
4039   addr = 0;
4040   for (i = SEG_E0; i < SEG_UNKNOWN; i++)
4041     {
4042       long size;
4043
4044       segment_info[i].scnhdr.s_paddr = addr;
4045       segment_info[i].scnhdr.s_vaddr = addr;
4046
4047       if (segment_info[i].scnhdr.s_name[0])
4048         {
4049           H_SET_NUMBER_OF_SECTIONS (&headers,
4050                                     H_GET_NUMBER_OF_SECTIONS (&headers) + 1);
4051
4052 #ifdef COFF_LONG_SECTION_NAMES
4053           /* Support long section names as found in PE.  This code
4054              must coordinate with that in coff_header_append and
4055              w_strings.  */
4056           {
4057             unsigned int len;
4058
4059             len = strlen (segment_info[i].name);
4060             if (len > SCNNMLEN)
4061               string_byte_count += len + 1;
4062           }
4063 #endif /* COFF_LONG_SECTION_NAMES */
4064         }
4065
4066       size = size_section (abfd, (unsigned int) i);
4067       addr += size;
4068
4069       /* I think the section alignment is only used on the i960; the
4070          i960 needs it, and it should do no harm on other targets.  */
4071 #ifdef ALIGNMENT_IN_S_FLAGS
4072       segment_info[i].scnhdr.s_flags |= (section_alignment[i] & 0xF) << 8;
4073 #else
4074       segment_info[i].scnhdr.s_align = 1 << section_alignment[i];
4075 #endif
4076
4077       if (i == SEG_E0)
4078         H_SET_TEXT_SIZE (&headers, size);
4079       else if (i == SEG_E1)
4080         H_SET_DATA_SIZE (&headers, size);
4081       else if (i == SEG_E2)
4082         H_SET_BSS_SIZE (&headers, size);
4083     }
4084
4085   /* Turn the gas native symbol table shape into a coff symbol table.  */
4086   crawl_symbols (&headers, abfd);
4087
4088   if (string_byte_count == 4)
4089     string_byte_count = 0;
4090
4091   H_SET_STRING_SIZE (&headers, string_byte_count);
4092
4093 #ifdef tc_frob_file
4094   tc_frob_file ();
4095 #endif
4096
4097   for (i = SEG_E0; i < SEG_UNKNOWN; i++)
4098     {
4099       fixup_mdeps (segment_info[i].frchainP->frch_root, &headers, i);
4100       fixup_segment (&segment_info[i], i);
4101     }
4102
4103   /* Look for ".stab" segments and fill in their initial symbols
4104      correctly.  */
4105   for (i = SEG_E0; i < SEG_UNKNOWN; i++)
4106     {
4107       name = segment_info[i].name;
4108
4109       if (name != NULL
4110           && strneq (".stab", name, 5)
4111           && ! strneq (".stabstr", name, 8))
4112         adjust_stab_section (abfd, i);
4113     }
4114
4115   file_cursor = H_GET_TEXT_FILE_OFFSET (&headers);
4116
4117   bfd_seek (abfd, (file_ptr) file_cursor, 0);
4118
4119   /* Plant the data.  */
4120   fill_section (abfd, &headers, &file_cursor);
4121
4122   do_relocs_for (abfd, &headers, &file_cursor);
4123
4124   do_linenos_for (abfd, &headers, &file_cursor);
4125
4126   H_SET_FILE_MAGIC_NUMBER (&headers, COFF_MAGIC);
4127 #ifndef OBJ_COFF_OMIT_TIMESTAMP
4128   H_SET_TIME_STAMP (&headers, (long) time (NULL));
4129 #else
4130   H_SET_TIME_STAMP (&headers, 0);
4131 #endif
4132 #ifdef TC_COFF_SET_MACHINE
4133   TC_COFF_SET_MACHINE (&headers);
4134 #endif
4135
4136 #ifndef COFF_FLAGS
4137 #define COFF_FLAGS 0
4138 #endif
4139
4140 #ifdef KEEP_RELOC_INFO
4141   H_SET_FLAGS (&headers, ((H_GET_LINENO_SIZE (&headers) ? 0 : F_LNNO) |
4142                           COFF_FLAGS | coff_flags));
4143 #else
4144   H_SET_FLAGS (&headers, ((H_GET_LINENO_SIZE (&headers)     ? 0 : F_LNNO)   |
4145                           (H_GET_RELOCATION_SIZE (&headers) ? 0 : F_RELFLG) |
4146                           COFF_FLAGS | coff_flags));
4147 #endif
4148
4149   {
4150     unsigned int symtable_size = H_GET_SYMBOL_TABLE_SIZE (&headers);
4151     char *buffer1 = xmalloc (symtable_size + string_byte_count + 1);
4152
4153     H_SET_SYMBOL_TABLE_POINTER (&headers, bfd_tell (abfd));
4154     w_symbols (abfd, buffer1, symbol_rootP);
4155     if (string_byte_count > 0)
4156       w_strings (buffer1 + symtable_size);
4157     bfd_bwrite (buffer1, (bfd_size_type) symtable_size + string_byte_count,
4158                 abfd);
4159     free (buffer1);
4160   }
4161
4162   coff_header_append (abfd, &headers);
4163
4164   {
4165     extern bfd *stdoutput;
4166     stdoutput = abfd;
4167   }
4168 }
4169
4170 /* Add a new segment.  This is called from subseg_new via the
4171    obj_new_segment macro.  */
4172
4173 segT
4174 obj_coff_add_segment (const char *name)
4175 {
4176   unsigned int i;
4177
4178 #ifndef COFF_LONG_SECTION_NAMES
4179   char buf[SCNNMLEN + 1];
4180
4181   strncpy (buf, name, SCNNMLEN);
4182   buf[SCNNMLEN] = '\0';
4183   name = buf;
4184 #endif
4185
4186   for (i = SEG_E0; i < SEG_LAST && segment_info[i].scnhdr.s_name[0]; i++)
4187     if (streq (name, segment_info[i].name))
4188       return (segT) i;
4189
4190   if (i == SEG_LAST)
4191     {
4192       as_bad (_("Too many new sections; can't add \"%s\""), name);
4193       return now_seg;
4194     }
4195
4196   /* Add a new section.  */
4197   strncpy (segment_info[i].scnhdr.s_name, name,
4198            sizeof (segment_info[i].scnhdr.s_name));
4199   segment_info[i].scnhdr.s_flags = STYP_REG;
4200   segment_info[i].name = xstrdup (name);
4201
4202   return (segT) i;
4203 }
4204
4205 /* Implement the .section pseudo op:
4206         .section name {, "flags"}
4207                   ^         ^
4208                   |         +--- optional flags: 'b' for bss
4209                   |                              'i' for info
4210                   +-- section name               'l' for lib
4211                                                  'n' for noload
4212                                                  'o' for over
4213                                                  'w' for data
4214                                                  'd' (apparently m88k for data)
4215                                                  'x' for text
4216                                                  'r' for read-only data
4217    But if the argument is not a quoted string, treat it as a
4218    subsegment number.  */
4219
4220 void
4221 obj_coff_section (int ignore ATTRIBUTE_UNUSED)
4222 {
4223   /* Strip out the section name.  */
4224   char *section_name, *name;
4225   char c;
4226   unsigned int exp;
4227   long flags;
4228
4229   if (flag_mri)
4230     {
4231       char type;
4232
4233       s_mri_sect (&type);
4234       flags = 0;
4235       if (type == 'C')
4236         flags = STYP_TEXT;
4237       else if (type == 'D')
4238         flags = STYP_DATA;
4239       segment_info[now_seg].scnhdr.s_flags |= flags;
4240
4241       return;
4242     }
4243
4244   section_name = input_line_pointer;
4245   c = get_symbol_end ();
4246
4247   name = xmalloc (input_line_pointer - section_name + 1);
4248   strcpy (name, section_name);
4249
4250   *input_line_pointer = c;
4251
4252   exp = 0;
4253   flags = 0;
4254
4255   SKIP_WHITESPACE ();
4256   if (*input_line_pointer == ',')
4257     {
4258       ++input_line_pointer;
4259       SKIP_WHITESPACE ();
4260
4261       if (*input_line_pointer != '"')
4262         exp = get_absolute_expression ();
4263       else
4264         {
4265           ++input_line_pointer;
4266           while (*input_line_pointer != '"'
4267                  && ! is_end_of_line[(unsigned char) *input_line_pointer])
4268             {
4269               switch (*input_line_pointer)
4270                 {
4271                 case 'b': flags |= STYP_BSS;    break;
4272                 case 'i': flags |= STYP_INFO;   break;
4273                 case 'l': flags |= STYP_LIB;    break;
4274                 case 'n': flags |= STYP_NOLOAD; break;
4275                 case 'o': flags |= STYP_OVER;   break;
4276                 case 'd':
4277                 case 'w': flags |= STYP_DATA;   break;
4278                 case 'x': flags |= STYP_TEXT;   break;
4279                 case 'r': flags |= STYP_LIT;    break;
4280                 default:
4281                   as_warn (_("unknown section attribute '%c'"),
4282                            *input_line_pointer);
4283                   break;
4284                 }
4285               ++input_line_pointer;
4286             }
4287           if (*input_line_pointer == '"')
4288             ++input_line_pointer;
4289         }
4290     }
4291
4292   subseg_new (name, (subsegT) exp);
4293
4294   segment_info[now_seg].scnhdr.s_flags |= flags;
4295
4296   demand_empty_rest_of_line ();
4297 }
4298
4299 static void
4300 obj_coff_text (int ignore ATTRIBUTE_UNUSED)
4301 {
4302   subseg_new (".text", get_absolute_expression ());
4303 }
4304
4305 static void
4306 obj_coff_data (int ignore ATTRIBUTE_UNUSED)
4307 {
4308   if (flag_readonly_data_in_text)
4309     subseg_new (".text", get_absolute_expression () + 1000);
4310   else
4311     subseg_new (".data", get_absolute_expression ());
4312 }
4313
4314 static void
4315 obj_coff_ident (int ignore ATTRIBUTE_UNUSED)
4316 {
4317   segT current_seg = now_seg;           /* Save current seg.  */
4318   subsegT current_subseg = now_subseg;
4319
4320   subseg_new (".comment", 0);           /* .comment seg.  */
4321   stringer (1);                         /* Read string.  */
4322   subseg_set (current_seg, current_subseg);     /* Restore current seg.  */
4323 }
4324
4325 void
4326 c_dot_file_symbol (const char *filename, int appfile ATTRIBUTE_UNUSED)
4327 {
4328   symbolS *symbolP;
4329
4330   symbolP = symbol_new (".file", SEG_DEBUG, 0, & zero_address_frag);
4331
4332   S_SET_STORAGE_CLASS (symbolP, C_FILE);
4333   S_SET_NUMBER_AUXILIARY (symbolP, 1);
4334
4335   if (strlen (filename) > FILNMLEN)
4336     {
4337       /* Filename is too long to fit into an auxent,
4338          we stick it into the string table instead.  We keep
4339          a linked list of the filenames we find so we can emit
4340          them later.  */
4341       struct filename_list *f = xmalloc (sizeof (* f));
4342
4343       f->filename = filename;
4344       f->next = 0;
4345
4346       SA_SET_FILE_FNAME_ZEROS (symbolP, 0);
4347       SA_SET_FILE_FNAME_OFFSET (symbolP, 1);
4348
4349       if (filename_list_tail)
4350         filename_list_tail->next = f;
4351       else
4352         filename_list_head = f;
4353       filename_list_tail = f;
4354     }
4355   else
4356     SA_SET_FILE_FNAME (symbolP, filename);
4357
4358 #ifndef NO_LISTING
4359   {
4360     extern int listing;
4361     if (listing)
4362       listing_source_file (filename);
4363   }
4364 #endif
4365
4366   SF_SET_DEBUG (symbolP);
4367   S_SET_VALUE (symbolP, (valueT) previous_file_symbol);
4368
4369   previous_file_symbol = symbolP;
4370
4371   /* Make sure that the symbol is first on the symbol chain.  */
4372   if (symbol_rootP != symbolP)
4373     {
4374       symbol_remove (symbolP, &symbol_rootP, &symbol_lastP);
4375       symbol_insert (symbolP, symbol_rootP, &symbol_rootP, &symbol_lastP);
4376     }
4377 }
4378
4379 static void
4380 obj_coff_lcomm (int ignore ATTRIBUTE_UNUSED)
4381 {
4382   s_lcomm (0);
4383   return;
4384 }
4385
4386 /* The first entry in a .stab section is special.  */
4387
4388 void
4389 obj_coff_init_stab_section (segT seg)
4390 {
4391   char *file;
4392   char *p;
4393   char *stabstr_name;
4394   unsigned int stroff;
4395
4396   /* Make space for this first symbol.  */
4397   p = frag_more (12);
4398   /* Zero it out.  */
4399   memset (p, 0, 12);
4400   as_where (&file, (unsigned int *) NULL);
4401   stabstr_name = alloca (strlen (segment_info[seg].name) + 4);
4402   strcpy (stabstr_name, segment_info[seg].name);
4403   strcat (stabstr_name, "str");
4404   stroff = get_stab_string_offset (file, stabstr_name);
4405   know (stroff == 1);
4406   md_number_to_chars (p, stroff, 4);
4407 }
4408
4409 #endif /* not BFD_ASSEMBLER */
4410
4411 const pseudo_typeS coff_pseudo_table[] =
4412 {
4413   {"ABORT", s_abort, 0},
4414   {"appline", obj_coff_ln, 1},
4415   /* We accept the .bss directive for backward compatibility with
4416      earlier versions of gas.  */
4417   {"bss", obj_coff_bss, 0},
4418   {"def", obj_coff_def, 0},
4419   {"dim", obj_coff_dim, 0},
4420   {"endef", obj_coff_endef, 0},
4421   {"ident", obj_coff_ident, 0},
4422   {"line", obj_coff_line, 0},
4423   {"ln", obj_coff_ln, 0},
4424   {"scl", obj_coff_scl, 0},
4425   {"sect", obj_coff_section, 0},
4426   {"sect.s", obj_coff_section, 0},
4427   {"section", obj_coff_section, 0},
4428   {"section.s", obj_coff_section, 0},
4429   /* FIXME: We ignore the MRI short attribute.  */
4430   {"size", obj_coff_size, 0},
4431   {"tag", obj_coff_tag, 0},
4432   {"type", obj_coff_type, 0},
4433   {"val", obj_coff_val, 0},
4434   {"version", s_ignore, 0},
4435 #ifdef BFD_ASSEMBLER
4436   {"loc", obj_coff_loc, 0},
4437   {"optim", s_ignore, 0},       /* For sun386i cc (?) */
4438   {"weak", obj_coff_weak, 0},
4439 #else
4440   {"data", obj_coff_data, 0},
4441   {"lcomm", obj_coff_lcomm, 0},
4442   {"text", obj_coff_text, 0},
4443   {"use", obj_coff_section, 0},
4444 #endif
4445 #if defined TC_M88K || defined TC_TIC4X
4446   /* The m88k and tic4x uses sdef instead of def.  */
4447   {"sdef", obj_coff_def, 0},
4448 #endif
4449   {NULL, NULL, 0}
4450 };
4451 \f
4452 #ifdef BFD_ASSEMBLER
4453
4454 /* Support for a COFF emulation.  */
4455
4456 static void
4457 coff_pop_insert (void)
4458 {
4459   pop_insert (coff_pseudo_table);
4460 }
4461
4462 static int
4463 coff_separate_stab_sections (void)
4464 {
4465   return 1;
4466 }
4467
4468 const struct format_ops coff_format_ops =
4469 {
4470   bfd_target_coff_flavour,
4471   0,    /* dfl_leading_underscore */
4472   1,    /* emit_section_symbols */
4473   0,    /* begin */
4474   c_dot_file_symbol,
4475   coff_frob_symbol,
4476   0,    /* frob_file */
4477   0,    /* frob_file_before_adjust */
4478   0,    /* frob_file_before_fix */
4479   coff_frob_file_after_relocs,
4480   0,    /* s_get_size */
4481   0,    /* s_set_size */
4482   0,    /* s_get_align */
4483   0,    /* s_set_align */
4484   0,    /* s_get_other */
4485   0,    /* s_set_other */
4486   0,    /* s_get_desc */
4487   0,    /* s_set_desc */
4488   0,    /* s_get_type */
4489   0,    /* s_set_type */
4490   0,    /* copy_symbol_attributes */
4491   0,    /* generate_asm_lineno */
4492   0,    /* process_stab */
4493   coff_separate_stab_sections,
4494   obj_coff_init_stab_section,
4495   0,    /* sec_sym_ok_for_reloc */
4496   coff_pop_insert,
4497   0,    /* ecoff_set_ext */
4498   coff_obj_read_begin_hook,
4499   coff_obj_symbol_new_hook
4500 };
4501
4502 #endif