OSDN Git Service

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