OSDN Git Service

* sibcall-1.c (track): Mark noinline.
[pf3gnuchains/gcc-fork.git] / gcc / mips-tfile.c
1 /* Update the symbol table (the .T file) in a MIPS object to
2    contain debugging information specified by the GNU compiler
3    in the form of comments (the mips assembler does not support
4    assembly access to debug information).
5    Copyright (C) 1991, 1993, 1994, 1995, 1997, 1998, 1999, 2000, 2001,
6    2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009
7    Free Software Foundation, Inc.
8    Contributed by Michael Meissner (meissner@cygnus.com).
9
10 This file is part of GCC.
11
12 GCC is free software; you can redistribute it and/or modify it under
13 the terms of the GNU General Public License as published by the Free
14 Software Foundation; either version 3, or (at your option) any later
15 version.
16
17 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
18 WARRANTY; without even the implied warranty of MERCHANTABILITY or
19 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
20 for more details.
21
22 You should have received a copy of the GNU General Public License
23 along with GCC; see the file COPYING3.  If not see
24 <http://www.gnu.org/licenses/>.  */
25
26 \f
27 /* Here is a brief description of the MIPS ECOFF symbol table.  The
28    MIPS symbol table has the following pieces:
29
30         Symbolic Header
31             |
32             +-- Auxiliary Symbols
33             |
34             +-- Dense number table
35             |
36             +-- Optimizer Symbols
37             |
38             +-- External Strings
39             |
40             +-- External Symbols
41             |
42             +-- Relative file descriptors
43             |
44             +-- File table
45                     |
46                     +-- Procedure table
47                     |
48                     +-- Line number table
49                     |
50                     +-- Local Strings
51                     |
52                     +-- Local Symbols
53
54    The symbolic header points to each of the other tables, and also
55    contains the number of entries.  It also contains a magic number
56    and MIPS compiler version number, such as 2.0.
57
58    The auxiliary table is a series of 32 bit integers, that are
59    referenced as needed from the local symbol table.  Unlike standard
60    COFF, the aux. information does not follow the symbol that uses
61    it, but rather is a separate table.  In theory, this would allow
62    the MIPS compilers to collapse duplicate aux. entries, but I've not
63    noticed this happening with the 1.31 compiler suite.  The different
64    types of aux. entries are:
65
66     1)  dnLow: Low bound on array dimension.
67
68     2)  dnHigh: High bound on array dimension.
69
70     3)  isym: Index to the local symbol which is the start of the
71         function for the end of function first aux. entry.
72
73     4)  width: Width of structures and bitfields.
74
75     5)  count: Count of ranges for variant part.
76
77     6)  rndx: A relative index into the symbol table.  The relative
78         index field has two parts: rfd which is a pointer into the
79         relative file index table or ST_RFDESCAPE which says the next
80         aux. entry is the file number, and index: which is the pointer
81         into the local symbol within a given file table.  This is for
82         things like references to types defined in another file.
83
84     7)  Type information: This is like the COFF type bits, except it
85         is 32 bits instead of 16; they still have room to add new
86         basic types; and they can handle more than 6 levels of array,
87         pointer, function, etc.  Each type information field contains
88         the following structure members:
89
90             a)  fBitfield: a bit that says this is a bitfield, and the
91                 size in bits follows as the next aux. entry.
92
93             b)  continued: a bit that says the next aux. entry is a
94                 continuation of the current type information (in case
95                 there are more than 6 levels of array/ptr/function).
96
97             c)  bt: an integer containing the base type before adding
98                 array, pointer, function, etc. qualifiers.  The
99                 current base types that I have documentation for are:
100
101                         btNil           -- undefined
102                         btAdr           -- address - integer same size as ptr
103                         btChar          -- character
104                         btUChar         -- unsigned character
105                         btShort         -- short
106                         btUShort        -- unsigned short
107                         btInt           -- int
108                         btUInt          -- unsigned int
109                         btLong          -- long
110                         btULong         -- unsigned long
111                         btFloat         -- float (real)
112                         btDouble        -- Double (real)
113                         btStruct        -- Structure (Record)
114                         btUnion         -- Union (variant)
115                         btEnum          -- Enumerated
116                         btTypedef       -- defined via a typedef isymRef
117                         btRange         -- subrange of int
118                         btSet           -- pascal sets
119                         btComplex       -- fortran complex
120                         btDComplex      -- fortran double complex
121                         btIndirect      -- forward or unnamed typedef
122                         btFixedDec      -- Fixed Decimal
123                         btFloatDec      -- Float Decimal
124                         btString        -- Varying Length Character String
125                         btBit           -- Aligned Bit String
126                         btPicture       -- Picture
127                         btVoid          -- Void (MIPS cc revision >= 2.00)
128
129             d)  tq0 - tq5: type qualifier fields as needed.  The
130                 current type qualifier fields I have documentation for
131                 are:
132
133                         tqNil           -- no more qualifiers
134                         tqPtr           -- pointer
135                         tqProc          -- procedure
136                         tqArray         -- array
137                         tqFar           -- 8086 far pointers
138                         tqVol           -- volatile
139
140
141    The dense number table is used in the front ends, and disappears by
142    the time the .o is created.
143
144    With the 1.31 compiler suite, the optimization symbols don't seem
145    to be used as far as I can tell.
146
147    The linker is the first entity that creates the relative file
148    descriptor table, and I believe it is used so that the individual
149    file table pointers don't have to be rewritten when the objects are
150    merged together into the program file.
151
152    Unlike COFF, the basic symbol & string tables are split into
153    external and local symbols/strings.  The relocation information
154    only goes off of the external symbol table, and the debug
155    information only goes off of the internal symbol table.  The
156    external symbols can have links to an appropriate file index and
157    symbol within the file to give it the appropriate type information.
158    Because of this, the external symbols are actually larger than the
159    internal symbols (to contain the link information), and contain the
160    local symbol structure as a member, though this member is not the
161    first member of the external symbol structure (!).  I suspect this
162    split is to make strip easier to deal with.
163
164    Each file table has offsets for where the line numbers, local
165    strings, local symbols, and procedure table starts from within the
166    global tables, and the indices are reset to 0 for each of those
167    tables for the file.
168
169    The procedure table contains the binary equivalents of the .ent
170    (start of the function address), .frame (what register is the
171    virtual frame pointer, constant offset from the register to obtain
172    the VFP, and what register holds the return address), .mask/.fmask
173    (bitmask of saved registers, and where the first register is stored
174    relative to the VFP) assembler directives.  It also contains the
175    low and high bounds of the line numbers if debugging is turned on.
176
177    The line number table is a compressed form of the normal COFF line
178    table.  Each line number entry is either 1 or 3 bytes long, and
179    contains a signed delta from the previous line, and an unsigned
180    count of the number of instructions this statement takes.
181
182    The local symbol table contains the following fields:
183
184     1)  iss: index to the local string table giving the name of the
185         symbol.
186
187     2)  value: value of the symbol (address, register number, etc.).
188
189     3)  st: symbol type.  The current symbol types are:
190
191             stNil         -- Nuthin' special
192             stGlobal      -- external symbol
193             stStatic      -- static
194             stParam       -- procedure argument
195             stLocal       -- local variable
196             stLabel       -- label
197             stProc        -- External Procedure
198             stBlock       -- beginning of block
199             stEnd         -- end (of anything)
200             stMember      -- member (of anything)
201             stTypedef     -- type definition
202             stFile        -- file name
203             stRegReloc    -- register relocation
204             stForward     -- forwarding address
205             stStaticProc  -- Static procedure
206             stConstant    -- const
207
208     4)  sc: storage class.  The current storage classes are:
209
210             scText        -- text symbol
211             scData        -- initialized data symbol
212             scBss         -- un-initialized data symbol
213             scRegister    -- value of symbol is register number
214             scAbs         -- value of symbol is absolute
215             scUndefined   -- who knows?
216             scCdbLocal    -- variable's value is IN se->va.??
217             scBits        -- this is a bit field
218             scCdbSystem   -- value is IN debugger's address space
219             scRegImage    -- register value saved on stack
220             scInfo        -- symbol contains debugger information
221             scUserStruct  -- addr in struct user for current process
222             scSData       -- load time only small data
223             scSBss        -- load time only small common
224             scRData       -- load time only read only data
225             scVar         -- Var parameter (fortranpascal)
226             scCommon      -- common variable
227             scSCommon     -- small common
228             scVarRegister -- Var parameter in a register
229             scVariant     -- Variant record
230             scSUndefined  -- small undefined(external) data
231             scInit        -- .init section symbol
232
233     5)  index: pointer to a local symbol or aux. entry.
234
235
236
237    For the following program:
238
239         #include <stdio.h>
240
241         main(){
242                 printf("Hello World!\n");
243                 return 0;
244         }
245
246    Mips-tdump produces the following information:
247
248    Global file header:
249        magic number             0x162
250        # sections               2
251        timestamp                645311799, Wed Jun 13 17:16:39 1990
252        symbolic header offset   284
253        symbolic header size     96
254        optional header          56
255        flags                    0x0
256
257    Symbolic header, magic number = 0x7009, vstamp = 1.31:
258
259        Info                      Offset      Number       Bytes
260        ====                      ======      ======      =====
261
262        Line numbers                 380           4           4 [13]
263        Dense numbers                  0           0           0
264        Procedures Tables            384           1          52
265        Local Symbols                436          16         192
266        Optimization Symbols           0           0           0
267        Auxiliary Symbols            628          39         156
268        Local Strings                784          80          80
269        External Strings             864         144         144
270        File Tables                 1008           2         144
271        Relative Files                 0           0           0
272        External Symbols            1152          20         320
273
274    File #0, "hello2.c"
275
276        Name index  = 1          Readin      = No
277        Merge       = No         Endian      = LITTLE
278        Debug level = G2         Language    = C
279        Adr         = 0x00000000
280
281        Info                       Start      Number        Size      Offset
282        ====                       =====      ======        ====      ======
283        Local strings                  0          15          15         784
284        Local symbols                  0           6          72         436
285        Line numbers                   0          13          13         380
286        Optimization symbols           0           0           0           0
287        Procedures                     0           1          52         384
288        Auxiliary symbols              0          14          56         628
289        Relative Files                 0           0           0           0
290
291     There are 6 local symbols, starting at 436
292
293         Symbol# 0: "hello2.c"
294             End+1 symbol  = 6
295             String index  = 1
296             Storage class = Text        Index  = 6
297             Symbol type   = File        Value  = 0
298
299         Symbol# 1: "main"
300             End+1 symbol  = 5
301             Type          = int
302             String index  = 10
303             Storage class = Text        Index  = 12
304             Symbol type   = Proc        Value  = 0
305
306         Symbol# 2: ""
307             End+1 symbol  = 4
308             String index  = 0
309             Storage class = Text        Index  = 4
310             Symbol type   = Block       Value  = 8
311
312         Symbol# 3: ""
313             First symbol  = 2
314             String index  = 0
315             Storage class = Text        Index  = 2
316             Symbol type   = End         Value  = 28
317
318         Symbol# 4: "main"
319             First symbol  = 1
320             String index  = 10
321             Storage class = Text        Index  = 1
322             Symbol type   = End         Value  = 52
323
324         Symbol# 5: "hello2.c"
325             First symbol  = 0
326             String index  = 1
327             Storage class = Text        Index  = 0
328             Symbol type   = End         Value  = 0
329
330     There are 14 auxiliary table entries, starting at 628.
331
332         * #0               0, [   0/      0], [ 0 0:0 0:0:0:0:0:0]
333         * #1              24, [  24/      0], [ 6 0:0 0:0:0:0:0:0]
334         * #2               8, [   8/      0], [ 2 0:0 0:0:0:0:0:0]
335         * #3              16, [  16/      0], [ 4 0:0 0:0:0:0:0:0]
336         * #4              24, [  24/      0], [ 6 0:0 0:0:0:0:0:0]
337         * #5              32, [  32/      0], [ 8 0:0 0:0:0:0:0:0]
338         * #6              40, [  40/      0], [10 0:0 0:0:0:0:0:0]
339         * #7              44, [  44/      0], [11 0:0 0:0:0:0:0:0]
340         * #8              12, [  12/      0], [ 3 0:0 0:0:0:0:0:0]
341         * #9              20, [  20/      0], [ 5 0:0 0:0:0:0:0:0]
342         * #10             28, [  28/      0], [ 7 0:0 0:0:0:0:0:0]
343         * #11             36, [  36/      0], [ 9 0:0 0:0:0:0:0:0]
344           #12              5, [   5/      0], [ 1 1:0 0:0:0:0:0:0]
345           #13             24, [  24/      0], [ 6 0:0 0:0:0:0:0:0]
346
347     There are 1 procedure descriptor entries, starting at 0.
348
349         Procedure descriptor 0:
350             Name index   = 10          Name          = "main"
351             .mask 0x80000000,-4        .fmask 0x00000000,0
352             .frame $29,24,$31
353             Opt. start   = -1          Symbols start = 1
354             First line # = 3           Last line #   = 6
355             Line Offset  = 0           Address       = 0x00000000
356
357         There are 4 bytes holding line numbers, starting at 380.
358             Line           3,   delta     0,   count  2
359             Line           4,   delta     1,   count  3
360             Line           5,   delta     1,   count  2
361             Line           6,   delta     1,   count  6
362
363    File #1, "/usr/include/stdio.h"
364
365     Name index  = 1          Readin      = No
366     Merge       = Yes        Endian      = LITTLE
367     Debug level = G2         Language    = C
368     Adr         = 0x00000000
369
370     Info                       Start      Number        Size      Offset
371     ====                       =====      ======        ====      ======
372     Local strings                 15          65          65         799
373     Local symbols                  6          10         120         508
374     Line numbers                   0           0           0         380
375     Optimization symbols           0           0           0           0
376     Procedures                     1           0           0         436
377     Auxiliary symbols             14          25         100         684
378     Relative Files                 0           0           0           0
379
380     There are 10 local symbols, starting at 442
381
382         Symbol# 0: "/usr/include/stdio.h"
383             End+1 symbol  = 10
384             String index  = 1
385             Storage class = Text        Index  = 10
386             Symbol type   = File        Value  = 0
387
388         Symbol# 1: "_iobuf"
389             End+1 symbol  = 9
390             String index  = 22
391             Storage class = Info        Index  = 9
392             Symbol type   = Block       Value  = 20
393
394         Symbol# 2: "_cnt"
395             Type          = int
396             String index  = 29
397             Storage class = Info        Index  = 4
398             Symbol type   = Member      Value  = 0
399
400         Symbol# 3: "_ptr"
401             Type          = ptr to char
402             String index  = 34
403             Storage class = Info        Index  = 15
404             Symbol type   = Member      Value  = 32
405
406         Symbol# 4: "_base"
407             Type          = ptr to char
408             String index  = 39
409             Storage class = Info        Index  = 16
410             Symbol type   = Member      Value  = 64
411
412         Symbol# 5: "_bufsiz"
413             Type          = int
414             String index  = 45
415             Storage class = Info        Index  = 4
416             Symbol type   = Member      Value  = 96
417
418         Symbol# 6: "_flag"
419             Type          = short
420             String index  = 53
421             Storage class = Info        Index  = 3
422             Symbol type   = Member      Value  = 128
423
424         Symbol# 7: "_file"
425             Type          = char
426             String index  = 59
427             Storage class = Info        Index  = 2
428             Symbol type   = Member      Value  = 144
429
430         Symbol# 8: ""
431             First symbol  = 1
432             String index  = 0
433             Storage class = Info        Index  = 1
434             Symbol type   = End         Value  = 0
435
436         Symbol# 9: "/usr/include/stdio.h"
437             First symbol  = 0
438             String index  = 1
439             Storage class = Text        Index  = 0
440             Symbol type   = End         Value  = 0
441
442     There are 25 auxiliary table entries, starting at 642.
443
444         * #14             -1, [4095/1048575], [63 1:1 f:f:f:f:f:f]
445           #15          65544, [   8/     16], [ 2 0:0 1:0:0:0:0:0]
446           #16          65544, [   8/     16], [ 2 0:0 1:0:0:0:0:0]
447         * #17         196656, [  48/     48], [12 0:0 3:0:0:0:0:0]
448         * #18           8191, [4095/      1], [63 1:1 0:0:0:0:f:1]
449         * #19              1, [   1/      0], [ 0 1:0 0:0:0:0:0:0]
450         * #20          20479, [4095/      4], [63 1:1 0:0:0:0:f:4]
451         * #21              1, [   1/      0], [ 0 1:0 0:0:0:0:0:0]
452         * #22              0, [   0/      0], [ 0 0:0 0:0:0:0:0:0]
453         * #23              2, [   2/      0], [ 0 0:1 0:0:0:0:0:0]
454         * #24            160, [ 160/      0], [40 0:0 0:0:0:0:0:0]
455         * #25              0, [   0/      0], [ 0 0:0 0:0:0:0:0:0]
456         * #26              0, [   0/      0], [ 0 0:0 0:0:0:0:0:0]
457         * #27              0, [   0/      0], [ 0 0:0 0:0:0:0:0:0]
458         * #28              0, [   0/      0], [ 0 0:0 0:0:0:0:0:0]
459         * #29              0, [   0/      0], [ 0 0:0 0:0:0:0:0:0]
460         * #30              0, [   0/      0], [ 0 0:0 0:0:0:0:0:0]
461         * #31              0, [   0/      0], [ 0 0:0 0:0:0:0:0:0]
462         * #32              0, [   0/      0], [ 0 0:0 0:0:0:0:0:0]
463         * #33              0, [   0/      0], [ 0 0:0 0:0:0:0:0:0]
464         * #34              0, [   0/      0], [ 0 0:0 0:0:0:0:0:0]
465         * #35              0, [   0/      0], [ 0 0:0 0:0:0:0:0:0]
466         * #36              0, [   0/      0], [ 0 0:0 0:0:0:0:0:0]
467         * #37              0, [   0/      0], [ 0 0:0 0:0:0:0:0:0]
468         * #38              0, [   0/      0], [ 0 0:0 0:0:0:0:0:0]
469
470     There are 0 procedure descriptor entries, starting at 1.
471
472    There are 20 external symbols, starting at 1152
473
474         Symbol# 0: "_iob"
475             Type          = array [3 {160}] of struct _iobuf { ifd = 1, index = 1 }
476             String index  = 0           Ifd    = 1
477             Storage class = Nil         Index  = 17
478             Symbol type   = Global      Value  = 60
479
480         Symbol# 1: "fopen"
481             String index  = 5           Ifd    = 1
482             Storage class = Nil         Index  = 1048575
483             Symbol type   = Proc        Value  = 0
484
485         Symbol# 2: "fdopen"
486             String index  = 11          Ifd    = 1
487             Storage class = Nil         Index  = 1048575
488             Symbol type   = Proc        Value  = 0
489
490         Symbol# 3: "freopen"
491             String index  = 18          Ifd    = 1
492             Storage class = Nil         Index  = 1048575
493             Symbol type   = Proc        Value  = 0
494
495         Symbol# 4: "popen"
496             String index  = 26          Ifd    = 1
497             Storage class = Nil         Index  = 1048575
498             Symbol type   = Proc        Value  = 0
499
500         Symbol# 5: "tmpfile"
501             String index  = 32          Ifd    = 1
502             Storage class = Nil         Index  = 1048575
503             Symbol type   = Proc        Value  = 0
504
505         Symbol# 6: "ftell"
506             String index  = 40          Ifd    = 1
507             Storage class = Nil         Index  = 1048575
508             Symbol type   = Proc        Value  = 0
509
510         Symbol# 7: "rewind"
511             String index  = 46          Ifd    = 1
512             Storage class = Nil         Index  = 1048575
513             Symbol type   = Proc        Value  = 0
514
515         Symbol# 8: "setbuf"
516             String index  = 53          Ifd    = 1
517             Storage class = Nil         Index  = 1048575
518             Symbol type   = Proc        Value  = 0
519
520         Symbol# 9: "setbuffer"
521             String index  = 60          Ifd    = 1
522             Storage class = Nil         Index  = 1048575
523             Symbol type   = Proc        Value  = 0
524
525         Symbol# 10: "setlinebuf"
526             String index  = 70          Ifd    = 1
527             Storage class = Nil         Index  = 1048575
528             Symbol type   = Proc        Value  = 0
529
530         Symbol# 11: "fgets"
531             String index  = 81          Ifd    = 1
532             Storage class = Nil         Index  = 1048575
533             Symbol type   = Proc        Value  = 0
534
535         Symbol# 12: "gets"
536             String index  = 87          Ifd    = 1
537             Storage class = Nil         Index  = 1048575
538             Symbol type   = Proc        Value  = 0
539
540         Symbol# 13: "ctermid"
541             String index  = 92          Ifd    = 1
542             Storage class = Nil         Index  = 1048575
543             Symbol type   = Proc        Value  = 0
544
545         Symbol# 14: "cuserid"
546             String index  = 100         Ifd    = 1
547             Storage class = Nil         Index  = 1048575
548             Symbol type   = Proc        Value  = 0
549
550         Symbol# 15: "tempnam"
551             String index  = 108         Ifd    = 1
552             Storage class = Nil         Index  = 1048575
553             Symbol type   = Proc        Value  = 0
554
555         Symbol# 16: "tmpnam"
556             String index  = 116         Ifd    = 1
557             Storage class = Nil         Index  = 1048575
558             Symbol type   = Proc        Value  = 0
559
560         Symbol# 17: "sprintf"
561             String index  = 123         Ifd    = 1
562             Storage class = Nil         Index  = 1048575
563             Symbol type   = Proc        Value  = 0
564
565         Symbol# 18: "main"
566             Type          = int
567             String index  = 131         Ifd    = 0
568             Storage class = Text        Index  = 1
569             Symbol type   = Proc        Value  = 0
570
571         Symbol# 19: "printf"
572             String index  = 136         Ifd    = 0
573             Storage class = Undefined   Index  = 1048575
574             Symbol type   = Proc        Value  = 0
575
576    The following auxiliary table entries were unused:
577
578     #0               0  0x00000000  void
579     #2               8  0x00000008  char
580     #3              16  0x00000010  short
581     #4              24  0x00000018  int
582     #5              32  0x00000020  long
583     #6              40  0x00000028  float
584     #7              44  0x0000002c  double
585     #8              12  0x0000000c  unsigned char
586     #9              20  0x00000014  unsigned short
587     #10             28  0x0000001c  unsigned int
588     #11             36  0x00000024  unsigned long
589     #14              0  0x00000000  void
590     #15             24  0x00000018  int
591     #19             32  0x00000020  long
592     #20             40  0x00000028  float
593     #21             44  0x0000002c  double
594     #22             12  0x0000000c  unsigned char
595     #23             20  0x00000014  unsigned short
596     #24             28  0x0000001c  unsigned int
597     #25             36  0x00000024  unsigned long
598     #26             48  0x00000030  struct no name { ifd = -1, index = 1048575 }
599
600 */
601 \f
602
603 #include "config.h"
604 #include "system.h"
605 #include "coretypes.h"
606 #include "tm.h"
607 #include "version.h"
608 #include "intl.h"
609
610 #ifndef __SABER__
611 #define saber_stop()
612 #endif
613
614 /* Include getopt.h for the sake of getopt_long.  */
615 #include "getopt.h"
616
617 #ifndef __LINE__
618 #define __LINE__ 0
619 #endif
620
621 /* Due to size_t being defined in sys/types.h and different
622    in stddef.h, we have to do this by hand.....  Note, these
623    types are correct for MIPS based systems, and may not be
624    correct for other systems.  Ultrix 4.0 and Silicon Graphics
625    have this fixed, but since the following is correct, and
626    the fact that including stddef.h gets you GCC's version
627    instead of the standard one it's not worth it to fix it.  */
628
629 #if defined(__OSF1__) || defined(__OSF__) || defined(__osf__)
630 #define Size_t          long unsigned int
631 #else
632 #define Size_t          unsigned int
633 #endif
634 #define Ptrdiff_t       long
635
636 /* The following might be called from obstack or malloc,
637    so they can't be static.  */
638
639 extern void pfatal_with_name (const char *) ATTRIBUTE_NORETURN;
640 extern void botch (const char *) ATTRIBUTE_NORETURN;
641
642 extern void fatal (const char *format, ...) ATTRIBUTE_PRINTF_1 ATTRIBUTE_NORETURN;
643 extern void error (const char *format, ...) ATTRIBUTE_PRINTF_1;
644 \f
645 #ifndef MIPS_DEBUGGING_INFO
646
647 static int       line_number;
648 static int       cur_line_start;
649 static int       debug;
650 static int       had_errors;
651 static const char *progname;
652 static const char *input_name;
653
654 int
655 main (void)
656 {
657   fprintf (stderr, "Mips-tfile should only be run on a MIPS computer!\n");
658   exit (1);
659 }
660
661 #else                           /* MIPS_DEBUGGING defined */
662 \f
663 /* The local and global symbols have a field index, so undo any defines
664    of index -> strchr.  */
665
666 #undef index
667
668 #include <signal.h>
669
670 #ifndef CROSS_DIRECTORY_STRUCTURE
671 #include <a.out.h>
672 #else
673 #include "mips/a.out.h"
674 #endif /* CROSS_DIRECTORY_STRUCTURE */
675
676 #include "gstab.h"
677
678 #define STAB_CODE_TYPE enum __stab_debug_code
679
680 #ifndef MALLOC_CHECK
681 #ifdef  __SABER__
682 #define MALLOC_CHECK
683 #endif
684 #endif
685
686 #define IS_ASM_IDENT(ch) \
687   (ISIDNUM (ch) || (ch) == '.' || (ch) == '$')
688
689 \f
690 /* Redefinition of storage classes as an enumeration for better
691    debugging.  */
692
693 typedef enum sc {
694   sc_Nil         = scNil,         /* no storage class */
695   sc_Text        = scText,        /* text symbol */
696   sc_Data        = scData,        /* initialized data symbol */
697   sc_Bss         = scBss,         /* un-initialized data symbol */
698   sc_Register    = scRegister,    /* value of symbol is register number */
699   sc_Abs         = scAbs,         /* value of symbol is absolute */
700   sc_Undefined   = scUndefined,   /* who knows? */
701   sc_CdbLocal    = scCdbLocal,    /* variable's value is IN se->va.?? */
702   sc_Bits        = scBits,        /* this is a bit field */
703   sc_CdbSystem   = scCdbSystem,   /* value is IN CDB's address space */
704   sc_RegImage    = scRegImage,    /* register value saved on stack */
705   sc_Info        = scInfo,        /* symbol contains debugger information */
706   sc_UserStruct  = scUserStruct,  /* addr in struct user for current process */
707   sc_SData       = scSData,       /* load time only small data */
708   sc_SBss        = scSBss,        /* load time only small common */
709   sc_RData       = scRData,       /* load time only read only data */
710   sc_Var         = scVar,         /* Var parameter (fortran,pascal) */
711   sc_Common      = scCommon,      /* common variable */
712   sc_SCommon     = scSCommon,     /* small common */
713   sc_VarRegister = scVarRegister, /* Var parameter in a register */
714   sc_Variant     = scVariant,     /* Variant record */
715   sc_SUndefined  = scSUndefined,  /* small undefined(external) data */
716   sc_Init        = scInit,        /* .init section symbol */
717   sc_Max         = scMax          /* Max storage class+1 */
718 } sc_t;
719
720 /* Redefinition of symbol type.  */
721
722 typedef enum st {
723   st_Nil        = stNil,        /* Nuthin' special */
724   st_Global     = stGlobal,     /* external symbol */
725   st_Static     = stStatic,     /* static */
726   st_Param      = stParam,      /* procedure argument */
727   st_Local      = stLocal,      /* local variable */
728   st_Label      = stLabel,      /* label */
729   st_Proc       = stProc,       /*     "      "  Procedure */
730   st_Block      = stBlock,      /* beginning of block */
731   st_End        = stEnd,        /* end (of anything) */
732   st_Member     = stMember,     /* member (of anything  - struct/union/enum */
733   st_Typedef    = stTypedef,    /* type definition */
734   st_File       = stFile,       /* file name */
735   st_RegReloc   = stRegReloc,   /* register relocation */
736   st_Forward    = stForward,    /* forwarding address */
737   st_StaticProc = stStaticProc, /* load time only static procs */
738   st_Constant   = stConstant,   /* const */
739   st_Str        = stStr,        /* string */
740   st_Number     = stNumber,     /* pure number (i.e. 4 NOR 2+2) */
741   st_Expr       = stExpr,       /* 2+2 vs. 4 */
742   st_Type       = stType,       /* post-coercion SER */
743   st_Max        = stMax         /* max type+1 */
744 } st_t;
745
746 /* Redefinition of type qualifiers.  */
747
748 typedef enum tq {
749   tq_Nil        = tqNil,        /* bt is what you see */
750   tq_Ptr        = tqPtr,        /* pointer */
751   tq_Proc       = tqProc,       /* procedure */
752   tq_Array      = tqArray,      /* duh */
753   tq_Far        = tqFar,        /* longer addressing - 8086/8 land */
754   tq_Vol        = tqVol,        /* volatile */
755   tq_Max        = tqMax         /* Max type qualifier+1 */
756 } tq_t;
757
758 /* Redefinition of basic types.  */
759
760 typedef enum bt {
761   bt_Nil        = btNil,        /* undefined */
762   bt_Adr        = btAdr,        /* address - integer same size as pointer */
763   bt_Char       = btChar,       /* character */
764   bt_UChar      = btUChar,      /* unsigned character */
765   bt_Short      = btShort,      /* short */
766   bt_UShort     = btUShort,     /* unsigned short */
767   bt_Int        = btInt,        /* int */
768   bt_UInt       = btUInt,       /* unsigned int */
769   bt_Long       = btLong,       /* long */
770   bt_ULong      = btULong,      /* unsigned long */
771   bt_Float      = btFloat,      /* float (real) */
772   bt_Double     = btDouble,     /* Double (real) */
773   bt_Struct     = btStruct,     /* Structure (Record) */
774   bt_Union      = btUnion,      /* Union (variant) */
775   bt_Enum       = btEnum,       /* Enumerated */
776   bt_Typedef    = btTypedef,    /* defined via a typedef, isymRef points */
777   bt_Range      = btRange,      /* subrange of int */
778   bt_Set        = btSet,        /* pascal sets */
779   bt_Complex    = btComplex,    /* fortran complex */
780   bt_DComplex   = btDComplex,   /* fortran double complex */
781   bt_Indirect   = btIndirect,   /* forward or unnamed typedef */
782   bt_FixedDec   = btFixedDec,   /* Fixed Decimal */
783   bt_FloatDec   = btFloatDec,   /* Float Decimal */
784   bt_String     = btString,     /* Varying Length Character String */
785   bt_Bit        = btBit,        /* Aligned Bit String */
786   bt_Picture    = btPicture,    /* Picture */
787
788 #ifdef btVoid
789   bt_Void       = btVoid,       /* Void */
790 #else
791 #define bt_Void bt_Nil
792 #endif
793
794   bt_Max        = btMax         /* Max basic type+1 */
795 } bt_t;
796
797 \f
798
799 /* Basic COFF storage classes.  */
800 enum coff_storage {
801   C_EFCN        = -1,
802   C_NULL        = 0,
803   C_AUTO        = 1,
804   C_EXT         = 2,
805   C_STAT        = 3,
806   C_REG         = 4,
807   C_EXTDEF      = 5,
808   C_LABEL       = 6,
809   C_ULABEL      = 7,
810   C_MOS         = 8,
811   C_ARG         = 9,
812   C_STRTAG      = 10,
813   C_MOU         = 11,
814   C_UNTAG       = 12,
815   C_TPDEF       = 13,
816   C_USTATIC     = 14,
817   C_ENTAG       = 15,
818   C_MOE         = 16,
819   C_REGPARM     = 17,
820   C_FIELD       = 18,
821   C_BLOCK       = 100,
822   C_FCN         = 101,
823   C_EOS         = 102,
824   C_FILE        = 103,
825   C_LINE        = 104,
826   C_ALIAS       = 105,
827   C_HIDDEN      = 106,
828   C_MAX         = 107
829 } coff_storage_t;
830
831 /* Regular COFF fundamental type.  */
832 typedef enum coff_type {
833   T_NULL        = 0,
834   T_ARG         = 1,
835   T_CHAR        = 2,
836   T_SHORT       = 3,
837   T_INT         = 4,
838   T_LONG        = 5,
839   T_FLOAT       = 6,
840   T_DOUBLE      = 7,
841   T_STRUCT      = 8,
842   T_UNION       = 9,
843   T_ENUM        = 10,
844   T_MOE         = 11,
845   T_UCHAR       = 12,
846   T_USHORT      = 13,
847   T_UINT        = 14,
848   T_ULONG       = 15,
849   T_MAX         = 16
850 } coff_type_t;
851
852 /* Regular COFF derived types.  */
853 typedef enum coff_dt {
854   DT_NON        = 0,
855   DT_PTR        = 1,
856   DT_FCN        = 2,
857   DT_ARY        = 3,
858   DT_MAX        = 4
859 } coff_dt_t;
860
861 #define N_BTMASK        017     /* bitmask to isolate basic type */
862 #define N_TMASK         003     /* bitmask to isolate derived type */
863 #define N_BT_SHIFT      4       /* # bits to shift past basic type */
864 #define N_TQ_SHIFT      2       /* # bits to shift derived types */
865 #define N_TQ            6       /* # of type qualifiers */
866
867 /* States for whether to hash type or not.  */
868 typedef enum hash_state {
869   hash_no       = 0,            /* don't hash type */
870   hash_yes      = 1,            /* ok to hash type, or use previous hash */
871   hash_record   = 2             /* ok to record hash, but don't use prev.  */
872 } hash_state_t;
873
874
875 /* Types of different sized allocation requests.  */
876 enum alloc_type {
877   alloc_type_none,              /* dummy value */
878   alloc_type_scope,             /* nested scopes linked list */
879   alloc_type_vlinks,            /* glue linking pages in varray */
880   alloc_type_shash,             /* string hash element */
881   alloc_type_thash,             /* type hash element */
882   alloc_type_tag,               /* struct/union/tag element */
883   alloc_type_forward,           /* element to hold unknown tag */
884   alloc_type_thead,             /* head of type hash list */
885   alloc_type_varray,            /* general varray allocation */
886   alloc_type_last               /* last+1 element for array bounds */
887 };
888
889 \f
890 #define WORD_ALIGN(x)  (((x) + (sizeof (long) - 1)) & ~ (sizeof (long) - 1))
891 #define DWORD_ALIGN(x) (((x) + 7) & ~7)
892
893
894 /* Structures to provide n-number of virtual arrays, each of which can
895    grow linearly, and which are written in the object file as sequential
896    pages.  On systems with a BSD malloc that define USE_MALLOC, the
897    MAX_CLUSTER_PAGES should be 1 less than a power of two, since malloc
898    adds its overhead, and rounds up to the next power of 2.  Pages are
899    linked together via a linked list.  */
900
901 #ifndef PAGE_SIZE
902 #define PAGE_SIZE 32768         /* size of varray pages */
903 #endif
904
905 #define PAGE_USIZE ((Size_t) PAGE_SIZE)
906
907
908 #ifndef MAX_CLUSTER_PAGES       /* # pages to get from system */
909 #ifndef USE_MALLOC              /* in one memory request */
910 #define MAX_CLUSTER_PAGES 64
911 #else
912 #define MAX_CLUSTER_PAGES 63
913 #endif
914 #endif
915
916
917 /* Linked list connecting separate page allocations.  */
918 typedef struct vlinks {
919   struct vlinks *prev;          /* previous set of pages */
920   struct vlinks *next;          /* next set of pages */
921   union  page   *datum;         /* start of page */
922   unsigned long  start_index;   /* starting index # of page */
923 } vlinks_t;
924
925
926 /* Virtual array header.  */
927 typedef struct varray {
928   vlinks_t      *first;                 /* first page link */
929   vlinks_t      *last;                  /* last page link */
930   unsigned long  num_allocated;         /* # objects allocated */
931   unsigned short object_size;           /* size in bytes of each object */
932   unsigned short objects_per_page;      /* # objects that can fit on a page */
933   unsigned short objects_last_page;     /* # objects allocated on last page */
934 } varray_t;
935
936 #ifndef MALLOC_CHECK
937 #define OBJECTS_PER_PAGE(type) (PAGE_SIZE / sizeof (type))
938 #else
939 #define OBJECTS_PER_PAGE(type) ((sizeof (type) > 1) ? 1 : PAGE_SIZE)
940 #endif
941
942 #define INIT_VARRAY(type) {     /* macro to initialize a varray */      \
943   (vlinks_t *) 0,               /* first */                             \
944   (vlinks_t *) 0,               /* last */                              \
945   0,                            /* num_allocated */                     \
946   sizeof (type),                /* object_size */                       \
947   OBJECTS_PER_PAGE (type),      /* objects_per_page */                  \
948   OBJECTS_PER_PAGE (type),      /* objects_last_page */                 \
949 }
950
951 #define INITIALIZE_VARRAY(x,type)                       \
952 do {                                                    \
953   (x)->object_size = sizeof (type);                     \
954   (x)->objects_per_page = OBJECTS_PER_PAGE (type);      \
955   (x)->objects_last_page = OBJECTS_PER_PAGE (type);     \
956 } while (0)
957
958 /* Master type for indexes within the symbol table.  */
959 typedef unsigned long symint_t;
960
961
962 /* Linked list support for nested scopes (file, block, structure, etc.).  */
963 typedef struct scope {
964   struct scope  *prev;          /* previous scope level */
965   struct scope  *free;          /* free list pointer */
966   SYMR          *lsym;          /* pointer to local symbol node */
967   symint_t       lnumber;       /* lsym index */
968   st_t           type;          /* type of the node */
969 } scope_t;
970
971
972 /* Forward reference list for tags referenced, but not yet defined.  */
973 typedef struct forward {
974   struct forward *next;         /* next forward reference */
975   struct forward *free;         /* free list pointer */
976   AUXU           *ifd_ptr;      /* pointer to store file index */
977   AUXU           *index_ptr;    /* pointer to store symbol index */
978   AUXU           *type_ptr;     /* pointer to munge type info */
979 } forward_t;
980
981
982 /* Linked list support for tags.  The first tag in the list is always
983    the current tag for that block.  */
984 typedef struct tag {
985   struct tag     *free;         /* free list pointer */
986   struct shash   *hash_ptr;     /* pointer to the hash table head */
987   struct tag     *same_name;    /* tag with same name in outer scope */
988   struct tag     *same_block;   /* next tag defined in the same block.  */
989   struct forward *forward_ref;  /* list of forward references */
990   bt_t            basic_type;   /* bt_Struct, bt_Union, or bt_Enum */
991   symint_t        ifd;          /* file # tag defined in */
992   symint_t        indx;         /* index within file's local symbols */
993 } tag_t;
994
995
996 /* Head of a block's linked list of tags.  */
997 typedef struct thead {
998   struct thead  *prev;          /* previous block */
999   struct thead  *free;          /* free list pointer */
1000   struct tag    *first_tag;     /* first tag in block defined */
1001 } thead_t;
1002
1003
1004 /* Union containing pointers to each the small structures which are freed up.  */
1005 typedef union small_free {
1006   scope_t       *f_scope;       /* scope structure */
1007   thead_t       *f_thead;       /* tag head structure */
1008   tag_t         *f_tag;         /* tag element structure */
1009   forward_t     *f_forward;     /* forward tag reference */
1010 } small_free_t;
1011
1012
1013 /* String hash table support.  The size of the hash table must fit
1014    within a page.  */
1015
1016 #ifndef SHASH_SIZE
1017 #define SHASH_SIZE 1009
1018 #endif
1019
1020 #define HASH_LEN_MAX ((1 << 12) - 1)    /* Max length we can store */
1021
1022 typedef struct shash {
1023   struct shash  *next;          /* next hash value */
1024   char          *string;        /* string we are hashing */
1025   symint_t       len;           /* string length */
1026   symint_t       indx;          /* index within string table */
1027   EXTR          *esym_ptr;      /* global symbol pointer */
1028   SYMR          *sym_ptr;       /* local symbol pointer */
1029   SYMR          *end_ptr;       /* symbol pointer to end block */
1030   tag_t         *tag_ptr;       /* tag pointer */
1031   PDR           *proc_ptr;      /* procedure descriptor pointer */
1032 } shash_t;
1033
1034
1035 /* Type hash table support.  The size of the hash table must fit
1036    within a page with the other extended file descriptor information.
1037    Because unique types which are hashed are fewer in number than
1038    strings, we use a smaller hash value.  */
1039
1040 #ifndef THASH_SIZE
1041 #define THASH_SIZE 113
1042 #endif
1043
1044 typedef struct thash {
1045   struct thash  *next;          /* next hash value */
1046   AUXU           type;          /* type we are hashing */
1047   symint_t       indx;          /* index within string table */
1048 } thash_t;
1049
1050
1051 /* Extended file descriptor that contains all of the support necessary
1052    to add things to each file separately.  */
1053 typedef struct efdr {
1054   FDR            fdr;           /* File header to be written out */
1055   FDR           *orig_fdr;      /* original file header */
1056   char          *name;          /* filename */
1057   int            name_len;      /* length of the filename */
1058   symint_t       void_type;     /* aux. pointer to 'void' type */
1059   symint_t       int_type;      /* aux. pointer to 'int' type */
1060   scope_t       *cur_scope;     /* current nested scopes */
1061   symint_t       file_index;    /* current file number */
1062   int            nested_scopes; /* # nested scopes */
1063   varray_t       strings;       /* local strings */
1064   varray_t       symbols;       /* local symbols */
1065   varray_t       procs;         /* procedures */
1066   varray_t       aux_syms;      /* auxiliary symbols */
1067   struct efdr   *next_file;     /* next file descriptor */
1068                                 /* string/type hash tables */
1069   shash_t      **shash_head;    /* string hash table */
1070   thash_t       *thash_head[THASH_SIZE];
1071 } efdr_t;
1072
1073 /* Pre-initialized extended file structure.  */
1074 static int init_file_initialized = 0;
1075 static efdr_t init_file;
1076
1077 static efdr_t *first_file;                      /* first file descriptor */
1078 static efdr_t **last_file_ptr = &first_file;    /* file descriptor tail */
1079
1080
1081 /* Union of various things that are held in pages.  */
1082 typedef union page {
1083   char          byte    [ PAGE_SIZE ];
1084   unsigned char ubyte   [ PAGE_SIZE ];
1085   efdr_t        file    [ PAGE_SIZE / sizeof (efdr_t)    ];
1086   FDR           ofile   [ PAGE_SIZE / sizeof (FDR)       ];
1087   PDR           proc    [ PAGE_SIZE / sizeof (PDR)       ];
1088   SYMR          sym     [ PAGE_SIZE / sizeof (SYMR)      ];
1089   EXTR          esym    [ PAGE_SIZE / sizeof (EXTR)      ];
1090   AUXU          aux     [ PAGE_SIZE / sizeof (AUXU)      ];
1091   DNR           dense   [ PAGE_SIZE / sizeof (DNR)       ];
1092   scope_t       scope   [ PAGE_SIZE / sizeof (scope_t)   ];
1093   vlinks_t      vlinks  [ PAGE_SIZE / sizeof (vlinks_t)  ];
1094   shash_t       shash   [ PAGE_SIZE / sizeof (shash_t)   ];
1095   thash_t       thash   [ PAGE_SIZE / sizeof (thash_t)   ];
1096   tag_t         tag     [ PAGE_SIZE / sizeof (tag_t)     ];
1097   forward_t     forward [ PAGE_SIZE / sizeof (forward_t) ];
1098   thead_t       thead   [ PAGE_SIZE / sizeof (thead_t)   ];
1099 } page_t;
1100
1101
1102 /* Structure holding allocation information for small sized structures.  */
1103 typedef struct alloc_info {
1104   const char    *alloc_name;    /* name of this allocation type (must be first) */
1105   page_t        *cur_page;      /* current page being allocated from */
1106   small_free_t   free_list;     /* current free list if any */
1107   int            unallocated;   /* number of elements unallocated on page */
1108   int            total_alloc;   /* total number of allocations */
1109   int            total_free;    /* total number of frees */
1110   int            total_pages;   /* total number of pages allocated */
1111 } alloc_info_t;
1112
1113 /* Type information collected together.  */
1114 typedef struct type_info {
1115   bt_t        basic_type;               /* basic type */
1116   coff_type_t orig_type;                /* original COFF-based type */
1117   int         num_tq;                   /* # type qualifiers */
1118   int         num_dims;                 /* # dimensions */
1119   int         num_sizes;                /* # sizes */
1120   int         extra_sizes;              /* # extra sizes not tied with dims */
1121   tag_t *     tag_ptr;                  /* tag pointer */
1122   int         bitfield;                 /* symbol is a bitfield */
1123   int         unknown_tag;              /* this is an unknown tag */
1124   tq_t        type_qualifiers[N_TQ];    /* type qualifiers (ptr, func, array)*/
1125   symint_t    dimensions     [N_TQ];    /* dimensions for each array */
1126   symint_t    sizes          [N_TQ+2];  /* sizes of each array slice + size of
1127                                            struct/union/enum + bitfield size */
1128 } type_info_t;
1129
1130 /* Pre-initialized type_info struct.  */
1131 static type_info_t type_info_init = {
1132   bt_Nil,                               /* basic type */
1133   T_NULL,                               /* original COFF-based type */
1134   0,                                    /* # type qualifiers */
1135   0,                                    /* # dimensions */
1136   0,                                    /* # sizes */
1137   0,                                    /* sizes not tied with dims */
1138   NULL,                                 /* ptr to tag */
1139   0,                                    /* bitfield */
1140   0,                                    /* unknown tag */
1141   {                                     /* type qualifiers */
1142     tq_Nil,
1143     tq_Nil,
1144     tq_Nil,
1145     tq_Nil,
1146     tq_Nil,
1147     tq_Nil,
1148   },
1149   {                                     /* dimensions */
1150     0,
1151     0,
1152     0,
1153     0,
1154     0,
1155     0
1156   },
1157   {                                     /* sizes */
1158     0,
1159     0,
1160     0,
1161     0,
1162     0,
1163     0,
1164     0,
1165     0,
1166   },
1167 };
1168
1169
1170 /* Global virtual arrays & hash table for external strings as well as
1171    for the tags table and global tables for file descriptors, and
1172    dense numbers.  */
1173
1174 static varray_t file_desc       = INIT_VARRAY (efdr_t);
1175 static varray_t dense_num       = INIT_VARRAY (DNR);
1176 static varray_t tag_strings     = INIT_VARRAY (char);
1177 static varray_t ext_strings     = INIT_VARRAY (char);
1178 static varray_t ext_symbols     = INIT_VARRAY (EXTR);
1179
1180 static shash_t  *orig_str_hash[SHASH_SIZE];
1181 static shash_t  *ext_str_hash [SHASH_SIZE];
1182 static shash_t  *tag_hash     [SHASH_SIZE];
1183
1184 /* Static types for int and void.  Also, remember the last function's
1185    type (which is set up when we encounter the declaration for the
1186    function, and used when the end block for the function is emitted.  */
1187
1188 static type_info_t int_type_info;
1189 static type_info_t void_type_info;
1190 static type_info_t last_func_type_info;
1191 static EXTR       *last_func_eptr;
1192
1193
1194 /* Convert COFF basic type to ECOFF basic type.  The T_NULL type
1195    really should use bt_Void, but this causes the current ecoff GDB to
1196    issue unsupported type messages, and the Ultrix 4.00 dbx (aka MIPS
1197    2.0) doesn't understand it, even though the compiler generates it.
1198    Maybe this will be fixed in 2.10 or 2.20 of the MIPS compiler
1199    suite, but for now go with what works.  */
1200
1201 static const bt_t map_coff_types[ (int) T_MAX ] = {
1202   bt_Nil,                       /* T_NULL */
1203   bt_Nil,                       /* T_ARG */
1204   bt_Char,                      /* T_CHAR */
1205   bt_Short,                     /* T_SHORT */
1206   bt_Int,                       /* T_INT */
1207   bt_Long,                      /* T_LONG */
1208   bt_Float,                     /* T_FLOAT */
1209   bt_Double,                    /* T_DOUBLE */
1210   bt_Struct,                    /* T_STRUCT */
1211   bt_Union,                     /* T_UNION */
1212   bt_Enum,                      /* T_ENUM */
1213   bt_Enum,                      /* T_MOE */
1214   bt_UChar,                     /* T_UCHAR */
1215   bt_UShort,                    /* T_USHORT */
1216   bt_UInt,                      /* T_UINT */
1217   bt_ULong                      /* T_ULONG */
1218 };
1219
1220 /* Convert COFF storage class to ECOFF storage class.  */
1221 static const sc_t map_coff_storage[ (int) C_MAX ] = {
1222   sc_Nil,                       /*   0: C_NULL */
1223   sc_Abs,                       /*   1: C_AUTO    auto var */
1224   sc_Undefined,                 /*   2: C_EXT     external */
1225   sc_Data,                      /*   3: C_STAT    static */
1226   sc_Register,                  /*   4: C_REG     register */
1227   sc_Undefined,                 /*   5: C_EXTDEF  ??? */
1228   sc_Text,                      /*   6: C_LABEL   label */
1229   sc_Text,                      /*   7: C_ULABEL  user label */
1230   sc_Info,                      /*   8: C_MOS     member of struct */
1231   sc_Abs,                       /*   9: C_ARG     argument */
1232   sc_Info,                      /*  10: C_STRTAG  struct tag */
1233   sc_Info,                      /*  11: C_MOU     member of union */
1234   sc_Info,                      /*  12: C_UNTAG   union tag */
1235   sc_Info,                      /*  13: C_TPDEF   typedef */
1236   sc_Data,                      /*  14: C_USTATIC ??? */
1237   sc_Info,                      /*  15: C_ENTAG   enum tag */
1238   sc_Info,                      /*  16: C_MOE     member of enum */
1239   sc_Register,                  /*  17: C_REGPARM register parameter */
1240   sc_Bits,                      /*  18; C_FIELD   bitfield */
1241   sc_Nil,                       /*  19 */
1242   sc_Nil,                       /*  20 */
1243   sc_Nil,                       /*  21 */
1244   sc_Nil,                       /*  22 */
1245   sc_Nil,                       /*  23 */
1246   sc_Nil,                       /*  24 */
1247   sc_Nil,                       /*  25 */
1248   sc_Nil,                       /*  26 */
1249   sc_Nil,                       /*  27 */
1250   sc_Nil,                       /*  28 */
1251   sc_Nil,                       /*  29 */
1252   sc_Nil,                       /*  30 */
1253   sc_Nil,                       /*  31 */
1254   sc_Nil,                       /*  32 */
1255   sc_Nil,                       /*  33 */
1256   sc_Nil,                       /*  34 */
1257   sc_Nil,                       /*  35 */
1258   sc_Nil,                       /*  36 */
1259   sc_Nil,                       /*  37 */
1260   sc_Nil,                       /*  38 */
1261   sc_Nil,                       /*  39 */
1262   sc_Nil,                       /*  40 */
1263   sc_Nil,                       /*  41 */
1264   sc_Nil,                       /*  42 */
1265   sc_Nil,                       /*  43 */
1266   sc_Nil,                       /*  44 */
1267   sc_Nil,                       /*  45 */
1268   sc_Nil,                       /*  46 */
1269   sc_Nil,                       /*  47 */
1270   sc_Nil,                       /*  48 */
1271   sc_Nil,                       /*  49 */
1272   sc_Nil,                       /*  50 */
1273   sc_Nil,                       /*  51 */
1274   sc_Nil,                       /*  52 */
1275   sc_Nil,                       /*  53 */
1276   sc_Nil,                       /*  54 */
1277   sc_Nil,                       /*  55 */
1278   sc_Nil,                       /*  56 */
1279   sc_Nil,                       /*  57 */
1280   sc_Nil,                       /*  58 */
1281   sc_Nil,                       /*  59 */
1282   sc_Nil,                       /*  60 */
1283   sc_Nil,                       /*  61 */
1284   sc_Nil,                       /*  62 */
1285   sc_Nil,                       /*  63 */
1286   sc_Nil,                       /*  64 */
1287   sc_Nil,                       /*  65 */
1288   sc_Nil,                       /*  66 */
1289   sc_Nil,                       /*  67 */
1290   sc_Nil,                       /*  68 */
1291   sc_Nil,                       /*  69 */
1292   sc_Nil,                       /*  70 */
1293   sc_Nil,                       /*  71 */
1294   sc_Nil,                       /*  72 */
1295   sc_Nil,                       /*  73 */
1296   sc_Nil,                       /*  74 */
1297   sc_Nil,                       /*  75 */
1298   sc_Nil,                       /*  76 */
1299   sc_Nil,                       /*  77 */
1300   sc_Nil,                       /*  78 */
1301   sc_Nil,                       /*  79 */
1302   sc_Nil,                       /*  80 */
1303   sc_Nil,                       /*  81 */
1304   sc_Nil,                       /*  82 */
1305   sc_Nil,                       /*  83 */
1306   sc_Nil,                       /*  84 */
1307   sc_Nil,                       /*  85 */
1308   sc_Nil,                       /*  86 */
1309   sc_Nil,                       /*  87 */
1310   sc_Nil,                       /*  88 */
1311   sc_Nil,                       /*  89 */
1312   sc_Nil,                       /*  90 */
1313   sc_Nil,                       /*  91 */
1314   sc_Nil,                       /*  92 */
1315   sc_Nil,                       /*  93 */
1316   sc_Nil,                       /*  94 */
1317   sc_Nil,                       /*  95 */
1318   sc_Nil,                       /*  96 */
1319   sc_Nil,                       /*  97 */
1320   sc_Nil,                       /*  98 */
1321   sc_Nil,                       /*  99 */
1322   sc_Text,                      /* 100: C_BLOCK  block start/end */
1323   sc_Text,                      /* 101: C_FCN    function start/end */
1324   sc_Info,                      /* 102: C_EOS    end of struct/union/enum */
1325   sc_Nil,                       /* 103: C_FILE   file start */
1326   sc_Nil,                       /* 104: C_LINE   line number */
1327   sc_Nil,                       /* 105: C_ALIAS  combined type info */
1328   sc_Nil,                       /* 106: C_HIDDEN ??? */
1329 };
1330
1331 /* Convert COFF storage class to ECOFF symbol type.  */
1332 static const st_t map_coff_sym_type[ (int) C_MAX ] = {
1333   st_Nil,                       /*   0: C_NULL */
1334   st_Local,                     /*   1: C_AUTO    auto var */
1335   st_Global,                    /*   2: C_EXT     external */
1336   st_Static,                    /*   3: C_STAT    static */
1337   st_Local,                     /*   4: C_REG     register */
1338   st_Global,                    /*   5: C_EXTDEF  ??? */
1339   st_Label,                     /*   6: C_LABEL   label */
1340   st_Label,                     /*   7: C_ULABEL  user label */
1341   st_Member,                    /*   8: C_MOS     member of struct */
1342   st_Param,                     /*   9: C_ARG     argument */
1343   st_Block,                     /*  10: C_STRTAG  struct tag */
1344   st_Member,                    /*  11: C_MOU     member of union */
1345   st_Block,                     /*  12: C_UNTAG   union tag */
1346   st_Typedef,                   /*  13: C_TPDEF   typedef */
1347   st_Static,                    /*  14: C_USTATIC ??? */
1348   st_Block,                     /*  15: C_ENTAG   enum tag */
1349   st_Member,                    /*  16: C_MOE     member of enum */
1350   st_Param,                     /*  17: C_REGPARM register parameter */
1351   st_Member,                    /*  18; C_FIELD   bitfield */
1352   st_Nil,                       /*  19 */
1353   st_Nil,                       /*  20 */
1354   st_Nil,                       /*  21 */
1355   st_Nil,                       /*  22 */
1356   st_Nil,                       /*  23 */
1357   st_Nil,                       /*  24 */
1358   st_Nil,                       /*  25 */
1359   st_Nil,                       /*  26 */
1360   st_Nil,                       /*  27 */
1361   st_Nil,                       /*  28 */
1362   st_Nil,                       /*  29 */
1363   st_Nil,                       /*  30 */
1364   st_Nil,                       /*  31 */
1365   st_Nil,                       /*  32 */
1366   st_Nil,                       /*  33 */
1367   st_Nil,                       /*  34 */
1368   st_Nil,                       /*  35 */
1369   st_Nil,                       /*  36 */
1370   st_Nil,                       /*  37 */
1371   st_Nil,                       /*  38 */
1372   st_Nil,                       /*  39 */
1373   st_Nil,                       /*  40 */
1374   st_Nil,                       /*  41 */
1375   st_Nil,                       /*  42 */
1376   st_Nil,                       /*  43 */
1377   st_Nil,                       /*  44 */
1378   st_Nil,                       /*  45 */
1379   st_Nil,                       /*  46 */
1380   st_Nil,                       /*  47 */
1381   st_Nil,                       /*  48 */
1382   st_Nil,                       /*  49 */
1383   st_Nil,                       /*  50 */
1384   st_Nil,                       /*  51 */
1385   st_Nil,                       /*  52 */
1386   st_Nil,                       /*  53 */
1387   st_Nil,                       /*  54 */
1388   st_Nil,                       /*  55 */
1389   st_Nil,                       /*  56 */
1390   st_Nil,                       /*  57 */
1391   st_Nil,                       /*  58 */
1392   st_Nil,                       /*  59 */
1393   st_Nil,                       /*  60 */
1394   st_Nil,                       /*  61 */
1395   st_Nil,                       /*  62 */
1396   st_Nil,                       /*  63 */
1397   st_Nil,                       /*  64 */
1398   st_Nil,                       /*  65 */
1399   st_Nil,                       /*  66 */
1400   st_Nil,                       /*  67 */
1401   st_Nil,                       /*  68 */
1402   st_Nil,                       /*  69 */
1403   st_Nil,                       /*  70 */
1404   st_Nil,                       /*  71 */
1405   st_Nil,                       /*  72 */
1406   st_Nil,                       /*  73 */
1407   st_Nil,                       /*  74 */
1408   st_Nil,                       /*  75 */
1409   st_Nil,                       /*  76 */
1410   st_Nil,                       /*  77 */
1411   st_Nil,                       /*  78 */
1412   st_Nil,                       /*  79 */
1413   st_Nil,                       /*  80 */
1414   st_Nil,                       /*  81 */
1415   st_Nil,                       /*  82 */
1416   st_Nil,                       /*  83 */
1417   st_Nil,                       /*  84 */
1418   st_Nil,                       /*  85 */
1419   st_Nil,                       /*  86 */
1420   st_Nil,                       /*  87 */
1421   st_Nil,                       /*  88 */
1422   st_Nil,                       /*  89 */
1423   st_Nil,                       /*  90 */
1424   st_Nil,                       /*  91 */
1425   st_Nil,                       /*  92 */
1426   st_Nil,                       /*  93 */
1427   st_Nil,                       /*  94 */
1428   st_Nil,                       /*  95 */
1429   st_Nil,                       /*  96 */
1430   st_Nil,                       /*  97 */
1431   st_Nil,                       /*  98 */
1432   st_Nil,                       /*  99 */
1433   st_Block,                     /* 100: C_BLOCK  block start/end */
1434   st_Proc,                      /* 101: C_FCN    function start/end */
1435   st_End,                       /* 102: C_EOS    end of struct/union/enum */
1436   st_File,                      /* 103: C_FILE   file start */
1437   st_Nil,                       /* 104: C_LINE   line number */
1438   st_Nil,                       /* 105: C_ALIAS  combined type info */
1439   st_Nil,                       /* 106: C_HIDDEN ??? */
1440 };
1441
1442 /* Map COFF derived types to ECOFF type qualifiers.  */
1443 static const tq_t map_coff_derived_type[ (int) DT_MAX ] = {
1444   tq_Nil,                       /* 0: DT_NON    no more qualifiers */
1445   tq_Ptr,                       /* 1: DT_PTR    pointer */
1446   tq_Proc,                      /* 2: DT_FCN    function */
1447   tq_Array,                     /* 3: DT_ARY    array */
1448 };
1449
1450
1451 /* Keep track of different sized allocation requests.  */
1452 static alloc_info_t alloc_counts[ (int) alloc_type_last ];
1453
1454 \f
1455 /* Pointers and such to the original symbol table that is read in.  */
1456 static struct filehdr orig_file_header;         /* global object file header */
1457
1458 static HDRR      orig_sym_hdr;                  /* symbolic header on input */
1459 static char     *orig_linenum;                  /* line numbers */
1460 static DNR      *orig_dense;                    /* dense numbers */
1461 static PDR      *orig_procs;                    /* procedures */
1462 static SYMR     *orig_local_syms;               /* local symbols */
1463 static OPTR     *orig_opt_syms;                 /* optimization symbols */
1464 static AUXU     *orig_aux_syms;                 /* auxiliary symbols */
1465 static char     *orig_local_strs;               /* local strings */
1466 static char     *orig_ext_strs;                 /* external strings */
1467 static FDR      *orig_files;                    /* file descriptors */
1468 static symint_t *orig_rfds;                     /* relative file desc's */
1469 static EXTR     *orig_ext_syms;                 /* external symbols */
1470
1471 /* Macros to convert an index into a given object within the original
1472    symbol table.  */
1473 #define CHECK(num,max,str) \
1474   (((unsigned long) num > (unsigned long) max) ? out_of_bounds (num, max, str, __LINE__) : 0)
1475
1476 #define ORIG_LINENUM(indx)      (CHECK ((indx), orig_sym_hdr.cbLine,    "line#"), (indx) + orig_linenum)
1477 #define ORIG_DENSE(indx)        (CHECK ((indx), orig_sym_hdr.idnMax,    "dense"), (indx) + orig_dense)
1478 #define ORIG_PROCS(indx)        (CHECK ((indx), orig_sym_hdr.ipdMax,    "procs"), (indx) + orig_procs)
1479 #define ORIG_FILES(indx)        (CHECK ((indx), orig_sym_hdr.ifdMax,    "funcs"), (indx) + orig_files)
1480 #define ORIG_LSYMS(indx)        (CHECK ((indx), orig_sym_hdr.isymMax,   "lsyms"), (indx) + orig_local_syms)
1481 #define ORIG_LSTRS(indx)        (CHECK ((indx), orig_sym_hdr.issMax,    "lstrs"), (indx) + orig_local_strs)
1482 #define ORIG_ESYMS(indx)        (CHECK ((indx), orig_sym_hdr.iextMax,   "esyms"), (indx) + orig_ext_syms)
1483 #define ORIG_ESTRS(indx)        (CHECK ((indx), orig_sym_hdr.issExtMax, "estrs"), (indx) + orig_ext_strs)
1484 #define ORIG_OPT(indx)          (CHECK ((indx), orig_sym_hdr.ioptMax,   "opt"),   (indx) + orig_opt_syms)
1485 #define ORIG_AUX(indx)          (CHECK ((indx), orig_sym_hdr.iauxMax,   "aux"),   (indx) + orig_aux_syms)
1486 #define ORIG_RFDS(indx)         (CHECK ((indx), orig_sym_hdr.crfd,      "rfds"),  (indx) + orig_rfds)
1487
1488 /* Various other statics.  */
1489 static HDRR     symbolic_header;                /* symbolic header */
1490 static efdr_t  *cur_file_ptr    = (efdr_t *) 0; /* current file desc. header */
1491 static PDR     *cur_proc_ptr    = (PDR *) 0;    /* current procedure header */
1492 static SYMR    *cur_oproc_begin = (SYMR *) 0;   /* original proc. sym begin info */
1493 static SYMR    *cur_oproc_end   = (SYMR *) 0;   /* original proc. sym end info */
1494 static PDR     *cur_oproc_ptr   = (PDR *) 0;    /* current original procedure*/
1495 static thead_t *cur_tag_head    = (thead_t *) 0;/* current tag head */
1496 static unsigned long file_offset        = 0;    /* current file offset */
1497 static unsigned long max_file_offset    = 0;    /* maximum file offset */
1498 static FILE    *object_stream   = (FILE *) 0;   /* file desc. to output .o */
1499 static FILE    *obj_in_stream   = (FILE *) 0;   /* file desc. to input .o */
1500 static char    *progname        = (char *) 0;   /* program name for errors */
1501 static const char *input_name   = "stdin";      /* name of input file */
1502 static char    *object_name     = (char *) 0;   /* tmp. name of object file */
1503 static char    *obj_in_name     = (char *) 0;   /* name of input object file */
1504 static char    *cur_line_start  = (char *) 0;   /* current line read in */
1505 static char    *cur_line_ptr    = (char *) 0;   /* ptr within current line */
1506 static unsigned cur_line_nbytes = 0;            /* # bytes for current line */
1507 static unsigned cur_line_alloc  = 0;            /* # bytes total in buffer */
1508 static long     line_number     = 0;            /* current input line number */
1509 static int      debug           = 0;            /* trace functions */
1510 static int      version         = 0;            /* print version # */
1511 static int      verbose         = 0;
1512 static int      had_errors      = 0;            /* != 0 if errors were found */
1513 static int      rename_output   = 0;            /* != 0 if rename output file*/
1514 static int      delete_input    = 0;            /* != 0 if delete input after done */
1515 static int      stabs_seen      = 0;            /* != 0 if stabs have been seen */
1516
1517
1518 /* Pseudo symbol to use when putting stabs into the symbol table.  */
1519 #ifndef STABS_SYMBOL
1520 #define STABS_SYMBOL "@stabs"
1521 #endif
1522
1523 static const char stabs_symbol[] = STABS_SYMBOL;
1524
1525 \f
1526 /* Forward reference for functions.  See the definition for more details.  */
1527
1528 #ifndef STATIC
1529 #define STATIC static
1530 #endif
1531
1532 STATIC int out_of_bounds (symint_t, symint_t, const char *, int);
1533 STATIC shash_t *hash_string (const char *, Ptrdiff_t, shash_t **, symint_t *);
1534 STATIC symint_t add_string (varray_t *, shash_t **, const char *, const char *,
1535                             shash_t **);
1536 STATIC symint_t add_local_symbol (const char *, const char *, st_t, sc_t,
1537                                   symint_t, symint_t);
1538 STATIC symint_t add_ext_symbol (EXTR *, int);
1539 STATIC symint_t add_aux_sym_symint (symint_t);
1540 STATIC symint_t add_aux_sym_rndx (int, symint_t);
1541 STATIC symint_t add_aux_sym_tir (type_info_t *, hash_state_t, thash_t **);
1542 STATIC tag_t *  get_tag (const char *, const char *, symint_t, bt_t);
1543 STATIC void add_unknown_tag (tag_t *);
1544 STATIC void add_procedure (const char *, const char *);
1545 STATIC void initialize_init_file (void);
1546 STATIC void add_file (const char *, const char *);
1547 STATIC void add_bytes (varray_t *, char *, Size_t);
1548 STATIC void add_varray_page (varray_t *);
1549 STATIC void update_headers (void);
1550 STATIC void write_varray (varray_t *, off_t, const char *);
1551 STATIC void write_object (void);
1552 STATIC const char *st_to_string (st_t);
1553 STATIC const char *sc_to_string (sc_t);
1554 STATIC char *read_line (void);
1555 STATIC void parse_input (void);
1556 STATIC void mark_stabs (const char *);
1557 STATIC void parse_begin (const char *);
1558 STATIC void parse_bend (const char *);
1559 STATIC void parse_def (const char *);
1560 STATIC void parse_end (const char *);
1561 STATIC void parse_ent (const char *);
1562 STATIC void parse_file (const char *);
1563 STATIC void parse_stabs_common (const char *, const char *, const char *);
1564 STATIC void parse_stabs (const char *);
1565 STATIC void parse_stabn (const char *);
1566 STATIC page_t  *read_seek (Size_t, off_t, const char *);
1567 STATIC void copy_object (void);
1568
1569 STATIC void catch_signal (int) ATTRIBUTE_NORETURN;
1570 STATIC page_t *allocate_page (void);
1571 STATIC page_t *allocate_multiple_pages (Size_t);
1572 STATIC void     free_multiple_pages (page_t *, Size_t);
1573
1574 #ifndef MALLOC_CHECK
1575 STATIC page_t  *allocate_cluster (Size_t);
1576 #endif
1577
1578 STATIC forward_t *allocate_forward (void);
1579 STATIC scope_t *allocate_scope (void);
1580 STATIC shash_t *allocate_shash (void);
1581 STATIC tag_t  *allocate_tag (void);
1582 STATIC thash_t *allocate_thash (void);
1583 STATIC thead_t *allocate_thead (void);
1584 STATIC vlinks_t *allocate_vlinks (void);
1585
1586 STATIC void free_forward (forward_t *);
1587 STATIC void free_scope (scope_t *);
1588 STATIC void free_tag (tag_t *);
1589 STATIC void free_thead (thead_t *);
1590
1591 extern char *optarg;
1592 extern int   optind;
1593 extern int   opterr;
1594 \f
1595 /* List of assembler pseudo ops and beginning sequences that need
1596    special actions.  Someday, this should be a hash table, and such,
1597    but for now a linear list of names and calls to memcmp will
1598    do......  */
1599
1600 typedef struct _pseudo_ops {
1601   const char *const name;                       /* pseudo-op in ascii */
1602   const int len;                                /* length of name to compare */
1603   void (*const func) (const char *);    /* function to handle line */
1604 } pseudo_ops_t;
1605
1606 static const pseudo_ops_t pseudo_ops[] = {
1607   { "#.def",    sizeof("#.def")-1,      parse_def },
1608   { "#.begin",  sizeof("#.begin")-1,    parse_begin },
1609   { "#.bend",   sizeof("#.bend")-1,     parse_bend },
1610   { ".end",     sizeof(".end")-1,       parse_end },
1611   { ".ent",     sizeof(".ent")-1,       parse_ent },
1612   { ".file",    sizeof(".file")-1,      parse_file },
1613   { "#.stabs",  sizeof("#.stabs")-1,    parse_stabs },
1614   { "#.stabn",  sizeof("#.stabn")-1,    parse_stabn },
1615   { ".stabs",   sizeof(".stabs")-1,     parse_stabs },
1616   { ".stabn",   sizeof(".stabn")-1,     parse_stabn },
1617   { "#@stabs",  sizeof("#@stabs")-1,    mark_stabs },
1618 };
1619
1620 \f
1621 /* Command line options for getopt_long.  */
1622
1623 static const struct option options[] =
1624 {
1625   { "version", 0, 0, 'V' },
1626   { "verbose", 0, 0, 'v' },
1627   { 0, 0, 0, 0 }
1628 };
1629 \f
1630 /* Add a page to a varray object.  */
1631
1632 STATIC void
1633 add_varray_page (varray_t *vp)
1634 {
1635   vlinks_t *new_links = allocate_vlinks ();
1636
1637 #ifdef MALLOC_CHECK
1638   if (vp->object_size > 1)
1639     new_links->datum = xcalloc (1, vp->object_size);
1640   else
1641 #endif
1642     new_links->datum = allocate_page ();
1643
1644   alloc_counts[ (int) alloc_type_varray ].total_alloc++;
1645   alloc_counts[ (int) alloc_type_varray ].total_pages++;
1646
1647   new_links->start_index = vp->num_allocated;
1648   vp->objects_last_page = 0;
1649
1650   if (vp->first == (vlinks_t *) 0)              /* first allocation? */
1651     vp->first = vp->last = new_links;
1652   else
1653     {                                           /* 2nd or greater allocation */
1654       new_links->prev = vp->last;
1655       vp->last->next = new_links;
1656       vp->last = new_links;
1657     }
1658 }
1659
1660 \f
1661 /* Compute hash code (from tree.c) */
1662
1663 #define HASHBITS 30
1664
1665 STATIC shash_t *
1666 hash_string (const char *text, Ptrdiff_t hash_len, shash_t **hash_tbl,
1667              symint_t *ret_hash_index)
1668 {
1669   unsigned long hi;
1670   Ptrdiff_t i;
1671   shash_t *ptr;
1672   int first_ch = *text;
1673
1674   hi = hash_len;
1675   for (i = 0; i < hash_len; i++)
1676     hi = ((hi & 0x003fffff) * 613) + (text[i] & 0xff);
1677
1678   hi &= (1 << HASHBITS) - 1;
1679   hi %= SHASH_SIZE;
1680
1681   if (ret_hash_index != (symint_t *) 0)
1682     *ret_hash_index = hi;
1683
1684   for (ptr = hash_tbl[hi]; ptr != (shash_t *) 0; ptr = ptr->next)
1685     if ((symint_t) hash_len == ptr->len
1686         && first_ch == ptr->string[0]
1687         && memcmp (text, ptr->string, hash_len) == 0)
1688       break;
1689
1690   return ptr;
1691 }
1692
1693 \f
1694 /* Add a string (and null pad) to one of the string tables.  A
1695    consequence of hashing strings, is that we don't let strings cross
1696    page boundaries.  The extra nulls will be ignored.  VP is a string
1697    virtual array, HASH_TBL a pointer to the hash table, the string
1698    starts at START and the position one byte after the string is given
1699    with END_P1, the resulting hash pointer is returned in RET_HASH.  */
1700
1701 STATIC symint_t
1702 add_string (varray_t *vp, shash_t **hash_tbl, const char *start,
1703             const char *end_p1, shash_t **ret_hash)
1704 {
1705   Ptrdiff_t len = end_p1 - start;
1706   shash_t *hash_ptr;
1707   symint_t hi;
1708
1709   if (len >= (Ptrdiff_t) PAGE_USIZE)
1710     fatal ("string too big (%ld bytes)", (long) len);
1711
1712   hash_ptr = hash_string (start, len, hash_tbl, &hi);
1713   if (hash_ptr == (shash_t *) 0)
1714     {
1715       char *p;
1716
1717       if (vp->objects_last_page + len >= (long) PAGE_USIZE)
1718         {
1719           vp->num_allocated
1720             = ((vp->num_allocated + PAGE_USIZE - 1) / PAGE_USIZE) * PAGE_USIZE;
1721           add_varray_page (vp);
1722         }
1723
1724       hash_ptr = allocate_shash ();
1725       hash_ptr->next = hash_tbl[hi];
1726       hash_tbl[hi] = hash_ptr;
1727
1728       hash_ptr->len = len;
1729       hash_ptr->indx = vp->num_allocated;
1730       hash_ptr->string = p = & vp->last->datum->byte[ vp->objects_last_page ];
1731
1732       vp->objects_last_page += len+1;
1733       vp->num_allocated += len+1;
1734
1735       while (len-- > 0)
1736         *p++ = *start++;
1737
1738       *p = '\0';
1739     }
1740
1741   if (ret_hash != (shash_t **) 0)
1742     *ret_hash = hash_ptr;
1743
1744   return hash_ptr->indx;
1745 }
1746
1747 \f
1748 /* Add a local symbol.  The symbol string starts at STR_START and the
1749    first byte after it is marked by STR_END_P1.  The symbol has type
1750    TYPE and storage class STORAGE and value VALUE.  INDX is an index
1751    to local/aux. symbols.  */
1752
1753 STATIC symint_t
1754 add_local_symbol (const char *str_start, const char *str_end_p1, st_t type,
1755                   sc_t storage,  symint_t value, symint_t indx)
1756 {
1757   symint_t ret;
1758   SYMR *psym;
1759   scope_t *pscope;
1760   thead_t *ptag_head;
1761   tag_t *ptag;
1762   tag_t *ptag_next;
1763   varray_t *vp = &cur_file_ptr->symbols;
1764   int scope_delta = 0;
1765   shash_t *hash_ptr = (shash_t *) 0;
1766
1767   if (vp->objects_last_page == vp->objects_per_page)
1768     add_varray_page (vp);
1769
1770   psym = &vp->last->datum->sym[ vp->objects_last_page++ ];
1771
1772   psym->value = value;
1773   psym->st = (unsigned) type;
1774   psym->sc = (unsigned) storage;
1775   psym->index = indx;
1776   psym->iss = (str_start == (const char *) 0)
1777                 ? 0
1778                 : add_string (&cur_file_ptr->strings,
1779                               &cur_file_ptr->shash_head[0],
1780                               str_start,
1781                               str_end_p1,
1782                               &hash_ptr);
1783
1784   ret = vp->num_allocated++;
1785
1786   if (MIPS_IS_STAB (psym))
1787     return ret;
1788
1789   /* Save the symbol within the hash table if this is a static
1790      item, and it has a name.  */
1791   if (hash_ptr != (shash_t *) 0
1792       && (type == st_Global || type == st_Static || type == st_Label
1793           || type == st_Proc || type == st_StaticProc))
1794     hash_ptr->sym_ptr = psym;
1795
1796   /* push or pop a scope if appropriate.  */
1797   switch (type)
1798     {
1799     default:
1800       break;
1801
1802     case st_File:                       /* beginning of file */
1803     case st_Proc:                       /* procedure */
1804     case st_StaticProc:                 /* static procedure */
1805     case st_Block:                      /* begin scope */
1806       pscope = allocate_scope ();
1807       pscope->prev = cur_file_ptr->cur_scope;
1808       pscope->lsym = psym;
1809       pscope->lnumber = ret;
1810       pscope->type = type;
1811       cur_file_ptr->cur_scope = pscope;
1812
1813       if (type != st_File)
1814         scope_delta = 1;
1815
1816       /* For every block type except file, struct, union, or
1817          enumeration blocks, push a level on the tag stack.  We omit
1818          file types, so that tags can span file boundaries.  */
1819       if (type != st_File && storage != sc_Info)
1820         {
1821           ptag_head = allocate_thead ();
1822           ptag_head->first_tag = 0;
1823           ptag_head->prev = cur_tag_head;
1824           cur_tag_head = ptag_head;
1825         }
1826       break;
1827
1828     case st_End:
1829       pscope = cur_file_ptr->cur_scope;
1830       if (pscope == (scope_t *) 0)
1831         error ("internal error, too many st_End's");
1832
1833       else
1834         {
1835           st_t begin_type = (st_t) pscope->lsym->st;
1836
1837           if (begin_type != st_File)
1838             scope_delta = -1;
1839
1840           /* Except for file, structure, union, or enumeration end
1841              blocks remove all tags created within this scope.  */
1842           if (begin_type != st_File && storage != sc_Info)
1843             {
1844               ptag_head = cur_tag_head;
1845               cur_tag_head = ptag_head->prev;
1846
1847               for (ptag = ptag_head->first_tag;
1848                    ptag != (tag_t *) 0;
1849                    ptag = ptag_next)
1850                 {
1851                   if (ptag->forward_ref != (forward_t *) 0)
1852                     add_unknown_tag (ptag);
1853
1854                   ptag_next = ptag->same_block;
1855                   ptag->hash_ptr->tag_ptr = ptag->same_name;
1856                   free_tag (ptag);
1857                 }
1858
1859               free_thead (ptag_head);
1860             }
1861
1862           cur_file_ptr->cur_scope = pscope->prev;
1863           psym->index = pscope->lnumber;        /* blk end gets begin sym # */
1864
1865           if (storage != sc_Info)
1866             psym->iss = pscope->lsym->iss;      /* blk end gets same name */
1867
1868           if (begin_type == st_File || begin_type == st_Block)
1869             pscope->lsym->index = ret+1;        /* block begin gets next sym # */
1870
1871           /* Functions push two or more aux words as follows:
1872              1st word: index+1 of the end symbol
1873              2nd word: type of the function (plus any aux words needed).
1874              Also, tie the external pointer back to the function begin symbol.  */
1875           else
1876             {
1877               symint_t type;
1878               pscope->lsym->index = add_aux_sym_symint (ret+1);
1879               type = add_aux_sym_tir (&last_func_type_info,
1880                                       hash_no,
1881                                       &cur_file_ptr->thash_head[0]);
1882               if (last_func_eptr)
1883                 {
1884                   last_func_eptr->ifd = cur_file_ptr->file_index;
1885
1886                   /* The index for an external st_Proc symbol is the index
1887                      of the st_Proc symbol in the local symbol table.  */
1888                   last_func_eptr->asym.index = psym->index;
1889                 }
1890             }
1891
1892           free_scope (pscope);
1893         }
1894     }
1895
1896   cur_file_ptr->nested_scopes += scope_delta;
1897
1898   if (debug && type != st_File
1899       && (debug > 2 || type == st_Block || type == st_End
1900           || type == st_Proc || type == st_StaticProc))
1901     {
1902       const char *sc_str = sc_to_string (storage);
1903       const char *st_str = st_to_string (type);
1904       int depth = cur_file_ptr->nested_scopes + (scope_delta < 0);
1905
1906       fprintf (stderr,
1907                "\tlsym\tv= %10ld, depth= %2d, sc= %-12s",
1908                value, depth, sc_str);
1909
1910       if (str_start && str_end_p1 - str_start > 0)
1911         fprintf (stderr, " st= %-11s name= %.*s\n",
1912                  st_str, (int) (str_end_p1 - str_start), str_start);
1913       else
1914         {
1915           Size_t len = strlen (st_str);
1916           fprintf (stderr, " st= %.*s\n", (int) (len-1), st_str);
1917         }
1918     }
1919
1920   return ret;
1921 }
1922
1923 \f
1924 /* Add an external symbol with symbol pointer ESYM and file index
1925    IFD.  */
1926
1927 STATIC symint_t
1928 add_ext_symbol (EXTR *esym, int ifd)
1929 {
1930   const char *str_start;                /* first byte in string */
1931   const char *str_end_p1;               /* first byte after string */
1932   EXTR *psym;
1933   varray_t *vp = &ext_symbols;
1934   shash_t *hash_ptr = (shash_t *) 0;
1935
1936   str_start = ORIG_ESTRS (esym->asym.iss);
1937   str_end_p1 = str_start + strlen (str_start);
1938
1939   if (debug > 1)
1940     {
1941       long value = esym->asym.value;
1942       const char *sc_str = sc_to_string ((sc_t) esym->asym.sc);
1943       const char *st_str = st_to_string ((st_t) esym->asym.st);
1944
1945       fprintf (stderr,
1946                "\tesym\tv= %10ld, ifd= %2d, sc= %-12s",
1947                value, ifd, sc_str);
1948
1949       if (str_start && str_end_p1 - str_start > 0)
1950         fprintf (stderr, " st= %-11s name= %.*s\n",
1951                  st_str, (int) (str_end_p1 - str_start), str_start);
1952       else
1953         fprintf (stderr, " st= %s\n", st_str);
1954     }
1955
1956   if (vp->objects_last_page == vp->objects_per_page)
1957     add_varray_page (vp);
1958
1959   psym = &vp->last->datum->esym[ vp->objects_last_page++ ];
1960
1961   *psym = *esym;
1962   psym->ifd = ifd;
1963   psym->asym.index = indexNil;
1964   psym->asym.iss   = (str_start == (const char *) 0)
1965                         ? 0
1966                         : add_string (&ext_strings,
1967                                       &ext_str_hash[0],
1968                                       str_start,
1969                                       str_end_p1,
1970                                       &hash_ptr);
1971
1972   hash_ptr->esym_ptr = psym;
1973   return vp->num_allocated++;
1974 }
1975
1976 \f
1977 /* Add an auxiliary symbol (passing a symint).  */
1978
1979 STATIC symint_t
1980 add_aux_sym_symint (symint_t aux_word)
1981 {
1982   AUXU *aux_ptr;
1983   efdr_t *file_ptr = cur_file_ptr;
1984   varray_t *vp = &file_ptr->aux_syms;
1985
1986   if (vp->objects_last_page == vp->objects_per_page)
1987     add_varray_page (vp);
1988
1989   aux_ptr = &vp->last->datum->aux[ vp->objects_last_page++ ];
1990   aux_ptr->isym = aux_word;
1991
1992   return vp->num_allocated++;
1993 }
1994
1995
1996 /* Add an auxiliary symbol (passing a file/symbol index combo).  */
1997
1998 STATIC symint_t
1999 add_aux_sym_rndx (int file_index, symint_t sym_index)
2000 {
2001   AUXU *aux_ptr;
2002   efdr_t *file_ptr = cur_file_ptr;
2003   varray_t *vp = &file_ptr->aux_syms;
2004
2005   if (vp->objects_last_page == vp->objects_per_page)
2006     add_varray_page (vp);
2007
2008   aux_ptr = &vp->last->datum->aux[ vp->objects_last_page++ ];
2009   aux_ptr->rndx.rfd   = file_index;
2010   aux_ptr->rndx.index = sym_index;
2011
2012   return vp->num_allocated++;
2013 }
2014
2015 \f
2016 /* Add an auxiliary symbol (passing the basic type and possibly
2017    type qualifiers).  */
2018
2019 STATIC symint_t
2020 add_aux_sym_tir (type_info_t *t, hash_state_t state, thash_t **hash_tbl)
2021 {
2022   AUXU *aux_ptr;
2023   efdr_t *file_ptr = cur_file_ptr;
2024   varray_t *vp = &file_ptr->aux_syms;
2025   static AUXU init_aux;
2026   symint_t ret;
2027   int i;
2028   AUXU aux;
2029
2030   aux = init_aux;
2031   aux.ti.bt = (int) t->basic_type;
2032   aux.ti.continued = 0;
2033   aux.ti.fBitfield = t->bitfield;
2034
2035   aux.ti.tq0 = (int) t->type_qualifiers[0];
2036   aux.ti.tq1 = (int) t->type_qualifiers[1];
2037   aux.ti.tq2 = (int) t->type_qualifiers[2];
2038   aux.ti.tq3 = (int) t->type_qualifiers[3];
2039   aux.ti.tq4 = (int) t->type_qualifiers[4];
2040   aux.ti.tq5 = (int) t->type_qualifiers[5];
2041
2042
2043   /* For anything that adds additional information, we must not hash,
2044      so check here, and reset our state.  */
2045
2046   if (state != hash_no
2047       && (t->type_qualifiers[0] == tq_Array
2048           || t->type_qualifiers[1] == tq_Array
2049           || t->type_qualifiers[2] == tq_Array
2050           || t->type_qualifiers[3] == tq_Array
2051           || t->type_qualifiers[4] == tq_Array
2052           || t->type_qualifiers[5] == tq_Array
2053           || t->basic_type == bt_Struct
2054           || t->basic_type == bt_Union
2055           || t->basic_type == bt_Enum
2056           || t->bitfield
2057           || t->num_dims > 0))
2058     state = hash_no;
2059
2060   /* See if we can hash this type, and save some space, but some types
2061      can't be hashed (because they contain arrays or continuations),
2062      and others can be put into the hash list, but cannot use existing
2063      types because other aux entries precede this one.  */
2064
2065   if (state != hash_no)
2066     {
2067       thash_t *hash_ptr;
2068       symint_t hi;
2069
2070       hi = aux.isym & ((1 << HASHBITS) - 1);
2071       hi %= THASH_SIZE;
2072
2073       for (hash_ptr = hash_tbl[hi];
2074            hash_ptr != (thash_t *) 0;
2075            hash_ptr = hash_ptr->next)
2076         {
2077           if (aux.isym == hash_ptr->type.isym)
2078             break;
2079         }
2080
2081       if (hash_ptr != (thash_t *) 0 && state == hash_yes)
2082         return hash_ptr->indx;
2083
2084       if (hash_ptr == (thash_t *) 0)
2085         {
2086           hash_ptr = allocate_thash ();
2087           hash_ptr->next = hash_tbl[hi];
2088           hash_ptr->type = aux;
2089           hash_ptr->indx = vp->num_allocated;
2090           hash_tbl[hi] = hash_ptr;
2091         }
2092     }
2093
2094   /* Everything is set up, add the aux symbol.  */
2095   if (vp->objects_last_page == vp->objects_per_page)
2096     add_varray_page (vp);
2097
2098   aux_ptr = &vp->last->datum->aux[ vp->objects_last_page++ ];
2099   *aux_ptr = aux;
2100
2101   ret = vp->num_allocated++;
2102
2103   /* Add bitfield length if it exists.
2104
2105      NOTE:  Mips documentation claims bitfield goes at the end of the
2106      AUX record, but the DECstation compiler emits it here.
2107      (This would only make a difference for enum bitfields.)
2108
2109      Also note:  We use the last size given since gcc may emit 2
2110      for an enum bitfield.  */
2111
2112   if (t->bitfield)
2113     (void) add_aux_sym_symint ((symint_t) t->sizes[t->num_sizes-1]);
2114
2115
2116   /* Add tag information if needed.  Structure, union, and enum
2117      references add 2 aux symbols: a [file index, symbol index]
2118      pointer to the structure type, and the current file index.  */
2119
2120   if (t->basic_type == bt_Struct
2121       || t->basic_type == bt_Union
2122       || t->basic_type == bt_Enum)
2123     {
2124       symint_t file_index = t->tag_ptr->ifd;
2125       symint_t sym_index  = t->tag_ptr->indx;
2126
2127       if (t->unknown_tag)
2128         {
2129           (void) add_aux_sym_rndx (ST_RFDESCAPE, sym_index);
2130           (void) add_aux_sym_symint ((symint_t)-1);
2131         }
2132       else if (sym_index != indexNil)
2133         {
2134           (void) add_aux_sym_rndx (ST_RFDESCAPE, sym_index);
2135           (void) add_aux_sym_symint (file_index);
2136         }
2137       else
2138         {
2139           forward_t *forward_ref = allocate_forward ();
2140
2141           forward_ref->type_ptr = aux_ptr;
2142           forward_ref->next = t->tag_ptr->forward_ref;
2143           t->tag_ptr->forward_ref = forward_ref;
2144
2145           (void) add_aux_sym_rndx (ST_RFDESCAPE, sym_index);
2146           forward_ref->index_ptr
2147             = &vp->last->datum->aux[ vp->objects_last_page - 1];
2148
2149           (void) add_aux_sym_symint (file_index);
2150           forward_ref->ifd_ptr
2151             = &vp->last->datum->aux[ vp->objects_last_page - 1];
2152         }
2153     }
2154
2155   /* Add information about array bounds if they exist.  */
2156   for (i = 0; i < t->num_dims; i++)
2157     {
2158       (void) add_aux_sym_rndx (ST_RFDESCAPE,
2159                                cur_file_ptr->int_type);
2160
2161       (void) add_aux_sym_symint (cur_file_ptr->file_index);     /* file index*/
2162       (void) add_aux_sym_symint ((symint_t) 0);                 /* low bound */
2163       (void) add_aux_sym_symint (t->dimensions[i] - 1);         /* high bound*/
2164       (void) add_aux_sym_symint ((t->dimensions[i] == 0)        /* stride */
2165                               ? 0
2166                               : (t->sizes[i] * 8) / t->dimensions[i]);
2167     };
2168
2169   /* NOTE:  Mips documentation claims that the bitfield width goes here.
2170      But it needs to be emitted earlier.  */
2171
2172   return ret;
2173 }
2174
2175 \f
2176 /* Add a tag to the tag table (unless it already exists).  */
2177
2178 STATIC tag_t *
2179 get_tag (const char *tag_start,         /* 1st byte of tag name */
2180          const char *tag_end_p1,        /* 1st byte after tag name */
2181          symint_t indx,         /* index of tag start block */
2182          bt_t basic_type)               /* bt_Struct, bt_Union, or bt_Enum */
2183
2184 {
2185   shash_t *hash_ptr;
2186   tag_t *tag_ptr;
2187   hash_ptr = hash_string (tag_start,
2188                           tag_end_p1 - tag_start,
2189                           &tag_hash[0],
2190                           (symint_t *) 0);
2191
2192   if (hash_ptr != (shash_t *) 0
2193       && hash_ptr->tag_ptr != (tag_t *) 0)
2194   {
2195     tag_ptr = hash_ptr->tag_ptr;
2196     if (indx != indexNil)
2197       {
2198         tag_ptr->basic_type = basic_type;
2199         tag_ptr->ifd        = cur_file_ptr->file_index;
2200         tag_ptr->indx       = indx;
2201       }
2202     return tag_ptr;
2203   }
2204
2205   (void) add_string (&tag_strings,
2206                      &tag_hash[0],
2207                      tag_start,
2208                      tag_end_p1,
2209                      &hash_ptr);
2210
2211   tag_ptr = allocate_tag ();
2212   tag_ptr->forward_ref  = (forward_t *) 0;
2213   tag_ptr->hash_ptr     = hash_ptr;
2214   tag_ptr->same_name    = hash_ptr->tag_ptr;
2215   tag_ptr->basic_type   = basic_type;
2216   tag_ptr->indx         = indx;
2217   tag_ptr->ifd          = (indx == indexNil
2218                            ? (symint_t) -1 : cur_file_ptr->file_index);
2219   tag_ptr->same_block   = cur_tag_head->first_tag;
2220
2221   cur_tag_head->first_tag = tag_ptr;
2222   hash_ptr->tag_ptr       = tag_ptr;
2223
2224   return tag_ptr;
2225 }
2226
2227 \f
2228 /* Add an unknown {struct, union, enum} tag.  */
2229
2230 STATIC void
2231 add_unknown_tag (tag_t *ptag)
2232 {
2233   shash_t *hash_ptr     = ptag->hash_ptr;
2234   char *name_start      = hash_ptr->string;
2235   char *name_end_p1     = name_start + hash_ptr->len;
2236   forward_t *f_next     = ptag->forward_ref;
2237   forward_t *f_cur;
2238   int sym_index;
2239   int file_index        = cur_file_ptr->file_index;
2240
2241   if (debug > 1)
2242     {
2243       const char *agg_type = "{unknown aggregate type}";
2244       switch (ptag->basic_type)
2245         {
2246         case bt_Struct: agg_type = "struct";    break;
2247         case bt_Union:  agg_type = "union";     break;
2248         case bt_Enum:   agg_type = "enum";      break;
2249         default:                                break;
2250         }
2251
2252       fprintf (stderr, "unknown %s %.*s found\n",
2253                agg_type, (int) hash_ptr->len, name_start);
2254     }
2255
2256   sym_index = add_local_symbol (name_start,
2257                                 name_end_p1,
2258                                 st_Block,
2259                                 sc_Info,
2260                                 (symint_t) 0,
2261                                 (symint_t) 0);
2262
2263   (void) add_local_symbol (name_start,
2264                            name_end_p1,
2265                            st_End,
2266                            sc_Info,
2267                            (symint_t) 0,
2268                            (symint_t) 0);
2269
2270   while (f_next != (forward_t *) 0)
2271     {
2272       f_cur  = f_next;
2273       f_next = f_next->next;
2274
2275       f_cur->ifd_ptr->isym = file_index;
2276       f_cur->index_ptr->rndx.index = sym_index;
2277
2278       free_forward (f_cur);
2279     }
2280
2281   return;
2282 }
2283
2284 \f
2285 /* Add a procedure to the current file's list of procedures, and record
2286    this is the current procedure.  If the assembler created a PDR for
2287    this procedure, use that to initialize the current PDR.  */
2288
2289 STATIC void
2290 add_procedure (const char *func_start,  /* 1st byte of func name */
2291                const char *func_end_p1) /* 1st byte after func name */
2292 {
2293   PDR *new_proc_ptr;
2294   efdr_t *file_ptr = cur_file_ptr;
2295   varray_t *vp = &file_ptr->procs;
2296   symint_t value = 0;
2297   st_t proc_type = st_Proc;
2298   shash_t *shash_ptr = hash_string (func_start,
2299                                     func_end_p1 - func_start,
2300                                     &orig_str_hash[0],
2301                                     (symint_t *) 0);
2302
2303   if (debug)
2304     fputc ('\n', stderr);
2305
2306   if (vp->objects_last_page == vp->objects_per_page)
2307     add_varray_page (vp);
2308
2309   cur_proc_ptr = new_proc_ptr = &vp->last->datum->proc[ vp->objects_last_page++ ];
2310
2311   vp->num_allocated++;
2312
2313
2314   /* Did the assembler create this procedure?  If so, get the PDR information.  */
2315   cur_oproc_ptr = (PDR *) 0;
2316   if (shash_ptr != (shash_t *) 0)
2317     {
2318       PDR *old_proc_ptr = shash_ptr->proc_ptr;
2319       SYMR *sym_ptr = shash_ptr->sym_ptr;
2320
2321       if (old_proc_ptr != (PDR *) 0
2322           && sym_ptr != (SYMR *) 0
2323           && ((st_t) sym_ptr->st == st_Proc || (st_t) sym_ptr->st == st_StaticProc))
2324         {
2325           cur_oproc_begin = sym_ptr;
2326           cur_oproc_end = shash_ptr->end_ptr;
2327           value = sym_ptr->value;
2328
2329           cur_oproc_ptr = old_proc_ptr;
2330           proc_type = (st_t) sym_ptr->st;
2331           *new_proc_ptr = *old_proc_ptr;        /* initialize */
2332         }
2333     }
2334
2335   if (cur_oproc_ptr == (PDR *) 0)
2336     error ("did not find a PDR block for %.*s",
2337            (int) (func_end_p1 - func_start), func_start);
2338
2339   /* Determine the start of symbols.  */
2340   new_proc_ptr->isym = file_ptr->symbols.num_allocated;
2341
2342   /* Push the start of the function.  */
2343   (void) add_local_symbol (func_start, func_end_p1,
2344                            proc_type, sc_Text,
2345                            value,
2346                            (symint_t) 0);
2347 }
2348
2349 \f
2350 /* Initialize the init_file structure.  */
2351
2352 STATIC void
2353 initialize_init_file (void)
2354 {
2355   union {
2356     unsigned char c[4];
2357     int i;
2358   } endian_test;
2359
2360   memset (&init_file, 0, sizeof (init_file));
2361
2362   init_file.fdr.lang = langC;
2363   init_file.fdr.fMerge = 1;
2364   init_file.fdr.glevel = GLEVEL_2;
2365
2366   /* mips-tfile doesn't attempt to perform byte swapping and always writes
2367      out integers in its native ordering.  For cross-compilers, this need
2368      not be the same as either the host or the target.  The simplest thing
2369      to do is skip the configury and perform an introspective test.  */
2370   /* ??? Despite the name, mips-tfile is currently only used on alpha/Tru64
2371      and would/may require significant work to be used in cross-compiler
2372      configurations, so we could simply admit defeat and hard code this as
2373      little-endian, i.e. init_file.fdr.fBigendian = 0.  */
2374   endian_test.i = 1;
2375   if (endian_test.c[3])
2376     init_file.fdr.fBigendian = 1;
2377
2378   INITIALIZE_VARRAY (&init_file.strings, char);
2379   INITIALIZE_VARRAY (&init_file.symbols, SYMR);
2380   INITIALIZE_VARRAY (&init_file.procs, PDR);
2381   INITIALIZE_VARRAY (&init_file.aux_syms, AUXU);
2382
2383   init_file_initialized = 1;
2384 }
2385
2386 /* Add a new filename, and set up all of the file relative
2387    virtual arrays (strings, symbols, aux syms, etc.).  Record
2388    where the current file structure lives.  */
2389
2390 STATIC void
2391 add_file (const char *file_start,  /* first byte in string */
2392           const char *file_end_p1) /* first byte after string */
2393 {
2394   static char zero_bytes[2] = { '\0', '\0' };
2395
2396   Ptrdiff_t len = file_end_p1 - file_start;
2397   int first_ch = *file_start;
2398   efdr_t *file_ptr;
2399
2400   if (debug)
2401     fprintf (stderr, "\tfile\t%.*s\n", (int) len, file_start);
2402
2403   /* See if the file has already been created.  */
2404   for (file_ptr = first_file;
2405        file_ptr != (efdr_t *) 0;
2406        file_ptr = file_ptr->next_file)
2407     {
2408       if (first_ch == file_ptr->name[0]
2409           && file_ptr->name[len] == '\0'
2410           && memcmp (file_start, file_ptr->name, len) == 0)
2411         {
2412           cur_file_ptr = file_ptr;
2413           break;
2414         }
2415     }
2416
2417   /* If this is a new file, create it.  */
2418   if (file_ptr == (efdr_t *) 0)
2419     {
2420       if (file_desc.objects_last_page == file_desc.objects_per_page)
2421         add_varray_page (&file_desc);
2422
2423       if (! init_file_initialized)
2424         initialize_init_file ();
2425
2426       file_ptr = cur_file_ptr
2427         = &file_desc.last->datum->file[ file_desc.objects_last_page++ ];
2428       *file_ptr = init_file;
2429
2430       file_ptr->file_index = file_desc.num_allocated++;
2431
2432       /* Allocate the string hash table.  */
2433       file_ptr->shash_head = (shash_t **) allocate_page ();
2434
2435       /* Make sure 0 byte in string table is null  */
2436       add_string (&file_ptr->strings,
2437                   &file_ptr->shash_head[0],
2438                   &zero_bytes[0],
2439                   &zero_bytes[0],
2440                   (shash_t **) 0);
2441
2442       if (file_end_p1 - file_start > (long) PAGE_USIZE-2)
2443         fatal ("filename goes over one page boundary");
2444
2445       /* Push the start of the filename. We assume that the filename
2446          will be stored at string offset 1.  */
2447       (void) add_local_symbol (file_start, file_end_p1, st_File, sc_Text,
2448                                (symint_t) 0, (symint_t) 0);
2449       file_ptr->fdr.rss = 1;
2450       file_ptr->name = &file_ptr->strings.last->datum->byte[1];
2451       file_ptr->name_len = file_end_p1 - file_start;
2452
2453       /* Update the linked list of file descriptors.  */
2454       *last_file_ptr = file_ptr;
2455       last_file_ptr = &file_ptr->next_file;
2456
2457       /* Add void & int types to the file (void should be first to catch
2458          errant 0's within the index fields).  */
2459       file_ptr->void_type = add_aux_sym_tir (&void_type_info,
2460                                              hash_yes,
2461                                              &cur_file_ptr->thash_head[0]);
2462
2463       file_ptr->int_type = add_aux_sym_tir (&int_type_info,
2464                                             hash_yes,
2465                                             &cur_file_ptr->thash_head[0]);
2466     }
2467 }
2468
2469 \f
2470 /* Add a stream of random bytes to a varray.  */
2471
2472 STATIC void
2473 add_bytes (varray_t *vp,        /* virtual array to add too */
2474            char *input_ptr,     /* start of the bytes */
2475            Size_t nitems)       /* # items to move */
2476 {
2477   Size_t move_items;
2478   Size_t move_bytes;
2479   char *ptr;
2480
2481   while (nitems > 0)
2482     {
2483       if (vp->objects_last_page >= vp->objects_per_page)
2484         add_varray_page (vp);
2485
2486       ptr = &vp->last->datum->byte[ vp->objects_last_page * vp->object_size ];
2487       move_items = vp->objects_per_page - vp->objects_last_page;
2488       if (move_items > nitems)
2489         move_items = nitems;
2490
2491       move_bytes = move_items * vp->object_size;
2492       nitems -= move_items;
2493
2494       if (move_bytes >= 32)
2495         {
2496           (void) memcpy (ptr, input_ptr, move_bytes);
2497           input_ptr += move_bytes;
2498         }
2499       else
2500         {
2501           while (move_bytes-- > 0)
2502             *ptr++ = *input_ptr++;
2503         }
2504     }
2505 }
2506
2507 \f
2508 /* Convert storage class to string.  */
2509
2510 STATIC const char *
2511 sc_to_string (sc_t storage_class)
2512 {
2513   switch (storage_class)
2514     {
2515     case sc_Nil:         return "Nil,";
2516     case sc_Text:        return "Text,";
2517     case sc_Data:        return "Data,";
2518     case sc_Bss:         return "Bss,";
2519     case sc_Register:    return "Register,";
2520     case sc_Abs:         return "Abs,";
2521     case sc_Undefined:   return "Undefined,";
2522     case sc_CdbLocal:    return "CdbLocal,";
2523     case sc_Bits:        return "Bits,";
2524     case sc_CdbSystem:   return "CdbSystem,";
2525     case sc_RegImage:    return "RegImage,";
2526     case sc_Info:        return "Info,";
2527     case sc_UserStruct:  return "UserStruct,";
2528     case sc_SData:       return "SData,";
2529     case sc_SBss:        return "SBss,";
2530     case sc_RData:       return "RData,";
2531     case sc_Var:         return "Var,";
2532     case sc_Common:      return "Common,";
2533     case sc_SCommon:     return "SCommon,";
2534     case sc_VarRegister: return "VarRegister,";
2535     case sc_Variant:     return "Variant,";
2536     case sc_SUndefined:  return "SUndefined,";
2537     case sc_Init:        return "Init,";
2538     case sc_Max:         return "Max,";
2539     }
2540
2541   return "???,";
2542 }
2543
2544 \f
2545 /* Convert symbol type to string.  */
2546
2547 STATIC const char *
2548 st_to_string (st_t symbol_type)
2549 {
2550   switch (symbol_type)
2551     {
2552     case st_Nil:        return "Nil,";
2553     case st_Global:     return "Global,";
2554     case st_Static:     return "Static,";
2555     case st_Param:      return "Param,";
2556     case st_Local:      return "Local,";
2557     case st_Label:      return "Label,";
2558     case st_Proc:       return "Proc,";
2559     case st_Block:      return "Block,";
2560     case st_End:        return "End,";
2561     case st_Member:     return "Member,";
2562     case st_Typedef:    return "Typedef,";
2563     case st_File:       return "File,";
2564     case st_RegReloc:   return "RegReloc,";
2565     case st_Forward:    return "Forward,";
2566     case st_StaticProc: return "StaticProc,";
2567     case st_Constant:   return "Constant,";
2568     case st_Str:        return "String,";
2569     case st_Number:     return "Number,";
2570     case st_Expr:       return "Expr,";
2571     case st_Type:       return "Type,";
2572     case st_Max:        return "Max,";
2573     }
2574
2575   return "???,";
2576 }
2577
2578 \f
2579 /* Read a line from standard input, and return the start of the buffer
2580    (which is grows if the line is too big).  We split lines at the
2581    semi-colon, and return each logical line independently.  */
2582
2583 STATIC char *
2584 read_line (void)
2585 {
2586   static   int line_split_p     = 0;
2587   int string_p          = 0;
2588   int comment_p = 0;
2589   int ch;
2590   char *ptr;
2591
2592   if (cur_line_start == (char *) 0)
2593     {                           /* allocate initial page */
2594       cur_line_start = (char *) allocate_page ();
2595       cur_line_alloc = PAGE_SIZE;
2596     }
2597
2598   if (!line_split_p)
2599     line_number++;
2600
2601   line_split_p = 0;
2602   cur_line_nbytes = 0;
2603
2604   for (ptr = cur_line_start; (ch = getchar ()) != EOF; *ptr++ = ch)
2605     {
2606       if (++cur_line_nbytes >= cur_line_alloc-1)
2607         {
2608           int num_pages = cur_line_alloc / PAGE_SIZE;
2609           char *old_buffer = cur_line_start;
2610
2611           cur_line_alloc += PAGE_SIZE;
2612           cur_line_start = (char *) allocate_multiple_pages (num_pages+1);
2613           memcpy (cur_line_start, old_buffer, num_pages * PAGE_SIZE);
2614
2615           ptr = cur_line_start + cur_line_nbytes - 1;
2616         }
2617
2618       if (ch == '\n')
2619         {
2620           *ptr++ = '\n';
2621           *ptr = '\0';
2622           cur_line_ptr = cur_line_start;
2623           return cur_line_ptr;
2624         }
2625
2626       else if (ch == '\0')
2627         error ("null character found in input");
2628
2629       else if (!comment_p)
2630         {
2631           if (ch == '"')
2632             string_p = !string_p;
2633
2634           else if (ch == '#')
2635             comment_p++;
2636
2637           else if (ch == ';' && !string_p)
2638             {
2639               line_split_p = 1;
2640               *ptr++ = '\n';
2641               *ptr = '\0';
2642               cur_line_ptr = cur_line_start;
2643               return cur_line_ptr;
2644             }
2645         }
2646     }
2647
2648   if (ferror (stdin))
2649     pfatal_with_name (input_name);
2650
2651   cur_line_ptr = (char *) 0;
2652   return (char *) 0;
2653 }
2654
2655 \f
2656 /* Parse #.begin directives which have a label as the first argument
2657    which gives the location of the start of the block.  */
2658
2659 STATIC void
2660 parse_begin (const char *start)
2661 {
2662   const char *end_p1;                   /* end of label */
2663   int ch;
2664   shash_t *hash_ptr;                    /* hash pointer to lookup label */
2665
2666   if (cur_file_ptr == (efdr_t *) 0)
2667     {
2668       error ("#.begin directive without a preceding .file directive");
2669       return;
2670     }
2671
2672   if (cur_proc_ptr == (PDR *) 0)
2673     {
2674       error ("#.begin directive without a preceding .ent directive");
2675       return;
2676     }
2677
2678   for (end_p1 = start; (ch = *end_p1) != '\0' && !ISSPACE (ch); end_p1++)
2679     ;
2680
2681   hash_ptr = hash_string (start,
2682                           end_p1 - start,
2683                           &orig_str_hash[0],
2684                           (symint_t *) 0);
2685
2686   if (hash_ptr == (shash_t *) 0)
2687     {
2688       error ("label %.*s not found for #.begin",
2689              (int) (end_p1 - start), start);
2690       return;
2691     }
2692
2693   if (cur_oproc_begin == (SYMR *) 0)
2694     {
2695       error ("procedure table %.*s not found for #.begin",
2696              (int) (end_p1 - start), start);
2697       return;
2698     }
2699
2700   (void) add_local_symbol ((const char *) 0, (const char *) 0,
2701                            st_Block, sc_Text,
2702                            (symint_t) hash_ptr->sym_ptr->value - cur_oproc_begin->value,
2703                            (symint_t) 0);
2704 }
2705
2706 \f
2707 /* Parse #.bend directives which have a label as the first argument
2708    which gives the location of the end of the block.  */
2709
2710 STATIC void
2711 parse_bend (const char *start)
2712 {
2713   const char *end_p1;                   /* end of label */
2714   int ch;
2715   shash_t *hash_ptr;                    /* hash pointer to lookup label */
2716
2717   if (cur_file_ptr == (efdr_t *) 0)
2718     {
2719       error ("#.begin directive without a preceding .file directive");
2720       return;
2721     }
2722
2723   if (cur_proc_ptr == (PDR *) 0)
2724     {
2725       error ("#.bend directive without a preceding .ent directive");
2726       return;
2727     }
2728
2729   for (end_p1 = start; (ch = *end_p1) != '\0' && !ISSPACE (ch); end_p1++)
2730     ;
2731
2732   hash_ptr = hash_string (start,
2733                           end_p1 - start,
2734                           &orig_str_hash[0],
2735                           (symint_t *) 0);
2736
2737   if (hash_ptr == (shash_t *) 0)
2738     {
2739       error ("label %.*s not found for #.bend", (int) (end_p1 - start), start);
2740       return;
2741     }
2742
2743   if (cur_oproc_begin == (SYMR *) 0)
2744     {
2745       error ("procedure table %.*s not found for #.bend",
2746              (int) (end_p1 - start), start);
2747       return;
2748     }
2749
2750   (void) add_local_symbol ((const char *) 0, (const char *) 0,
2751                            st_End, sc_Text,
2752                            (symint_t) hash_ptr->sym_ptr->value - cur_oproc_begin->value,
2753                            (symint_t) 0);
2754 }
2755
2756 \f
2757 /* Parse #.def directives, which are contain standard COFF subdirectives
2758    to describe the debugging format.  These subdirectives include:
2759
2760         .scl    specify storage class
2761         .val    specify a value
2762         .endef  specify end of COFF directives
2763         .type   specify the type
2764         .size   specify the size of an array
2765         .dim    specify an array dimension
2766         .tag    specify a tag for a struct, union, or enum.  */
2767
2768 STATIC void
2769 parse_def (const char *name_start)
2770 {
2771   const char *dir_start;                        /* start of current directive*/
2772   const char *dir_end_p1;                       /* end+1 of current directive*/
2773   const char *arg_start;                        /* start of current argument */
2774   const char *arg_end_p1;                       /* end+1 of current argument */
2775   const char *name_end_p1;                      /* end+1 of label */
2776   const char *tag_start   = 0;                  /* start of tag name */
2777   const char *tag_end_p1  = 0;                  /* end+1 of tag name */
2778   sc_t storage_class      = sc_Nil;
2779   st_t symbol_type        = st_Nil;
2780   type_info_t t;
2781   EXTR *eptr              = (EXTR *) 0;         /* ext. sym equivalent to def*/
2782   int is_function         = 0;                  /* != 0 if function */
2783   symint_t value          = 0;
2784   symint_t indx           = cur_file_ptr->void_type;
2785   int error_line          = 0;
2786   symint_t arg_number;
2787   symint_t temp_array[ N_TQ ];
2788   int arg_was_number;
2789   int ch, i;
2790   Ptrdiff_t len;
2791
2792   static int inside_enumeration = 0;            /* is this an enumeration? */
2793
2794
2795   /* Initialize the type information.  */
2796   t = type_info_init;
2797
2798
2799   /* Search for the end of the name being defined.  */
2800   /* Allow spaces and such in names for G++ templates, which produce stabs
2801      that look like:
2802
2803      #.def   SMANIP<long unsigned int>; .scl 10; .type 0x8; .size 8; .endef */
2804
2805   for (name_end_p1 = name_start; (ch = *name_end_p1) != ';' && ch != '\0'; name_end_p1++)
2806     ;
2807
2808   if (ch == '\0')
2809     {
2810       error_line = __LINE__;
2811       saber_stop ();
2812       goto bomb_out;
2813     }
2814
2815   /* Parse the remaining subdirectives now.  */
2816   dir_start = name_end_p1+1;
2817   for (;;)
2818     {
2819       while ((ch = *dir_start) == ' ' || ch == '\t')
2820         ++dir_start;
2821
2822       if (ch != '.')
2823         {
2824           error_line = __LINE__;
2825           saber_stop ();
2826           goto bomb_out;
2827         }
2828
2829       /* Are we done? */
2830       if (dir_start[1] == 'e'
2831           && memcmp (dir_start, ".endef", sizeof (".endef")-1) == 0)
2832         break;
2833
2834       /* Pick up the subdirective now.  */
2835       for (dir_end_p1 = dir_start+1;
2836            (ch = *dir_end_p1) != ' ' && ch != '\t';
2837            dir_end_p1++)
2838         {
2839           if (ch == '\0' || ISSPACE (ch))
2840             {
2841               error_line = __LINE__;
2842               saber_stop ();
2843               goto bomb_out;
2844             }
2845         }
2846
2847       /* Pick up the subdirective argument now.  */
2848       arg_was_number = arg_number = 0;
2849       arg_end_p1 = 0;
2850       arg_start = dir_end_p1+1;
2851       ch = *arg_start;
2852       while (ch == ' ' || ch == '\t')
2853         ch = *++arg_start;
2854
2855       if (ISDIGIT (ch) || ch == '-' || ch == '+')
2856         {
2857           int ch2;
2858           arg_number = strtol (arg_start, (char **) &arg_end_p1, 0);
2859           /* It's only a number if followed by ';' or ','. */
2860           if (arg_end_p1 != arg_start && (((ch2 = *arg_end_p1) == ';') || ch2 == ','))
2861             arg_was_number++;
2862         }
2863
2864       else if (ch == '\0' || ISSPACE (ch))
2865         {
2866           error_line = __LINE__;
2867           saber_stop ();
2868           goto bomb_out;
2869         }
2870
2871       if (!arg_was_number)
2872         {
2873           /* Allow spaces and such in names for G++ templates.  */
2874           for (arg_end_p1 = arg_start+1;
2875                (ch = *arg_end_p1) != ';' && ch != '\0';
2876                arg_end_p1++)
2877             ;
2878
2879           if (ch == '\0')
2880             {
2881               error_line = __LINE__;
2882               saber_stop ();
2883               goto bomb_out;
2884             }
2885         }
2886
2887       /* Classify the directives now.  */
2888       len = dir_end_p1 - dir_start;
2889       switch (dir_start[1])
2890         {
2891         default:
2892           error_line = __LINE__;
2893           saber_stop ();
2894           goto bomb_out;
2895
2896         case 'd':
2897           if (len == sizeof (".dim")-1
2898               && memcmp (dir_start, ".dim", sizeof (".dim")-1) == 0
2899               && arg_was_number)
2900             {
2901               symint_t *t_ptr = &temp_array[ N_TQ-1 ];
2902
2903               *t_ptr = arg_number;
2904               while (*arg_end_p1 == ',' && arg_was_number)
2905                 {
2906                   arg_start = arg_end_p1+1;
2907                   ch = *arg_start;
2908                   while (ch == ' ' || ch == '\t')
2909                     ch = *++arg_start;
2910
2911                   arg_was_number = 0;
2912                   if (ISDIGIT (ch) || ch == '-' || ch == '+')
2913                     {
2914                       int ch2;
2915                       arg_number = strtol (arg_start, (char **) &arg_end_p1, 0);
2916                       if (arg_end_p1 != arg_start && (((ch2 = *arg_end_p1) == ';') || ch2 == ','))
2917                         arg_was_number++;
2918
2919                       if (t_ptr == &temp_array[0])
2920                         {
2921                           error_line = __LINE__;
2922                           saber_stop ();
2923                           goto bomb_out;
2924                         }
2925
2926                       *--t_ptr = arg_number;
2927                     }
2928                 }
2929
2930               /* Reverse order of dimensions.  */
2931               while (t_ptr <= &temp_array[ N_TQ-1 ])
2932                 {
2933                   if (t.num_dims >= N_TQ-1)
2934                     {
2935                       error_line = __LINE__;
2936                       saber_stop ();
2937                       goto bomb_out;
2938                     }
2939
2940                   t.dimensions[ t.num_dims++ ] = *t_ptr++;
2941                 }
2942               break;
2943             }
2944           else
2945             {
2946               error_line = __LINE__;
2947               saber_stop ();
2948               goto bomb_out;
2949             }
2950
2951
2952         case 's':
2953           if (len == sizeof (".scl")-1
2954               && memcmp (dir_start, ".scl", sizeof (".scl")-1) == 0
2955               && arg_was_number
2956               && arg_number < ((symint_t) C_MAX))
2957             {
2958               /* If the symbol is a static or external, we have
2959                  already gotten the appropriate type and class, so
2960                  make sure we don't override those values.  This is
2961                  needed because there are some type and classes that
2962                  are not in COFF, such as short data, etc.  */
2963               if (symbol_type == st_Nil)
2964                 {
2965                   symbol_type   = map_coff_sym_type[arg_number];
2966                   storage_class = map_coff_storage [arg_number];
2967                 }
2968               break;
2969             }
2970
2971           else if (len == sizeof (".size")-1
2972                    && memcmp (dir_start, ".size", sizeof (".size")-1) == 0
2973                    && arg_was_number)
2974             {
2975               symint_t *t_ptr = &temp_array[ N_TQ-1 ];
2976
2977               *t_ptr = arg_number;
2978               while (*arg_end_p1 == ',' && arg_was_number)
2979                 {
2980                   arg_start = arg_end_p1+1;
2981                   ch = *arg_start;
2982                   while (ch == ' ' || ch == '\t')
2983                     ch = *++arg_start;
2984
2985                   arg_was_number = 0;
2986                   if (ISDIGIT (ch) || ch == '-' || ch == '+')
2987                     {
2988                       int ch2;
2989                       arg_number = strtol (arg_start, (char **) &arg_end_p1, 0);
2990                       if (arg_end_p1 != arg_start && (((ch2 = *arg_end_p1) == ';') || ch2 == ','))
2991                         arg_was_number++;
2992
2993                       if (t_ptr == &temp_array[0])
2994                         {
2995                           error_line = __LINE__;
2996                           saber_stop ();
2997                           goto bomb_out;
2998                         }
2999
3000                       *--t_ptr = arg_number;
3001                     }
3002                 }
3003
3004               /* Reverse order of sizes.  */
3005               while (t_ptr <= &temp_array[ N_TQ-1 ])
3006                 {
3007                   if (t.num_sizes >= N_TQ-1)
3008                     {
3009                       error_line = __LINE__;
3010                       saber_stop ();
3011                       goto bomb_out;
3012                     }
3013
3014                   t.sizes[ t.num_sizes++ ] = *t_ptr++;
3015                 }
3016               break;
3017             }
3018
3019           else
3020             {
3021               error_line = __LINE__;
3022               saber_stop ();
3023               goto bomb_out;
3024             }
3025
3026
3027         case 't':
3028           if (len == sizeof (".type")-1
3029               && memcmp (dir_start, ".type", sizeof (".type")-1) == 0
3030               && arg_was_number)
3031             {
3032               tq_t *tq_ptr = &t.type_qualifiers[0];
3033
3034               t.orig_type = (coff_type_t) (arg_number & N_BTMASK);
3035               t.basic_type = map_coff_types [(int) t.orig_type];
3036               for (i = N_TQ-1; i >= 0; i--)
3037                 {
3038                   int dt = (arg_number >> ((i * N_TQ_SHIFT) + N_BT_SHIFT)
3039                             & N_TMASK);
3040
3041                   if (dt != (int) DT_NON)
3042                     *tq_ptr++ = map_coff_derived_type [dt];
3043                 }
3044
3045               /* If this is a function, ignore it, so that we don't get
3046                  two entries (one from the .ent, and one for the .def
3047                  that precedes it).  Save the type information so that
3048                  the end block can properly add it after the begin block
3049                  index.  For MIPS knows what reason, we must strip off
3050                  the function type at this point.  */
3051               if (tq_ptr != &t.type_qualifiers[0] && tq_ptr[-1] == tq_Proc)
3052                 {
3053                   is_function = 1;
3054                   tq_ptr[-1] = tq_Nil;
3055                 }
3056
3057               break;
3058             }
3059
3060           else if (len == sizeof (".tag")-1
3061               && memcmp (dir_start, ".tag", sizeof (".tag")-1) == 0)
3062             {
3063               tag_start = arg_start;
3064               tag_end_p1 = arg_end_p1;
3065               break;
3066             }
3067
3068           else
3069             {
3070               error_line = __LINE__;
3071               saber_stop ();
3072               goto bomb_out;
3073             }
3074
3075
3076         case 'v':
3077           if (len == sizeof (".val")-1
3078               && memcmp (dir_start, ".val", sizeof (".val")-1) == 0)
3079             {
3080               if (arg_was_number)
3081                 value = arg_number;
3082
3083               /* If the value is not an integer value, it must be the
3084                  name of a static or global item.  Look up the name in
3085                  the original symbol table to pick up the storage
3086                  class, symbol type, etc.  */
3087               else
3088                 {
3089                   shash_t *orig_hash_ptr;       /* hash within orig sym table*/
3090                   shash_t *ext_hash_ptr;        /* hash within ext. sym table*/
3091
3092                   ext_hash_ptr = hash_string (arg_start,
3093                                               arg_end_p1 - arg_start,
3094                                               &ext_str_hash[0],
3095                                               (symint_t *) 0);
3096
3097                   if (ext_hash_ptr != (shash_t *) 0
3098                       && ext_hash_ptr->esym_ptr != (EXTR *) 0)
3099                     eptr = ext_hash_ptr->esym_ptr;
3100
3101                   orig_hash_ptr = hash_string (arg_start,
3102                                                arg_end_p1 - arg_start,
3103                                                &orig_str_hash[0],
3104                                                (symint_t *) 0);
3105
3106                   if ((orig_hash_ptr == (shash_t *) 0
3107                        || orig_hash_ptr->sym_ptr == (SYMR *) 0)
3108                       && eptr == (EXTR *) 0)
3109                     {
3110                       fprintf (stderr, "warning, %.*s not found in original or external symbol tables, value defaults to 0\n",
3111                                (int) (arg_end_p1 - arg_start),
3112                                arg_start);
3113                       value = 0;
3114                     }
3115                   else
3116                     {
3117                       SYMR *ptr = (orig_hash_ptr != (shash_t *) 0
3118                                    && orig_hash_ptr->sym_ptr != (SYMR *) 0)
3119                                         ? orig_hash_ptr->sym_ptr
3120                                         : &eptr->asym;
3121
3122                       symbol_type = (st_t) ptr->st;
3123                       storage_class = (sc_t) ptr->sc;
3124                       value = ptr->value;
3125                     }
3126                 }
3127               break;
3128             }
3129           else
3130             {
3131               error_line = __LINE__;
3132               saber_stop ();
3133               goto bomb_out;
3134             }
3135         }
3136
3137       /* Set up to find next directive.  */
3138       dir_start = arg_end_p1 + 1;
3139     }
3140
3141
3142   if (storage_class == sc_Bits)
3143     {
3144       t.bitfield = 1;
3145       t.extra_sizes = 1;
3146     }
3147   else
3148     t.extra_sizes = 0;
3149
3150   if (t.num_dims > 0)
3151     {
3152       int num_real_sizes = t.num_sizes - t.extra_sizes;
3153       int diff = t.num_dims - num_real_sizes;
3154       int i = t.num_dims - 1;
3155       int j;
3156
3157       if (num_real_sizes != 1 || diff < 0)
3158         {
3159           error_line = __LINE__;
3160           saber_stop ();
3161           goto bomb_out;
3162         }
3163
3164       /* If this is an array, make sure the same number of dimensions
3165          and sizes were passed, creating extra sizes for multiply
3166          dimensioned arrays if not passed.  */
3167
3168       if (diff)
3169         {
3170           for (j = ARRAY_SIZE (t.sizes) - 1; j >= 0; j--)
3171             t.sizes[ j ] = ((j-diff) >= 0) ? t.sizes[ j-diff ] : 0;
3172
3173           t.num_sizes = i + 1;
3174           for ( i--; i >= 0; i-- )
3175             {
3176               if (t.dimensions[ i+1 ])
3177                 t.sizes[ i ] = t.sizes[ i+1 ] / t.dimensions[ i+1 ];
3178               else
3179                 t.sizes[ i ] = t.sizes[ i+1 ];
3180             }
3181         }
3182     }
3183
3184   /* Except for enumeration members & begin/ending of scopes, put the
3185      type word in the aux. symbol table.  */
3186
3187   if (symbol_type == st_Block || symbol_type == st_End)
3188     indx = 0;
3189
3190   else if (inside_enumeration)
3191     indx = cur_file_ptr->void_type;
3192
3193   else
3194     {
3195       if (t.basic_type == bt_Struct
3196           || t.basic_type == bt_Union
3197           || t.basic_type == bt_Enum)
3198         {
3199           if (tag_start == (char *) 0)
3200             {
3201               error ("no tag specified for %.*s",
3202                      (int) (name_end_p1 - name_start),
3203                      name_start);
3204               return;
3205             }
3206
3207           t.tag_ptr = get_tag (tag_start, tag_end_p1,  (symint_t) indexNil,
3208                                t.basic_type);
3209         }
3210
3211       if (is_function)
3212         {
3213           last_func_type_info = t;
3214           last_func_eptr = eptr;
3215           return;
3216         }
3217
3218       indx = add_aux_sym_tir (&t,
3219                               hash_yes,
3220                               &cur_file_ptr->thash_head[0]);
3221     }
3222
3223
3224   /* If this is an external or static symbol, update the appropriate
3225      external symbol.  */
3226
3227   if (eptr != (EXTR *) 0
3228       && (eptr->asym.index == indexNil || cur_proc_ptr == (PDR *) 0))
3229     {
3230       eptr->ifd = cur_file_ptr->file_index;
3231       eptr->asym.index = indx;
3232     }
3233
3234
3235   /* Do any last minute adjustments that are necessary.  */
3236   switch (symbol_type)
3237     {
3238     default:
3239       break;
3240
3241
3242       /* For the beginning of structs, unions, and enumerations, the
3243          size info needs to be passed in the value field.  */
3244
3245     case st_Block:
3246       if (t.num_sizes - t.num_dims - t.extra_sizes != 1)
3247         {
3248           error_line = __LINE__;
3249           saber_stop ();
3250           goto bomb_out;
3251         }
3252
3253       else
3254         value = t.sizes[0];
3255
3256       inside_enumeration = (t.orig_type == T_ENUM);
3257       break;
3258
3259
3260       /* For the end of structs, unions, and enumerations, omit the
3261          name which is always ".eos".  This needs to be done last, so
3262          that any error reporting above gives the correct name.  */
3263
3264     case st_End:
3265       name_start = name_end_p1 = 0;
3266       value = inside_enumeration = 0;
3267       break;
3268
3269
3270       /* Members of structures and unions that aren't bitfields, need
3271          to adjust the value from a byte offset to a bit offset.
3272          Members of enumerations do not have the value adjusted, and
3273          can be distinguished by indx == indexNil.  For enumerations,
3274          update the maximum enumeration value.  */
3275
3276     case st_Member:
3277       if (!t.bitfield && !inside_enumeration)
3278         value *= 8;
3279
3280       break;
3281     }
3282
3283
3284   /* Add the symbol, except for global symbols outside of functions,
3285      for which the external symbol table is fine enough.  */
3286
3287   if (eptr == (EXTR *) 0
3288       || eptr->asym.st == (int) st_Nil
3289       || cur_proc_ptr != (PDR *) 0)
3290     {
3291       symint_t isym = add_local_symbol (name_start, name_end_p1,
3292                                         symbol_type, storage_class,
3293                                         value,
3294                                         indx);
3295
3296       /* Deal with struct, union, and enum tags.  */
3297       if (symbol_type == st_Block)
3298         {
3299           /* Create or update the tag information.  */
3300           tag_t *tag_ptr = get_tag (name_start,
3301                                     name_end_p1,
3302                                     isym,
3303                                     t.basic_type);
3304
3305           /* If there are any forward references, fill in the appropriate
3306              file and symbol indexes.  */
3307
3308           symint_t file_index  = cur_file_ptr->file_index;
3309           forward_t *f_next = tag_ptr->forward_ref;
3310           forward_t *f_cur;
3311
3312           while (f_next != (forward_t *) 0)
3313             {
3314               f_cur  = f_next;
3315               f_next = f_next->next;
3316
3317               f_cur->ifd_ptr->isym = file_index;
3318               f_cur->index_ptr->rndx.index = isym;
3319
3320               free_forward (f_cur);
3321             }
3322
3323           tag_ptr->forward_ref = (forward_t *) 0;
3324         }
3325     }
3326
3327   /* Normal return  */
3328   return;
3329
3330   /* Error return, issue message.  */
3331 bomb_out:
3332   if (error_line)
3333     error ("compiler error, badly formed #.def (internal line # = %d)", error_line);
3334   else
3335     error ("compiler error, badly formed #.def");
3336
3337   return;
3338 }
3339
3340 \f
3341 /* Parse .end directives.  */
3342
3343 STATIC void
3344 parse_end (const char *start)
3345 {
3346   const char *start_func, *end_func_p1;
3347   int ch;
3348   symint_t value;
3349   FDR *orig_fdr;
3350
3351   if (cur_file_ptr == (efdr_t *) 0)
3352     {
3353       error (".end directive without a preceding .file directive");
3354       return;
3355     }
3356
3357   if (cur_proc_ptr == (PDR *) 0)
3358     {
3359       error (".end directive without a preceding .ent directive");
3360       return;
3361     }
3362
3363   /* Get the function name, skipping whitespace.  */
3364   for (start_func = start; ISSPACE ((unsigned char)*start_func); start_func++)
3365     ;
3366
3367   ch = *start_func;
3368   if (!IS_ASM_IDENT (ch))
3369     {
3370       error (".end directive has no name");
3371       return;
3372     }
3373
3374   for (end_func_p1 = start_func; IS_ASM_IDENT (ch); ch = *++end_func_p1)
3375     ;
3376
3377
3378   /* Get the value field for creating the end from the original object
3379      file (which we find by locating the procedure start, and using the
3380      pointer to the end+1 block and backing up.  The index points to a
3381      two word aux. symbol, whose first word is the index of the end
3382      symbol, and the second word is the type of the function return
3383      value.  */
3384
3385   orig_fdr = cur_file_ptr->orig_fdr;
3386   value = 0;
3387   if (orig_fdr != (FDR *) 0 && cur_oproc_end != (SYMR *) 0)
3388     value = cur_oproc_end->value;
3389
3390   else
3391     error ("cannot find .end block for %.*s",
3392            (int) (end_func_p1 - start_func), start_func);
3393
3394   (void) add_local_symbol (start_func, end_func_p1,
3395                            st_End, sc_Text,
3396                            value,
3397                            (symint_t) 0);
3398
3399   cur_proc_ptr = cur_oproc_ptr = (PDR *) 0;
3400 }
3401
3402 \f
3403 /* Parse .ent directives.  */
3404
3405 STATIC void
3406 parse_ent (const char *start)
3407 {
3408   const char *start_func, *end_func_p1;
3409   int ch;
3410
3411   if (cur_file_ptr == (efdr_t *) 0)
3412     {
3413       error (".ent directive without a preceding .file directive");
3414       return;
3415     }
3416
3417   if (cur_proc_ptr != (PDR *) 0)
3418     {
3419       error ("second .ent directive found before .end directive");
3420       return;
3421     }
3422
3423   for (start_func = start; ISSPACE ((unsigned char)*start_func); start_func++)
3424     ;
3425
3426   ch = *start_func;
3427   if (!IS_ASM_IDENT (ch))
3428     {
3429       error (".ent directive has no name");
3430       return;
3431     }
3432
3433   for (end_func_p1 = start_func; IS_ASM_IDENT (ch); ch = *++end_func_p1)
3434     ;
3435
3436   (void) add_procedure (start_func, end_func_p1);
3437 }
3438
3439 \f
3440 /* Parse .file directives.  */
3441
3442 STATIC void
3443 parse_file (const char *start)
3444 {
3445   char *p;
3446   char *start_name, *end_name_p1;
3447
3448   (void) strtol (start, &p, 0);
3449   if (start == p
3450       || (start_name = strchr (p, '"')) == (char *) 0
3451       || (end_name_p1 = strrchr (++start_name, '"')) == (char *) 0)
3452     {
3453       error ("invalid .file directive");
3454       return;
3455     }
3456
3457   if (cur_proc_ptr != (PDR *) 0)
3458     {
3459       error ("no way to handle .file within .ent/.end section");
3460       return;
3461     }
3462
3463   add_file (start_name, end_name_p1);
3464 }
3465
3466 \f
3467 /* Make sure the @stabs symbol is emitted.  */
3468
3469 static void
3470 mark_stabs (const char *start ATTRIBUTE_UNUSED)
3471 {
3472   if (!stabs_seen)
3473     {
3474       /* Add a dummy @stabs symbol.  */
3475       stabs_seen = 1;
3476       (void) add_local_symbol (stabs_symbol,
3477                                stabs_symbol + sizeof (stabs_symbol),
3478                                (st_t) stNil, (sc_t) scInfo, -1,
3479                                MIPS_MARK_STAB (0));
3480
3481     }
3482 }
3483
3484 \f
3485 /* Parse .stabs directives.
3486
3487    .stabs directives have five fields:
3488         "string"        a string, encoding the type information.
3489         code            a numeric code, defined in <stab.h>
3490         0               a zero
3491         0               a zero or line number
3492         value           a numeric value or an address.
3493
3494     If the value is relocatable, we transform this into:
3495         iss             points as an index into string space
3496         value           value from lookup of the name
3497         st              st from lookup of the name
3498         sc              sc from lookup of the name
3499         index           code|CODE_MASK
3500
3501     If the value is not relocatable, we transform this into:
3502         iss             points as an index into string space
3503         value           value
3504         st              st_Nil
3505         sc              sc_Nil
3506         index           code|CODE_MASK
3507
3508     .stabn directives have four fields (string is null):
3509         code            a numeric code, defined in <stab.h>
3510         0               a zero
3511         0               a zero or a line number
3512         value           a numeric value or an address.  */
3513
3514 STATIC void
3515 parse_stabs_common (const char *string_start,   /* start of string or NULL */
3516                     const char *string_end,     /* end+1 of string or NULL */
3517                     const char *rest)           /* rest of the directive.  */
3518 {
3519   efdr_t *save_file_ptr = cur_file_ptr;
3520   symint_t code;
3521   symint_t value;
3522   char *p;
3523   st_t st;
3524   sc_t sc;
3525   int ch;
3526
3527   if (stabs_seen == 0)
3528     mark_stabs ("");
3529
3530   /* Read code from stabs.  */
3531   if (!ISDIGIT (*rest))
3532     {
3533       error ("invalid .stabs/.stabn directive, code is non-numeric");
3534       return;
3535     }
3536
3537   code = strtol (rest, &p, 0);
3538
3539   /* Line number stabs are handled differently, since they have two values,
3540      the line number and the address of the label.  We use the index field
3541      (aka code) to hold the line number, and the value field to hold the
3542      address.  The symbol type is st_Label, which should be different from
3543      the other stabs, so that gdb can recognize it.  */
3544
3545   if (code == (int) N_SLINE)
3546     {
3547       SYMR *sym_ptr, dummy_symr;
3548       shash_t *shash_ptr;
3549
3550       /* Skip ,0, */
3551       if (p[0] != ',' || p[1] != '0' || p[2] != ',' || !ISDIGIT (p[3]))
3552         {
3553           error ("invalid line number .stabs/.stabn directive");
3554           return;
3555         }
3556
3557       code = strtol (p+3, &p, 0);
3558       ch = *++p;
3559       if (p[-1] != ',' || ISDIGIT (ch) || !IS_ASM_IDENT (ch))
3560         {
3561           error ("invalid line number .stabs/.stabn directive");
3562           return;
3563         }
3564
3565       dummy_symr.index = code;
3566       if (dummy_symr.index != code)
3567         {
3568           error ("line number (%lu) for .stabs/.stabn directive cannot fit in index field (20 bits)",
3569                  code);
3570
3571           return;
3572         }
3573
3574       shash_ptr = hash_string (p,
3575                                strlen (p) - 1,
3576                                &orig_str_hash[0],
3577                                (symint_t *) 0);
3578
3579       if (shash_ptr == (shash_t *) 0
3580           || (sym_ptr = shash_ptr->sym_ptr) == (SYMR *) 0)
3581         {
3582           error ("invalid .stabs/.stabn directive, value not found");
3583           return;
3584         }
3585
3586       if ((st_t) sym_ptr->st != st_Label)
3587         {
3588           error ("invalid line number .stabs/.stabn directive");
3589           return;
3590         }
3591
3592       st = st_Label;
3593       sc = (sc_t) sym_ptr->sc;
3594       value = sym_ptr->value;
3595     }
3596   else
3597     {
3598       /* Skip ,<num>,<num>, */
3599       if (*p++ != ',')
3600         goto failure;
3601       for (; ISDIGIT (*p); p++)
3602         ;
3603       if (*p++ != ',')
3604         goto failure;
3605       for (; ISDIGIT (*p); p++)
3606         ;
3607       if (*p++ != ',')
3608         goto failure;
3609       ch = *p;
3610       if (!IS_ASM_IDENT (ch) && ch != '-')
3611         {
3612         failure:
3613           error ("invalid .stabs/.stabn directive, bad character");
3614           return;
3615         }
3616
3617       if (ISDIGIT (ch) || ch == '-')
3618         {
3619           st = st_Nil;
3620           sc = sc_Nil;
3621           value = strtol (p, &p, 0);
3622           if (*p != '\n')
3623             {
3624               error ("invalid .stabs/.stabn directive, stuff after numeric value");
3625               return;
3626             }
3627         }
3628       else if (!IS_ASM_IDENT (ch))
3629         {
3630           error ("invalid .stabs/.stabn directive, bad character");
3631           return;
3632         }
3633       else
3634         {
3635           SYMR *sym_ptr;
3636           shash_t *shash_ptr;
3637           const char *start, *end_p1;
3638
3639           start = p;
3640           if ((end_p1 = strchr (start, '+')) == (char *) 0)
3641             {
3642               if ((end_p1 = strchr (start, '-')) == (char *) 0)
3643                 end_p1 = start + strlen (start) - 1;
3644             }
3645
3646           shash_ptr = hash_string (start,
3647                                    end_p1 - start,
3648                                    &orig_str_hash[0],
3649                                    (symint_t *) 0);
3650
3651           if (shash_ptr == (shash_t *) 0
3652               || (sym_ptr = shash_ptr->sym_ptr) == (SYMR *) 0)
3653             {
3654               shash_ptr = hash_string (start,
3655                                        end_p1 - start,
3656                                        &ext_str_hash[0],
3657                                        (symint_t *) 0);
3658
3659               if (shash_ptr == (shash_t *) 0
3660                   || shash_ptr->esym_ptr == (EXTR *) 0)
3661                 {
3662                   error ("invalid .stabs/.stabn directive, value not found");
3663                   return;
3664                 }
3665               else
3666                 sym_ptr = &(shash_ptr->esym_ptr->asym);
3667             }
3668
3669           /* Traditionally, N_LBRAC and N_RBRAC are *not* relocated.  */
3670           if (code == (int) N_LBRAC || code == (int) N_RBRAC)
3671             {
3672               sc = (sc_t) scNil;
3673               st = (st_t) stNil;
3674             }
3675           else
3676             {
3677               sc = (sc_t) sym_ptr->sc;
3678               st = (st_t) sym_ptr->st;
3679             }
3680           value = sym_ptr->value;
3681
3682           ch = *end_p1++;
3683           if (ch != '\n')
3684             {
3685               if (((!ISDIGIT (*end_p1)) && (*end_p1 != '-'))
3686                   || ((ch != '+') && (ch != '-')))
3687                 {
3688                   error ("invalid .stabs/.stabn directive, badly formed value");
3689                   return;
3690                 }
3691               if (ch == '+')
3692                 value += strtol (end_p1, &p, 0);
3693               else if (ch == '-')
3694                 value -= strtol (end_p1, &p, 0);
3695
3696               if (*p != '\n')
3697                 {
3698                   error ("invalid .stabs/.stabn directive, stuff after numeric value");
3699                   return;
3700                 }
3701             }
3702         }
3703       code = MIPS_MARK_STAB (code);
3704     }
3705
3706   (void) add_local_symbol (string_start, string_end, st, sc, value, code);
3707   /* Restore normal file type.  */
3708   cur_file_ptr = save_file_ptr;
3709 }
3710
3711
3712 STATIC void
3713 parse_stabs (const char *start)
3714 {
3715   const char *end = strchr (start+1, '"');
3716
3717   if (*start != '"' || end == (const char *) 0 || end[1] != ',')
3718     {
3719       error ("invalid .stabs directive, no string");
3720       return;
3721     }
3722
3723   parse_stabs_common (start+1, end, end+2);
3724 }
3725
3726
3727 STATIC void
3728 parse_stabn (const char *start)
3729 {
3730   parse_stabs_common ((const char *) 0, (const char *) 0, start);
3731 }
3732
3733 \f
3734 /* Parse the input file, and write the lines to the output file
3735    if needed.  */
3736
3737 STATIC void
3738 parse_input (void)
3739 {
3740   char *p;
3741   Size_t i;
3742   thead_t *ptag_head;
3743   tag_t *ptag;
3744   tag_t *ptag_next;
3745
3746   if (debug)
3747     fprintf (stderr, "\tinput\n");
3748
3749   /* Add a dummy scope block around the entire compilation unit for
3750      structures defined outside of blocks.  */
3751   ptag_head = allocate_thead ();
3752   ptag_head->first_tag = 0;
3753   ptag_head->prev = cur_tag_head;
3754   cur_tag_head = ptag_head;
3755
3756   while ((p = read_line ()) != (char *) 0)
3757     {
3758       /* Skip leading blanks.  */
3759       while (ISSPACE ((unsigned char)*p))
3760         p++;
3761
3762       /* See if it's a directive we handle.  If so, dispatch handler.  */
3763       for (i = 0; i < ARRAY_SIZE (pseudo_ops); i++)
3764         if (memcmp (p, pseudo_ops[i].name, pseudo_ops[i].len) == 0
3765             && ISSPACE ((unsigned char)(p[pseudo_ops[i].len])))
3766           {
3767             p += pseudo_ops[i].len;     /* skip to first argument */
3768             while (ISSPACE ((unsigned char)*p))
3769               p++;
3770
3771             (*pseudo_ops[i].func)( p );
3772             break;
3773           }
3774     }
3775
3776   /* Process any tags at global level.  */
3777   ptag_head = cur_tag_head;
3778   cur_tag_head = ptag_head->prev;
3779
3780   for (ptag = ptag_head->first_tag;
3781        ptag != (tag_t *) 0;
3782        ptag = ptag_next)
3783     {
3784       if (ptag->forward_ref != (forward_t *) 0)
3785         add_unknown_tag (ptag);
3786
3787       ptag_next = ptag->same_block;
3788       ptag->hash_ptr->tag_ptr = ptag->same_name;
3789       free_tag (ptag);
3790     }
3791
3792   free_thead (ptag_head);
3793
3794 }
3795
3796 \f
3797 /* Update the global headers with the final offsets in preparation
3798    to write out the .T file.  */
3799
3800 STATIC void
3801 update_headers (void)
3802 {
3803   symint_t i;
3804   efdr_t *file_ptr;
3805
3806   /* Set up the symbolic header.  */
3807   file_offset = sizeof (symbolic_header) + orig_file_header.f_symptr;
3808   symbolic_header.magic = orig_sym_hdr.magic;
3809   symbolic_header.vstamp = orig_sym_hdr.vstamp;
3810
3811   /* Set up global counts.  */
3812   symbolic_header.issExtMax = ext_strings.num_allocated;
3813   symbolic_header.idnMax    = dense_num.num_allocated;
3814   symbolic_header.ifdMax    = file_desc.num_allocated;
3815   symbolic_header.iextMax   = ext_symbols.num_allocated;
3816   symbolic_header.ilineMax  = orig_sym_hdr.ilineMax;
3817   symbolic_header.ioptMax   = orig_sym_hdr.ioptMax;
3818   symbolic_header.cbLine    = orig_sym_hdr.cbLine;
3819   symbolic_header.crfd      = orig_sym_hdr.crfd;
3820
3821
3822   /* Loop through each file, figuring out how many local syms,
3823      line numbers, etc. there are.  Also, put out end symbol
3824      for the filename.  */
3825
3826   for (file_ptr = first_file;
3827        file_ptr != (efdr_t *) 0;
3828        file_ptr = file_ptr->next_file)
3829     {
3830       SYMR *sym_start;
3831       SYMR *sym;
3832       SYMR *sym_end_p1;
3833       FDR *fd_ptr = file_ptr->orig_fdr;
3834
3835       cur_file_ptr = file_ptr;
3836
3837       /* Copy st_Static symbols from the original local symbol table if
3838          they did not get added to the new local symbol table.
3839          This happens with stabs-in-ecoff or if the source file is
3840          compiled without debugging.  */
3841       sym_start = ORIG_LSYMS (fd_ptr->isymBase);
3842       sym_end_p1 = sym_start + fd_ptr->csym;
3843       for (sym = sym_start; sym < sym_end_p1; sym++)
3844         {
3845           if ((st_t) sym->st == st_Static)
3846             {
3847               char *str = ORIG_LSTRS (fd_ptr->issBase + sym->iss);
3848               Size_t len = strlen (str);
3849               shash_t *hash_ptr;
3850
3851               /* Ignore internal labels.  */
3852               if (str[0] == '$' && str[1] == 'L')
3853                 continue;
3854               hash_ptr = hash_string (str,
3855                                       (Ptrdiff_t) len,
3856                                       &file_ptr->shash_head[0],
3857                                       (symint_t *) 0);
3858               if (hash_ptr == (shash_t *) 0)
3859                 {
3860                   (void) add_local_symbol (str, str + len,
3861                                            (st_t) sym->st, (sc_t) sym->sc,
3862                                            (symint_t) sym->value,
3863                                            (symint_t) indexNil);
3864                 }
3865             }
3866         }
3867       (void) add_local_symbol ((const char *) 0, (const char *) 0,
3868                                st_End, sc_Text,
3869                                (symint_t) 0,
3870                                (symint_t) 0);
3871
3872       file_ptr->fdr.cpd = file_ptr->procs.num_allocated;
3873       file_ptr->fdr.ipdFirst = symbolic_header.ipdMax;
3874       symbolic_header.ipdMax += file_ptr->fdr.cpd;
3875
3876       file_ptr->fdr.csym = file_ptr->symbols.num_allocated;
3877       file_ptr->fdr.isymBase = symbolic_header.isymMax;
3878       symbolic_header.isymMax += file_ptr->fdr.csym;
3879
3880       file_ptr->fdr.caux = file_ptr->aux_syms.num_allocated;
3881       file_ptr->fdr.iauxBase = symbolic_header.iauxMax;
3882       symbolic_header.iauxMax += file_ptr->fdr.caux;
3883
3884       file_ptr->fdr.cbSs = file_ptr->strings.num_allocated;
3885       file_ptr->fdr.issBase = symbolic_header.issMax;
3886       symbolic_header.issMax += file_ptr->fdr.cbSs;
3887     }
3888
3889 #ifndef ALIGN_SYMTABLE_OFFSET
3890 #define ALIGN_SYMTABLE_OFFSET(OFFSET) (OFFSET)
3891 #endif
3892
3893   file_offset = ALIGN_SYMTABLE_OFFSET (file_offset);
3894   i = WORD_ALIGN (symbolic_header.cbLine);      /* line numbers */
3895   if (i > 0)
3896     {
3897       symbolic_header.cbLineOffset = file_offset;
3898       file_offset += i;
3899       file_offset = ALIGN_SYMTABLE_OFFSET (file_offset);
3900     }
3901
3902   i = symbolic_header.ioptMax;                  /* optimization symbols */
3903   if (((long) i) > 0)
3904     {
3905       symbolic_header.cbOptOffset = file_offset;
3906       file_offset += i * sizeof (OPTR);
3907       file_offset = ALIGN_SYMTABLE_OFFSET (file_offset);
3908     }
3909
3910   i = symbolic_header.idnMax;                   /* dense numbers */
3911   if (i > 0)
3912     {
3913       symbolic_header.cbDnOffset = file_offset;
3914       file_offset += i * sizeof (DNR);
3915       file_offset = ALIGN_SYMTABLE_OFFSET (file_offset);
3916     }
3917
3918   i = symbolic_header.ipdMax;                   /* procedure tables */
3919   if (i > 0)
3920     {
3921       symbolic_header.cbPdOffset = file_offset;
3922       file_offset += i * sizeof (PDR);
3923       file_offset = ALIGN_SYMTABLE_OFFSET (file_offset);
3924     }
3925
3926   i = symbolic_header.isymMax;                  /* local symbols */
3927   if (i > 0)
3928     {
3929       symbolic_header.cbSymOffset = file_offset;
3930       file_offset += i * sizeof (SYMR);
3931       file_offset = ALIGN_SYMTABLE_OFFSET (file_offset);
3932     }
3933
3934   i = symbolic_header.iauxMax;                  /* aux syms.  */
3935   if (i > 0)
3936     {
3937       symbolic_header.cbAuxOffset = file_offset;
3938       file_offset += i * sizeof (TIR);
3939       file_offset = ALIGN_SYMTABLE_OFFSET (file_offset);
3940     }
3941
3942   i = WORD_ALIGN (symbolic_header.issMax);      /* local strings */
3943   if (i > 0)
3944     {
3945       symbolic_header.cbSsOffset = file_offset;
3946       file_offset += i;
3947       file_offset = ALIGN_SYMTABLE_OFFSET (file_offset);
3948     }
3949
3950   i = WORD_ALIGN (symbolic_header.issExtMax);   /* external strings */
3951   if (i > 0)
3952     {
3953       symbolic_header.cbSsExtOffset = file_offset;
3954       file_offset += i;
3955       file_offset = ALIGN_SYMTABLE_OFFSET (file_offset);
3956     }
3957
3958   i = symbolic_header.ifdMax;                   /* file tables */
3959   if (i > 0)
3960     {
3961       symbolic_header.cbFdOffset = file_offset;
3962       file_offset += i * sizeof (FDR);
3963       file_offset = ALIGN_SYMTABLE_OFFSET (file_offset);
3964     }
3965
3966   i = symbolic_header.crfd;                     /* relative file descriptors */
3967   if (i > 0)
3968     {
3969       symbolic_header.cbRfdOffset = file_offset;
3970       file_offset += i * sizeof (symint_t);
3971       file_offset = ALIGN_SYMTABLE_OFFSET (file_offset);
3972     }
3973
3974   i = symbolic_header.iextMax;                  /* external symbols */
3975   if (i > 0)
3976     {
3977       symbolic_header.cbExtOffset = file_offset;
3978       file_offset += i * sizeof (EXTR);
3979       file_offset = ALIGN_SYMTABLE_OFFSET (file_offset);
3980     }
3981 }
3982
3983 \f
3984 /* Write out a varray at a given location.  */
3985
3986 STATIC void
3987 write_varray (varray_t *vp,    /* virtual array */
3988               off_t offset,    /* offset to write varray to */
3989               const char *str) /* string to print out when tracing */
3990 {
3991   int num_write, sys_write;
3992   vlinks_t *ptr;
3993
3994   if (vp->num_allocated == 0)
3995     return;
3996
3997   if (debug)
3998     fprintf (stderr, "\twarray\tvp = %p, offset = %7lu, size = %7lu, %s\n",
3999              (void *) vp, (unsigned long) offset,
4000              vp->num_allocated * vp->object_size, str);
4001
4002   if (file_offset != (unsigned long) offset
4003       && fseek (object_stream, (long) offset, SEEK_SET) < 0)
4004     pfatal_with_name (object_name);
4005
4006   for (ptr = vp->first; ptr != (vlinks_t *) 0; ptr = ptr->next)
4007     {
4008       num_write = (ptr->next == (vlinks_t *) 0)
4009         ? vp->objects_last_page * vp->object_size
4010         : vp->objects_per_page  * vp->object_size;
4011
4012       sys_write = fwrite (ptr->datum, 1, num_write, object_stream);
4013       if (sys_write <= 0)
4014         pfatal_with_name (object_name);
4015
4016       else if (sys_write != num_write)
4017         fatal ("wrote %d bytes to %s, system returned %d",
4018                num_write,
4019                object_name,
4020                sys_write);
4021
4022       file_offset += num_write;
4023     }
4024 }
4025
4026 \f
4027 /* Write out the symbol table in the object file.  */
4028
4029 STATIC void
4030 write_object (void)
4031 {
4032   int sys_write;
4033   efdr_t *file_ptr;
4034   off_t offset;
4035
4036   if (debug)
4037     fprintf (stderr, "\n\twrite\tvp = %p, offset = %7u, size = %7lu, %s\n",
4038              (void *) &symbolic_header, 0,
4039              (unsigned long) sizeof (symbolic_header), "symbolic header");
4040
4041   sys_write = fwrite (&symbolic_header,
4042                       1,
4043                       sizeof (symbolic_header),
4044                       object_stream);
4045
4046   if (sys_write < 0)
4047     pfatal_with_name (object_name);
4048
4049   else if (sys_write != sizeof (symbolic_header))
4050     fatal ("wrote %d bytes to %s, system returned %d",
4051            (int) sizeof (symbolic_header),
4052            object_name,
4053            sys_write);
4054
4055
4056   file_offset = sizeof (symbolic_header) + orig_file_header.f_symptr;
4057
4058   if (symbolic_header.cbLine > 0)               /* line numbers */
4059     {
4060       long sys_write;
4061
4062       if (file_offset != (unsigned long) symbolic_header.cbLineOffset
4063           && fseek (object_stream, symbolic_header.cbLineOffset, SEEK_SET) != 0)
4064         pfatal_with_name (object_name);
4065
4066       if (debug)
4067         fprintf (stderr, "\twrite\tvp = %p, offset = %7lu, size = %7lu, %s\n",
4068                  (void *) &orig_linenum, (long) symbolic_header.cbLineOffset,
4069                  (long) symbolic_header.cbLine, "Line numbers");
4070
4071       sys_write = fwrite (orig_linenum,
4072                           1,
4073                           symbolic_header.cbLine,
4074                           object_stream);
4075
4076       if (sys_write <= 0)
4077         pfatal_with_name (object_name);
4078
4079       else if (sys_write != symbolic_header.cbLine)
4080         fatal ("wrote %ld bytes to %s, system returned %ld",
4081                (long) symbolic_header.cbLine,
4082                object_name,
4083                sys_write);
4084
4085       file_offset = symbolic_header.cbLineOffset + symbolic_header.cbLine;
4086     }
4087
4088   if (symbolic_header.ioptMax > 0)              /* optimization symbols */
4089     {
4090       long sys_write;
4091       long num_write = symbolic_header.ioptMax * sizeof (OPTR);
4092
4093       if (file_offset != (unsigned long) symbolic_header.cbOptOffset
4094           && fseek (object_stream, symbolic_header.cbOptOffset, SEEK_SET) != 0)
4095         pfatal_with_name (object_name);
4096
4097       if (debug)
4098         fprintf (stderr, "\twrite\tvp = %p, offset = %7lu, size = %7lu, %s\n",
4099                  (void *) &orig_opt_syms, (long) symbolic_header.cbOptOffset,
4100                  num_write, "Optimizer symbols");
4101
4102       sys_write = fwrite (orig_opt_syms,
4103                           1,
4104                           num_write,
4105                           object_stream);
4106
4107       if (sys_write <= 0)
4108         pfatal_with_name (object_name);
4109
4110       else if (sys_write != num_write)
4111         fatal ("wrote %ld bytes to %s, system returned %ld",
4112                num_write,
4113                object_name,
4114                sys_write);
4115
4116       file_offset = symbolic_header.cbOptOffset + num_write;
4117     }
4118
4119   if (symbolic_header.idnMax > 0)               /* dense numbers */
4120     write_varray (&dense_num, (off_t) symbolic_header.cbDnOffset, "Dense numbers");
4121
4122   if (symbolic_header.ipdMax > 0)               /* procedure tables */
4123     {
4124       offset = symbolic_header.cbPdOffset;
4125       for (file_ptr = first_file;
4126            file_ptr != (efdr_t *) 0;
4127            file_ptr = file_ptr->next_file)
4128         {
4129           write_varray (&file_ptr->procs, offset, "Procedure tables");
4130           offset = file_offset;
4131         }
4132     }
4133
4134   if (symbolic_header.isymMax > 0)              /* local symbols */
4135     {
4136       offset = symbolic_header.cbSymOffset;
4137       for (file_ptr = first_file;
4138            file_ptr != (efdr_t *) 0;
4139            file_ptr = file_ptr->next_file)
4140         {
4141           write_varray (&file_ptr->symbols, offset, "Local symbols");
4142           offset = file_offset;
4143         }
4144     }
4145
4146   if (symbolic_header.iauxMax > 0)              /* aux symbols */
4147     {
4148       offset = symbolic_header.cbAuxOffset;
4149       for (file_ptr = first_file;
4150            file_ptr != (efdr_t *) 0;
4151            file_ptr = file_ptr->next_file)
4152         {
4153           write_varray (&file_ptr->aux_syms, offset, "Aux. symbols");
4154           offset = file_offset;
4155         }
4156     }
4157
4158   if (symbolic_header.issMax > 0)               /* local strings */
4159     {
4160       offset = symbolic_header.cbSsOffset;
4161       for (file_ptr = first_file;
4162            file_ptr != (efdr_t *) 0;
4163            file_ptr = file_ptr->next_file)
4164         {
4165           write_varray (&file_ptr->strings, offset, "Local strings");
4166           offset = file_offset;
4167         }
4168     }
4169
4170   if (symbolic_header.issExtMax > 0)            /* external strings */
4171     write_varray (&ext_strings, symbolic_header.cbSsExtOffset, "External strings");
4172
4173   if (symbolic_header.ifdMax > 0)               /* file tables */
4174     {
4175       offset = symbolic_header.cbFdOffset;
4176       if (file_offset != (unsigned long) offset
4177           && fseek (object_stream, (long) offset, SEEK_SET) < 0)
4178         pfatal_with_name (object_name);
4179
4180       file_offset = offset;
4181       for (file_ptr = first_file;
4182            file_ptr != (efdr_t *) 0;
4183            file_ptr = file_ptr->next_file)
4184         {
4185           if (debug)
4186             fprintf (stderr, "\twrite\tvp = %p, offset = %7lu, size = %7lu, %s\n",
4187                      (void *) &file_ptr->fdr, file_offset,
4188                      (unsigned long) sizeof (FDR), "File header");
4189
4190           sys_write = fwrite (&file_ptr->fdr,
4191                               1,
4192                               sizeof (FDR),
4193                               object_stream);
4194
4195           if (sys_write < 0)
4196             pfatal_with_name (object_name);
4197
4198           else if (sys_write != sizeof (FDR))
4199             fatal ("wrote %d bytes to %s, system returned %d",
4200                    (int) sizeof (FDR),
4201                    object_name,
4202                    sys_write);
4203
4204           file_offset = offset += sizeof (FDR);
4205         }
4206     }
4207
4208   if (symbolic_header.crfd > 0)                 /* relative file descriptors */
4209     {
4210       long sys_write;
4211       symint_t num_write = symbolic_header.crfd * sizeof (symint_t);
4212
4213       if (file_offset != (unsigned long) symbolic_header.cbRfdOffset
4214           && fseek (object_stream, symbolic_header.cbRfdOffset, SEEK_SET) != 0)
4215         pfatal_with_name (object_name);
4216
4217       if (debug)
4218         fprintf (stderr, "\twrite\tvp = %p, offset = %7lu, size = %7lu, %s\n",
4219                  (void *) &orig_rfds, (long) symbolic_header.cbRfdOffset,
4220                  num_write, "Relative file descriptors");
4221
4222       sys_write = fwrite (orig_rfds,
4223                           1,
4224                           num_write,
4225                           object_stream);
4226
4227       if (sys_write <= 0)
4228         pfatal_with_name (object_name);
4229
4230       else if (sys_write != (long) num_write)
4231         fatal ("wrote %lu bytes to %s, system returned %ld",
4232                num_write,
4233                object_name,
4234                sys_write);
4235
4236       file_offset = symbolic_header.cbRfdOffset + num_write;
4237     }
4238
4239   if (symbolic_header.issExtMax > 0)            /* external symbols */
4240     write_varray (&ext_symbols, (off_t) symbolic_header.cbExtOffset, "External symbols");
4241
4242   if (fclose (object_stream) != 0)
4243     pfatal_with_name (object_name);
4244 }
4245
4246 \f
4247 /* Read some bytes at a specified location, and return a pointer.  */
4248
4249 STATIC page_t *
4250 read_seek (Size_t size,         /* # bytes to read */
4251            off_t offset,        /* offset to read at */
4252            const char *str)     /* name for tracing */
4253 {
4254   page_t *ptr;
4255   long sys_read = 0;
4256
4257   if (size == 0)                /* nothing to read */
4258     return (page_t *) 0;
4259
4260   if (debug)
4261     fprintf (stderr,
4262              "\trseek\tsize = %7lu, offset = %7lu, currently at %7lu, %s\n",
4263              (unsigned long) size, (unsigned long) offset, file_offset, str);
4264
4265 #ifndef MALLOC_CHECK
4266   ptr = allocate_multiple_pages ((size + PAGE_USIZE - 1) / PAGE_USIZE);
4267 #else
4268   ptr = xcalloc (1, size);
4269 #endif
4270
4271   /* If we need to seek, and the distance is nearby, just do some reads,
4272      to speed things up.  */
4273   if (file_offset != (unsigned long) offset)
4274     {
4275       symint_t difference = offset - file_offset;
4276
4277       if (difference < 8)
4278         {
4279           char small_buffer[8];
4280
4281           sys_read = fread (small_buffer, 1, difference, obj_in_stream);
4282           if (sys_read <= 0)
4283             pfatal_with_name (obj_in_name);
4284
4285           if ((symint_t) sys_read != difference)
4286             fatal ("wanted to read %lu bytes from %s, system returned %ld",
4287                    (unsigned long) size,
4288                    obj_in_name,
4289                    sys_read);
4290         }
4291       else if (fseek (obj_in_stream, offset, SEEK_SET) < 0)
4292         pfatal_with_name (obj_in_name);
4293     }
4294
4295   sys_read = fread (ptr, 1, size, obj_in_stream);
4296   if (sys_read <= 0)
4297     pfatal_with_name (obj_in_name);
4298
4299   if (sys_read != (long) size)
4300     fatal ("wanted to read %lu bytes from %s, system returned %ld",
4301            (unsigned long) size,
4302            obj_in_name,
4303            sys_read);
4304
4305   file_offset = offset + size;
4306
4307   if (file_offset > max_file_offset)
4308     max_file_offset = file_offset;
4309
4310   return ptr;
4311 }
4312
4313 \f
4314 /* Read the existing object file (and copy to the output object file
4315    if it is different from the input object file), and remove the old
4316    symbol table.  */
4317
4318 STATIC void
4319 copy_object (void)
4320 {
4321   char buffer[ PAGE_SIZE ];
4322   int sys_read;
4323   int remaining;
4324   int num_write;
4325   int sys_write;
4326   int fd, es;
4327   int delete_ifd = 0;
4328   int *remap_file_number;
4329   struct stat stat_buf;
4330
4331   if (debug)
4332     fprintf (stderr, "\tcopy\n");
4333
4334   if (fstat (fileno (obj_in_stream), &stat_buf) != 0
4335       || fseek (obj_in_stream, 0L, SEEK_SET) != 0)
4336     pfatal_with_name (obj_in_name);
4337
4338   sys_read = fread (&orig_file_header,
4339                     1,
4340                     sizeof (struct filehdr),
4341                     obj_in_stream);
4342
4343   if (sys_read < 0)
4344     pfatal_with_name (obj_in_name);
4345
4346   else if (sys_read == 0 && feof (obj_in_stream))
4347     return;                     /* create a .T file sans file header */
4348
4349   else if (sys_read < (int) sizeof (struct filehdr))
4350     fatal ("wanted to read %d bytes from %s, system returned %d",
4351            (int) sizeof (struct filehdr),
4352            obj_in_name,
4353            sys_read);
4354
4355
4356   if (orig_file_header.f_nsyms != sizeof (HDRR))
4357     fatal ("%s symbolic header wrong size (%ld bytes, should be %ld)",
4358            input_name, (long) orig_file_header.f_nsyms, (long) sizeof (HDRR));
4359
4360
4361   /* Read in the current symbolic header.  */
4362   if (fseek (obj_in_stream, (long) orig_file_header.f_symptr, SEEK_SET) != 0)
4363     pfatal_with_name (input_name);
4364
4365   sys_read = fread (&orig_sym_hdr,
4366                     1,
4367                     sizeof (orig_sym_hdr),
4368                     obj_in_stream);
4369
4370   if (sys_read < 0)
4371     pfatal_with_name (object_name);
4372
4373   else if (sys_read < (int) sizeof (struct filehdr))
4374     fatal ("wanted to read %d bytes from %s, system returned %d",
4375            (int) sizeof (struct filehdr),
4376            obj_in_name,
4377            sys_read);
4378
4379
4380   /* Read in each of the sections if they exist in the object file.
4381      We read things in the order the mips assembler creates the
4382      sections, so in theory no extra seeks are done.
4383
4384      For simplicity sake, round each read up to a page boundary,
4385      we may want to revisit this later....  */
4386
4387   file_offset =  orig_file_header.f_symptr + sizeof (struct filehdr);
4388
4389   if (orig_sym_hdr.cbLine > 0)                  /* line numbers */
4390     orig_linenum = (char *) read_seek (orig_sym_hdr.cbLine,
4391                                        orig_sym_hdr.cbLineOffset,
4392                                        "Line numbers");
4393
4394   if (orig_sym_hdr.ipdMax > 0)                  /* procedure tables */
4395     orig_procs = (PDR *) read_seek (orig_sym_hdr.ipdMax * sizeof (PDR),
4396                                     orig_sym_hdr.cbPdOffset,
4397                                     "Procedure tables");
4398
4399   if (orig_sym_hdr.isymMax > 0)                 /* local symbols */
4400     orig_local_syms = (SYMR *) read_seek (orig_sym_hdr.isymMax * sizeof (SYMR),
4401                                           orig_sym_hdr.cbSymOffset,
4402                                           "Local symbols");
4403
4404   if (orig_sym_hdr.iauxMax > 0)                 /* aux symbols */
4405     orig_aux_syms = (AUXU *) read_seek (orig_sym_hdr.iauxMax * sizeof (AUXU),
4406                                         orig_sym_hdr.cbAuxOffset,
4407                                         "Aux. symbols");
4408
4409   if (orig_sym_hdr.issMax > 0)                  /* local strings */
4410     orig_local_strs = (char *) read_seek (orig_sym_hdr.issMax,
4411                                           orig_sym_hdr.cbSsOffset,
4412                                           "Local strings");
4413
4414   if (orig_sym_hdr.issExtMax > 0)               /* external strings */
4415     orig_ext_strs = (char *) read_seek (orig_sym_hdr.issExtMax,
4416                                         orig_sym_hdr.cbSsExtOffset,
4417                                         "External strings");
4418
4419   if (orig_sym_hdr.ifdMax > 0)                  /* file tables */
4420     orig_files = (FDR *) read_seek (orig_sym_hdr.ifdMax * sizeof (FDR),
4421                                     orig_sym_hdr.cbFdOffset,
4422                                     "File tables");
4423
4424   if (orig_sym_hdr.crfd > 0)                    /* relative file descriptors */
4425     orig_rfds = (symint_t *) read_seek (orig_sym_hdr.crfd * sizeof (symint_t),
4426                                         orig_sym_hdr.cbRfdOffset,
4427                                         "Relative file descriptors");
4428
4429   if (orig_sym_hdr.issExtMax > 0)               /* external symbols */
4430     orig_ext_syms = (EXTR *) read_seek (orig_sym_hdr.iextMax * sizeof (EXTR),
4431                                         orig_sym_hdr.cbExtOffset,
4432                                         "External symbols");
4433
4434   if (orig_sym_hdr.idnMax > 0)                  /* dense numbers */
4435     {
4436       orig_dense = (DNR *) read_seek (orig_sym_hdr.idnMax * sizeof (DNR),
4437                                       orig_sym_hdr.cbDnOffset,
4438                                       "Dense numbers");
4439
4440       add_bytes (&dense_num, (char *) orig_dense, orig_sym_hdr.idnMax);
4441     }
4442
4443   if (orig_sym_hdr.ioptMax > 0)                 /* opt symbols */
4444     orig_opt_syms = (OPTR *) read_seek (orig_sym_hdr.ioptMax * sizeof (OPTR),
4445                                         orig_sym_hdr.cbOptOffset,
4446                                         "Optimizer symbols");
4447
4448
4449
4450   /* The symbol table should be last.  */
4451   if (max_file_offset != (unsigned long) stat_buf.st_size)
4452     fatal ("symbol table is not last (symbol table ends at %ld, .o ends at %ld",
4453            max_file_offset,
4454            (long) stat_buf.st_size);
4455
4456
4457   /* If the first original file descriptor is a dummy which the assembler
4458      put out, but there are no symbols in it, skip it now.  */
4459   if (orig_sym_hdr.ifdMax > 1
4460       && orig_files->csym == 2
4461       && orig_files->caux == 0)
4462     {
4463       char *filename = orig_local_strs + (orig_files->issBase + orig_files->rss);
4464       char *suffix = strrchr (filename, '.');
4465
4466       if (suffix != (char *) 0 && strcmp (suffix, ".s") == 0)
4467         delete_ifd = 1;
4468     }
4469
4470
4471   /* Create array to map original file numbers to the new file numbers
4472      (in case there are duplicate filenames, we collapse them into one
4473      file section, the MIPS assembler may or may not collapse them).  */
4474
4475   remap_file_number = (int *) alloca (sizeof (int) * orig_sym_hdr.ifdMax);
4476
4477   for (fd = delete_ifd; fd < orig_sym_hdr.ifdMax; fd++)
4478     {
4479       FDR *fd_ptr = ORIG_FILES (fd);
4480       char *filename = ORIG_LSTRS (fd_ptr->issBase + fd_ptr->rss);
4481
4482       /* file support itself.  */
4483       add_file (filename, filename + strlen (filename));
4484       remap_file_number[fd] = cur_file_ptr->file_index;
4485     }
4486
4487   if (delete_ifd > 0)           /* just in case */
4488     remap_file_number[0] = remap_file_number[1];
4489
4490
4491   /* Loop, adding each of the external symbols.  These must be in
4492      order or otherwise we would have to change the relocation
4493      entries.  We don't just call add_bytes, because we need to have
4494      the names put into the external hash table.  We set the type to
4495      'void' for now, and parse_def will fill in the correct type if it
4496      is in the symbol table.  We must add the external symbols before
4497      the locals, since the locals do lookups against the externals.  */
4498
4499   if (debug)
4500     fprintf (stderr, "\tehash\n");
4501
4502   for (es = 0; es < orig_sym_hdr.iextMax; es++)
4503     {
4504       EXTR *eptr = orig_ext_syms + es;
4505       int ifd = eptr->ifd;
4506
4507       (void) add_ext_symbol (eptr, ((long) ifd < orig_sym_hdr.ifdMax)
4508                              ? remap_file_number[ ifd ] : ifd );
4509     }
4510
4511
4512   /* For each of the files in the object file, copy the symbols, and such
4513      into the varrays for the new object file.  */
4514
4515   for (fd = delete_ifd; fd < orig_sym_hdr.ifdMax; fd++)
4516     {
4517       FDR *fd_ptr = ORIG_FILES (fd);
4518       char *filename = ORIG_LSTRS (fd_ptr->issBase + fd_ptr->rss);
4519       SYMR *sym_start;
4520       SYMR *sym;
4521       SYMR *sym_end_p1;
4522       PDR *proc_start;
4523       PDR *proc;
4524       PDR *proc_end_p1;
4525
4526       /* file support itself.  */
4527       add_file (filename, filename + strlen (filename));
4528       cur_file_ptr->orig_fdr = fd_ptr;
4529
4530       /* Copy stuff that's just passed through (such as line #'s) */
4531       cur_file_ptr->fdr.adr          = fd_ptr->adr;
4532       cur_file_ptr->fdr.ilineBase    = fd_ptr->ilineBase;
4533       cur_file_ptr->fdr.cline        = fd_ptr->cline;
4534       cur_file_ptr->fdr.rfdBase      = fd_ptr->rfdBase;
4535       cur_file_ptr->fdr.crfd         = fd_ptr->crfd;
4536       cur_file_ptr->fdr.cbLineOffset = fd_ptr->cbLineOffset;
4537       cur_file_ptr->fdr.cbLine       = fd_ptr->cbLine;
4538       cur_file_ptr->fdr.fMerge       = fd_ptr->fMerge;
4539       cur_file_ptr->fdr.fReadin      = fd_ptr->fReadin;
4540       cur_file_ptr->fdr.glevel       = fd_ptr->glevel;
4541
4542       if (debug)
4543         fprintf (stderr, "\thash\tstart, filename %s\n", filename);
4544
4545       /* For each of the static and global symbols defined, add them
4546          to the hash table of original symbols, so we can look up
4547          their values.  */
4548
4549       sym_start = ORIG_LSYMS (fd_ptr->isymBase);
4550       sym_end_p1 = sym_start + fd_ptr->csym;
4551       for (sym = sym_start; sym < sym_end_p1; sym++)
4552         {
4553           switch ((st_t) sym->st)
4554             {
4555             default:
4556               break;
4557
4558             case st_Global:
4559             case st_Static:
4560             case st_Label:
4561             case st_Proc:
4562             case st_StaticProc:
4563               {
4564                 auto symint_t hash_index;
4565                 char *str = ORIG_LSTRS (fd_ptr->issBase + sym->iss);
4566                 Size_t len = strlen (str);
4567                 shash_t *shash_ptr = hash_string (str,
4568                                                   (Ptrdiff_t) len,
4569                                                   &orig_str_hash[0],
4570                                                   &hash_index);
4571
4572                 if (shash_ptr != (shash_t *) 0)
4573                   error ("internal error, %s is already in original symbol table", str);
4574
4575                 else
4576                   {
4577                     shash_ptr = allocate_shash ();
4578                     shash_ptr->next = orig_str_hash[hash_index];
4579                     orig_str_hash[hash_index] = shash_ptr;
4580
4581                     shash_ptr->len = len;
4582                     shash_ptr->indx = indexNil;
4583                     shash_ptr->string = str;
4584                     shash_ptr->sym_ptr = sym;
4585                   }
4586               }
4587               break;
4588
4589             case st_End:
4590               if ((sc_t) sym->sc == sc_Text)
4591                 {
4592                   char *str = ORIG_LSTRS (fd_ptr->issBase + sym->iss);
4593
4594                   if (*str != '\0')
4595                     {
4596                       Size_t len = strlen (str);
4597                       shash_t *shash_ptr = hash_string (str,
4598                                                         (Ptrdiff_t) len,
4599                                                         &orig_str_hash[0],
4600                                                         (symint_t *) 0);
4601
4602                       if (shash_ptr != (shash_t *) 0)
4603                         shash_ptr->end_ptr = sym;
4604                     }
4605                 }
4606               break;
4607
4608             }
4609         }
4610
4611       if (debug)
4612         {
4613           fprintf (stderr, "\thash\tdone,  filename %s\n", filename);
4614           fprintf (stderr, "\tproc\tstart, filename %s\n", filename);
4615         }
4616
4617       /* Go through each of the procedures in this file, and add the
4618          procedure pointer to the hash entry for the given name.  */
4619
4620       proc_start = ORIG_PROCS (fd_ptr->ipdFirst);
4621       proc_end_p1 = proc_start + fd_ptr->cpd;
4622       for (proc = proc_start; proc < proc_end_p1; proc++)
4623         {
4624           SYMR *proc_sym = ORIG_LSYMS (fd_ptr->isymBase + proc->isym);
4625           char *str = ORIG_LSTRS (fd_ptr->issBase + proc_sym->iss);
4626           Size_t len = strlen (str);
4627           shash_t *shash_ptr = hash_string (str,
4628                                             (Ptrdiff_t) len,
4629                                             &orig_str_hash[0],
4630                                             (symint_t *) 0);
4631
4632           if (shash_ptr == (shash_t *) 0)
4633             error ("internal error, function %s is not in original symbol table", str);
4634
4635           else
4636             shash_ptr->proc_ptr = proc;
4637         }
4638
4639       if (debug)
4640         fprintf (stderr, "\tproc\tdone,  filename %s\n", filename);
4641
4642     }
4643   cur_file_ptr = first_file;
4644
4645
4646   /* Copy all of the object file up to the symbol table.  Originally
4647      we were going to use ftruncate, but that doesn't seem to work
4648      on Ultrix 3.1....  */
4649
4650   if (fseek (obj_in_stream, (long) 0, SEEK_SET) != 0)
4651     pfatal_with_name (obj_in_name);
4652
4653   if (fseek (object_stream, (long) 0, SEEK_SET) != 0)
4654     pfatal_with_name (object_name);
4655
4656   for (remaining = orig_file_header.f_symptr;
4657        remaining > 0;
4658        remaining -= num_write)
4659     {
4660       num_write
4661         = (remaining <= (int) sizeof (buffer))
4662           ? remaining : (int) sizeof (buffer);
4663       sys_read = fread (buffer, 1, num_write, obj_in_stream);
4664       if (sys_read <= 0)
4665         pfatal_with_name (obj_in_name);
4666
4667       else if (sys_read != num_write)
4668         fatal ("wanted to read %d bytes from %s, system returned %d",
4669                num_write,
4670                obj_in_name,
4671                sys_read);
4672
4673       sys_write = fwrite (buffer, 1, num_write, object_stream);
4674       if (sys_write <= 0)
4675         pfatal_with_name (object_name);
4676
4677       else if (sys_write != num_write)
4678         fatal ("wrote %d bytes to %s, system returned %d",
4679                num_write,
4680                object_name,
4681                sys_write);
4682     }
4683 }
4684
4685 \f
4686 /* Ye olde main program.  */
4687
4688 extern int main (int, char **);
4689
4690 int
4691 main (int argc, char **argv)
4692 {
4693   int iflag = 0;
4694   char *p = strrchr (argv[0], '/');
4695   char *num_end;
4696   int option;
4697   int i;
4698
4699   progname = (p != 0) ? p+1 : argv[0];
4700
4701   (void) signal (SIGSEGV, catch_signal);
4702   (void) signal (SIGBUS,  catch_signal);
4703   (void) signal (SIGABRT, catch_signal);
4704
4705 #if !defined(__SABER__) && !defined(lint)
4706   if (sizeof (efdr_t) > PAGE_USIZE)
4707     fatal ("efdr_t has a sizeof %d bytes, when it should be less than %d",
4708            (int) sizeof (efdr_t),
4709            (int) PAGE_USIZE);
4710
4711   if (sizeof (page_t) != PAGE_USIZE)
4712     fatal ("page_t has a sizeof %d bytes, when it should be %d",
4713            (int) sizeof (page_t),
4714            (int) PAGE_USIZE);
4715
4716 #endif
4717
4718   alloc_counts[ alloc_type_none    ].alloc_name = "none";
4719   alloc_counts[ alloc_type_scope   ].alloc_name = "scope";
4720   alloc_counts[ alloc_type_vlinks  ].alloc_name = "vlinks";
4721   alloc_counts[ alloc_type_shash   ].alloc_name = "shash";
4722   alloc_counts[ alloc_type_thash   ].alloc_name = "thash";
4723   alloc_counts[ alloc_type_tag     ].alloc_name = "tag";
4724   alloc_counts[ alloc_type_forward ].alloc_name = "forward";
4725   alloc_counts[ alloc_type_thead   ].alloc_name = "thead";
4726   alloc_counts[ alloc_type_varray  ].alloc_name = "varray";
4727
4728   int_type_info  = type_info_init;
4729   int_type_info.basic_type = bt_Int;
4730
4731   void_type_info = type_info_init;
4732   void_type_info.basic_type = bt_Void;
4733
4734   while ((option = getopt_long (argc, argv, "d:i:I:o:v", options, NULL)) != -1)
4735     switch (option)
4736       {
4737       default:
4738         had_errors++;
4739         break;
4740
4741       case 'd':
4742         debug = strtol (optarg, &num_end, 0);
4743         if ((unsigned) debug > 4 || num_end == optarg)
4744           had_errors++;
4745
4746         break;
4747
4748       case 'I':
4749         if (rename_output || obj_in_name != (char *) 0)
4750           had_errors++;
4751         else
4752           rename_output = 1;
4753
4754         /* Fall through to 'i' case.  */
4755
4756       case 'i':
4757         if (obj_in_name == (char *) 0)
4758           {
4759             obj_in_name = optarg;
4760             iflag++;
4761           }
4762         else
4763           had_errors++;
4764         break;
4765
4766       case 'o':
4767         if (object_name == (char *) 0)
4768           object_name = optarg;
4769         else
4770           had_errors++;
4771         break;
4772
4773       case 'v':
4774         verbose++;
4775         break;
4776
4777       case 'V':
4778         version++;
4779         break;
4780       }
4781
4782   if (version)
4783     {
4784       printf (_("mips-tfile %s%s\n"), pkgversion_string, version_string);
4785       fputs ("Copyright (C) 2009 Free Software Foundation, Inc.\n", stdout);
4786       fputs (_("This is free software; see the source for copying conditions.  There is NO\n\
4787 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\n"),
4788              stdout);
4789       exit (0);
4790     }
4791
4792   if (obj_in_name == (char *) 0 && optind <= argc - 2)
4793     obj_in_name = argv[--argc];
4794
4795   if (object_name == (char *) 0 && optind <= argc - 2)
4796     object_name = argv[--argc];
4797
4798   /* If there is an output name, but no input name use
4799      the same file for both, deleting the name between
4800      opening it for input and opening it for output.  */
4801   if (obj_in_name == (char *) 0 && object_name != (char *) 0)
4802     {
4803       obj_in_name = object_name;
4804       delete_input = 1;
4805     }
4806
4807   if (optind != argc - 1)
4808     had_errors++;
4809
4810   if (verbose || had_errors)
4811     {
4812       fprintf (stderr, _("mips-tfile (GCC) %s"), version_string);
4813 #ifdef TARGET_VERSION
4814       TARGET_VERSION;
4815 #endif
4816       fputc ('\n', stderr);
4817     }
4818
4819   if (object_name == (char *) 0 || had_errors)
4820     {
4821       fprintf (stderr, _("Calling Sequence:\n"));
4822       fprintf (stderr, _("\tmips-tfile [-d <num>] [-v] [-i <o-in-file>] -o <o-out-file> <s-file> (or)\n"));
4823       fprintf (stderr, _("\tmips-tfile [-d <num>] [-v] [-I <o-in-file>] -o <o-out-file> <s-file> (or)\n"));
4824       fprintf (stderr, _("\tmips-tfile [-d <num>] [-v] <s-file> <o-in-file> <o-out-file>\n"));
4825       fprintf (stderr, "\n");
4826       fprintf (stderr, _("Debug levels are:\n"));
4827       fprintf (stderr, _("    1\tGeneral debug + trace functions/blocks.\n"));
4828       fprintf (stderr, _("    2\tDebug level 1 + trace externals.\n"));
4829       fprintf (stderr, _("    3\tDebug level 2 + trace all symbols.\n"));
4830       fprintf (stderr, _("    4\tDebug level 3 + trace memory allocations.\n"));
4831       return 1;
4832     }
4833
4834   if (obj_in_name == (char *) 0)
4835     obj_in_name = object_name;
4836
4837   if (rename_output && rename (object_name, obj_in_name) != 0)
4838     {
4839       char *buffer = (char *) allocate_multiple_pages (4);
4840       int len;
4841       int len2;
4842       int in_fd;
4843       int out_fd;
4844
4845       /* Rename failed, copy input file */
4846       in_fd = open (object_name, O_RDONLY, 0666);
4847       if (in_fd < 0)
4848         pfatal_with_name (object_name);
4849
4850       out_fd = open (obj_in_name, O_WRONLY | O_CREAT | O_TRUNC, 0666);
4851       if (out_fd < 0)
4852         pfatal_with_name (obj_in_name);
4853
4854       while ((len = read (in_fd, buffer, 4*PAGE_SIZE)) > 0)
4855         {
4856           len2 = write (out_fd, buffer, len);
4857           if (len2 < 0)
4858             pfatal_with_name (object_name);
4859
4860           if (len != len2)
4861             fatal ("wrote %d bytes to %s, expected to write %d", len2, obj_in_name, len);
4862         }
4863
4864       free_multiple_pages ((page_t *) buffer, 4);
4865
4866       if (len < 0)
4867         pfatal_with_name (object_name);
4868
4869       if (close (in_fd) < 0)
4870         pfatal_with_name (object_name);
4871
4872       if (close (out_fd) < 0)
4873         pfatal_with_name (obj_in_name);
4874     }
4875
4876   /* Must open input before output, since the output may be the same file, and
4877      we need to get the input handle before truncating it.  */
4878   obj_in_stream = fopen (obj_in_name, "r");
4879   if (obj_in_stream == (FILE *) 0)
4880     pfatal_with_name (obj_in_name);
4881
4882   if (delete_input && unlink (obj_in_name) != 0)
4883     pfatal_with_name (obj_in_name);
4884
4885   object_stream = fopen (object_name, "w");
4886   if (object_stream == (FILE *) 0)
4887     pfatal_with_name (object_name);
4888
4889   if (strcmp (argv[optind], "-") != 0)
4890     {
4891       input_name = argv[optind];
4892       if (freopen (argv[optind], "r", stdin) != stdin)
4893         pfatal_with_name (argv[optind]);
4894     }
4895
4896   copy_object ();                       /* scan & copy object file */
4897   parse_input ();                       /* scan all of input */
4898
4899   update_headers ();                    /* write out tfile */
4900   write_object ();
4901
4902   if (debug)
4903     {
4904       fprintf (stderr, "\n\tAllocation summary:\n\n");
4905       for (i = (int) alloc_type_none; i < (int) alloc_type_last; i++)
4906         if (alloc_counts[i].total_alloc)
4907           {
4908             fprintf (stderr,
4909                      "\t%s\t%5d allocation(s), %5d free(s), %2d page(s)\n",
4910                      alloc_counts[i].alloc_name,
4911                      alloc_counts[i].total_alloc,
4912                      alloc_counts[i].total_free,
4913                      alloc_counts[i].total_pages);
4914           }
4915     }
4916
4917   return (had_errors) ? 1 : 0;
4918 }
4919
4920 \f
4921 /* Catch a signal and exit without dumping core.  */
4922
4923 STATIC void
4924 catch_signal (int signum)
4925 {
4926   (void) signal (signum, SIG_DFL);      /* just in case...  */
4927   fatal ("%s", strsignal (signum));
4928 }
4929
4930 /* Print a fatal error message.  NAME is the text.
4931    Also include a system error message based on `errno'.  */
4932
4933 void
4934 pfatal_with_name (const char *msg)
4935 {
4936   int save_errno = errno;               /* just in case....  */
4937   if (line_number > 0)
4938     fprintf (stderr, "%s, %s:%ld ", progname, input_name, line_number);
4939   else
4940     fprintf (stderr, "%s:", progname);
4941
4942   errno = save_errno;
4943   if (errno == 0)
4944     fprintf (stderr, "[errno = 0] %s\n", msg);
4945   else
4946     perror (msg);
4947
4948   exit (1);
4949 }
4950
4951 \f
4952 /* Procedure to die with an out of bounds error message.  It has
4953    type int, so it can be used with an ?: expression within the
4954    ORIG_xxx macros, but the function never returns.  */
4955
4956 static int
4957 out_of_bounds (symint_t indx,   /* index that is out of bounds */
4958                symint_t max,    /* maximum index */
4959                const char *str, /* string to print out */
4960                int prog_line)   /* line number within mips-tfile.c */
4961 {
4962   if (indx < max)               /* just in case */
4963     return 0;
4964
4965   fprintf (stderr, "%s, %s:%ld index %lu is out of bounds for %s, max is %lu, mips-tfile.c line# %d\n",
4966            progname, input_name, line_number, indx, str, max, prog_line);
4967
4968   exit (1);
4969   return 0;                     /* turn off warning messages */
4970 }
4971
4972 \f
4973 /* Allocate a cluster of pages.  USE_MALLOC says that malloc does not
4974    like sbrk's behind its back (or sbrk isn't available).  If we use
4975    sbrk, we assume it gives us zeroed pages.  */
4976
4977 #ifndef MALLOC_CHECK
4978 #ifdef USE_MALLOC
4979
4980 STATIC page_t *
4981 allocate_cluster (Size_t npages)
4982 {
4983   page_t *value = xcalloc (npages, PAGE_USIZE);
4984
4985   if (debug > 3)
4986     fprintf (stderr, "\talloc\tnpages = %d, value = 0x%.8x\n", npages, value);
4987
4988   return value;
4989 }
4990
4991 #else /* USE_MALLOC */
4992
4993 STATIC page_t *
4994 allocate_cluster (Size_t npages)
4995 {
4996   page_t *ptr = (page_t *) sbrk (0);    /* current sbreak */
4997   unsigned long offset = ((unsigned long) ptr) & (PAGE_SIZE - 1);
4998
4999   if (offset != 0)                      /* align to a page boundary */
5000     {
5001       if (sbrk (PAGE_USIZE - offset) == (char *)-1)
5002         pfatal_with_name ("allocate_cluster");
5003
5004       ptr = (page_t *) (((char *) ptr) + PAGE_SIZE - offset);
5005     }
5006
5007   if (sbrk (npages * PAGE_USIZE) == (char *) -1)
5008     pfatal_with_name ("allocate_cluster");
5009
5010   if (debug > 3)
5011     fprintf (stderr, "\talloc\tnpages = %lu, value = %p\n",
5012              (unsigned long) npages, (void *) ptr);
5013
5014   return ptr;
5015 }
5016
5017 #endif /* USE_MALLOC */
5018
5019
5020 static page_t   *cluster_ptr    = NULL;
5021 static unsigned  pages_left     = 0;
5022
5023 #endif /* MALLOC_CHECK */
5024
5025
5026 /* Allocate some pages (which is initialized to 0).  */
5027
5028 STATIC page_t *
5029 allocate_multiple_pages (Size_t npages)
5030 {
5031 #ifndef MALLOC_CHECK
5032   if (pages_left == 0 && npages < MAX_CLUSTER_PAGES)
5033     {
5034       pages_left = MAX_CLUSTER_PAGES;
5035       cluster_ptr = allocate_cluster (MAX_CLUSTER_PAGES);
5036     }
5037
5038   if (npages <= pages_left)
5039     {
5040       page_t *ptr = cluster_ptr;
5041       cluster_ptr += npages;
5042       pages_left -= npages;
5043       return ptr;
5044     }
5045
5046   return allocate_cluster (npages);
5047
5048 #else   /* MALLOC_CHECK */
5049   return xcalloc (npages, PAGE_SIZE);
5050
5051 #endif  /* MALLOC_CHECK */
5052 }
5053
5054
5055 /* Release some pages.  */
5056
5057 STATIC void
5058 free_multiple_pages (page_t *page_ptr, Size_t npages)
5059 {
5060 #ifndef MALLOC_CHECK
5061   if (pages_left == 0)
5062     {
5063       cluster_ptr = page_ptr;
5064       pages_left = npages;
5065     }
5066
5067   else if ((page_ptr + npages) == cluster_ptr)
5068     {
5069       cluster_ptr -= npages;
5070       pages_left += npages;
5071     }
5072
5073   /* otherwise the page is not freed.  If more than call is
5074      done, we probably should worry about it, but at present,
5075      the free pages is done right after an allocate.  */
5076
5077 #else   /* MALLOC_CHECK */
5078   free (page_ptr);
5079
5080 #endif  /* MALLOC_CHECK */
5081 }
5082
5083
5084 /* Allocate one page (which is initialized to 0).  */
5085
5086 STATIC page_t *
5087 allocate_page (void)
5088 {
5089 #ifndef MALLOC_CHECK
5090   if (pages_left == 0)
5091     {
5092       pages_left = MAX_CLUSTER_PAGES;
5093       cluster_ptr = allocate_cluster (MAX_CLUSTER_PAGES);
5094     }
5095
5096   pages_left--;
5097   return cluster_ptr++;
5098
5099 #else   /* MALLOC_CHECK */
5100   return xcalloc (1, PAGE_SIZE);
5101
5102 #endif  /* MALLOC_CHECK */
5103 }
5104
5105 \f
5106 /* Allocate scoping information.  */
5107
5108 STATIC scope_t *
5109 allocate_scope (void)
5110 {
5111   scope_t *ptr;
5112   static scope_t initial_scope;
5113
5114 #ifndef MALLOC_CHECK
5115   ptr = alloc_counts[ (int) alloc_type_scope ].free_list.f_scope;
5116   if (ptr != (scope_t *) 0)
5117     alloc_counts[ (int) alloc_type_scope ].free_list.f_scope = ptr->free;
5118
5119   else
5120     {
5121       int unallocated   = alloc_counts[ (int) alloc_type_scope ].unallocated;
5122       page_t *cur_page  = alloc_counts[ (int) alloc_type_scope ].cur_page;
5123
5124       if (unallocated == 0)
5125         {
5126           unallocated = PAGE_SIZE / sizeof (scope_t);
5127           alloc_counts[ (int) alloc_type_scope ].cur_page = cur_page = allocate_page ();
5128           alloc_counts[ (int) alloc_type_scope ].total_pages++;
5129         }
5130
5131       ptr = &cur_page->scope[ --unallocated ];
5132       alloc_counts[ (int) alloc_type_scope ].unallocated = unallocated;
5133     }
5134
5135 #else
5136   ptr = xmalloc (sizeof (scope_t));
5137
5138 #endif
5139
5140   alloc_counts[ (int) alloc_type_scope ].total_alloc++;
5141   *ptr = initial_scope;
5142   return ptr;
5143 }
5144
5145 /* Free scoping information.  */
5146
5147 STATIC void
5148 free_scope (scope_t *ptr)
5149 {
5150   alloc_counts[ (int) alloc_type_scope ].total_free++;
5151
5152 #ifndef MALLOC_CHECK
5153   ptr->free = alloc_counts[ (int) alloc_type_scope ].free_list.f_scope;
5154   alloc_counts[ (int) alloc_type_scope ].free_list.f_scope = ptr;
5155
5156 #else
5157   free (ptr);
5158 #endif
5159
5160 }
5161
5162 \f
5163 /* Allocate links for pages in a virtual array.  */
5164
5165 STATIC vlinks_t *
5166 allocate_vlinks (void)
5167 {
5168   vlinks_t *ptr;
5169   static vlinks_t initial_vlinks;
5170
5171 #ifndef MALLOC_CHECK
5172   int unallocated       = alloc_counts[ (int) alloc_type_vlinks ].unallocated;
5173   page_t *cur_page      = alloc_counts[ (int) alloc_type_vlinks ].cur_page;
5174
5175   if (unallocated == 0)
5176     {
5177       unallocated = PAGE_SIZE / sizeof (vlinks_t);
5178       alloc_counts[ (int) alloc_type_vlinks ].cur_page = cur_page = allocate_page ();
5179       alloc_counts[ (int) alloc_type_vlinks ].total_pages++;
5180     }
5181
5182   ptr = &cur_page->vlinks[ --unallocated ];
5183   alloc_counts[ (int) alloc_type_vlinks ].unallocated = unallocated;
5184
5185 #else
5186   ptr = xmalloc (sizeof (vlinks_t));
5187
5188 #endif
5189
5190   alloc_counts[ (int) alloc_type_vlinks ].total_alloc++;
5191   *ptr = initial_vlinks;
5192   return ptr;
5193 }
5194
5195 \f
5196 /* Allocate string hash buckets.  */
5197
5198 STATIC shash_t *
5199 allocate_shash (void)
5200 {
5201   shash_t *ptr;
5202   static shash_t initial_shash;
5203
5204 #ifndef MALLOC_CHECK
5205   int unallocated       = alloc_counts[ (int) alloc_type_shash ].unallocated;
5206   page_t *cur_page      = alloc_counts[ (int) alloc_type_shash ].cur_page;
5207
5208   if (unallocated == 0)
5209     {
5210       unallocated = PAGE_SIZE / sizeof (shash_t);
5211       alloc_counts[ (int) alloc_type_shash ].cur_page = cur_page = allocate_page ();
5212       alloc_counts[ (int) alloc_type_shash ].total_pages++;
5213     }
5214
5215   ptr = &cur_page->shash[ --unallocated ];
5216   alloc_counts[ (int) alloc_type_shash ].unallocated = unallocated;
5217
5218 #else
5219   ptr = xmalloc (sizeof (shash_t));
5220
5221 #endif
5222
5223   alloc_counts[ (int) alloc_type_shash ].total_alloc++;
5224   *ptr = initial_shash;
5225   return ptr;
5226 }
5227
5228 \f
5229 /* Allocate type hash buckets.  */
5230
5231 STATIC thash_t *
5232 allocate_thash (void)
5233 {
5234   thash_t *ptr;
5235   static thash_t initial_thash;
5236
5237 #ifndef MALLOC_CHECK
5238   int unallocated       = alloc_counts[ (int) alloc_type_thash ].unallocated;
5239   page_t *cur_page      = alloc_counts[ (int) alloc_type_thash ].cur_page;
5240
5241   if (unallocated == 0)
5242     {
5243       unallocated = PAGE_SIZE / sizeof (thash_t);
5244       alloc_counts[ (int) alloc_type_thash ].cur_page = cur_page = allocate_page ();
5245       alloc_counts[ (int) alloc_type_thash ].total_pages++;
5246     }
5247
5248   ptr = &cur_page->thash[ --unallocated ];
5249   alloc_counts[ (int) alloc_type_thash ].unallocated = unallocated;
5250
5251 #else
5252   ptr = xmalloc (sizeof (thash_t));
5253
5254 #endif
5255
5256   alloc_counts[ (int) alloc_type_thash ].total_alloc++;
5257   *ptr = initial_thash;
5258   return ptr;
5259 }
5260
5261 \f
5262 /* Allocate structure, union, or enum tag information.  */
5263
5264 STATIC tag_t *
5265 allocate_tag (void)
5266 {
5267   tag_t *ptr;
5268   static tag_t initial_tag;
5269
5270 #ifndef MALLOC_CHECK
5271   ptr = alloc_counts[ (int) alloc_type_tag ].free_list.f_tag;
5272   if (ptr != (tag_t *) 0)
5273     alloc_counts[ (int) alloc_type_tag ].free_list.f_tag = ptr->free;
5274
5275   else
5276     {
5277       int unallocated   = alloc_counts[ (int) alloc_type_tag ].unallocated;
5278       page_t *cur_page  = alloc_counts[ (int) alloc_type_tag ].cur_page;
5279
5280       if (unallocated == 0)
5281         {
5282           unallocated = PAGE_SIZE / sizeof (tag_t);
5283           alloc_counts[ (int) alloc_type_tag ].cur_page = cur_page = allocate_page ();
5284           alloc_counts[ (int) alloc_type_tag ].total_pages++;
5285         }
5286
5287       ptr = &cur_page->tag[ --unallocated ];
5288       alloc_counts[ (int) alloc_type_tag ].unallocated = unallocated;
5289     }
5290
5291 #else
5292   ptr = xmalloc (sizeof (tag_t));
5293
5294 #endif
5295
5296   alloc_counts[ (int) alloc_type_tag ].total_alloc++;
5297   *ptr = initial_tag;
5298   return ptr;
5299 }
5300
5301 /* Free scoping information.  */
5302
5303 STATIC void
5304 free_tag (tag_t *ptr)
5305 {
5306   alloc_counts[ (int) alloc_type_tag ].total_free++;
5307
5308 #ifndef MALLOC_CHECK
5309   ptr->free = alloc_counts[ (int) alloc_type_tag ].free_list.f_tag;
5310   alloc_counts[ (int) alloc_type_tag ].free_list.f_tag = ptr;
5311
5312 #else
5313   free (ptr);
5314 #endif
5315
5316 }
5317
5318 \f
5319 /* Allocate forward reference to a yet unknown tag.  */
5320
5321 STATIC forward_t *
5322 allocate_forward (void)
5323 {
5324   forward_t *ptr;
5325   static forward_t initial_forward;
5326
5327 #ifndef MALLOC_CHECK
5328   ptr = alloc_counts[ (int) alloc_type_forward ].free_list.f_forward;
5329   if (ptr != (forward_t *) 0)
5330     alloc_counts[ (int) alloc_type_forward ].free_list.f_forward = ptr->free;
5331
5332   else
5333     {
5334       int unallocated   = alloc_counts[ (int) alloc_type_forward ].unallocated;
5335       page_t *cur_page  = alloc_counts[ (int) alloc_type_forward ].cur_page;
5336
5337       if (unallocated == 0)
5338         {
5339           unallocated = PAGE_SIZE / sizeof (forward_t);
5340           alloc_counts[ (int) alloc_type_forward ].cur_page = cur_page = allocate_page ();
5341           alloc_counts[ (int) alloc_type_forward ].total_pages++;
5342         }
5343
5344       ptr = &cur_page->forward[ --unallocated ];
5345       alloc_counts[ (int) alloc_type_forward ].unallocated = unallocated;
5346     }
5347
5348 #else
5349   ptr = xmalloc (sizeof (forward_t));
5350
5351 #endif
5352
5353   alloc_counts[ (int) alloc_type_forward ].total_alloc++;
5354   *ptr = initial_forward;
5355   return ptr;
5356 }
5357
5358 /* Free scoping information.  */
5359
5360 STATIC void
5361 free_forward (forward_t *ptr)
5362 {
5363   alloc_counts[ (int) alloc_type_forward ].total_free++;
5364
5365 #ifndef MALLOC_CHECK
5366   ptr->free = alloc_counts[ (int) alloc_type_forward ].free_list.f_forward;
5367   alloc_counts[ (int) alloc_type_forward ].free_list.f_forward = ptr;
5368
5369 #else
5370   free (ptr);
5371 #endif
5372
5373 }
5374
5375 \f
5376 /* Allocate head of type hash list.  */
5377
5378 STATIC thead_t *
5379 allocate_thead (void)
5380 {
5381   thead_t *ptr;
5382   static thead_t initial_thead;
5383
5384 #ifndef MALLOC_CHECK
5385   ptr = alloc_counts[ (int) alloc_type_thead ].free_list.f_thead;
5386   if (ptr != (thead_t *) 0)
5387     alloc_counts[ (int) alloc_type_thead ].free_list.f_thead = ptr->free;
5388
5389   else
5390     {
5391       int unallocated   = alloc_counts[ (int) alloc_type_thead ].unallocated;
5392       page_t *cur_page  = alloc_counts[ (int) alloc_type_thead ].cur_page;
5393
5394       if (unallocated == 0)
5395         {
5396           unallocated = PAGE_SIZE / sizeof (thead_t);
5397           alloc_counts[ (int) alloc_type_thead ].cur_page = cur_page = allocate_page ();
5398           alloc_counts[ (int) alloc_type_thead ].total_pages++;
5399         }
5400
5401       ptr = &cur_page->thead[ --unallocated ];
5402       alloc_counts[ (int) alloc_type_thead ].unallocated = unallocated;
5403     }
5404
5405 #else
5406   ptr = xmalloc (sizeof (thead_t));
5407
5408 #endif
5409
5410   alloc_counts[ (int) alloc_type_thead ].total_alloc++;
5411   *ptr = initial_thead;
5412   return ptr;
5413 }
5414
5415 /* Free scoping information.  */
5416
5417 STATIC void
5418 free_thead (thead_t *ptr)
5419 {
5420   alloc_counts[ (int) alloc_type_thead ].total_free++;
5421
5422 #ifndef MALLOC_CHECK
5423   ptr->free = (thead_t *) alloc_counts[ (int) alloc_type_thead ].free_list.f_thead;
5424   alloc_counts[ (int) alloc_type_thead ].free_list.f_thead = ptr;
5425
5426 #else
5427   free (ptr);
5428 #endif
5429
5430 }
5431
5432 #endif /* MIPS_DEBUGGING_INFO */
5433
5434 \f
5435 /* Output an error message and exit.  */
5436
5437 void
5438 fatal (const char *format, ...)
5439 {
5440   va_list ap;
5441
5442   va_start (ap, format);
5443
5444   if (line_number > 0)
5445     fprintf (stderr, "%s, %s:%ld ", progname, input_name, line_number);
5446   else
5447     fprintf (stderr, "%s:", progname);
5448
5449   vfprintf (stderr, format, ap);
5450   va_end (ap);
5451   fprintf (stderr, "\n");
5452   if (line_number > 0)
5453     fprintf (stderr, "line:\t%s\n", cur_line_start);
5454
5455   saber_stop ();
5456   exit (1);
5457 }
5458
5459 void
5460 error (const char *format, ...)
5461 {
5462   va_list ap;
5463
5464   va_start (ap, format);
5465
5466   if (line_number > 0)
5467     fprintf (stderr, "%s, %s:%ld ", progname, input_name, line_number);
5468   else
5469     fprintf (stderr, "%s:", progname);
5470
5471   vfprintf (stderr, format, ap);
5472   fprintf (stderr, "\n");
5473   if (line_number > 0)
5474     fprintf (stderr, "line:\t%s\n", cur_line_start);
5475
5476   had_errors++;
5477   va_end (ap);
5478
5479   saber_stop ();
5480 }
5481
5482 /* More 'friendly' abort that prints the line and file.  */
5483
5484 void
5485 fancy_abort (const char *file, int line, const char *func)
5486 {
5487   fatal ("abort in %s, at %s:%d", func, file, line);
5488 }
5489 \f
5490
5491 /* When `malloc.c' is compiled with `rcheck' defined,
5492    it calls this function to report clobberage.  */
5493
5494 void
5495 botch (const char *s)
5496 {
5497   fatal ("%s", s);
5498 }