OSDN Git Service

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