OSDN Git Service

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