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