Convert to ISO C90 formatting
[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 out of scope"));
1305               SA_SET_SYM_FSIZE (coff_last_function,
1306                                 (long) (S_GET_VALUE (symp)
1307                                         - S_GET_VALUE (coff_last_function)));
1308               next_set_end = coff_last_function;
1309               coff_last_function = 0;
1310             }
1311         }
1312
1313       if (S_IS_EXTERNAL (symp))
1314         S_SET_STORAGE_CLASS (symp, C_EXT);
1315       else if (SF_GET_LOCAL (symp))
1316         *punt = 1;
1317
1318       if (SF_GET_FUNCTION (symp))
1319         symbol_get_bfdsym (symp)->flags |= BSF_FUNCTION;
1320     }
1321
1322   /* Double check weak symbols.  */
1323   if (S_IS_WEAK (symp) && S_IS_COMMON (symp))
1324     as_bad (_("Symbol `%s' can not be both weak and common"),
1325             S_GET_NAME (symp));
1326
1327   if (SF_GET_TAG (symp))
1328     last_tagP = symp;
1329   else if (S_GET_STORAGE_CLASS (symp) == C_EOS)
1330     next_set_end = last_tagP;
1331
1332 #ifdef OBJ_XCOFF
1333   /* This is pretty horrible, but we have to set *punt correctly in
1334      order to call SA_SET_SYM_ENDNDX correctly.  */
1335   if (! symbol_used_in_reloc_p (symp)
1336       && ((symbol_get_bfdsym (symp)->flags & BSF_SECTION_SYM) != 0
1337           || (! (S_IS_EXTERNAL (symp) || S_IS_WEAK (symp))
1338               && ! symbol_get_tc (symp)->output
1339               && S_GET_STORAGE_CLASS (symp) != C_FILE)))
1340     *punt = 1;
1341 #endif
1342
1343   if (set_end != (symbolS *) NULL
1344       && ! *punt
1345       && ((symbol_get_bfdsym (symp)->flags & BSF_NOT_AT_END) != 0
1346           || (S_IS_DEFINED (symp)
1347               && ! S_IS_COMMON (symp)
1348               && (! S_IS_EXTERNAL (symp) || SF_GET_FUNCTION (symp)))))
1349     {
1350       SA_SET_SYM_ENDNDX (set_end, symp);
1351       set_end = NULL;
1352     }
1353
1354   if (next_set_end != NULL)
1355     {
1356       if (set_end != NULL)
1357         as_warn ("Warning: internal error: forgetting to set endndx of %s",
1358                  S_GET_NAME (set_end));
1359       set_end = next_set_end;
1360     }
1361
1362 #ifndef OBJ_XCOFF
1363   if (! *punt
1364       && S_GET_STORAGE_CLASS (symp) == C_FCN
1365       && streq (S_GET_NAME (symp), ".bf"))
1366     {
1367       if (coff_last_bf != NULL)
1368         SA_SET_SYM_ENDNDX (coff_last_bf, symp);
1369       coff_last_bf = symp;
1370     }
1371 #endif
1372   if (coffsymbol (symbol_get_bfdsym (symp))->lineno)
1373     {
1374       int i;
1375       struct line_no *lptr;
1376       alent *l;
1377
1378       lptr = (struct line_no *) coffsymbol (symbol_get_bfdsym (symp))->lineno;
1379       for (i = 0; lptr; lptr = lptr->next)
1380         i++;
1381       lptr = (struct line_no *) coffsymbol (symbol_get_bfdsym (symp))->lineno;
1382
1383       /* We need i entries for line numbers, plus 1 for the first
1384          entry which BFD will override, plus 1 for the last zero
1385          entry (a marker for BFD).  */
1386       l = xmalloc ((i + 2) * sizeof (* l));
1387       coffsymbol (symbol_get_bfdsym (symp))->lineno = l;
1388       l[i + 1].line_number = 0;
1389       l[i + 1].u.sym = NULL;
1390       for (; i > 0; i--)
1391         {
1392           if (lptr->frag)
1393             lptr->l.u.offset += lptr->frag->fr_address / OCTETS_PER_BYTE;
1394           l[i] = lptr->l;
1395           lptr = lptr->next;
1396         }
1397     }
1398 }
1399
1400 void
1401 coff_adjust_section_syms (bfd *abfd ATTRIBUTE_UNUSED,
1402                           asection *sec,
1403                           void * x ATTRIBUTE_UNUSED)
1404 {
1405   symbolS *secsym;
1406   segment_info_type *seginfo = seg_info (sec);
1407   int nlnno, nrelocs = 0;
1408
1409   /* RS/6000 gas creates a .debug section manually in ppc_frob_file in
1410      tc-ppc.c.  Do not get confused by it.  */
1411   if (seginfo == NULL)
1412     return;
1413
1414   if (streq (sec->name, ".text"))
1415     nlnno = coff_n_line_nos;
1416   else
1417     nlnno = 0;
1418   {
1419     /* @@ Hope that none of the fixups expand to more than one reloc
1420        entry...  */
1421     fixS *fixp = seginfo->fix_root;
1422     while (fixp)
1423       {
1424         if (! fixp->fx_done)
1425           nrelocs++;
1426         fixp = fixp->fx_next;
1427       }
1428   }
1429   if (bfd_get_section_size (sec) == 0
1430       && nrelocs == 0
1431       && nlnno == 0
1432       && sec != text_section
1433       && sec != data_section
1434       && sec != bss_section)
1435     return;
1436
1437   secsym = section_symbol (sec);
1438   /* This is an estimate; we'll plug in the real value using
1439      SET_SECTION_RELOCS later */
1440   SA_SET_SCN_NRELOC (secsym, nrelocs);
1441   SA_SET_SCN_NLINNO (secsym, nlnno);
1442 }
1443
1444 void
1445 coff_frob_file_after_relocs (void)
1446 {
1447   bfd_map_over_sections (stdoutput, coff_adjust_section_syms, NULL);
1448 }
1449
1450 /* Implement the .section pseudo op:
1451         .section name {, "flags"}
1452                   ^         ^
1453                   |         +--- optional flags: 'b' for bss
1454                   |                              'i' for info
1455                   +-- section name               'l' for lib
1456                                                  'n' for noload
1457                                                  'o' for over
1458                                                  'w' for data
1459                                                  'd' (apparently m88k for data)
1460                                                  'x' for text
1461                                                  'r' for read-only data
1462                                                  's' for shared data (PE)
1463    But if the argument is not a quoted string, treat it as a
1464    subsegment number.
1465
1466    Note the 'a' flag is silently ignored.  This allows the same
1467    .section directive to be parsed in both ELF and COFF formats.  */
1468
1469 void
1470 obj_coff_section (int ignore ATTRIBUTE_UNUSED)
1471 {
1472   /* Strip out the section name.  */
1473   char *section_name;
1474   char c;
1475   char *name;
1476   unsigned int exp;
1477   flagword flags, oldflags;
1478   asection *sec;
1479
1480   if (flag_mri)
1481     {
1482       char type;
1483
1484       s_mri_sect (&type);
1485       return;
1486     }
1487
1488   section_name = input_line_pointer;
1489   c = get_symbol_end ();
1490
1491   name = xmalloc (input_line_pointer - section_name + 1);
1492   strcpy (name, section_name);
1493
1494   *input_line_pointer = c;
1495
1496   SKIP_WHITESPACE ();
1497
1498   exp = 0;
1499   flags = SEC_NO_FLAGS;
1500
1501   if (*input_line_pointer == ',')
1502     {
1503       ++input_line_pointer;
1504       SKIP_WHITESPACE ();
1505       if (*input_line_pointer != '"')
1506         exp = get_absolute_expression ();
1507       else
1508         {
1509           ++input_line_pointer;
1510           while (*input_line_pointer != '"'
1511                  && ! is_end_of_line[(unsigned char) *input_line_pointer])
1512             {
1513               switch (*input_line_pointer)
1514                 {
1515                 case 'b': flags |= SEC_ALLOC; flags &=~ SEC_LOAD; break;
1516                 case 'n': flags &=~ SEC_LOAD; flags |= SEC_NEVER_LOAD; break;
1517
1518                 case 's': flags |= SEC_COFF_SHARED; /* Fall through.  */
1519                 case 'd': flags |= SEC_DATA | SEC_LOAD; /* Fall through.  */
1520                 case 'w': flags &=~ SEC_READONLY; break;
1521
1522                 case 'a': break; /* For compatibility with ELF.  */
1523                 case 'x': flags |= SEC_CODE | SEC_LOAD; break;
1524                 case 'r': flags |= SEC_DATA | SEC_LOAD | SEC_READONLY; break;
1525
1526                 case 'i': /* STYP_INFO */
1527                 case 'l': /* STYP_LIB */
1528                 case 'o': /* STYP_OVER */
1529                   as_warn (_("unsupported section attribute '%c'"),
1530                            *input_line_pointer);
1531                   break;
1532
1533                 default:
1534                   as_warn (_("unknown section attribute '%c'"),
1535                            *input_line_pointer);
1536                   break;
1537                 }
1538               ++input_line_pointer;
1539             }
1540           if (*input_line_pointer == '"')
1541             ++input_line_pointer;
1542         }
1543     }
1544
1545   sec = subseg_new (name, (subsegT) exp);
1546
1547   oldflags = bfd_get_section_flags (stdoutput, sec);
1548   if (oldflags == SEC_NO_FLAGS)
1549     {
1550       /* Set section flags for a new section just created by subseg_new.
1551          Provide a default if no flags were parsed.  */
1552       if (flags == SEC_NO_FLAGS)
1553         flags = TC_COFF_SECTION_DEFAULT_ATTRIBUTES;
1554
1555 #ifdef COFF_LONG_SECTION_NAMES
1556       /* Add SEC_LINK_ONCE and SEC_LINK_DUPLICATES_DISCARD to .gnu.linkonce
1557          sections so adjust_reloc_syms in write.c will correctly handle
1558          relocs which refer to non-local symbols in these sections.  */
1559       if (strneq (name, ".gnu.linkonce", sizeof (".gnu.linkonce") - 1))
1560         flags |= SEC_LINK_ONCE | SEC_LINK_DUPLICATES_DISCARD;
1561 #endif
1562
1563       if (! bfd_set_section_flags (stdoutput, sec, flags))
1564         as_warn (_("error setting flags for \"%s\": %s"),
1565                  bfd_section_name (stdoutput, sec),
1566                  bfd_errmsg (bfd_get_error ()));
1567     }
1568   else if (flags != SEC_NO_FLAGS)
1569     {
1570       /* This section's attributes have already been set.  Warn if the
1571          attributes don't match.  */
1572       flagword matchflags = (SEC_ALLOC | SEC_LOAD | SEC_READONLY | SEC_CODE
1573                              | SEC_DATA | SEC_COFF_SHARED | SEC_NEVER_LOAD);
1574       if ((flags ^ oldflags) & matchflags)
1575         as_warn (_("Ignoring changed section attributes for %s"), name);
1576     }
1577
1578   demand_empty_rest_of_line ();
1579 }
1580
1581 void
1582 coff_adjust_symtab (void)
1583 {
1584   if (symbol_rootP == NULL
1585       || S_GET_STORAGE_CLASS (symbol_rootP) != C_FILE)
1586     c_dot_file_symbol ("fake", 0);
1587 }
1588
1589 void
1590 coff_frob_section (segT sec)
1591 {
1592   segT strsec;
1593   char *p;
1594   fragS *fragp;
1595   bfd_vma size, n_entries, mask;
1596   bfd_vma align_power = (bfd_vma)sec->alignment_power + OCTETS_PER_BYTE_POWER;
1597
1598   /* The COFF back end in BFD requires that all section sizes be
1599      rounded up to multiples of the corresponding section alignments,
1600      supposedly because standard COFF has no other way of encoding alignment
1601      for sections.  If your COFF flavor has a different way of encoding
1602      section alignment, then skip this step, as TICOFF does.  */
1603   size = bfd_get_section_size (sec);
1604   mask = ((bfd_vma) 1 << align_power) - 1;
1605 #if !defined(TICOFF)
1606   if (size & mask)
1607     {
1608       bfd_vma new_size;
1609       fragS *last;
1610
1611       new_size = (size + mask) & ~mask;
1612       bfd_set_section_size (stdoutput, sec, new_size);
1613
1614       /* If the size had to be rounded up, add some padding in
1615          the last non-empty frag.  */
1616       fragp = seg_info (sec)->frchainP->frch_root;
1617       last = seg_info (sec)->frchainP->frch_last;
1618       while (fragp->fr_next != last)
1619         fragp = fragp->fr_next;
1620       last->fr_address = size;
1621       fragp->fr_offset += new_size - size;
1622     }
1623 #endif
1624
1625   /* If the section size is non-zero, the section symbol needs an aux
1626      entry associated with it, indicating the size.  We don't know
1627      all the values yet; coff_frob_symbol will fill them in later.  */
1628 #ifndef TICOFF
1629   if (size != 0
1630       || sec == text_section
1631       || sec == data_section
1632       || sec == bss_section)
1633 #endif
1634     {
1635       symbolS *secsym = section_symbol (sec);
1636
1637       S_SET_STORAGE_CLASS (secsym, C_STAT);
1638       S_SET_NUMBER_AUXILIARY (secsym, 1);
1639       SF_SET_STATICS (secsym);
1640       SA_SET_SCN_SCNLEN (secsym, size);
1641     }
1642
1643   /* FIXME: These should be in a "stabs.h" file, or maybe as.h.  */
1644 #ifndef STAB_SECTION_NAME
1645 #define STAB_SECTION_NAME ".stab"
1646 #endif
1647 #ifndef STAB_STRING_SECTION_NAME
1648 #define STAB_STRING_SECTION_NAME ".stabstr"
1649 #endif
1650   if (! streq (STAB_STRING_SECTION_NAME, sec->name))
1651     return;
1652
1653   strsec = sec;
1654   sec = subseg_get (STAB_SECTION_NAME, 0);
1655   /* size is already rounded up, since other section will be listed first */
1656   size = bfd_get_section_size (strsec);
1657
1658   n_entries = bfd_get_section_size (sec) / 12 - 1;
1659
1660   /* Find first non-empty frag.  It should be large enough.  */
1661   fragp = seg_info (sec)->frchainP->frch_root;
1662   while (fragp && fragp->fr_fix == 0)
1663     fragp = fragp->fr_next;
1664   assert (fragp != 0 && fragp->fr_fix >= 12);
1665
1666   /* Store the values.  */
1667   p = fragp->fr_literal;
1668   bfd_h_put_16 (stdoutput, n_entries, (bfd_byte *) p + 6);
1669   bfd_h_put_32 (stdoutput, size, (bfd_byte *) p + 8);
1670 }
1671
1672 void
1673 obj_coff_init_stab_section (segT seg)
1674 {
1675   char *file;
1676   char *p;
1677   char *stabstr_name;
1678   unsigned int stroff;
1679
1680   /* Make space for this first symbol.  */
1681   p = frag_more (12);
1682   /* Zero it out.  */
1683   memset (p, 0, 12);
1684   as_where (&file, (unsigned int *) NULL);
1685   stabstr_name = xmalloc (strlen (seg->name) + 4);
1686   strcpy (stabstr_name, seg->name);
1687   strcat (stabstr_name, "str");
1688   stroff = get_stab_string_offset (file, stabstr_name);
1689   know (stroff == 1);
1690   md_number_to_chars (p, stroff, 4);
1691 }
1692
1693 #ifdef DEBUG
1694 const char *
1695 s_get_name (symbolS *s)
1696 {
1697   return ((s == NULL) ? "(NULL)" : S_GET_NAME (s));
1698 }
1699
1700 void
1701 symbol_dump (void)
1702 {
1703   symbolS *symbolP;
1704
1705   for (symbolP = symbol_rootP; symbolP; symbolP = symbol_next (symbolP))
1706     printf (_("0x%lx: \"%s\" type = %ld, class = %d, segment = %d\n"),
1707             (unsigned long) symbolP,
1708             S_GET_NAME (symbolP),
1709             (long) S_GET_DATA_TYPE (symbolP),
1710             S_GET_STORAGE_CLASS (symbolP),
1711             (int) S_GET_SEGMENT (symbolP));
1712 }
1713
1714 #endif /* DEBUG */
1715
1716 #else /* not BFD_ASSEMBLER */
1717
1718 #include "frags.h"
1719 /* This is needed because we include internal bfd things.  */
1720 #include <time.h>
1721
1722 #include "libbfd.h"
1723 #include "libcoff.h"
1724
1725 /* The NOP_OPCODE is for the alignment fill value.  Fill with nop so
1726    that we can stick sections together without causing trouble.  */
1727 #ifndef NOP_OPCODE
1728 #define NOP_OPCODE 0x00
1729 #endif
1730
1731 /* The zeroes if symbol name is longer than 8 chars */
1732 #define S_SET_ZEROES(s,v)               ((s)->sy_symbol.ost_entry.n_zeroes = (v))
1733
1734 #define MIN(a,b) ((a) < (b)? (a) : (b))
1735
1736 /* This vector is used to turn a gas internal segment number into a
1737    section number suitable for insertion into a coff symbol table.
1738    This must correspond to seg_info_off_by_4.  */
1739
1740 const short seg_N_TYPE[] =
1741 {                               /* in: segT   out: N_TYPE bits */
1742   C_ABS_SECTION,
1743   1,    2,  3,   4,    5,   6,   7,   8,   9,  10,
1744   11,  12,  13,  14,  15,  16,  17,  18,  19,  20,
1745   21,  22,  23,  24,  25,  26,  27,  28,  29,  30,
1746   31,  32,  33,  34,  35,  36,  37,  38,  39,  40,
1747   C_UNDEF_SECTION,              /* SEG_UNKNOWN */
1748   C_UNDEF_SECTION,              /* SEG_GOOF */
1749   C_UNDEF_SECTION,              /* SEG_EXPR */
1750   C_DEBUG_SECTION,              /* SEG_DEBUG */
1751   C_NTV_SECTION,                /* SEG_NTV */
1752   C_PTV_SECTION,                /* SEG_PTV */
1753   C_REGISTER_SECTION,           /* SEG_REGISTER */
1754 };
1755
1756 int function_lineoff = -1;      /* Offset in line#s where the last function
1757                                    started (the odd entry for line #0) */
1758
1759 /* Structure used to keep the filenames which
1760    are too long around so that we can stick them
1761    into the string table.  */
1762 struct filename_list
1763 {
1764   const char *filename;
1765   struct filename_list *next;
1766 };
1767
1768 static struct filename_list *filename_list_head;
1769 static struct filename_list *filename_list_tail;
1770
1771 static symbolS *last_line_symbol;
1772
1773 /* Add 4 to the real value to get the index and compensate the
1774    negatives. This vector is used by S_GET_SEGMENT to turn a coff
1775    section number into a segment number.  */
1776
1777 bfd *abfd;
1778 static symbolS *previous_file_symbol;
1779 static int line_base;
1780
1781 /* When not using BFD_ASSEMBLER, we permit up to 40 sections.
1782
1783    This array maps a COFF section number into a gas section number.
1784    Because COFF uses negative section numbers, you must add 4 to the
1785    COFF section number when indexing into this array; this is done via
1786    the SEG_INFO_FROM_SECTION_NUMBER macro.  This must correspond to
1787    seg_N_TYPE.  */
1788
1789 static const segT seg_info_off_by_4[] =
1790 {
1791  SEG_PTV,
1792  SEG_NTV,
1793  SEG_DEBUG,
1794  SEG_ABSOLUTE,
1795  SEG_UNKNOWN,
1796  SEG_E0,  SEG_E1,  SEG_E2,  SEG_E3,  SEG_E4,
1797  SEG_E5,  SEG_E6,  SEG_E7,  SEG_E8,  SEG_E9,
1798  SEG_E10, SEG_E11, SEG_E12, SEG_E13, SEG_E14,
1799  SEG_E15, SEG_E16, SEG_E17, SEG_E18, SEG_E19,
1800  SEG_E20, SEG_E21, SEG_E22, SEG_E23, SEG_E24,
1801  SEG_E25, SEG_E26, SEG_E27, SEG_E28, SEG_E29,
1802  SEG_E30, SEG_E31, SEG_E32, SEG_E33, SEG_E34,
1803  SEG_E35, SEG_E36, SEG_E37, SEG_E38, SEG_E39,
1804  (segT) 40,
1805  (segT) 41,
1806  (segT) 42,
1807  (segT) 43,
1808  (segT) 44,
1809  (segT) 45,
1810  (segT) 0,
1811  (segT) 0,
1812  (segT) 0,
1813  SEG_REGISTER
1814 };
1815
1816 #define SEG_INFO_FROM_SECTION_NUMBER(x) (seg_info_off_by_4[(x)+4])
1817
1818 static relax_addressT
1819 relax_align (relax_addressT address, long alignment)
1820 {
1821   relax_addressT mask;
1822   relax_addressT new_address;
1823
1824   mask = ~((~0) << alignment);
1825   new_address = (address + mask) & (~mask);
1826
1827   return new_address - address;
1828 }
1829
1830 segT
1831 s_get_segment (symbolS * x)
1832 {
1833   return SEG_INFO_FROM_SECTION_NUMBER (x->sy_symbol.ost_entry.n_scnum);
1834 }
1835
1836 /* Calculate the size of the frag chain and fill in the section header
1837    to contain all of it, also fill in the addr of the sections.  */
1838
1839 static unsigned int
1840 size_section (bfd *abfd ATTRIBUTE_UNUSED, unsigned int idx)
1841 {
1842   unsigned int size = 0;
1843   fragS *frag = segment_info[idx].frchainP->frch_root;
1844
1845   while (frag)
1846     {
1847       size = frag->fr_address;
1848       if (frag->fr_address != size)
1849         {
1850           fprintf (stderr, _("Out of step\n"));
1851           size = frag->fr_address;
1852         }
1853
1854       switch (frag->fr_type)
1855         {
1856 #ifdef TC_COFF_SIZEMACHDEP
1857         case rs_machine_dependent:
1858           size += TC_COFF_SIZEMACHDEP (frag);
1859           break;
1860 #endif
1861         case rs_space:
1862         case rs_fill:
1863         case rs_org:
1864           size += frag->fr_fix;
1865           size += frag->fr_offset * frag->fr_var;
1866           break;
1867         case rs_align:
1868         case rs_align_code:
1869         case rs_align_test:
1870           {
1871             addressT off;
1872
1873             size += frag->fr_fix;
1874             off = relax_align (size, frag->fr_offset);
1875             if (frag->fr_subtype != 0 && off > frag->fr_subtype)
1876               off = 0;
1877             size += off;
1878           }
1879           break;
1880         default:
1881           BAD_CASE (frag->fr_type);
1882           break;
1883         }
1884       frag = frag->fr_next;
1885     }
1886   segment_info[idx].scnhdr.s_size = size;
1887   return size;
1888 }
1889
1890 static unsigned int
1891 count_entries_in_chain (unsigned int idx)
1892 {
1893   unsigned int nrelocs;
1894   fixS *fixup_ptr;
1895
1896   /* Count the relocations.  */
1897   fixup_ptr = segment_info[idx].fix_root;
1898   nrelocs = 0;
1899   while (fixup_ptr != (fixS *) NULL)
1900     {
1901       if (fixup_ptr->fx_done == 0 && TC_COUNT_RELOC (fixup_ptr))
1902         {
1903 #if defined(TC_A29K) || defined(TC_OR32)
1904           if (fixup_ptr->fx_r_type == RELOC_CONSTH)
1905             nrelocs += 2;
1906           else
1907             nrelocs++;
1908 #else
1909           nrelocs++;
1910 #endif
1911         }
1912
1913       fixup_ptr = fixup_ptr->fx_next;
1914     }
1915   return nrelocs;
1916 }
1917
1918 #ifdef TE_AUX
1919
1920 /* AUX's ld expects relocations to be sorted.  */
1921
1922 static int
1923 compare_external_relocs (const void * x, const void * y)
1924 {
1925   struct external_reloc *a = (struct external_reloc *) x;
1926   struct external_reloc *b = (struct external_reloc *) y;
1927   bfd_vma aadr = bfd_getb32 (a->r_vaddr);
1928   bfd_vma badr = bfd_getb32 (b->r_vaddr);
1929
1930   return (aadr < badr ? -1 : badr < aadr ? 1 : 0);
1931 }
1932
1933 #endif
1934
1935 /* Output all the relocations for a section.  */
1936
1937 static void
1938 do_relocs_for (bfd * abfd, object_headers * h, unsigned long *file_cursor)
1939 {
1940   unsigned int nrelocs;
1941   unsigned int idx;
1942   unsigned long reloc_start = *file_cursor;
1943
1944   for (idx = SEG_E0; idx < SEG_LAST; idx++)
1945     {
1946       if (segment_info[idx].scnhdr.s_name[0])
1947         {
1948           struct external_reloc *ext_ptr;
1949           struct external_reloc *external_reloc_vec;
1950           unsigned int external_reloc_size;
1951           unsigned int base = segment_info[idx].scnhdr.s_paddr;
1952           fixS *fix_ptr = segment_info[idx].fix_root;
1953
1954           nrelocs = count_entries_in_chain (idx);
1955
1956           if (nrelocs)
1957             /* Bypass this stuff if no relocs.  This also incidentally
1958                avoids a SCO bug, where free(malloc(0)) tends to crash.  */
1959             {
1960               external_reloc_size = nrelocs * RELSZ;
1961               external_reloc_vec = malloc (external_reloc_size);
1962
1963               ext_ptr = external_reloc_vec;
1964
1965               /* Fill in the internal coff style reloc struct from the
1966                  internal fix list.  */
1967               while (fix_ptr)
1968                 {
1969                   struct internal_reloc intr;
1970
1971                   /* Only output some of the relocations.  */
1972                   if (fix_ptr->fx_done == 0 && TC_COUNT_RELOC (fix_ptr))
1973                     {
1974 #ifdef TC_RELOC_MANGLE
1975                       TC_RELOC_MANGLE (&segment_info[idx], fix_ptr, &intr,
1976                                        base);
1977 #else
1978                       symbolS *dot;
1979                       symbolS *symbol_ptr = fix_ptr->fx_addsy;
1980
1981                       intr.r_type = TC_COFF_FIX2RTYPE (fix_ptr);
1982                       intr.r_vaddr =
1983                         base + fix_ptr->fx_frag->fr_address + fix_ptr->fx_where;
1984
1985 #ifdef TC_KEEP_FX_OFFSET
1986                       intr.r_offset = fix_ptr->fx_offset;
1987 #else
1988                       intr.r_offset = 0;
1989 #endif
1990
1991                       while (symbol_ptr->sy_value.X_op == O_symbol
1992                              && (! S_IS_DEFINED (symbol_ptr)
1993                                  || S_IS_COMMON (symbol_ptr)))
1994                         {
1995                           symbolS *n;
1996
1997                           /* We must avoid looping, as that can occur
1998                              with a badly written program.  */
1999                           n = symbol_ptr->sy_value.X_add_symbol;
2000                           if (n == symbol_ptr)
2001                             break;
2002                           symbol_ptr = n;
2003                         }
2004
2005                       /* Turn the segment of the symbol into an offset.  */
2006                       if (symbol_ptr)
2007                         {
2008                           resolve_symbol_value (symbol_ptr);
2009                           if (! symbol_ptr->sy_resolved)
2010                             {
2011                               char *file;
2012                               unsigned int line;
2013
2014                               if (expr_symbol_where (symbol_ptr, &file, &line))
2015                                 as_bad_where (file, line,
2016                                               _("unresolved relocation"));
2017                               else
2018                                 as_bad (_("bad relocation: symbol `%s' not in symbol table"),
2019                                         S_GET_NAME (symbol_ptr));
2020                             }
2021
2022                           dot = segment_info[S_GET_SEGMENT (symbol_ptr)].dot;
2023                           if (dot)
2024                             intr.r_symndx = dot->sy_number;
2025                           else
2026                             intr.r_symndx = symbol_ptr->sy_number;
2027                         }
2028                       else
2029                         intr.r_symndx = -1;
2030 #endif
2031                       (void) bfd_coff_swap_reloc_out (abfd, &intr, ext_ptr);
2032                       ext_ptr++;
2033 #if defined(TC_A29K)
2034                       /* The 29k has a special kludge for the high 16 bit
2035                          reloc.  Two relocations are emitted, R_IHIHALF,
2036                          and R_IHCONST. The second one doesn't contain a
2037                          symbol, but uses the value for offset.  */
2038                       if (intr.r_type == R_IHIHALF)
2039                         {
2040                           /* Now emit the second bit.  */
2041                           intr.r_type = R_IHCONST;
2042                           intr.r_symndx = fix_ptr->fx_addnumber;
2043                           (void) bfd_coff_swap_reloc_out (abfd, &intr, ext_ptr);
2044                           ext_ptr++;
2045                         }
2046 #endif
2047 #if defined(TC_OR32)
2048                       /* The or32 has a special kludge for the high 16 bit
2049                          reloc.  Two relocations are emitted, R_IHIHALF,
2050                          and R_IHCONST. The second one doesn't contain a
2051                          symbol, but uses the value for offset.  */
2052                       if (intr.r_type == R_IHIHALF)
2053                         {
2054                           /* Now emit the second bit.  */
2055                           intr.r_type = R_IHCONST;
2056                           intr.r_symndx = fix_ptr->fx_addnumber;
2057                           (void) bfd_coff_swap_reloc_out (abfd, & intr, ext_ptr);
2058                           ext_ptr ++;
2059                         }
2060 #endif
2061                     }
2062
2063                   fix_ptr = fix_ptr->fx_next;
2064                 }
2065 #ifdef TE_AUX
2066               /* Sort the reloc table.  */
2067               qsort ((void *) external_reloc_vec, nrelocs,
2068                      sizeof (struct external_reloc), compare_external_relocs);
2069 #endif
2070               /* Write out the reloc table.  */
2071               bfd_bwrite ((void *) external_reloc_vec,
2072                           (bfd_size_type) external_reloc_size, abfd);
2073               free (external_reloc_vec);
2074
2075               /* Fill in section header info.  */
2076               segment_info[idx].scnhdr.s_relptr = *file_cursor;
2077               *file_cursor += external_reloc_size;
2078               segment_info[idx].scnhdr.s_nreloc = nrelocs;
2079             }
2080           else
2081             {
2082               /* No relocs.  */
2083               segment_info[idx].scnhdr.s_relptr = 0;
2084             }
2085         }
2086     }
2087
2088   /* Set relocation_size field in file headers.  */
2089   H_SET_RELOCATION_SIZE (h, *file_cursor - reloc_start, 0);
2090 }
2091
2092 /* Run through a frag chain and write out the data to go with it, fill
2093    in the scnhdrs with the info on the file positions.  */
2094
2095 static void
2096 fill_section (bfd * abfd,
2097               object_headers *h ATTRIBUTE_UNUSED,
2098               unsigned long *file_cursor)
2099 {
2100   unsigned int i;
2101   unsigned int paddr = 0;
2102
2103   for (i = SEG_E0; i < SEG_UNKNOWN; i++)
2104     {
2105       unsigned int offset = 0;
2106       struct internal_scnhdr *s = &(segment_info[i].scnhdr);
2107
2108       PROGRESS (1);
2109
2110       if (s->s_name[0])
2111         {
2112           fragS *frag = segment_info[i].frchainP->frch_root;
2113           char *buffer = NULL;
2114
2115           if (s->s_size == 0)
2116             s->s_scnptr = 0;
2117           else
2118             {
2119               buffer = xmalloc (s->s_size);
2120               s->s_scnptr = *file_cursor;
2121             }
2122           know (s->s_paddr == paddr);
2123
2124           if (streq (s->s_name, ".text"))
2125             s->s_flags |= STYP_TEXT;
2126           else if (streq (s->s_name, ".data"))
2127             s->s_flags |= STYP_DATA;
2128           else if (streq (s->s_name, ".bss"))
2129             {
2130               s->s_scnptr = 0;
2131               s->s_flags |= STYP_BSS;
2132
2133               /* @@ Should make the i386 and a29k coff targets define
2134                  COFF_NOLOAD_PROBLEM, and have only one test here.  */
2135 #ifndef TC_I386
2136 #ifndef TC_A29K
2137 #ifndef TC_OR32
2138 #ifndef COFF_NOLOAD_PROBLEM
2139               /* Apparently the SVR3 linker (and exec syscall) and UDI
2140                  mondfe progrem are confused by noload sections.  */
2141               s->s_flags |= STYP_NOLOAD;
2142 #endif
2143 #endif
2144 #endif
2145 #endif
2146             }
2147           else if (streq (s->s_name, ".lit"))
2148             s->s_flags = STYP_LIT | STYP_TEXT;
2149           else if (streq (s->s_name, ".init"))
2150             s->s_flags |= STYP_TEXT;
2151           else if (streq (s->s_name, ".fini"))
2152             s->s_flags |= STYP_TEXT;
2153           else if (strneq (s->s_name, ".comment", 8))
2154             s->s_flags |= STYP_INFO;
2155
2156           while (frag)
2157             {
2158               unsigned int fill_size;
2159
2160               switch (frag->fr_type)
2161                 {
2162                 case rs_machine_dependent:
2163                   if (frag->fr_fix)
2164                     {
2165                       memcpy (buffer + frag->fr_address,
2166                               frag->fr_literal,
2167                               (unsigned int) frag->fr_fix);
2168                       offset += frag->fr_fix;
2169                     }
2170
2171                   break;
2172                 case rs_space:
2173                 case rs_fill:
2174                 case rs_align:
2175                 case rs_align_code:
2176                 case rs_align_test:
2177                 case rs_org:
2178                   if (frag->fr_fix)
2179                     {
2180                       memcpy (buffer + frag->fr_address,
2181                               frag->fr_literal,
2182                               (unsigned int) frag->fr_fix);
2183                       offset += frag->fr_fix;
2184                     }
2185
2186                   fill_size = frag->fr_var;
2187                   if (fill_size && frag->fr_offset > 0)
2188                     {
2189                       unsigned int count;
2190                       unsigned int off = frag->fr_fix;
2191
2192                       for (count = frag->fr_offset; count; count--)
2193                         {
2194                           if (fill_size + frag->fr_address + off <= s->s_size)
2195                             {
2196                               memcpy (buffer + frag->fr_address + off,
2197                                       frag->fr_literal + frag->fr_fix,
2198                                       fill_size);
2199                               off += fill_size;
2200                               offset += fill_size;
2201                             }
2202                         }
2203                     }
2204                   break;
2205                 case rs_broken_word:
2206                   break;
2207                 default:
2208                   abort ();
2209                 }
2210               frag = frag->fr_next;
2211             }
2212
2213           if (s->s_size != 0)
2214             {
2215               if (s->s_scnptr != 0)
2216                 {
2217                   bfd_bwrite (buffer, s->s_size, abfd);
2218                   *file_cursor += s->s_size;
2219                 }
2220               free (buffer);
2221             }
2222           paddr += s->s_size;
2223         }
2224     }
2225 }
2226
2227 /* Coff file generation & utilities.  */
2228
2229 static void
2230 coff_header_append (bfd * abfd, object_headers * h)
2231 {
2232   unsigned int i;
2233   char buffer[1000];
2234   char buffero[1000];
2235 #ifdef COFF_LONG_SECTION_NAMES
2236   unsigned long string_size = 4;
2237 #endif
2238
2239   bfd_seek (abfd, 0, 0);
2240
2241 #ifndef OBJ_COFF_OMIT_OPTIONAL_HEADER
2242   H_SET_MAGIC_NUMBER (h, COFF_MAGIC);
2243   H_SET_VERSION_STAMP (h, 0);
2244   H_SET_ENTRY_POINT (h, 0);
2245   H_SET_TEXT_START (h, segment_info[SEG_E0].frchainP->frch_root->fr_address);
2246   H_SET_DATA_START (h, segment_info[SEG_E1].frchainP->frch_root->fr_address);
2247   H_SET_SIZEOF_OPTIONAL_HEADER (h, bfd_coff_swap_aouthdr_out (abfd, &h->aouthdr,
2248                                                               buffero));
2249 #else /* defined (OBJ_COFF_OMIT_OPTIONAL_HEADER) */
2250   H_SET_SIZEOF_OPTIONAL_HEADER (h, 0);
2251 #endif /* defined (OBJ_COFF_OMIT_OPTIONAL_HEADER) */
2252
2253   i = bfd_coff_swap_filehdr_out (abfd, &h->filehdr, buffer);
2254
2255   bfd_bwrite (buffer, (bfd_size_type) i, abfd);
2256   bfd_bwrite (buffero, (bfd_size_type) H_GET_SIZEOF_OPTIONAL_HEADER (h), abfd);
2257
2258   for (i = SEG_E0; i < SEG_LAST; i++)
2259     {
2260       if (segment_info[i].scnhdr.s_name[0])
2261         {
2262           unsigned int size;
2263
2264 #ifdef COFF_LONG_SECTION_NAMES
2265           /* Support long section names as found in PE.  This code
2266              must coordinate with that in write_object_file and
2267              w_strings.  */
2268           if (strlen (segment_info[i].name) > SCNNMLEN)
2269             {
2270               memset (segment_info[i].scnhdr.s_name, 0, SCNNMLEN);
2271               sprintf (segment_info[i].scnhdr.s_name, "/%lu", string_size);
2272               string_size += strlen (segment_info[i].name) + 1;
2273             }
2274 #endif
2275           size = bfd_coff_swap_scnhdr_out (abfd,
2276                                            &(segment_info[i].scnhdr),
2277                                            buffer);
2278           if (size == 0)
2279             as_bad (_("bfd_coff_swap_scnhdr_out failed"));
2280           bfd_bwrite (buffer, (bfd_size_type) size, abfd);
2281         }
2282     }
2283 }
2284
2285 static char *
2286 symbol_to_chars (bfd * abfd, char * where, symbolS * symbolP)
2287 {
2288   unsigned int numaux = symbolP->sy_symbol.ost_entry.n_numaux;
2289   unsigned int i;
2290   valueT val;
2291
2292   /* Turn any symbols with register attributes into abs symbols.  */
2293   if (S_GET_SEGMENT (symbolP) == reg_section)
2294     S_SET_SEGMENT (symbolP, absolute_section);
2295
2296   /* At the same time, relocate all symbols to their output value.  */
2297 #ifndef TE_PE
2298   val = (segment_info[S_GET_SEGMENT (symbolP)].scnhdr.s_paddr
2299          + S_GET_VALUE (symbolP));
2300 #else
2301   val = S_GET_VALUE (symbolP);
2302 #endif
2303
2304   S_SET_VALUE (symbolP, val);
2305
2306   symbolP->sy_symbol.ost_entry.n_value = val;
2307
2308   where += bfd_coff_swap_sym_out (abfd, &symbolP->sy_symbol.ost_entry,
2309                                   where);
2310
2311   for (i = 0; i < numaux; i++)
2312     {
2313       where += bfd_coff_swap_aux_out (abfd,
2314                                       &symbolP->sy_symbol.ost_auxent[i],
2315                                       S_GET_DATA_TYPE (symbolP),
2316                                       S_GET_STORAGE_CLASS (symbolP),
2317                                       i, numaux, where);
2318     }
2319
2320   return where;
2321 }
2322
2323 void
2324 coff_obj_symbol_new_hook (symbolS *symbolP)
2325 {
2326   char underscore = 0;          /* Symbol has leading _  */
2327
2328   /* Effective symbol.  */
2329   /* Store the pointer in the offset.  */
2330   S_SET_ZEROES (symbolP, 0L);
2331   S_SET_DATA_TYPE (symbolP, T_NULL);
2332   S_SET_STORAGE_CLASS (symbolP, 0);
2333   S_SET_NUMBER_AUXILIARY (symbolP, 0);
2334   /* Additional information.  */
2335   symbolP->sy_symbol.ost_flags = 0;
2336   /* Auxiliary entries.  */
2337   memset ((char *) &symbolP->sy_symbol.ost_auxent[0], 0, AUXESZ);
2338
2339   if (S_IS_STRING (symbolP))
2340     SF_SET_STRING (symbolP);
2341   if (!underscore && S_IS_LOCAL (symbolP))
2342     SF_SET_LOCAL (symbolP);
2343 }
2344
2345 static int
2346 c_line_new (symbolS * symbol, long paddr, int line_number, fragS * frag)
2347 {
2348   struct lineno_list *new_line = xmalloc (sizeof (* new_line));
2349
2350   segment_info_type *s = segment_info + now_seg;
2351   new_line->line.l_lnno = line_number;
2352
2353   if (line_number == 0)
2354     {
2355       last_line_symbol = symbol;
2356       new_line->line.l_addr.l_symndx = (long) symbol;
2357     }
2358   else
2359     {
2360       new_line->line.l_addr.l_paddr = paddr;
2361     }
2362
2363   new_line->frag = (char *) frag;
2364   new_line->next = NULL;
2365
2366   if (s->lineno_list_head == NULL)
2367     s->lineno_list_head = new_line;
2368   else
2369     s->lineno_list_tail->next = new_line;
2370
2371   s->lineno_list_tail = new_line;
2372   return LINESZ * s->scnhdr.s_nlnno++;
2373 }
2374
2375 /* Handle .ln directives.  */
2376
2377 static void
2378 obj_coff_ln (int appline)
2379 {
2380   int l;
2381
2382   if (! appline && def_symbol_in_progress != NULL)
2383     {
2384       /* Wrong context.  */
2385       as_warn (_(".ln pseudo-op inside .def/.endef: ignored."));
2386       demand_empty_rest_of_line ();
2387       return;
2388     }
2389
2390   l = get_absolute_expression ();
2391   c_line_new (0, frag_now_fix (), l, frag_now);
2392
2393   if (appline)
2394     new_logical_line ((char *) NULL, l - 1);
2395
2396 #ifndef NO_LISTING
2397   {
2398     extern int listing;
2399
2400     if (listing)
2401       {
2402         if (! appline)
2403           l += line_base - 1;
2404         listing_source_line ((unsigned int) l);
2405       }
2406   }
2407 #endif
2408   demand_empty_rest_of_line ();
2409 }
2410
2411 /* Handle .def directives.
2412
2413   One might ask : why can't we symbol_new if the symbol does not
2414   already exist and fill it with debug information.  Because of
2415   the C_EFCN special symbol. It would clobber the value of the
2416   function symbol before we have a chance to notice that it is
2417   a C_EFCN. And a second reason is that the code is more clear this
2418   way. (at least I think it is :-).  */
2419
2420 #define SKIP_SEMI_COLON()       while (*input_line_pointer++ != ';')
2421 #define SKIP_WHITESPACES()      while (*input_line_pointer == ' ' || \
2422                                        *input_line_pointer == '\t')  \
2423                                   input_line_pointer++;
2424
2425 static void
2426 obj_coff_def (int what ATTRIBUTE_UNUSED)
2427 {
2428   char name_end;                /* Char after the end of name.  */
2429   char *symbol_name;            /* Name of the debug symbol.  */
2430   char *symbol_name_copy;       /* Temporary copy of the name.  */
2431   unsigned int symbol_name_length;
2432
2433   if (def_symbol_in_progress != NULL)
2434     {
2435       as_warn (_(".def pseudo-op used inside of .def/.endef: ignored."));
2436       demand_empty_rest_of_line ();
2437       return;
2438     }
2439
2440   SKIP_WHITESPACES ();
2441
2442   def_symbol_in_progress = obstack_alloc (&notes, sizeof (*def_symbol_in_progress));
2443   memset (def_symbol_in_progress, 0, sizeof (*def_symbol_in_progress));
2444
2445   symbol_name = input_line_pointer;
2446   name_end = get_symbol_end ();
2447   symbol_name_length = strlen (symbol_name);
2448   symbol_name_copy = xmalloc (symbol_name_length + 1);
2449   strcpy (symbol_name_copy, symbol_name);
2450 #ifdef tc_canonicalize_symbol_name
2451   symbol_name_copy = tc_canonicalize_symbol_name (symbol_name_copy);
2452 #endif
2453
2454   /* Initialize the new symbol.  */
2455 #ifdef STRIP_UNDERSCORE
2456   S_SET_NAME (def_symbol_in_progress, (*symbol_name_copy == '_'
2457                                        ? symbol_name_copy + 1
2458                                        : symbol_name_copy));
2459 #else /* STRIP_UNDERSCORE */
2460   S_SET_NAME (def_symbol_in_progress, symbol_name_copy);
2461 #endif /* STRIP_UNDERSCORE */
2462   /* free(symbol_name_copy); */
2463   def_symbol_in_progress->sy_name_offset = (unsigned long) ~0;
2464   def_symbol_in_progress->sy_number = ~0;
2465   def_symbol_in_progress->sy_frag = &zero_address_frag;
2466   S_SET_VALUE (def_symbol_in_progress, 0);
2467
2468   if (S_IS_STRING (def_symbol_in_progress))
2469     SF_SET_STRING (def_symbol_in_progress);
2470
2471   *input_line_pointer = name_end;
2472
2473   demand_empty_rest_of_line ();
2474 }
2475
2476 static void
2477 c_symbol_merge (symbolS *debug, symbolS *normal)
2478 {
2479   S_SET_DATA_TYPE (normal, S_GET_DATA_TYPE (debug));
2480   S_SET_STORAGE_CLASS (normal, S_GET_STORAGE_CLASS (debug));
2481
2482   if (S_GET_NUMBER_AUXILIARY (debug) > S_GET_NUMBER_AUXILIARY (normal))
2483     S_SET_NUMBER_AUXILIARY (normal, S_GET_NUMBER_AUXILIARY (debug));
2484
2485   if (S_GET_NUMBER_AUXILIARY (debug) > 0)
2486     memcpy ((char *) &normal->sy_symbol.ost_auxent[0],
2487             (char *) &debug->sy_symbol.ost_auxent[0],
2488             (unsigned int) (S_GET_NUMBER_AUXILIARY (debug) * AUXESZ));
2489
2490   /* Move the debug flags.  */
2491   SF_SET_DEBUG_FIELD (normal, SF_GET_DEBUG_FIELD (debug));
2492 }
2493
2494 unsigned int dim_index;
2495
2496 static void
2497 obj_coff_endef (int ignore ATTRIBUTE_UNUSED)
2498 {
2499   symbolS *symbolP = 0;
2500
2501   dim_index = 0;
2502   if (def_symbol_in_progress == NULL)
2503     {
2504       as_warn (_(".endef pseudo-op used outside of .def/.endef: ignored."));
2505       demand_empty_rest_of_line ();
2506       return;
2507     }
2508
2509   /* Set the section number according to storage class.  */
2510   switch (S_GET_STORAGE_CLASS (def_symbol_in_progress))
2511     {
2512     case C_STRTAG:
2513     case C_ENTAG:
2514     case C_UNTAG:
2515       SF_SET_TAG (def_symbol_in_progress);
2516       /* Fall through.  */
2517
2518     case C_FILE:
2519     case C_TPDEF:
2520       SF_SET_DEBUG (def_symbol_in_progress);
2521       S_SET_SEGMENT (def_symbol_in_progress, SEG_DEBUG);
2522       break;
2523
2524     case C_EFCN:
2525       /* Do not emit this symbol.  */
2526       SF_SET_LOCAL (def_symbol_in_progress);
2527       /* Fall through.  */
2528
2529     case C_BLOCK:
2530       /* Will need processing before writing.  */
2531       SF_SET_PROCESS (def_symbol_in_progress);
2532       /* Fall through.  */
2533
2534     case C_FCN:
2535       S_SET_SEGMENT (def_symbol_in_progress, SEG_E0);
2536
2537       if (streq (S_GET_NAME (def_symbol_in_progress), ".bf"))
2538         {
2539           if (function_lineoff < 0)
2540             fprintf (stderr, _("`.bf' symbol without preceding function\n"));
2541
2542           SA_GET_SYM_LNNOPTR (last_line_symbol) = function_lineoff;
2543
2544           SF_SET_PROCESS (last_line_symbol);
2545           SF_SET_ADJ_LNNOPTR (last_line_symbol);
2546           SF_SET_PROCESS (def_symbol_in_progress);
2547           function_lineoff = -1;
2548         }
2549
2550       /* Value is always set to .  */
2551       def_symbol_in_progress->sy_frag = frag_now;
2552       S_SET_VALUE (def_symbol_in_progress, (valueT) frag_now_fix ());
2553       break;
2554
2555 #ifdef C_AUTOARG
2556     case C_AUTOARG:
2557 #endif /* C_AUTOARG */
2558     case C_AUTO:
2559     case C_REG:
2560     case C_MOS:
2561     case C_MOE:
2562     case C_MOU:
2563     case C_ARG:
2564     case C_REGPARM:
2565     case C_FIELD:
2566     case C_EOS:
2567       SF_SET_DEBUG (def_symbol_in_progress);
2568       S_SET_SEGMENT (def_symbol_in_progress, absolute_section);
2569       break;
2570
2571     case C_EXT:
2572     case C_WEAKEXT:
2573 #ifdef TE_PE
2574     case C_NT_WEAK:
2575 #endif
2576     case C_STAT:
2577     case C_LABEL:
2578       /* Valid but set somewhere else (s_comm, s_lcomm, colon).  */
2579       break;
2580
2581     case C_USTATIC:
2582     case C_EXTDEF:
2583     case C_ULABEL:
2584       as_warn (_("unexpected storage class %d"), S_GET_STORAGE_CLASS (def_symbol_in_progress));
2585       break;
2586     }
2587
2588   /* Now that we have built a debug symbol, try to find if we should
2589      merge with an existing symbol or not.  If a symbol is C_EFCN or
2590      absolute_section or untagged SEG_DEBUG it never merges.  We also
2591      don't merge labels, which are in a different namespace, nor
2592      symbols which have not yet been defined since they are typically
2593      unique, nor do we merge tags with non-tags.  */
2594
2595   /* Two cases for functions.  Either debug followed by definition or
2596      definition followed by debug.  For definition first, we will
2597      merge the debug symbol into the definition.  For debug first, the
2598      lineno entry MUST point to the definition function or else it
2599      will point off into space when crawl_symbols() merges the debug
2600      symbol into the real symbol.  Therefor, let's presume the debug
2601      symbol is a real function reference.  */
2602
2603   /* FIXME-SOON If for some reason the definition label/symbol is
2604      never seen, this will probably leave an undefined symbol at link
2605      time.  */
2606
2607   if (S_GET_STORAGE_CLASS (def_symbol_in_progress) == C_EFCN
2608       || S_GET_STORAGE_CLASS (def_symbol_in_progress) == C_LABEL
2609       || (S_GET_SEGMENT (def_symbol_in_progress) == SEG_DEBUG
2610           && !SF_GET_TAG (def_symbol_in_progress))
2611       || S_GET_SEGMENT (def_symbol_in_progress) == absolute_section
2612       || def_symbol_in_progress->sy_value.X_op != O_constant
2613       || (symbolP = symbol_find_base (S_GET_NAME (def_symbol_in_progress), DO_NOT_STRIP)) == NULL
2614       || (SF_GET_TAG (def_symbol_in_progress) != SF_GET_TAG (symbolP)))
2615     {
2616       symbol_append (def_symbol_in_progress, symbol_lastP, &symbol_rootP,
2617                      &symbol_lastP);
2618     }
2619   else
2620     {
2621       /* This symbol already exists, merge the newly created symbol
2622          into the old one.  This is not mandatory. The linker can
2623          handle duplicate symbols correctly. But I guess that it save
2624          a *lot* of space if the assembly file defines a lot of
2625          symbols. [loic] */
2626
2627       /* The debug entry (def_symbol_in_progress) is merged into the
2628          previous definition.  */
2629
2630       c_symbol_merge (def_symbol_in_progress, symbolP);
2631       /* FIXME-SOON Should *def_symbol_in_progress be free'd? xoxorich.  */
2632       def_symbol_in_progress = symbolP;
2633
2634       if (SF_GET_FUNCTION (def_symbol_in_progress)
2635           || SF_GET_TAG (def_symbol_in_progress)
2636           || S_GET_STORAGE_CLASS (def_symbol_in_progress) == C_STAT)
2637         {
2638           /* For functions, and tags, and static symbols, the symbol
2639              *must* be where the debug symbol appears.  Move the
2640              existing symbol to the current place.  */
2641           /* If it already is at the end of the symbol list, do nothing.  */
2642           if (def_symbol_in_progress != symbol_lastP)
2643             {
2644               symbol_remove (def_symbol_in_progress, &symbol_rootP,
2645                              &symbol_lastP);
2646               symbol_append (def_symbol_in_progress, symbol_lastP,
2647                              &symbol_rootP, &symbol_lastP);
2648             }
2649         }
2650     }
2651
2652   if (SF_GET_TAG (def_symbol_in_progress))
2653     {
2654       symbolS *oldtag;
2655
2656       oldtag = symbol_find_base (S_GET_NAME (def_symbol_in_progress),
2657                                  DO_NOT_STRIP);
2658       if (oldtag == NULL || ! SF_GET_TAG (oldtag))
2659         tag_insert (S_GET_NAME (def_symbol_in_progress),
2660                     def_symbol_in_progress);
2661     }
2662
2663   if (SF_GET_FUNCTION (def_symbol_in_progress))
2664     {
2665       know (sizeof (def_symbol_in_progress) <= sizeof (long));
2666       function_lineoff
2667         = c_line_new (def_symbol_in_progress, 0, 0, &zero_address_frag);
2668
2669       SF_SET_PROCESS (def_symbol_in_progress);
2670
2671       if (symbolP == NULL)
2672         /* That is, if this is the first time we've seen the function.  */
2673         symbol_table_insert (def_symbol_in_progress);
2674     }
2675
2676   def_symbol_in_progress = NULL;
2677   demand_empty_rest_of_line ();
2678 }
2679
2680 static void
2681 obj_coff_dim (int ignore ATTRIBUTE_UNUSED)
2682 {
2683   int dim_index;
2684
2685   if (def_symbol_in_progress == NULL)
2686     {
2687       as_warn (_(".dim pseudo-op used outside of .def/.endef: ignored."));
2688       demand_empty_rest_of_line ();
2689       return;
2690     }
2691
2692   S_SET_NUMBER_AUXILIARY (def_symbol_in_progress, 1);
2693
2694   for (dim_index = 0; dim_index < DIMNUM; dim_index++)
2695     {
2696       SKIP_WHITESPACES ();
2697       SA_SET_SYM_DIMEN (def_symbol_in_progress, dim_index,
2698                         get_absolute_expression ());
2699
2700       switch (*input_line_pointer)
2701         {
2702         case ',':
2703           input_line_pointer++;
2704           break;
2705
2706         default:
2707           as_warn (_("badly formed .dim directive ignored"));
2708           /* Fall through.  */
2709
2710         case '\n':
2711         case ';':
2712           dim_index = DIMNUM;
2713           break;
2714         }
2715     }
2716
2717   demand_empty_rest_of_line ();
2718 }
2719
2720 static void
2721 obj_coff_line (int ignore ATTRIBUTE_UNUSED)
2722 {
2723   int this_base;
2724   const char *name;
2725
2726   if (def_symbol_in_progress == NULL)
2727     {
2728       obj_coff_ln (0);
2729       return;
2730     }
2731
2732   name = S_GET_NAME (def_symbol_in_progress);
2733   this_base = get_absolute_expression ();
2734
2735   /* Only .bf symbols indicate the use of a new base line number; the
2736      line numbers associated with .ef, .bb, .eb are relative to the
2737      start of the containing function.  */
2738   if (streq (".bf", name))
2739     {
2740         line_base = this_base;
2741
2742 #ifndef NO_LISTING
2743       {
2744         extern int listing;
2745         if (listing)
2746           listing_source_line ((unsigned int) line_base);
2747       }
2748 #endif
2749     }
2750
2751   S_SET_NUMBER_AUXILIARY (def_symbol_in_progress, 1);
2752   SA_SET_SYM_LNNO (def_symbol_in_progress, this_base);
2753
2754   demand_empty_rest_of_line ();
2755 }
2756
2757 static void
2758 obj_coff_size (int ignore ATTRIBUTE_UNUSED)
2759 {
2760   if (def_symbol_in_progress == NULL)
2761     {
2762       as_warn (_(".size pseudo-op used outside of .def/.endef ignored."));
2763       demand_empty_rest_of_line ();
2764       return;
2765     }
2766
2767   S_SET_NUMBER_AUXILIARY (def_symbol_in_progress, 1);
2768   SA_SET_SYM_SIZE (def_symbol_in_progress, get_absolute_expression ());
2769   demand_empty_rest_of_line ();
2770 }
2771
2772 static void
2773 obj_coff_scl (int ignore ATTRIBUTE_UNUSED)
2774 {
2775   if (def_symbol_in_progress == NULL)
2776     {
2777       as_warn (_(".scl pseudo-op used outside of .def/.endef ignored."));
2778       demand_empty_rest_of_line ();
2779       return;
2780     }
2781
2782   S_SET_STORAGE_CLASS (def_symbol_in_progress, get_absolute_expression ());
2783   demand_empty_rest_of_line ();
2784 }
2785
2786 static void
2787 obj_coff_tag (int ignore ATTRIBUTE_UNUSED)
2788 {
2789   char *symbol_name;
2790   char name_end;
2791
2792   if (def_symbol_in_progress == NULL)
2793     {
2794       as_warn (_(".tag pseudo-op used outside of .def/.endef ignored."));
2795       demand_empty_rest_of_line ();
2796       return;
2797     }
2798
2799   S_SET_NUMBER_AUXILIARY (def_symbol_in_progress, 1);
2800   symbol_name = input_line_pointer;
2801   name_end = get_symbol_end ();
2802 #ifdef tc_canonicalize_symbol_name
2803   symbol_name = tc_canonicalize_symbol_name (symbol_name);
2804 #endif
2805
2806   /* Assume that the symbol referred to by .tag is always defined.
2807      This was a bad assumption.  I've added find_or_make. xoxorich.  */
2808   SA_SET_SYM_TAGNDX (def_symbol_in_progress,
2809                      (long) tag_find_or_make (symbol_name));
2810   if (SA_GET_SYM_TAGNDX (def_symbol_in_progress) == 0L)
2811     as_warn (_("tag not found for .tag %s"), symbol_name);
2812
2813   SF_SET_TAGGED (def_symbol_in_progress);
2814   *input_line_pointer = name_end;
2815
2816   demand_empty_rest_of_line ();
2817 }
2818
2819 static void
2820 obj_coff_type (int ignore ATTRIBUTE_UNUSED)
2821 {
2822   if (def_symbol_in_progress == NULL)
2823     {
2824       as_warn (_(".type pseudo-op used outside of .def/.endef ignored."));
2825       demand_empty_rest_of_line ();
2826       return;
2827     }
2828
2829   S_SET_DATA_TYPE (def_symbol_in_progress, get_absolute_expression ());
2830
2831   if (ISFCN (S_GET_DATA_TYPE (def_symbol_in_progress)) &&
2832       S_GET_STORAGE_CLASS (def_symbol_in_progress) != C_TPDEF)
2833     SF_SET_FUNCTION (def_symbol_in_progress);
2834
2835   demand_empty_rest_of_line ();
2836 }
2837
2838 static void
2839 obj_coff_val (int ignore ATTRIBUTE_UNUSED)
2840 {
2841   if (def_symbol_in_progress == NULL)
2842     {
2843       as_warn (_(".val pseudo-op used outside of .def/.endef ignored."));
2844       demand_empty_rest_of_line ();
2845       return;
2846     }
2847
2848   if (is_name_beginner (*input_line_pointer))
2849     {
2850       char *symbol_name = input_line_pointer;
2851       char name_end = get_symbol_end ();
2852
2853 #ifdef tc_canonicalize_symbol_name
2854   symbol_name = tc_canonicalize_symbol_name (symbol_name);
2855 #endif
2856
2857       if (streq (symbol_name, "."))
2858         {
2859           def_symbol_in_progress->sy_frag = frag_now;
2860           S_SET_VALUE (def_symbol_in_progress, (valueT) frag_now_fix ());
2861           /* If the .val is != from the .def (e.g. statics).  */
2862         }
2863       else if (! streq (S_GET_NAME (def_symbol_in_progress), symbol_name))
2864         {
2865           def_symbol_in_progress->sy_value.X_op = O_symbol;
2866           def_symbol_in_progress->sy_value.X_add_symbol =
2867             symbol_find_or_make (symbol_name);
2868           def_symbol_in_progress->sy_value.X_op_symbol = NULL;
2869           def_symbol_in_progress->sy_value.X_add_number = 0;
2870
2871           /* If the segment is undefined when the forward reference is
2872              resolved, then copy the segment id from the forward
2873              symbol.  */
2874           SF_SET_GET_SEGMENT (def_symbol_in_progress);
2875
2876           /* FIXME: gcc can generate address expressions here in
2877              unusual cases (search for "obscure" in sdbout.c).  We
2878              just ignore the offset here, thus generating incorrect
2879              debugging information.  We ignore the rest of the line
2880              just below.  */
2881         }
2882       /* Otherwise, it is the name of a non debug symbol and
2883          its value will be calculated later.  */
2884       *input_line_pointer = name_end;
2885
2886       /* FIXME: this is to avoid an error message in the
2887          FIXME case mentioned just above.  */
2888       while (! is_end_of_line[(unsigned char) *input_line_pointer])
2889         ++input_line_pointer;
2890     }
2891   else
2892     {
2893       S_SET_VALUE (def_symbol_in_progress,
2894                    (valueT) get_absolute_expression ());
2895     }
2896
2897   demand_empty_rest_of_line ();
2898 }
2899
2900 #ifdef TE_PE
2901
2902 /* Handle the .linkonce pseudo-op.  This is parsed by s_linkonce in
2903    read.c, which then calls this object file format specific routine.  */
2904
2905 void
2906 obj_coff_pe_handle_link_once (enum linkonce_type type)
2907 {
2908   seg_info (now_seg)->scnhdr.s_flags |= IMAGE_SCN_LNK_COMDAT;
2909
2910   /* We store the type in the seg_info structure, and use it to set up
2911      the auxiliary entry for the section symbol in c_section_symbol.  */
2912   seg_info (now_seg)->linkonce = type;
2913 }
2914
2915 #endif /* TE_PE */
2916
2917 void
2918 coff_obj_read_begin_hook (void)
2919 {
2920   /* These had better be the same.  Usually 18 bytes.  */
2921 #ifndef BFD_HEADERS
2922   know (sizeof (SYMENT) == sizeof (AUXENT));
2923   know (SYMESZ == AUXESZ);
2924 #endif
2925   tag_init ();
2926 }
2927
2928 /* This function runs through the symbol table and puts all the
2929    externals onto another chain.  */
2930
2931 /* The chain of globals.  */
2932 symbolS *symbol_globalP;
2933 symbolS *symbol_global_lastP;
2934
2935 /* The chain of externals.  */
2936 symbolS *symbol_externP;
2937 symbolS *symbol_extern_lastP;
2938
2939 stack *block_stack;
2940 symbolS *last_functionP;
2941 static symbolS *last_bfP;
2942 symbolS *last_tagP;
2943
2944 static unsigned int
2945 yank_symbols (void)
2946 {
2947   symbolS *symbolP;
2948   unsigned int symbol_number = 0;
2949   unsigned int last_file_symno = 0;
2950   struct filename_list *filename_list_scan = filename_list_head;
2951
2952   for (symbolP = symbol_rootP;
2953        symbolP;
2954        symbolP = symbolP ? symbol_next (symbolP) : symbol_rootP)
2955     {
2956       if (symbolP->sy_mri_common)
2957         {
2958           if (S_GET_STORAGE_CLASS (symbolP) == C_EXT
2959 #ifdef TE_PE
2960               || S_GET_STORAGE_CLASS (symbolP) == C_NT_WEAK
2961 #endif
2962               || S_GET_STORAGE_CLASS (symbolP) == C_WEAKEXT)
2963             as_bad (_("%s: global symbols not supported in common sections"),
2964                     S_GET_NAME (symbolP));
2965           symbol_remove (symbolP, &symbol_rootP, &symbol_lastP);
2966           continue;
2967         }
2968
2969       if (!SF_GET_DEBUG (symbolP))
2970         {
2971           /* Debug symbols do not need all this rubbish.  */
2972           symbolS *real_symbolP;
2973
2974           /* L* and C_EFCN symbols never merge.  */
2975           if (!SF_GET_LOCAL (symbolP)
2976               && !SF_GET_STATICS (symbolP)
2977               && S_GET_STORAGE_CLASS (symbolP) != C_LABEL
2978               && symbolP->sy_value.X_op == O_constant
2979               && (real_symbolP = symbol_find_base (S_GET_NAME (symbolP), DO_NOT_STRIP))
2980               && real_symbolP != symbolP)
2981             {
2982               /* FIXME-SOON: where do dups come from?
2983                  Maybe tag references before definitions? xoxorich.  */
2984               /* Move the debug data from the debug symbol to the
2985                  real symbol. Do NOT do the opposite (i.e. move from
2986                  real symbol to debug symbol and remove real symbol from the
2987                  list.) Because some pointers refer to the real symbol
2988                  whereas no pointers refer to the debug symbol.  */
2989               c_symbol_merge (symbolP, real_symbolP);
2990               /* Replace the current symbol by the real one.  */
2991               /* The symbols will never be the last or the first
2992                  because : 1st symbol is .file and 3 last symbols are
2993                  .text, .data, .bss.  */
2994               symbol_remove (real_symbolP, &symbol_rootP, &symbol_lastP);
2995               symbol_insert (real_symbolP, symbolP, &symbol_rootP, &symbol_lastP);
2996               symbol_remove (symbolP, &symbol_rootP, &symbol_lastP);
2997               symbolP = real_symbolP;
2998             }
2999
3000           if (flag_readonly_data_in_text && (S_GET_SEGMENT (symbolP) == SEG_E1))
3001             S_SET_SEGMENT (symbolP, SEG_E0);
3002
3003           resolve_symbol_value (symbolP);
3004
3005           if (S_GET_STORAGE_CLASS (symbolP) == C_NULL)
3006             {
3007               if (!S_IS_DEFINED (symbolP) && !SF_GET_LOCAL (symbolP))
3008                 S_SET_EXTERNAL (symbolP);
3009
3010               else if (S_GET_SEGMENT (symbolP) == SEG_E0)
3011                 S_SET_STORAGE_CLASS (symbolP, C_LABEL);
3012
3013               else
3014                 S_SET_STORAGE_CLASS (symbolP, C_STAT);
3015             }
3016
3017           /* Mainly to speed up if not -g.  */
3018           if (SF_GET_PROCESS (symbolP))
3019             {
3020               /* Handle the nested blocks auxiliary info.  */
3021               if (S_GET_STORAGE_CLASS (symbolP) == C_BLOCK)
3022                 {
3023                   if (streq (S_GET_NAME (symbolP), ".bb"))
3024                     stack_push (block_stack, (char *) &symbolP);
3025                   else
3026                     {
3027                       /* .eb */
3028                       symbolS *begin_symbolP;
3029
3030                       begin_symbolP = *(symbolS **) stack_pop (block_stack);
3031                       if (begin_symbolP == NULL)
3032                         as_warn (_("mismatched .eb"));
3033                       else
3034                         SA_SET_SYM_ENDNDX (begin_symbolP, symbol_number + 2);
3035                     }
3036                 }
3037
3038               /* If we are able to identify the type of a function, and we
3039                are out of a function (last_functionP == 0) then, the
3040                function symbol will be associated with an auxiliary
3041                entry.  */
3042               if (last_functionP == NULL && SF_GET_FUNCTION (symbolP))
3043                 {
3044                   last_functionP = symbolP;
3045
3046                   if (S_GET_NUMBER_AUXILIARY (symbolP) < 1)
3047                     S_SET_NUMBER_AUXILIARY (symbolP, 1);
3048                 }
3049
3050               if (S_GET_STORAGE_CLASS (symbolP) == C_FCN)
3051                 {
3052                   if (streq (S_GET_NAME (symbolP), ".bf"))
3053                     {
3054                       if (last_bfP != NULL)
3055                         SA_SET_SYM_ENDNDX (last_bfP, symbol_number);
3056                       last_bfP = symbolP;
3057                     }
3058                 }
3059               else if (S_GET_STORAGE_CLASS (symbolP) == C_EFCN)
3060                 {
3061                   /* I don't even know if this is needed for sdb. But
3062                      the standard assembler generates it, so...  */
3063                   if (last_functionP == NULL)
3064                     as_fatal (_("C_EFCN symbol out of scope"));
3065                   SA_SET_SYM_FSIZE (last_functionP,
3066                                     (long) (S_GET_VALUE (symbolP) -
3067                                             S_GET_VALUE (last_functionP)));
3068                   SA_SET_SYM_ENDNDX (last_functionP, symbol_number);
3069                  last_functionP = NULL;
3070                 }
3071             }
3072         }
3073       else if (SF_GET_TAG (symbolP))
3074         /* First descriptor of a structure must point to
3075            the first slot after the structure description.  */
3076         last_tagP = symbolP;
3077
3078       else if (S_GET_STORAGE_CLASS (symbolP) == C_EOS)
3079         /* +2 take in account the current symbol.  */
3080         SA_SET_SYM_ENDNDX (last_tagP, symbol_number + 2);
3081
3082       else if (S_GET_STORAGE_CLASS (symbolP) == C_FILE)
3083         {
3084           /* If the filename was too long to fit in the
3085              auxent, put it in the string table.  */
3086           if (SA_GET_FILE_FNAME_ZEROS (symbolP) == 0
3087               && SA_GET_FILE_FNAME_OFFSET (symbolP) != 0)
3088             {
3089               SA_SET_FILE_FNAME_OFFSET (symbolP, string_byte_count);
3090               string_byte_count += strlen (filename_list_scan->filename) + 1;
3091               filename_list_scan = filename_list_scan->next;
3092             }
3093           if (S_GET_VALUE (symbolP))
3094             {
3095               S_SET_VALUE (symbolP, last_file_symno);
3096               last_file_symno = symbol_number;
3097             }
3098         }
3099
3100 #ifdef tc_frob_coff_symbol
3101       tc_frob_coff_symbol (symbolP);
3102 #endif
3103
3104       /* We must put the external symbols apart. The loader
3105          does not bomb if we do not. But the references in
3106          the endndx field for a .bb symbol are not corrected
3107          if an external symbol is removed between .bb and .be.
3108          I.e in the following case :
3109          [20] .bb endndx = 22
3110          [21] foo external
3111          [22] .be
3112          ld will move the symbol 21 to the end of the list but
3113          endndx will still be 22 instead of 21.  */
3114
3115       if (SF_GET_LOCAL (symbolP))
3116         /* Remove C_EFCN and LOCAL (L...) symbols.  */
3117         /* Next pointer remains valid.  */
3118         symbol_remove (symbolP, &symbol_rootP, &symbol_lastP);
3119
3120       else if (symbolP->sy_value.X_op == O_symbol
3121                && (! S_IS_DEFINED (symbolP) || S_IS_COMMON (symbolP)))
3122         /* Skip symbols which were equated to undefined or common
3123            symbols.  */
3124         symbol_remove (symbolP, &symbol_rootP, &symbol_lastP);
3125
3126       else if (!S_IS_DEFINED (symbolP)
3127                && !S_IS_DEBUG (symbolP)
3128                && !SF_GET_STATICS (symbolP)
3129                && (S_GET_STORAGE_CLASS (symbolP) == C_EXT
3130 #ifdef TE_PE
3131                    || S_GET_STORAGE_CLASS (symbolP) == C_NT_WEAK
3132 #endif
3133                    || S_GET_STORAGE_CLASS (symbolP) == C_WEAKEXT))
3134         {
3135           /* If external, Remove from the list.  */
3136           symbolS *hold = symbol_previous (symbolP);
3137
3138           symbol_remove (symbolP, &symbol_rootP, &symbol_lastP);
3139           symbol_clear_list_pointers (symbolP);
3140           symbol_append (symbolP, symbol_extern_lastP, &symbol_externP, &symbol_extern_lastP);
3141           symbolP = hold;
3142         }
3143       else if (! S_IS_DEBUG (symbolP)
3144                && ! SF_GET_STATICS (symbolP)
3145                && ! SF_GET_FUNCTION (symbolP)
3146                && (S_GET_STORAGE_CLASS (symbolP) == C_EXT
3147 #ifdef TE_PE
3148                    || S_GET_STORAGE_CLASS (symbolP) == C_NT_WEAK
3149 #endif
3150                    || S_GET_STORAGE_CLASS (symbolP) == C_NT_WEAK))
3151         {
3152           symbolS *hold = symbol_previous (symbolP);
3153
3154           /* The O'Reilly COFF book says that defined global symbols
3155              come at the end of the symbol table, just before
3156              undefined global symbols.  */
3157           symbol_remove (symbolP, &symbol_rootP, &symbol_lastP);
3158           symbol_clear_list_pointers (symbolP);
3159           symbol_append (symbolP, symbol_global_lastP, &symbol_globalP,
3160                          &symbol_global_lastP);
3161           symbolP = hold;
3162         }
3163       else
3164         {
3165           if (SF_GET_STRING (symbolP))
3166             {
3167               symbolP->sy_name_offset = string_byte_count;
3168               string_byte_count += strlen (S_GET_NAME (symbolP)) + 1;
3169             }
3170           else
3171             symbolP->sy_name_offset = 0;
3172
3173           symbolP->sy_number = symbol_number;
3174           symbol_number += 1 + S_GET_NUMBER_AUXILIARY (symbolP);
3175         }
3176     }
3177
3178   return symbol_number;
3179 }
3180
3181 static unsigned int
3182 glue_symbols (symbolS **head, symbolS **tail)
3183 {
3184   unsigned int symbol_number = 0;
3185
3186   while (*head != NULL)
3187     {
3188       symbolS *tmp = *head;
3189
3190       /* Append.  */
3191       symbol_remove (tmp, head, tail);
3192       symbol_append (tmp, symbol_lastP, &symbol_rootP, &symbol_lastP);
3193
3194       /* Process.  */
3195       if (SF_GET_STRING (tmp))
3196         {
3197           tmp->sy_name_offset = string_byte_count;
3198           string_byte_count += strlen (S_GET_NAME (tmp)) + 1;
3199         }
3200       else
3201         /* Fix "long" names.  */
3202         tmp->sy_name_offset = 0;
3203
3204       tmp->sy_number = symbol_number;
3205       symbol_number += 1 + S_GET_NUMBER_AUXILIARY (tmp);
3206     }
3207
3208   return symbol_number;
3209 }
3210
3211 static unsigned int
3212 tie_tags (void)
3213 {
3214   unsigned int symbol_number = 0;
3215   symbolS *symbolP;
3216
3217   for (symbolP = symbol_rootP; symbolP; symbolP = symbol_next (symbolP))
3218     {
3219       symbolP->sy_number = symbol_number;
3220
3221       if (SF_GET_TAGGED (symbolP))
3222         {
3223           SA_SET_SYM_TAGNDX
3224             (symbolP,
3225              ((symbolS *) SA_GET_SYM_TAGNDX (symbolP))->sy_number);
3226         }
3227
3228       symbol_number += 1 + S_GET_NUMBER_AUXILIARY (symbolP);
3229     }
3230
3231   return symbol_number;
3232 }
3233
3234
3235 /* Build a 'section static' symbol.  */
3236
3237 static symbolS *
3238 c_section_symbol (char *name, int idx)
3239 {
3240   symbolS *symbolP;
3241
3242   symbolP = symbol_find_base (name, DO_NOT_STRIP);
3243   if (symbolP == NULL)
3244     symbolP = symbol_new (name, idx, 0, &zero_address_frag);
3245   else
3246     {
3247       /* Mmmm.  I just love violating interfaces.  Makes me feel...dirty.  */
3248       S_SET_SEGMENT (symbolP, idx);
3249       symbolP->sy_frag = &zero_address_frag;
3250     }
3251
3252   S_SET_STORAGE_CLASS (symbolP, C_STAT);
3253   S_SET_NUMBER_AUXILIARY (symbolP, 1);
3254
3255   SF_SET_STATICS (symbolP);
3256
3257 #ifdef TE_DELTA
3258   /* manfred@s-direktnet.de: section symbols *must* have the LOCAL bit cleared,
3259      which is set by the new definition of LOCAL_LABEL in tc-m68k.h.  */
3260   SF_CLEAR_LOCAL (symbolP);
3261 #endif
3262 #ifdef TE_PE
3263   /* If the .linkonce pseudo-op was used for this section, we must
3264      store the information in the auxiliary entry for the section
3265      symbol.  */
3266   if (segment_info[idx].linkonce != LINKONCE_UNSET)
3267     {
3268       int type;
3269
3270       switch (segment_info[idx].linkonce)
3271         {
3272         default:
3273           abort ();
3274         case LINKONCE_DISCARD:
3275           type = IMAGE_COMDAT_SELECT_ANY;
3276           break;
3277         case LINKONCE_ONE_ONLY:
3278           type = IMAGE_COMDAT_SELECT_NODUPLICATES;
3279           break;
3280         case LINKONCE_SAME_SIZE:
3281           type = IMAGE_COMDAT_SELECT_SAME_SIZE;
3282           break;
3283         case LINKONCE_SAME_CONTENTS:
3284           type = IMAGE_COMDAT_SELECT_EXACT_MATCH;
3285           break;
3286         }
3287
3288       SYM_AUXENT (symbolP)->x_scn.x_comdat = type;
3289     }
3290 #endif /* TE_PE */
3291
3292   return symbolP;
3293 }
3294
3295 static void
3296 crawl_symbols (object_headers *h, bfd *abfd ATTRIBUTE_UNUSED)
3297 {
3298   unsigned int i;
3299
3300   /* Initialize the stack used to keep track of the matching .bb .be.  */
3301   block_stack = stack_init (512, sizeof (symbolS *));
3302
3303   /* The symbol list should be ordered according to the following sequence
3304      order :
3305      . .file symbol
3306      . debug entries for functions
3307      . fake symbols for the sections, including .text .data and .bss
3308      . defined symbols
3309      . undefined symbols
3310      But this is not mandatory. The only important point is to put the
3311      undefined symbols at the end of the list.  */
3312
3313   /* Is there a .file symbol ? If not insert one at the beginning.  */
3314   if (symbol_rootP == NULL
3315       || S_GET_STORAGE_CLASS (symbol_rootP) != C_FILE)
3316     c_dot_file_symbol ("fake", 0);
3317
3318   /* Build up static symbols for the sections, they are filled in later.  */
3319   for (i = SEG_E0; i < SEG_LAST; i++)
3320     if (segment_info[i].scnhdr.s_name[0])
3321       segment_info[i].dot = c_section_symbol ((char *) segment_info[i].name,
3322                                               i - SEG_E0 + 1);
3323
3324   /* Take all the externals out and put them into another chain.  */
3325   H_SET_SYMBOL_TABLE_SIZE (h, yank_symbols ());
3326   /* Take the externals and glue them onto the end.  */
3327   H_SET_SYMBOL_TABLE_SIZE (h,
3328                            (H_GET_SYMBOL_COUNT (h)
3329                             + glue_symbols (&symbol_globalP,
3330                                             &symbol_global_lastP)
3331                             + glue_symbols (&symbol_externP,
3332                                             &symbol_extern_lastP)));
3333
3334   H_SET_SYMBOL_TABLE_SIZE (h, tie_tags ());
3335   know (symbol_globalP == NULL);
3336   know (symbol_global_lastP == NULL);
3337   know (symbol_externP == NULL);
3338   know (symbol_extern_lastP == NULL);
3339 }
3340
3341 /* Find strings by crawling along symbol table chain.  */
3342
3343 static void
3344 w_strings (char *where)
3345 {
3346   symbolS *symbolP;
3347   struct filename_list *filename_list_scan = filename_list_head;
3348
3349   /* Gotta do md_ byte-ordering stuff for string_byte_count first - KWK.  */
3350   md_number_to_chars (where, (valueT) string_byte_count, 4);
3351   where += 4;
3352
3353 #ifdef COFF_LONG_SECTION_NAMES
3354   /* Support long section names as found in PE.  This code must
3355      coordinate with that in coff_header_append and write_object_file.  */
3356   {
3357     unsigned int i;
3358
3359     for (i = SEG_E0; i < SEG_LAST; i++)
3360       {
3361         if (segment_info[i].scnhdr.s_name[0]
3362             && strlen (segment_info[i].name) > SCNNMLEN)
3363           {
3364             unsigned int size;
3365
3366             size = strlen (segment_info[i].name) + 1;
3367             memcpy (where, segment_info[i].name, size);
3368             where += size;
3369           }
3370       }
3371   }
3372 #endif /* COFF_LONG_SECTION_NAMES */
3373
3374   for (symbolP = symbol_rootP;
3375        symbolP;
3376        symbolP = symbol_next (symbolP))
3377     {
3378       unsigned int size;
3379
3380       if (SF_GET_STRING (symbolP))
3381         {
3382           size = strlen (S_GET_NAME (symbolP)) + 1;
3383           memcpy (where, S_GET_NAME (symbolP), size);
3384           where += size;
3385         }
3386       if (S_GET_STORAGE_CLASS (symbolP) == C_FILE
3387           && SA_GET_FILE_FNAME_ZEROS (symbolP) == 0
3388           && SA_GET_FILE_FNAME_OFFSET (symbolP) != 0)
3389         {
3390           size = strlen (filename_list_scan->filename) + 1;
3391           memcpy (where, filename_list_scan->filename, size);
3392           filename_list_scan = filename_list_scan ->next;
3393           where += size;
3394         }
3395     }
3396 }
3397
3398 static void
3399 do_linenos_for (bfd * abfd,
3400                 object_headers * h,
3401                 unsigned long *file_cursor)
3402 {
3403   unsigned int idx;
3404   unsigned long start = *file_cursor;
3405
3406   for (idx = SEG_E0; idx < SEG_LAST; idx++)
3407     {
3408       segment_info_type *s = segment_info + idx;
3409
3410       if (s->scnhdr.s_nlnno != 0)
3411         {
3412           struct lineno_list *line_ptr;
3413           struct external_lineno *buffer = xmalloc (s->scnhdr.s_nlnno * LINESZ);
3414           struct external_lineno *dst = buffer;
3415
3416           /* Run through the table we've built and turn it into its external
3417              form, take this chance to remove duplicates.  */
3418
3419           for (line_ptr = s->lineno_list_head;
3420                line_ptr != (struct lineno_list *) NULL;
3421                line_ptr = line_ptr->next)
3422             {
3423               if (line_ptr->line.l_lnno == 0)
3424                 {
3425                   /* Turn a pointer to a symbol into the symbols' index,
3426                      provided that it has been initialised.  */
3427                   if (line_ptr->line.l_addr.l_symndx)
3428                     line_ptr->line.l_addr.l_symndx =
3429                       ((symbolS *) line_ptr->line.l_addr.l_symndx)->sy_number;
3430                 }
3431               else
3432                 line_ptr->line.l_addr.l_paddr += ((struct frag *) (line_ptr->frag))->fr_address;
3433
3434               (void) bfd_coff_swap_lineno_out (abfd, &(line_ptr->line), dst);
3435               dst++;
3436             }
3437
3438           s->scnhdr.s_lnnoptr = *file_cursor;
3439
3440           bfd_bwrite (buffer, (bfd_size_type) s->scnhdr.s_nlnno * LINESZ, abfd);
3441           free (buffer);
3442
3443           *file_cursor += s->scnhdr.s_nlnno * LINESZ;
3444         }
3445     }
3446
3447   H_SET_LINENO_SIZE (h, *file_cursor - start);
3448 }
3449
3450 /* Now we run through the list of frag chains in a segment and
3451    make all the subsegment frags appear at the end of the
3452    list, as if the seg 0 was extra long.  */
3453
3454 static void
3455 remove_subsegs (void)
3456 {
3457   unsigned int i;
3458
3459   for (i = SEG_E0; i < SEG_UNKNOWN; i++)
3460     {
3461       frchainS *head = segment_info[i].frchainP;
3462       fragS dummy;
3463       fragS *prev_frag = &dummy;
3464
3465       while (head && head->frch_seg == i)
3466         {
3467           prev_frag->fr_next = head->frch_root;
3468           prev_frag = head->frch_last;
3469           head = head->frch_next;
3470         }
3471       prev_frag->fr_next = 0;
3472     }
3473 }
3474
3475 unsigned long machine;
3476 int coff_flags;
3477
3478 #ifndef SUB_SEGMENT_ALIGN
3479 #ifdef HANDLE_ALIGN
3480 /* The last subsegment gets an alignment corresponding to the alignment
3481    of the section.  This allows proper nop-filling at the end of
3482    code-bearing sections.  */
3483 #define SUB_SEGMENT_ALIGN(SEG, FRCHAIN)                                 \
3484   (!(FRCHAIN)->frch_next || (FRCHAIN)->frch_next->frch_seg != (SEG)     \
3485    ? get_recorded_alignment (SEG) : 0)
3486 #else
3487 #define SUB_SEGMENT_ALIGN(SEG, FRCHAIN) 1
3488 #endif
3489 #endif
3490
3491 static void
3492 w_symbols (bfd * abfd, char *where, symbolS * symbol_rootP)
3493 {
3494   symbolS *symbolP;
3495   unsigned int i;
3496
3497   /* First fill in those values we have only just worked out.  */
3498   for (i = SEG_E0; i < SEG_LAST; i++)
3499     {
3500       symbolP = segment_info[i].dot;
3501       if (symbolP)
3502         {
3503           SA_SET_SCN_SCNLEN (symbolP, segment_info[i].scnhdr.s_size);
3504           SA_SET_SCN_NRELOC (symbolP, segment_info[i].scnhdr.s_nreloc);
3505           SA_SET_SCN_NLINNO (symbolP, segment_info[i].scnhdr.s_nlnno);
3506         }
3507     }
3508
3509   /* Emit all symbols left in the symbol chain.  */
3510   for (symbolP = symbol_rootP; symbolP; symbolP = symbol_next (symbolP))
3511     {
3512       /* Used to save the offset of the name. It is used to point
3513          to the string in memory but must be a file offset.  */
3514       char *temp;
3515
3516       /* We can't fix the lnnoptr field in yank_symbols with the other
3517          adjustments, because we have to wait until we know where they
3518          go in the file.  */
3519       if (SF_GET_ADJ_LNNOPTR (symbolP))
3520         SA_GET_SYM_LNNOPTR (symbolP) +=
3521           segment_info[S_GET_SEGMENT (symbolP)].scnhdr.s_lnnoptr;
3522
3523       tc_coff_symbol_emit_hook (symbolP);
3524
3525       temp = S_GET_NAME (symbolP);
3526       if (SF_GET_STRING (symbolP))
3527         {
3528           S_SET_OFFSET (symbolP, symbolP->sy_name_offset);
3529           S_SET_ZEROES (symbolP, 0);
3530         }
3531       else
3532         {
3533           memset (symbolP->sy_symbol.ost_entry.n_name, 0, SYMNMLEN);
3534           strncpy (symbolP->sy_symbol.ost_entry.n_name, temp, SYMNMLEN);
3535         }
3536       where = symbol_to_chars (abfd, where, symbolP);
3537       S_SET_NAME (symbolP, temp);
3538     }
3539 }
3540
3541 static void
3542 fixup_mdeps (fragS *frags,
3543              object_headers *h ATTRIBUTE_UNUSED,
3544              segT this_segment)
3545 {
3546   subseg_change (this_segment, 0);
3547
3548   while (frags)
3549     {
3550       switch (frags->fr_type)
3551         {
3552         case rs_align:
3553         case rs_align_code:
3554         case rs_align_test:
3555         case rs_org:
3556 #ifdef HANDLE_ALIGN
3557           HANDLE_ALIGN (frags);
3558 #endif
3559           frags->fr_type = rs_fill;
3560           frags->fr_offset =
3561             ((frags->fr_next->fr_address - frags->fr_address - frags->fr_fix)
3562              / frags->fr_var);
3563           break;
3564         case rs_machine_dependent:
3565           md_convert_frag (h, this_segment, frags);
3566           frag_wane (frags);
3567           break;
3568         default:
3569           ;
3570         }
3571       frags = frags->fr_next;
3572     }
3573 }
3574
3575 #ifndef TC_FORCE_RELOCATION
3576 #define TC_FORCE_RELOCATION(fix) 0
3577 #endif
3578
3579 static void
3580 fixup_segment (segment_info_type * segP, segT this_segment_type)
3581 {
3582   fixS * fixP;
3583   symbolS *add_symbolP;
3584   symbolS *sub_symbolP;
3585   long add_number;
3586   int size;
3587   char *place;
3588   long where;
3589   char pcrel;
3590   fragS *fragP;
3591   segT add_symbol_segment = absolute_section;
3592
3593   for (fixP = segP->fix_root; fixP; fixP = fixP->fx_next)
3594     {
3595       fragP = fixP->fx_frag;
3596       know (fragP);
3597       where = fixP->fx_where;
3598       place = fragP->fr_literal + where;
3599       size = fixP->fx_size;
3600       add_symbolP = fixP->fx_addsy;
3601       sub_symbolP = fixP->fx_subsy;
3602       add_number = fixP->fx_offset;
3603       pcrel = fixP->fx_pcrel;
3604
3605       /* We want function-relative stabs to work on systems which
3606          may use a relaxing linker; thus we must handle the sym1-sym2
3607          fixups function-relative stabs generates.
3608
3609          Of course, if you actually enable relaxing in the linker, the
3610          line and block scoping information is going to be incorrect
3611          in some cases.  The only way to really fix this is to support
3612          a reloc involving the difference of two symbols.  */
3613       if (linkrelax
3614           && (!sub_symbolP || pcrel))
3615         continue;
3616
3617 #ifdef TC_I960
3618       if (fixP->fx_tcbit && SF_GET_CALLNAME (add_symbolP))
3619         {
3620           /* Relocation should be done via the associated 'bal' entry
3621              point symbol.  */
3622           if (!SF_GET_BALNAME (tc_get_bal_of_call (add_symbolP)))
3623             {
3624               as_bad_where (fixP->fx_file, fixP->fx_line,
3625                             _("No 'bal' entry point for leafproc %s"),
3626                             S_GET_NAME (add_symbolP));
3627               continue;
3628             }
3629           fixP->fx_addsy = add_symbolP = tc_get_bal_of_call (add_symbolP);
3630         }
3631 #endif
3632
3633       /* Make sure the symbols have been resolved; this may not have
3634          happened if these are expression symbols.  */
3635       if (add_symbolP != NULL && ! add_symbolP->sy_resolved)
3636         resolve_symbol_value (add_symbolP);
3637
3638       if (add_symbolP != NULL)
3639         {
3640           /* If this fixup is against a symbol which has been equated
3641              to another symbol, convert it to the other symbol.  */
3642           if (add_symbolP->sy_value.X_op == O_symbol
3643               && (! S_IS_DEFINED (add_symbolP)
3644                   || S_IS_COMMON (add_symbolP)))
3645             {
3646               while (add_symbolP->sy_value.X_op == O_symbol
3647                      && (! S_IS_DEFINED (add_symbolP)
3648                          || S_IS_COMMON (add_symbolP)))
3649                 {
3650                   symbolS *n;
3651
3652                   /* We must avoid looping, as that can occur with a
3653                      badly written program.  */
3654                   n = add_symbolP->sy_value.X_add_symbol;
3655                   if (n == add_symbolP)
3656                     break;
3657                   add_number += add_symbolP->sy_value.X_add_number;
3658                   add_symbolP = n;
3659                 }
3660               fixP->fx_addsy = add_symbolP;
3661               fixP->fx_offset = add_number;
3662             }
3663         }
3664
3665       if (sub_symbolP != NULL && ! sub_symbolP->sy_resolved)
3666         resolve_symbol_value (sub_symbolP);
3667
3668       if (add_symbolP != NULL
3669           && add_symbolP->sy_mri_common)
3670         {
3671           add_number += S_GET_VALUE (add_symbolP);
3672           fixP->fx_offset = add_number;
3673           add_symbolP = fixP->fx_addsy = add_symbolP->sy_value.X_add_symbol;
3674         }
3675
3676       if (add_symbolP)
3677         add_symbol_segment = S_GET_SEGMENT (add_symbolP);
3678
3679       if (sub_symbolP)
3680         {
3681           if (add_symbolP == NULL || add_symbol_segment == absolute_section)
3682             {
3683               if (add_symbolP != NULL)
3684                 {
3685                   add_number += S_GET_VALUE (add_symbolP);
3686                   add_symbolP = NULL;
3687                   fixP->fx_addsy = NULL;
3688                 }
3689
3690               /* It's just -sym.  */
3691               if (S_GET_SEGMENT (sub_symbolP) == absolute_section)
3692                 {
3693                   add_number -= S_GET_VALUE (sub_symbolP);
3694                   fixP->fx_subsy = 0;
3695                   fixP->fx_done = 1;
3696                 }
3697               else
3698                 {
3699 #ifndef TC_M68K
3700                   as_bad_where (fixP->fx_file, fixP->fx_line,
3701                                 _("Negative of non-absolute symbol %s"),
3702                                 S_GET_NAME (sub_symbolP));
3703 #endif
3704                   add_number -= S_GET_VALUE (sub_symbolP);
3705                 }               /* not absolute */
3706
3707               /* If sub_symbol is in the same segment that add_symbol
3708                  and add_symbol is either in DATA, TEXT, BSS or ABSOLUTE.  */
3709             }
3710           else if (S_GET_SEGMENT (sub_symbolP) == add_symbol_segment
3711                    && SEG_NORMAL (add_symbol_segment))
3712             {
3713               /* Difference of 2 symbols from same segment.  Can't
3714                  make difference of 2 undefineds: 'value' means
3715                  something different for N_UNDF.  */
3716 #ifdef TC_I960
3717               /* Makes no sense to use the difference of 2 arbitrary symbols
3718                  as the target of a call instruction.  */
3719               if (fixP->fx_tcbit)
3720                 as_bad_where (fixP->fx_file, fixP->fx_line,
3721                               _("callj to difference of 2 symbols"));
3722 #endif /* TC_I960 */
3723               add_number += S_GET_VALUE (add_symbolP) -
3724                 S_GET_VALUE (sub_symbolP);
3725               add_symbolP = NULL;
3726
3727               if (!TC_FORCE_RELOCATION (fixP))
3728                 {
3729                   fixP->fx_addsy = NULL;
3730                   fixP->fx_subsy = NULL;
3731                   fixP->fx_done = 1;
3732 #ifdef TC_M68K /* FIXME: Is this right?  */
3733                   pcrel = 0;
3734                   fixP->fx_pcrel = 0;
3735 #endif
3736                 }
3737             }
3738           else
3739             {
3740               /* Different segments in subtraction.  */
3741               know (!(S_IS_EXTERNAL (sub_symbolP) && (S_GET_SEGMENT (sub_symbolP) == absolute_section)));
3742
3743               if ((S_GET_SEGMENT (sub_symbolP) == absolute_section))
3744                 add_number -= S_GET_VALUE (sub_symbolP);
3745
3746 #ifdef DIFF_EXPR_OK
3747               else if (S_GET_SEGMENT (sub_symbolP) == this_segment_type)
3748                 {
3749                   /* Make it pc-relative.  */
3750                   add_number += (md_pcrel_from (fixP)
3751                                  - S_GET_VALUE (sub_symbolP));
3752                   pcrel = 1;
3753                   fixP->fx_pcrel = 1;
3754                   sub_symbolP = 0;
3755                   fixP->fx_subsy = 0;
3756                 }
3757 #endif
3758               else
3759                 {
3760                   as_bad_where (fixP->fx_file, fixP->fx_line,
3761                                 _("Can't emit reloc {- %s-seg symbol \"%s\"} @ file address %ld."),
3762                                 segment_name (S_GET_SEGMENT (sub_symbolP)),
3763                                 S_GET_NAME (sub_symbolP),
3764                                 (long) (fragP->fr_address + where));
3765                 }
3766             }
3767         }
3768
3769       if (add_symbolP)
3770         {
3771           if (add_symbol_segment == this_segment_type && pcrel)
3772             {
3773               /* This fixup was made when the symbol's segment was
3774                  SEG_UNKNOWN, but it is now in the local segment.
3775                  So we know how to do the address without relocation.  */
3776 #ifdef TC_I960
3777               /* reloc_callj() may replace a 'call' with a 'calls' or a 'bal',
3778                  in which cases it modifies *fixP as appropriate.  In the case
3779                  of a 'calls', no further work is required, and *fixP has been
3780                  set up to make the rest of the code below a no-op.  */
3781               reloc_callj (fixP);
3782 #endif
3783
3784               add_number += S_GET_VALUE (add_symbolP);
3785               add_number -= md_pcrel_from (fixP);
3786
3787               /* We used to do
3788                    add_number -= segP->scnhdr.s_vaddr;
3789                  if defined (TC_I386) || defined (TE_LYNX).  I now
3790                  think that was an error propagated from the case when
3791                  we are going to emit the relocation.  If we are not
3792                  going to emit the relocation, then we just want to
3793                  set add_number to the difference between the symbols.
3794                  This is a case that would only arise when there is a
3795                  PC relative reference from a section other than .text
3796                  to a symbol defined in the same section, and the
3797                  reference is not relaxed.  Since jump instructions on
3798                  the i386 are relaxed, this could only arise with a
3799                  call instruction.  */
3800
3801               /* Lie. Don't want further pcrel processing.  */
3802               pcrel = 0;
3803               if (!TC_FORCE_RELOCATION (fixP))
3804                 {
3805                   fixP->fx_addsy = NULL;
3806                   fixP->fx_done = 1;
3807                 }
3808             }
3809           else
3810             {
3811               switch (add_symbol_segment)
3812                 {
3813                 case absolute_section:
3814 #ifdef TC_I960
3815                   /* See comment about reloc_callj() above.  */
3816                   reloc_callj (fixP);
3817 #endif /* TC_I960 */
3818                   add_number += S_GET_VALUE (add_symbolP);
3819                   add_symbolP = NULL;
3820
3821                   if (!TC_FORCE_RELOCATION (fixP))
3822                     {
3823                       fixP->fx_addsy = NULL;
3824                       fixP->fx_done = 1;
3825                     }
3826                   break;
3827                 default:
3828
3829 #if defined(TC_A29K) || (defined(TE_PE) && defined(TC_I386)) || defined(TC_M88K) || defined(TC_OR32)
3830                   /* This really should be handled in the linker, but
3831                      backward compatibility forbids.  */
3832                   add_number += S_GET_VALUE (add_symbolP);
3833 #else
3834                   add_number += S_GET_VALUE (add_symbolP) +
3835                     segment_info[S_GET_SEGMENT (add_symbolP)].scnhdr.s_paddr;
3836 #endif
3837                   break;
3838
3839                 case SEG_UNKNOWN:
3840 #ifdef TC_I960
3841                   if ((int) fixP->fx_bit_fixP == 13)
3842                     {
3843                       /* This is a COBR instruction.  They have only a
3844                          13-bit displacement and are only to be used
3845                          for local branches: flag as error, don't generate
3846                          relocation.  */
3847                       as_bad_where (fixP->fx_file, fixP->fx_line,
3848                                     _("can't use COBR format with external label"));
3849                       fixP->fx_addsy = NULL;
3850                       fixP->fx_done = 1;
3851                       continue;
3852                     }
3853 #endif /* TC_I960 */
3854 #if ((defined (TC_I386) || defined (TE_LYNX) || defined (TE_AUX)) && !defined(TE_PE)) || defined (COFF_COMMON_ADDEND)
3855                   /* 386 COFF uses a peculiar format in which the
3856                      value of a common symbol is stored in the .text
3857                      segment (I've checked this on SVR3.2 and SCO
3858                      3.2.2) Ian Taylor <ian@cygnus.com>.  */
3859                   /* This is also true for 68k COFF on sysv machines
3860                      (Checked on Motorola sysv68 R3V6 and R3V7.1, and also on
3861                      UNIX System V/M68000, Release 1.0 from ATT/Bell Labs)
3862                      Philippe De Muyter <phdm@info.ucl.ac.be>.  */
3863                   if (S_IS_COMMON (add_symbolP))
3864                     add_number += S_GET_VALUE (add_symbolP);
3865 #endif
3866                   break;
3867
3868                 }
3869             }
3870         }
3871
3872       if (pcrel)
3873         {
3874 #if !defined(TC_M88K) && !(defined(TE_PE) && defined(TC_I386)) && !defined(TC_A29K) && !defined(TC_OR32)
3875           /* This adjustment is not correct on the m88k, for which the
3876              linker does all the computation.  */
3877           add_number -= md_pcrel_from (fixP);
3878 #endif
3879           if (add_symbolP == 0)
3880             fixP->fx_addsy = &abs_symbol;
3881 #if defined (TC_I386) || defined (TE_LYNX) || defined (TC_I960) || defined (TC_M68K)
3882           /* On the 386 we must adjust by the segment vaddr as well.
3883              Ian Taylor.
3884
3885              I changed the i960 to work this way as well.  This is
3886              compatible with the current GNU linker behaviour.  I do
3887              not know what other i960 COFF assemblers do.  This is not
3888              a common case: normally, only assembler code will contain
3889              a PC relative reloc, and only branches which do not
3890              originate in the .text section will have a non-zero
3891              address.
3892
3893              I changed the m68k to work this way as well.  This will
3894              break existing PC relative relocs from sections which do
3895              not start at address 0, but it will make ld -r work.
3896              Ian Taylor, 4 Oct 96.  */
3897
3898           add_number -= segP->scnhdr.s_vaddr;
3899 #endif
3900         }
3901
3902       md_apply_fix3 (fixP, (valueT *) & add_number, this_segment_type);
3903
3904       if (!fixP->fx_bit_fixP && ! fixP->fx_no_overflow)
3905         {
3906 #ifndef TC_M88K
3907           /* The m88k uses the offset field of the reloc to get around
3908              this problem.  */
3909           if ((size == 1
3910                && ((add_number & ~0xFF)
3911                    || (fixP->fx_signed && (add_number & 0x80)))
3912                && ((add_number & ~0xFF) != (-1 & ~0xFF)
3913                    || (add_number & 0x80) == 0))
3914               || (size == 2
3915                   && ((add_number & ~0xFFFF)
3916                       || (fixP->fx_signed && (add_number & 0x8000)))
3917                   && ((add_number & ~0xFFFF) != (-1 & ~0xFFFF)
3918                       || (add_number & 0x8000) == 0)))
3919             {
3920               as_bad_where (fixP->fx_file, fixP->fx_line,
3921                             _("Value of %ld too large for field of %d bytes at 0x%lx"),
3922                             (long) add_number, size,
3923                             (unsigned long) (fragP->fr_address + where));
3924             }
3925 #endif
3926 #ifdef WARN_SIGNED_OVERFLOW_WORD
3927           /* Warn if a .word value is too large when treated as a
3928              signed number.  We already know it is not too negative.
3929              This is to catch over-large switches generated by gcc on
3930              the 68k.  */
3931           if (!flag_signed_overflow_ok
3932               && size == 2
3933               && add_number > 0x7fff)
3934             as_bad_where (fixP->fx_file, fixP->fx_line,
3935                           _("Signed .word overflow; switch may be too large; %ld at 0x%lx"),
3936                           (long) add_number,
3937                           (unsigned long) (fragP->fr_address + where));
3938 #endif
3939         }
3940     }
3941 }
3942
3943 /* Fill in the counts in the first entry in a .stab section.  */
3944
3945 static void
3946 adjust_stab_section (bfd *abfd, segT seg)
3947 {
3948   segT stabstrseg = SEG_UNKNOWN;
3949   const char *secname, *name2;
3950   char *name;
3951   char *p = NULL;
3952   int i, strsz = 0, nsyms;
3953   fragS *frag = segment_info[seg].frchainP->frch_root;
3954
3955   /* Look for the associated string table section.  */
3956
3957   secname = segment_info[seg].name;
3958   name = alloca (strlen (secname) + 4);
3959   strcpy (name, secname);
3960   strcat (name, "str");
3961
3962   for (i = SEG_E0; i < SEG_UNKNOWN; i++)
3963     {
3964       name2 = segment_info[i].name;
3965       if (name2 != NULL && strneq (name2, name, 8))
3966         {
3967           stabstrseg = i;
3968           break;
3969         }
3970     }
3971
3972   /* If we found the section, get its size.  */
3973   if (stabstrseg != SEG_UNKNOWN)
3974     strsz = size_section (abfd, stabstrseg);
3975
3976   nsyms = size_section (abfd, seg) / 12 - 1;
3977
3978   /* Look for the first frag of sufficient size for the initial stab
3979      symbol, and collect a pointer to it.  */
3980   while (frag && frag->fr_fix < 12)
3981     frag = frag->fr_next;
3982   assert (frag != 0);
3983   p = frag->fr_literal;
3984   assert (p != 0);
3985
3986   /* Write in the number of stab symbols and the size of the string
3987      table.  */
3988   bfd_h_put_16 (abfd, (bfd_vma) nsyms, (bfd_byte *) p + 6);
3989   bfd_h_put_32 (abfd, (bfd_vma) strsz, (bfd_byte *) p + 8);
3990 }
3991
3992 void
3993 write_object_file (void)
3994 {
3995   int i;
3996   const char *name;
3997   struct frchain *frchain_ptr;
3998   object_headers headers;
3999   unsigned long file_cursor;
4000   bfd *abfd;
4001   unsigned int addr;
4002   abfd = bfd_openw (out_file_name, TARGET_FORMAT);
4003
4004   if (abfd == 0)
4005     {
4006       as_perror (_("FATAL: Can't create %s"), out_file_name);
4007       exit (EXIT_FAILURE);
4008     }
4009   bfd_set_format (abfd, bfd_object);
4010   bfd_set_arch_mach (abfd, BFD_ARCH, machine);
4011
4012   string_byte_count = 4;
4013
4014   /* Run through all the sub-segments and align them up.  Also
4015      close any open frags.  We tack a .fill onto the end of the
4016      frag chain so that any .align's size can be worked by looking
4017      at the next frag.  */
4018   for (frchain_ptr = frchain_root;
4019        frchain_ptr != (struct frchain *) NULL;
4020        frchain_ptr = frchain_ptr->frch_next)
4021     {
4022       int alignment;
4023
4024       subseg_set (frchain_ptr->frch_seg, frchain_ptr->frch_subseg);
4025
4026       alignment = SUB_SEGMENT_ALIGN (now_seg, frchain_ptr);
4027
4028 #ifdef md_do_align
4029       md_do_align (alignment, NULL, 0, 0, alignment_done);
4030 #endif
4031       if (subseg_text_p (now_seg))
4032         frag_align_code (alignment, 0);
4033       else
4034         frag_align (alignment, 0, 0);
4035
4036 #ifdef md_do_align
4037     alignment_done:
4038 #endif
4039
4040       frag_wane (frag_now);
4041       frag_now->fr_fix = 0;
4042       know (frag_now->fr_next == NULL);
4043     }
4044
4045   remove_subsegs ();
4046
4047   for (i = SEG_E0; i < SEG_UNKNOWN; i++)
4048     relax_segment (segment_info[i].frchainP->frch_root, i);
4049
4050   /* Relaxation has completed.  Freeze all syms.  */
4051   finalize_syms = 1;
4052
4053   H_SET_NUMBER_OF_SECTIONS (&headers, 0);
4054
4055   /* Find out how big the sections are, and set the addresses.  */
4056   addr = 0;
4057   for (i = SEG_E0; i < SEG_UNKNOWN; i++)
4058     {
4059       long size;
4060
4061       segment_info[i].scnhdr.s_paddr = addr;
4062       segment_info[i].scnhdr.s_vaddr = addr;
4063
4064       if (segment_info[i].scnhdr.s_name[0])
4065         {
4066           H_SET_NUMBER_OF_SECTIONS (&headers,
4067                                     H_GET_NUMBER_OF_SECTIONS (&headers) + 1);
4068
4069 #ifdef COFF_LONG_SECTION_NAMES
4070           /* Support long section names as found in PE.  This code
4071              must coordinate with that in coff_header_append and
4072              w_strings.  */
4073           {
4074             unsigned int len;
4075
4076             len = strlen (segment_info[i].name);
4077             if (len > SCNNMLEN)
4078               string_byte_count += len + 1;
4079           }
4080 #endif /* COFF_LONG_SECTION_NAMES */
4081         }
4082
4083       size = size_section (abfd, (unsigned int) i);
4084       addr += size;
4085
4086       /* I think the section alignment is only used on the i960; the
4087          i960 needs it, and it should do no harm on other targets.  */
4088 #ifdef ALIGNMENT_IN_S_FLAGS
4089       segment_info[i].scnhdr.s_flags |= (section_alignment[i] & 0xF) << 8;
4090 #else
4091       segment_info[i].scnhdr.s_align = 1 << section_alignment[i];
4092 #endif
4093
4094       if (i == SEG_E0)
4095         H_SET_TEXT_SIZE (&headers, size);
4096       else if (i == SEG_E1)
4097         H_SET_DATA_SIZE (&headers, size);
4098       else if (i == SEG_E2)
4099         H_SET_BSS_SIZE (&headers, size);
4100     }
4101
4102   /* Turn the gas native symbol table shape into a coff symbol table.  */
4103   crawl_symbols (&headers, abfd);
4104
4105   if (string_byte_count == 4)
4106     string_byte_count = 0;
4107
4108   H_SET_STRING_SIZE (&headers, string_byte_count);
4109
4110 #ifdef tc_frob_file
4111   tc_frob_file ();
4112 #endif
4113
4114   for (i = SEG_E0; i < SEG_UNKNOWN; i++)
4115     {
4116       fixup_mdeps (segment_info[i].frchainP->frch_root, &headers, i);
4117       fixup_segment (&segment_info[i], i);
4118     }
4119
4120   /* Look for ".stab" segments and fill in their initial symbols
4121      correctly.  */
4122   for (i = SEG_E0; i < SEG_UNKNOWN; i++)
4123     {
4124       name = segment_info[i].name;
4125
4126       if (name != NULL
4127           && strneq (".stab", name, 5)
4128           && ! strneq (".stabstr", name, 8))
4129         adjust_stab_section (abfd, i);
4130     }
4131
4132   file_cursor = H_GET_TEXT_FILE_OFFSET (&headers);
4133
4134   bfd_seek (abfd, (file_ptr) file_cursor, 0);
4135
4136   /* Plant the data.  */
4137   fill_section (abfd, &headers, &file_cursor);
4138
4139   do_relocs_for (abfd, &headers, &file_cursor);
4140
4141   do_linenos_for (abfd, &headers, &file_cursor);
4142
4143   H_SET_FILE_MAGIC_NUMBER (&headers, COFF_MAGIC);
4144 #ifndef OBJ_COFF_OMIT_TIMESTAMP
4145   H_SET_TIME_STAMP (&headers, (long) time (NULL));
4146 #else
4147   H_SET_TIME_STAMP (&headers, 0);
4148 #endif
4149 #ifdef TC_COFF_SET_MACHINE
4150   TC_COFF_SET_MACHINE (&headers);
4151 #endif
4152
4153 #ifndef COFF_FLAGS
4154 #define COFF_FLAGS 0
4155 #endif
4156
4157 #ifdef KEEP_RELOC_INFO
4158   H_SET_FLAGS (&headers, ((H_GET_LINENO_SIZE (&headers) ? 0 : F_LNNO) |
4159                           COFF_FLAGS | coff_flags));
4160 #else
4161   H_SET_FLAGS (&headers, ((H_GET_LINENO_SIZE (&headers)     ? 0 : F_LNNO)   |
4162                           (H_GET_RELOCATION_SIZE (&headers) ? 0 : F_RELFLG) |
4163                           COFF_FLAGS | coff_flags));
4164 #endif
4165
4166   {
4167     unsigned int symtable_size = H_GET_SYMBOL_TABLE_SIZE (&headers);
4168     char *buffer1 = xmalloc (symtable_size + string_byte_count + 1);
4169
4170     H_SET_SYMBOL_TABLE_POINTER (&headers, bfd_tell (abfd));
4171     w_symbols (abfd, buffer1, symbol_rootP);
4172     if (string_byte_count > 0)
4173       w_strings (buffer1 + symtable_size);
4174     bfd_bwrite (buffer1, (bfd_size_type) symtable_size + string_byte_count,
4175                 abfd);
4176     free (buffer1);
4177   }
4178
4179   coff_header_append (abfd, &headers);
4180
4181   {
4182     extern bfd *stdoutput;
4183     stdoutput = abfd;
4184   }
4185 }
4186
4187 /* Add a new segment.  This is called from subseg_new via the
4188    obj_new_segment macro.  */
4189
4190 segT
4191 obj_coff_add_segment (const char *name)
4192 {
4193   unsigned int i;
4194
4195 #ifndef COFF_LONG_SECTION_NAMES
4196   char buf[SCNNMLEN + 1];
4197
4198   strncpy (buf, name, SCNNMLEN);
4199   buf[SCNNMLEN] = '\0';
4200   name = buf;
4201 #endif
4202
4203   for (i = SEG_E0; i < SEG_LAST && segment_info[i].scnhdr.s_name[0]; i++)
4204     if (streq (name, segment_info[i].name))
4205       return (segT) i;
4206
4207   if (i == SEG_LAST)
4208     {
4209       as_bad (_("Too many new sections; can't add \"%s\""), name);
4210       return now_seg;
4211     }
4212
4213   /* Add a new section.  */
4214   strncpy (segment_info[i].scnhdr.s_name, name,
4215            sizeof (segment_info[i].scnhdr.s_name));
4216   segment_info[i].scnhdr.s_flags = STYP_REG;
4217   segment_info[i].name = xstrdup (name);
4218
4219   return (segT) i;
4220 }
4221
4222 /* Implement the .section pseudo op:
4223         .section name {, "flags"}
4224                   ^         ^
4225                   |         +--- optional flags: 'b' for bss
4226                   |                              'i' for info
4227                   +-- section name               'l' for lib
4228                                                  'n' for noload
4229                                                  'o' for over
4230                                                  'w' for data
4231                                                  'd' (apparently m88k for data)
4232                                                  'x' for text
4233                                                  'r' for read-only data
4234    But if the argument is not a quoted string, treat it as a
4235    subsegment number.  */
4236
4237 void
4238 obj_coff_section (int ignore ATTRIBUTE_UNUSED)
4239 {
4240   /* Strip out the section name.  */
4241   char *section_name, *name;
4242   char c;
4243   unsigned int exp;
4244   long flags;
4245
4246   if (flag_mri)
4247     {
4248       char type;
4249
4250       s_mri_sect (&type);
4251       flags = 0;
4252       if (type == 'C')
4253         flags = STYP_TEXT;
4254       else if (type == 'D')
4255         flags = STYP_DATA;
4256       segment_info[now_seg].scnhdr.s_flags |= flags;
4257
4258       return;
4259     }
4260
4261   section_name = input_line_pointer;
4262   c = get_symbol_end ();
4263
4264   name = xmalloc (input_line_pointer - section_name + 1);
4265   strcpy (name, section_name);
4266
4267   *input_line_pointer = c;
4268
4269   exp = 0;
4270   flags = 0;
4271
4272   SKIP_WHITESPACE ();
4273   if (*input_line_pointer == ',')
4274     {
4275       ++input_line_pointer;
4276       SKIP_WHITESPACE ();
4277
4278       if (*input_line_pointer != '"')
4279         exp = get_absolute_expression ();
4280       else
4281         {
4282           ++input_line_pointer;
4283           while (*input_line_pointer != '"'
4284                  && ! is_end_of_line[(unsigned char) *input_line_pointer])
4285             {
4286               switch (*input_line_pointer)
4287                 {
4288                 case 'b': flags |= STYP_BSS;    break;
4289                 case 'i': flags |= STYP_INFO;   break;
4290                 case 'l': flags |= STYP_LIB;    break;
4291                 case 'n': flags |= STYP_NOLOAD; break;
4292                 case 'o': flags |= STYP_OVER;   break;
4293                 case 'd':
4294                 case 'w': flags |= STYP_DATA;   break;
4295                 case 'x': flags |= STYP_TEXT;   break;
4296                 case 'r': flags |= STYP_LIT;    break;
4297                 default:
4298                   as_warn (_("unknown section attribute '%c'"),
4299                            *input_line_pointer);
4300                   break;
4301                 }
4302               ++input_line_pointer;
4303             }
4304           if (*input_line_pointer == '"')
4305             ++input_line_pointer;
4306         }
4307     }
4308
4309   subseg_new (name, (subsegT) exp);
4310
4311   segment_info[now_seg].scnhdr.s_flags |= flags;
4312
4313   demand_empty_rest_of_line ();
4314 }
4315
4316 static void
4317 obj_coff_text (int ignore ATTRIBUTE_UNUSED)
4318 {
4319   subseg_new (".text", get_absolute_expression ());
4320 }
4321
4322 static void
4323 obj_coff_data (int ignore ATTRIBUTE_UNUSED)
4324 {
4325   if (flag_readonly_data_in_text)
4326     subseg_new (".text", get_absolute_expression () + 1000);
4327   else
4328     subseg_new (".data", get_absolute_expression ());
4329 }
4330
4331 static void
4332 obj_coff_ident (int ignore ATTRIBUTE_UNUSED)
4333 {
4334   segT current_seg = now_seg;           /* Save current seg.  */
4335   subsegT current_subseg = now_subseg;
4336
4337   subseg_new (".comment", 0);           /* .comment seg.  */
4338   stringer (1);                         /* Read string.  */
4339   subseg_set (current_seg, current_subseg);     /* Restore current seg.  */
4340 }
4341
4342 void
4343 c_dot_file_symbol (const char *filename, int appfile ATTRIBUTE_UNUSED)
4344 {
4345   symbolS *symbolP;
4346
4347   symbolP = symbol_new (".file", SEG_DEBUG, 0, & zero_address_frag);
4348
4349   S_SET_STORAGE_CLASS (symbolP, C_FILE);
4350   S_SET_NUMBER_AUXILIARY (symbolP, 1);
4351
4352   if (strlen (filename) > FILNMLEN)
4353     {
4354       /* Filename is too long to fit into an auxent,
4355          we stick it into the string table instead.  We keep
4356          a linked list of the filenames we find so we can emit
4357          them later.  */
4358       struct filename_list *f = xmalloc (sizeof (* f));
4359
4360       f->filename = filename;
4361       f->next = 0;
4362
4363       SA_SET_FILE_FNAME_ZEROS (symbolP, 0);
4364       SA_SET_FILE_FNAME_OFFSET (symbolP, 1);
4365
4366       if (filename_list_tail)
4367         filename_list_tail->next = f;
4368       else
4369         filename_list_head = f;
4370       filename_list_tail = f;
4371     }
4372   else
4373     SA_SET_FILE_FNAME (symbolP, filename);
4374
4375 #ifndef NO_LISTING
4376   {
4377     extern int listing;
4378     if (listing)
4379       listing_source_file (filename);
4380   }
4381 #endif
4382
4383   SF_SET_DEBUG (symbolP);
4384   S_SET_VALUE (symbolP, (valueT) previous_file_symbol);
4385
4386   previous_file_symbol = symbolP;
4387
4388   /* Make sure that the symbol is first on the symbol chain.  */
4389   if (symbol_rootP != symbolP)
4390     {
4391       symbol_remove (symbolP, &symbol_rootP, &symbol_lastP);
4392       symbol_insert (symbolP, symbol_rootP, &symbol_rootP, &symbol_lastP);
4393     }
4394 }
4395
4396 static void
4397 obj_coff_lcomm (int ignore ATTRIBUTE_UNUSED)
4398 {
4399   s_lcomm (0);
4400   return;
4401 }
4402
4403 /* The first entry in a .stab section is special.  */
4404
4405 void
4406 obj_coff_init_stab_section (segT seg)
4407 {
4408   char *file;
4409   char *p;
4410   char *stabstr_name;
4411   unsigned int stroff;
4412
4413   /* Make space for this first symbol.  */
4414   p = frag_more (12);
4415   /* Zero it out.  */
4416   memset (p, 0, 12);
4417   as_where (&file, (unsigned int *) NULL);
4418   stabstr_name = alloca (strlen (segment_info[seg].name) + 4);
4419   strcpy (stabstr_name, segment_info[seg].name);
4420   strcat (stabstr_name, "str");
4421   stroff = get_stab_string_offset (file, stabstr_name);
4422   know (stroff == 1);
4423   md_number_to_chars (p, stroff, 4);
4424 }
4425
4426 #endif /* not BFD_ASSEMBLER */
4427
4428 const pseudo_typeS coff_pseudo_table[] =
4429 {
4430   {"ABORT", s_abort, 0},
4431   {"appline", obj_coff_ln, 1},
4432   /* We accept the .bss directive for backward compatibility with
4433      earlier versions of gas.  */
4434   {"bss", obj_coff_bss, 0},
4435   {"def", obj_coff_def, 0},
4436   {"dim", obj_coff_dim, 0},
4437   {"endef", obj_coff_endef, 0},
4438   {"ident", obj_coff_ident, 0},
4439   {"line", obj_coff_line, 0},
4440   {"ln", obj_coff_ln, 0},
4441   {"scl", obj_coff_scl, 0},
4442   {"sect", obj_coff_section, 0},
4443   {"sect.s", obj_coff_section, 0},
4444   {"section", obj_coff_section, 0},
4445   {"section.s", obj_coff_section, 0},
4446   /* FIXME: We ignore the MRI short attribute.  */
4447   {"size", obj_coff_size, 0},
4448   {"tag", obj_coff_tag, 0},
4449   {"type", obj_coff_type, 0},
4450   {"val", obj_coff_val, 0},
4451   {"version", s_ignore, 0},
4452 #ifdef BFD_ASSEMBLER
4453   {"loc", obj_coff_loc, 0},
4454   {"optim", s_ignore, 0},       /* For sun386i cc (?) */
4455   {"weak", obj_coff_weak, 0},
4456 #else
4457   {"data", obj_coff_data, 0},
4458   {"lcomm", obj_coff_lcomm, 0},
4459   {"text", obj_coff_text, 0},
4460   {"use", obj_coff_section, 0},
4461 #endif
4462 #if defined TC_M88K || defined TC_TIC4X
4463   /* The m88k and tic4x uses sdef instead of def.  */
4464   {"sdef", obj_coff_def, 0},
4465 #endif
4466   {NULL, NULL, 0}
4467 };
4468 \f
4469 #ifdef BFD_ASSEMBLER
4470
4471 /* Support for a COFF emulation.  */
4472
4473 static void
4474 coff_pop_insert (void)
4475 {
4476   pop_insert (coff_pseudo_table);
4477 }
4478
4479 static int
4480 coff_separate_stab_sections (void)
4481 {
4482   return 1;
4483 }
4484
4485 const struct format_ops coff_format_ops =
4486 {
4487   bfd_target_coff_flavour,
4488   0,    /* dfl_leading_underscore */
4489   1,    /* emit_section_symbols */
4490   0,    /* begin */
4491   c_dot_file_symbol,
4492   coff_frob_symbol,
4493   0,    /* frob_file */
4494   0,    /* frob_file_before_adjust */
4495   0,    /* frob_file_before_fix */
4496   coff_frob_file_after_relocs,
4497   0,    /* s_get_size */
4498   0,    /* s_set_size */
4499   0,    /* s_get_align */
4500   0,    /* s_set_align */
4501   0,    /* s_get_other */
4502   0,    /* s_set_other */
4503   0,    /* s_get_desc */
4504   0,    /* s_set_desc */
4505   0,    /* s_get_type */
4506   0,    /* s_set_type */
4507   0,    /* copy_symbol_attributes */
4508   0,    /* generate_asm_lineno */
4509   0,    /* process_stab */
4510   coff_separate_stab_sections,
4511   obj_coff_init_stab_section,
4512   0,    /* sec_sym_ok_for_reloc */
4513   coff_pop_insert,
4514   0,    /* ecoff_set_ext */
4515   coff_obj_read_begin_hook,
4516   coff_obj_symbol_new_hook
4517 };
4518
4519 #endif