Fixed ANSI compabillity.
[wine] / debugger / stabs.c
1 /*
2  * File stabs.c - read stabs information from the wine executable itself.
3  *
4  * Copyright (C) 1996, Eric Youngdale.
5  */
6
7 #include "config.h"
8
9 #include <sys/types.h>
10 #include <fcntl.h>
11 #include <sys/stat.h>
12 #include <sys/mman.h>
13 #include <limits.h>
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <string.h>
17 #include <unistd.h>
18 #ifndef PATH_MAX
19 #define PATH_MAX _MAX_PATH
20 #endif
21
22 #include "debugger.h"
23
24 #if defined(__svr4__) || defined(__sun)
25 #define __ELF__
26 #endif
27
28 #ifdef __ELF__
29 #ifdef HAVE_ELF_H
30 # include <elf.h>
31 #endif
32 #include <link.h>
33 #include <sys/mman.h>
34 #elif defined(__EMX__)
35 #include <a_out.h>
36 #else
37 #include <a.out.h>
38 #endif
39
40 #ifndef N_UNDF
41 #define N_UNDF          0x00
42 #endif
43
44 #define N_GSYM          0x20
45 #define N_FUN           0x24
46 #define N_STSYM         0x26
47 #define N_LCSYM         0x28
48 #define N_MAIN          0x2a
49 #define N_ROSYM         0x2c
50 #define N_OPT           0x3c
51 #define N_RSYM          0x40
52 #define N_SLINE         0x44
53 #define N_SO            0x64
54 #define N_LSYM          0x80
55 #define N_BINCL         0x82
56 #define N_SOL           0x84
57 #define N_PSYM          0xa0
58 #define N_EINCL         0xa2
59 #define N_LBRAC         0xc0
60 #define N_RBRAC         0xe0
61
62
63 /*
64  * This is how we translate stab types into our internal representations
65  * of datatypes.
66  */
67 static struct datatype ** stab_types = NULL;
68 static int num_stab_types = 0;
69
70 /*
71  * Set so that we know the main executable name and path.
72  */
73 char * DEBUG_argv0;
74
75 struct stab_nlist {
76   union {
77     char *n_name;
78     struct stab_nlist *n_next;
79     long n_strx;
80   } n_un;
81   unsigned char n_type;
82   char n_other;
83   short n_desc;
84   unsigned long n_value;
85 };
86
87 /*
88  * This is used to keep track of known datatypes so that we don't redefine
89  * them over and over again.  It sucks up lots of memory otherwise.
90  */
91 struct known_typedef
92 {
93   struct known_typedef * next;
94   char                 * name;
95   int                    ndefs;
96   struct datatype      * types[0];
97 };
98
99 #define NR_STAB_HASH 521
100
101 struct known_typedef * ktd_head[NR_STAB_HASH] = {NULL,};
102
103 static unsigned int stab_hash( const char * name )
104 {
105     unsigned int hash = 0;
106     unsigned int tmp;
107     const char * p;
108
109     p = name;
110
111     while (*p) 
112       {
113         hash = (hash << 4) + *p++;
114
115         if( (tmp = (hash & 0xf0000000)) )
116           {
117             hash ^= tmp >> 24;
118           }
119         hash &= ~tmp;
120       }
121     return hash % NR_STAB_HASH;
122 }
123
124
125 static void stab_strcpy(char * dest, const char * source)
126 {
127   /*
128    * A strcpy routine that stops when we hit the ':' character.
129    * Faster than copying the whole thing, and then nuking the
130    * ':'.
131    */
132   while(*source != '\0' && *source != ':')
133       *dest++ = *source++;
134   *dest++ = '\0';
135 }
136
137 #define MAX_TD_NESTING  128
138
139 static int **typenums;
140 static int *nroftypenums=NULL;
141 static int nrofnroftypenums=0;
142 static int curtypenum = 0;
143
144 static
145 int
146 DEBUG_FileSubNr2StabEnum(int filenr,int subnr) {
147     if (nrofnroftypenums<=filenr) {
148         nroftypenums = DBG_realloc(nroftypenums,sizeof(nroftypenums[0])*(filenr+1));
149         memset(nroftypenums+nrofnroftypenums,0,(filenr+1-nrofnroftypenums)*sizeof(nroftypenums[0]));
150         typenums = DBG_realloc(typenums,sizeof(typenums[0])*(filenr+1));
151         memset(typenums+nrofnroftypenums,0,sizeof(typenums[0])*(filenr+1-nrofnroftypenums));
152         nrofnroftypenums=filenr+1;
153     }
154     if (nroftypenums[filenr]<=subnr) {
155         typenums[filenr] = DBG_realloc(typenums[filenr],sizeof(typenums[0][0])*(subnr+1));
156         memset(typenums[filenr]+nroftypenums[filenr],0,sizeof(typenums[0][0])*(subnr+1-nroftypenums[filenr]));
157         nroftypenums[filenr] = subnr+1;
158     }
159     if (!typenums[filenr][subnr])
160         typenums[filenr][subnr]=++curtypenum;
161
162     if( num_stab_types <= curtypenum ) {
163         num_stab_types = curtypenum + 256;
164         stab_types = (struct datatype **) DBG_realloc(stab_types, 
165                     num_stab_types * sizeof(struct datatype *)
166         );
167         memset( stab_types + curtypenum, 0, sizeof(struct datatype *) * (num_stab_types - curtypenum) );
168     }
169     /*fprintf(stderr,"(%d,%d) is %d\n",filenr,subnr,typenums[filenr][subnr]); */
170     return typenums[filenr][subnr];
171 }
172
173 static
174 int
175 DEBUG_ReadTypeEnumBackwards(char*x) {
176     int filenr,subnr;
177
178     if (*x==')') {
179         while (*x!='(')
180             x--;
181         x++;                            /* '(' */
182         filenr=strtol(x,&x,10);         /* <int> */
183         x++;                            /* ',' */
184         subnr=strtol(x,&x,10);          /* <int> */
185         x++;                            /* ')' */
186     } else {
187         while ((*x>='0') && (*x<='9'))
188             x--;
189         filenr = 0;
190         subnr = atol(x+1);
191     }
192     return DEBUG_FileSubNr2StabEnum(filenr,subnr);
193 }
194
195 static 
196 int
197 DEBUG_ReadTypeEnum(char **x) {
198     int filenr,subnr;
199
200     if (**x=='(') {
201         (*x)++;                                 /* '(' */
202         filenr=strtol(*x,x,10);                 /* <int> */
203         (*x)++;                                 /* ',' */
204         subnr=strtol(*x,x,10);                  /* <int> */
205         (*x)++;                                 /* ')' */
206     } else {
207         filenr = 0;
208         subnr = strtol(*x,x,10);                /* <int> */
209     }
210     return DEBUG_FileSubNr2StabEnum(filenr,subnr);
211 }
212
213 static
214 int
215 DEBUG_RegisterTypedef(const char * name, struct datatype ** types, int ndef)
216 {
217   int                    hash;
218   struct known_typedef * ktd;
219
220   if( ndef == 1 )
221       return TRUE;
222
223   ktd = (struct known_typedef *) DBG_alloc(sizeof(struct known_typedef) 
224                                          + ndef * sizeof(struct datatype *));
225   
226   hash = stab_hash(name);
227
228   ktd->name = DBG_strdup(name);
229   ktd->ndefs = ndef;
230   memcpy(&ktd->types[0], types, ndef * sizeof(struct datatype *));
231   ktd->next = ktd_head[hash];
232   ktd_head[hash] = ktd;
233
234   return TRUE;
235 }
236
237 static
238 int
239 DEBUG_HandlePreviousTypedef(const char * name, const char * stab)
240 {
241   int                    count;
242   enum debug_type        expect;
243   int                    hash;
244   struct known_typedef * ktd;
245   char                 * ptr;
246
247   hash = stab_hash(name);
248
249   for(ktd = ktd_head[hash]; ktd; ktd = ktd->next)
250       if ((ktd->name[0] == name[0]) && (strcmp(name, ktd->name) == 0) )
251           break;
252
253   /*
254    * Didn't find it.  This must be a new one.
255    */
256   if( ktd == NULL )
257       return FALSE;
258
259   /*
260    * Examine the stab to make sure it has the same number of definitions.
261    */
262   count = 0;
263   for(ptr = strchr(stab, '='); ptr; ptr = strchr(ptr+1, '='))
264     {
265       if( count >= ktd->ndefs )
266           return FALSE;
267
268       /*
269        * Make sure the types of all of the objects is consistent with
270        * what we have already parsed.
271        */
272       switch(ptr[1])
273         {
274         case '*':
275           expect = DT_POINTER;
276           break;
277         case 's':
278         case 'u':
279           expect = DT_STRUCT;
280           break;
281         case 'a':
282           expect = DT_ARRAY;
283           break;
284         case '1':
285         case '(':
286         case 'r':
287           expect = DT_BASIC;
288           break;
289         case 'x':
290           expect = DT_STRUCT;
291           break;
292         case 'e':
293           expect = DT_ENUM;
294           break;
295         case 'f':
296           expect = DT_FUNC;
297           break;
298         default:
299           fprintf(stderr, "Unknown type (%c).\n",ptr[1]);
300           return FALSE;
301         }
302       if( expect != DEBUG_GetType(ktd->types[count]) )
303           return FALSE;
304       count++;
305     }
306
307   if( ktd->ndefs != count )
308       return FALSE;
309
310   /*
311    * Go through, dig out all of the type numbers, and substitute the
312    * appropriate things.
313    */
314   count = 0;
315   for(ptr = strchr(stab, '='); ptr; ptr = strchr(ptr+1, '='))
316       stab_types[DEBUG_ReadTypeEnumBackwards(ptr-1)] = ktd->types[count++];
317
318   return TRUE;
319 }
320
321 static int DEBUG_FreeRegisteredTypedefs()
322 {
323   int                    count;
324   int                    j;
325   struct known_typedef * ktd;
326   struct known_typedef * next;
327
328   count = 0;
329   for(j=0; j < NR_STAB_HASH; j++ )
330     {
331       for(ktd = ktd_head[j]; ktd; ktd = next)
332         {
333           count++;
334           next = ktd->next;
335           DBG_free(ktd->name);
336           DBG_free(ktd);
337         }  
338       ktd_head[j] = NULL;
339     }
340
341   return TRUE;
342
343 }
344
345 static 
346 int
347 DEBUG_ParseTypedefStab(char * ptr, const char * typename)
348 {
349   int               arrmax;
350   int               arrmin;
351   char            * c;
352   struct datatype * curr_type;
353   struct datatype * datatype;
354   struct datatype * curr_types[MAX_TD_NESTING];
355   char              element_name[1024];
356   int               ntypes = 0;
357   int               offset;
358   const char      * orig_typename;
359   int               size;
360   char            * tc;
361   char            * tc2;
362   int               typenum;
363
364   orig_typename = typename;
365
366   if( DEBUG_HandlePreviousTypedef(typename, ptr) )
367       return TRUE;
368
369   /* 
370    * Go from back to front.  First we go through and figure out what
371    * type numbers we need, and register those types.  Then we go in
372    * and fill the details.  
373    */
374
375   for( c = strchr(ptr, '='); c != NULL; c = strchr(c + 1, '=') )
376     {
377       /*
378        * Back up until we get to a non-numeric character.  This is the type
379        * number.
380        */
381       typenum = DEBUG_ReadTypeEnumBackwards(c-1);
382
383       if( ntypes >= MAX_TD_NESTING )
384         {
385           /*
386            * If this ever happens, just bump the counter.
387            */
388           fprintf(stderr, "Typedef nesting overflow\n");
389           return FALSE;
390         }
391
392       switch(c[1])
393         {
394         case '*':
395           stab_types[typenum] = DEBUG_NewDataType(DT_POINTER, NULL);
396           curr_types[ntypes++] = stab_types[typenum];
397           break;
398         case 's':
399         case 'u':
400           stab_types[typenum] = DEBUG_NewDataType(DT_STRUCT, typename);
401           curr_types[ntypes++] = stab_types[typenum];
402           break;
403         case 'a':
404           stab_types[typenum] = DEBUG_NewDataType(DT_ARRAY, NULL);
405           curr_types[ntypes++] = stab_types[typenum];
406           break;
407         case '(':
408         case '1':
409         case 'r':
410           stab_types[typenum] = DEBUG_NewDataType(DT_BASIC, typename);
411           curr_types[ntypes++] = stab_types[typenum];
412           break;
413         case 'x':
414           stab_strcpy(element_name, c + 3);
415           stab_types[typenum] = DEBUG_NewDataType(DT_STRUCT, element_name);
416           curr_types[ntypes++] = stab_types[typenum];
417           break;
418         case 'e':
419           stab_types[typenum] = DEBUG_NewDataType(DT_ENUM, NULL);
420           curr_types[ntypes++] = stab_types[typenum];
421           break;
422         case 'f':
423           stab_types[typenum] = DEBUG_NewDataType(DT_FUNC, NULL);
424           curr_types[ntypes++] = stab_types[typenum];
425           break;
426         default:
427           fprintf(stderr, "Unknown type (%c).\n",c[1]);
428         }
429       typename = NULL;
430     }
431
432       /*
433       * Now register the type so that if we encounter it again, we will know
434       * what to do.
435       */
436      DEBUG_RegisterTypedef(orig_typename, curr_types, ntypes);
437
438      /* 
439       * OK, now take a second sweep through.  Now we will be digging
440       * out the definitions of the various components, and storing
441       * them in the skeletons that we have already allocated.  We take
442       * a right-to left search as this is much easier to parse.  
443       */
444      for( c = strrchr(ptr, '='); c != NULL; c = strrchr(ptr, '=') )
445        {
446          int typenum = DEBUG_ReadTypeEnumBackwards(c-1);
447          curr_type = stab_types[typenum];
448          
449          switch(c[1])
450            {
451            case 'x':
452              tc = c + 3;
453              while( *tc != ':' )
454                  tc++;
455              tc++;
456              if( *tc == '\0' )
457                  *c = '\0';
458              else
459                  strcpy(c, tc);
460              break;
461            case '*':
462            case 'f':
463              tc = c + 2;
464              datatype = stab_types[DEBUG_ReadTypeEnum(&tc)];
465              DEBUG_SetPointerType(curr_type, datatype);
466              if( *tc == '\0' )
467                  *c = '\0';
468              else
469                  strcpy(c, tc);
470              break;
471            case '(':
472            case '1':
473            case 'r':
474              /*
475               * We have already handled these above.
476               */
477              *c = '\0';
478              break;
479            case 'a':
480              /* ar<typeinfo_nodef>;<int>;<int>;<typeinfo>,<int>,<int>;; */
481
482              tc  = c + 3;
483                                                         /* 'r' */
484              DEBUG_ReadTypeEnum(&tc);
485              tc++;                                      /* ';' */
486              arrmin = strtol(tc, &tc, 10);              /* <int> */
487              tc++;                                      /* ';' */
488              arrmax = strtol(tc, &tc, 10);              /* <int> */
489              tc++;                                      /* ';' */
490              datatype = stab_types[DEBUG_ReadTypeEnum(&tc)]; /* <typeinfo> */
491              if( *tc == '\0' )
492                  *c = '\0';
493              else
494                  strcpy(c, tc);
495              DEBUG_SetArrayParams(curr_type, arrmin, arrmax, datatype);
496              break;
497            case 's':
498            case 'u': {
499              int failure = 0;
500
501              tc = c + 2;
502              if( DEBUG_SetStructSize(curr_type, strtol(tc, &tc, 10)) == FALSE )
503                {
504                  /*
505                   * We have already filled out this structure.  Nothing to do,
506                   * so just skip forward to the end of the definition.
507                   */
508                  while( tc[0] != ';' && tc[1] != ';' )
509                      tc++;
510                  
511                  tc += 2;
512                  
513                  if( *tc == '\0' )
514                      *c = '\0';
515                  else
516                      strcpy(c, tc + 1);
517                  continue;
518                }
519
520              /*
521               * Now parse the individual elements of the structure/union.
522               */
523              while(*tc != ';')
524                {
525                  char *ti;
526                  tc2 = element_name;
527                  while(*tc != ':')
528                      *tc2++ = *tc++;
529                  tc++;
530                  *tc2++ = '\0';
531                  ti=tc;
532                  datatype = stab_types[DEBUG_ReadTypeEnum(&tc)];
533                  *tc='\0';
534                  tc++;
535                  offset  = strtol(tc, &tc, 10);
536                  tc++;
537                  size  = strtol(tc, &tc, 10);
538                  tc++;
539                  if (datatype)
540                     DEBUG_AddStructElement(curr_type, element_name, datatype, offset, size);
541                  else {
542                     failure = 1;
543                     /* ... but proceed parsing to the end of the stab */
544                  }
545                }
546
547              if (failure) {
548                 /* if we had a undeclared value this one is undeclared too.
549                  * remove it from the stab_types. 
550                  * I just set it to NULL to detect bugs in my thoughtprocess.
551                  * FIXME: leaks the memory for the structure elements.
552                  * FIXME: such structures should have been optimized away
553                  *        by ld.
554                  */
555                 stab_types[typenum] = NULL;
556              }
557              if( *tc == '\0' )
558                  *c = '\0';
559              else
560                  strcpy(c, tc + 1);
561              break;
562            }
563            case 'e':
564              tc = c + 2;
565              /*
566               * Now parse the individual elements of the structure/union.
567               */
568              while(*tc != ';')
569                {
570                  tc2 = element_name;
571                  while(*tc != ':')
572                      *tc2++ = *tc++;
573                  tc++;
574                  *tc2++ = '\0';
575                  offset  = strtol(tc, &tc, 10);
576                  tc++;
577                  DEBUG_AddStructElement(curr_type, element_name, NULL, offset, 0);
578                }
579              if( *tc == '\0' )
580                  *c = '\0';
581              else
582                  strcpy(c, tc + 1);
583              break;
584            default:
585              fprintf(stderr, "Unknown type (%c).\n",c[1]);
586              break;
587            }
588        }
589      
590      return TRUE;
591
592 }
593
594 static struct datatype *
595 DEBUG_ParseStabType(const char * stab)
596 {
597   char * c;
598
599   /*
600    * Look through the stab definition, and figure out what datatype
601    * this represents.  If we have something we know about, assign the
602    * type.
603    */
604   c = strchr(stab, ':');
605   if( c == NULL )
606       return NULL;
607
608   c++;
609   /*
610    * The next character says more about the type (i.e. data, function, etc)
611    * of symbol.  Skip it.
612    */
613   c++;
614   /* 
615    * The next is either an integer or a (integer,integer).
616    * The DEBUG_ReadTypeEnum takes care that stab_types is large enough.
617    */
618   return stab_types[DEBUG_ReadTypeEnum(&c)];
619 }
620
621 int
622 DEBUG_ParseStabs(char * addr, unsigned int load_offset,
623                  unsigned int staboff, int stablen, 
624                  unsigned int strtaboff, int strtablen)
625 {
626   struct name_hash    * curr_func = NULL;
627   struct wine_locals  * curr_loc = NULL;
628   struct name_hash    * curr_sym = NULL;
629   char                  currpath[PATH_MAX];
630   int                   i;
631   int                   ignore = FALSE;
632   int                   last_nso = -1;
633   int                   len;
634   DBG_ADDR              new_addr;
635   int                   nstab;
636   char                * ptr;
637   char                * stabbuff;
638   int                   stabbufflen;
639   struct stab_nlist   * stab_ptr;
640   char                * strs;
641   int                   strtabinc;
642   char                * subpath = NULL;
643   char                  symname[4096];
644
645   nstab = stablen / sizeof(struct stab_nlist);
646   stab_ptr = (struct stab_nlist *) (addr + staboff);
647   strs  = (char *) (addr + strtaboff);
648
649   memset(currpath, 0, sizeof(currpath));
650
651   /*
652    * Allocate a buffer into which we can build stab strings for cases
653    * where the stab is continued over multiple lines.
654    */
655   stabbufflen = 65536;
656   stabbuff = (char *) DBG_alloc(stabbufflen);
657
658   strtabinc = 0;
659   stabbuff[0] = '\0';
660   for(i=0; i < nstab; i++, stab_ptr++ )
661     {
662       ptr = strs + (unsigned int) stab_ptr->n_un.n_name;
663       if( ptr[strlen(ptr) - 1] == '\\' )
664         {
665           /*
666            * Indicates continuation.  Append this to the buffer, and go onto the
667            * next record.  Repeat the process until we find a stab without the
668            * '/' character, as this indicates we have the whole thing.
669            */
670           len = strlen(ptr);
671           if( strlen(stabbuff) + len > stabbufflen )
672             {
673               stabbufflen += 65536;
674               stabbuff = (char *) DBG_realloc(stabbuff, stabbufflen);
675             }
676           strncat(stabbuff, ptr, len - 1);
677           continue;
678         }
679       else if( stabbuff[0] != '\0' )
680         {
681           strcat( stabbuff, ptr);
682           ptr = stabbuff;
683         }
684
685       if( strchr(ptr, '=') != NULL )
686         {
687           /*
688            * The stabs aren't in writable memory, so copy it over so we are
689            * sure we can scribble on it.
690            */
691           if( ptr != stabbuff )
692             {
693               strcpy(stabbuff, ptr);
694               ptr = stabbuff;
695             }
696           stab_strcpy(symname, ptr);
697           DEBUG_ParseTypedefStab(ptr, symname);
698         }
699
700       switch(stab_ptr->n_type)
701         {
702         case N_GSYM:
703           /*
704            * These are useless with ELF.  They have no value, and you have to
705            * read the normal symbol table to get the address.  Thus we
706            * ignore them, and when we process the normal symbol table
707            * we should do the right thing.
708            *
709            * With a.out, they actually do make some amount of sense.
710            */
711           new_addr.seg = 0;
712           new_addr.type = DEBUG_ParseStabType(ptr);
713           new_addr.off = load_offset + stab_ptr->n_value;
714
715           stab_strcpy(symname, ptr);
716 #ifdef __ELF__
717           curr_sym = DEBUG_AddSymbol( symname, &new_addr, currpath,
718                                       SYM_WINE | SYM_DATA | SYM_INVALID);
719 #else
720           curr_sym = DEBUG_AddSymbol( symname, &new_addr, currpath, 
721                                       SYM_WINE | SYM_DATA );
722 #endif
723           break;
724         case N_RBRAC:
725         case N_LBRAC:
726           /*
727            * We need to keep track of these so we get symbol scoping
728            * right for local variables.  For now, we just ignore them.
729            * The hooks are already there for dealing with this however,
730            * so all we need to do is to keep count of the nesting level,
731            * and find the RBRAC for each matching LBRAC.
732            */
733           break;
734         case N_LCSYM:
735         case N_STSYM:
736           /*
737            * These are static symbols and BSS symbols.
738            */
739           new_addr.seg = 0;
740           new_addr.type = DEBUG_ParseStabType(ptr);
741           new_addr.off = load_offset + stab_ptr->n_value;
742
743           stab_strcpy(symname, ptr);
744           curr_sym = DEBUG_AddSymbol( symname, &new_addr, currpath, 
745                                       SYM_WINE | SYM_DATA );
746           break;
747         case N_PSYM:
748           /*
749            * These are function parameters.
750            */
751           if(     (curr_func != NULL)
752                && (stab_ptr->n_value != 0) )
753             {
754               stab_strcpy(symname, ptr);
755               curr_loc = DEBUG_AddLocal(curr_func, 0, 
756                                         stab_ptr->n_value, 0, 0, symname);
757               DEBUG_SetLocalSymbolType( curr_loc, DEBUG_ParseStabType(ptr));
758             }
759           break;
760         case N_RSYM:
761           if( curr_func != NULL )
762             {
763               stab_strcpy(symname, ptr);
764               curr_loc = DEBUG_AddLocal(curr_func, stab_ptr->n_value, 0, 0, 0, symname);
765               DEBUG_SetLocalSymbolType( curr_loc, DEBUG_ParseStabType(ptr));
766             }
767           break;
768         case N_LSYM:
769           if(     (curr_func != NULL)
770                && (stab_ptr->n_value != 0) )
771             {
772               stab_strcpy(symname, ptr);
773               DEBUG_AddLocal(curr_func, 0, 
774                              stab_ptr->n_value, 0, 0, symname);
775             }
776           else if (curr_func == NULL)
777             {
778               stab_strcpy(symname, ptr);
779             }
780           break;
781         case N_SLINE:
782           /*
783            * This is a line number.  These are always relative to the start
784            * of the function (N_FUN), and this makes the lookup easier.
785            */
786           if( curr_func != NULL )
787             {
788 #ifdef __ELF__
789               DEBUG_AddLineNumber(curr_func, stab_ptr->n_desc, 
790                                   stab_ptr->n_value);
791 #else
792 #if 0
793               /*
794                * This isn't right.  The order of the stabs is different under
795                * a.out, and as a result we would end up attaching the line
796                * number to the wrong function.
797                */
798               DEBUG_AddLineNumber(curr_func, stab_ptr->n_desc, 
799                                   stab_ptr->n_value - curr_func->addr.off);
800 #endif
801 #endif
802             }
803           break;
804         case N_FUN:
805           /*
806            * First, clean up the previous function we were working on.
807            */
808           DEBUG_Normalize(curr_func);
809
810           /*
811            * For now, just declare the various functions.  Later
812            * on, we will add the line number information and the
813            * local symbols.
814            */
815           if( !ignore )
816             {
817               new_addr.seg = 0;
818               new_addr.type = DEBUG_ParseStabType(ptr);
819               new_addr.off = load_offset + stab_ptr->n_value;
820               /*
821                * Copy the string to a temp buffer so we
822                * can kill everything after the ':'.  We do
823                * it this way because otherwise we end up dirtying
824                * all of the pages related to the stabs, and that
825                * sucks up swap space like crazy.
826                */
827               stab_strcpy(symname, ptr);
828               curr_func = DEBUG_AddSymbol( symname, &new_addr, currpath,
829                                            SYM_WINE | SYM_FUNC);
830             }
831           else
832             {
833               /*
834                * Don't add line number information for this function
835                * any more.
836                */
837               curr_func = NULL;
838             }
839           break;
840         case N_SO:
841           /*
842            * This indicates a new source file.  Append the records
843            * together, to build the correct path name.
844            */
845 #ifndef __ELF__
846           /*
847            * With a.out, there is no NULL string N_SO entry at the end of
848            * the file.  Thus when we find non-consecutive entries,
849            * we consider that a new file is started.
850            */
851           if( last_nso < i-1 )
852             {
853               currpath[0] = '\0';
854               DEBUG_Normalize(curr_func);
855               curr_func = NULL;
856             }
857 #endif
858
859           if( *ptr == '\0' )
860             {
861               /*
862                * Nuke old path.
863                */
864               currpath[0] = '\0';
865               DEBUG_Normalize(curr_func);
866               curr_func = NULL;
867               /*
868                * The datatypes that we would need to use are reset when
869                * we start a new file.
870                */
871               memset(stab_types, 0, num_stab_types * sizeof(stab_types[0]));
872               /*
873               for (i=0;i<nrofnroftypenums;i++)
874                 memset(typenums[i],0,sizeof(typenums[i][0])*nroftypenums[i]);
875                */
876             }
877           else
878             {
879               if (*ptr != '/')
880                 strcat(currpath, ptr);
881               else
882                 strcpy(currpath, ptr);
883               subpath = ptr;
884             }
885           last_nso = i;
886           break;
887         case N_SOL:
888           /*
889            * This indicates we are including stuff from an include file.
890            * If this is the main source, enable the debug stuff, otherwise
891            * ignore it.
892            */
893           if( subpath == NULL || strcmp(ptr, subpath) == 0 )
894             {
895               ignore = FALSE;
896             }
897           else
898             {
899               ignore = TRUE;
900               DEBUG_Normalize(curr_func);
901               curr_func = NULL;
902             }
903           break;
904         case N_UNDF:
905           strs += strtabinc;
906           strtabinc = stab_ptr->n_value;
907           DEBUG_Normalize(curr_func);
908           curr_func = NULL;
909           break;
910         case N_OPT:
911           /*
912            * Ignore this.  We don't care what it points to.
913            */
914           break;
915         case N_BINCL:
916         case N_EINCL:
917         case N_MAIN:
918           /*
919            * Always ignore these.  GCC doesn't even generate them.
920            */
921           break;
922         default:
923           break;
924         }
925
926       stabbuff[0] = '\0';
927
928 #if 0
929       fprintf(stderr, "%d %x %s\n", stab_ptr->n_type, 
930               (unsigned int) stab_ptr->n_value,
931               strs + (unsigned int) stab_ptr->n_un.n_name);
932 #endif
933     }
934
935   if( stab_types != NULL )
936     {
937       DBG_free(stab_types);
938       stab_types = NULL;
939       num_stab_types = 0;
940     }
941
942
943   DEBUG_FreeRegisteredTypedefs();
944
945   return TRUE;
946 }
947
948 #ifdef __ELF__
949
950 /*
951  * Walk through the entire symbol table and add any symbols we find there.
952  * This can be used in cases where we have stripped ELF shared libraries,
953  * or it can be used in cases where we have data symbols for which the address
954  * isn't encoded in the stabs.
955  *
956  * This is all really quite easy, since we don't have to worry about line
957  * numbers or local data variables.
958  */
959 static
960 int
961 DEBUG_ProcessElfSymtab(char * addr, unsigned int load_offset,
962                        Elf32_Shdr * symtab, Elf32_Shdr * strtab)
963 {
964   char          * curfile = NULL;
965   struct name_hash * curr_sym = NULL;
966   int             flags;
967   int             i;
968   DBG_ADDR        new_addr;
969   int             nsym;
970   char          * strp;
971   char          * symname;
972   Elf32_Sym     * symp;
973
974
975   symp = (Elf32_Sym *) (addr + symtab->sh_offset);
976   nsym = symtab->sh_size / sizeof(*symp);
977   strp = (char *) (addr + strtab->sh_offset);
978
979   for(i=0; i < nsym; i++, symp++)
980     {
981       /*
982        * Ignore certain types of entries which really aren't of that much
983        * interest.
984        */
985       if( ELF32_ST_TYPE(symp->st_info) == STT_SECTION )
986         {
987           continue;
988         }
989
990       symname = strp + symp->st_name;
991
992       /*
993        * Save the name of the current file, so we have a way of tracking
994        * static functions/data.
995        */
996       if( ELF32_ST_TYPE(symp->st_info) == STT_FILE )
997         {
998           curfile = symname;
999           continue;
1000         }
1001
1002
1003       /*
1004        * See if we already have something for this symbol.
1005        * If so, ignore this entry, because it would have come from the
1006        * stabs or from a previous symbol.  If the value is different,
1007        * we will have to keep the darned thing, because there can be
1008        * multiple local symbols by the same name.
1009        */
1010       if(    (DEBUG_GetSymbolValue(symname, -1, &new_addr, FALSE ) == TRUE)
1011           && (new_addr.off == (load_offset + symp->st_value)) )
1012           continue;
1013
1014       new_addr.seg = 0;
1015       new_addr.type = NULL;
1016       new_addr.off = load_offset + symp->st_value;
1017       flags = SYM_WINE | (ELF32_ST_BIND(symp->st_info) == STT_FUNC 
1018                           ? SYM_FUNC : SYM_DATA);
1019       if( ELF32_ST_BIND(symp->st_info) == STB_GLOBAL )
1020           curr_sym = DEBUG_AddSymbol( symname, &new_addr, NULL, flags );
1021       else
1022           curr_sym = DEBUG_AddSymbol( symname, &new_addr, curfile, flags );
1023
1024       /*
1025        * Record the size of the symbol.  This can come in handy in
1026        * some cases.  Not really used yet, however.
1027        */
1028       if(  symp->st_size != 0 )
1029           DEBUG_SetSymbolSize(curr_sym, symp->st_size);
1030     }
1031
1032   return TRUE;
1033 }
1034
1035 static
1036 int
1037 DEBUG_ProcessElfObject(char * filename, unsigned int load_offset)
1038 {
1039   int                   rtn = FALSE;
1040   struct stat           statbuf;
1041   int                   fd = -1;
1042   int                   status;
1043   char                * addr = (char *) 0xffffffff;
1044   Elf32_Ehdr          * ehptr;
1045   Elf32_Shdr          * spnt;
1046   char                * shstrtab;
1047   int                   nsect;
1048   int                   i;
1049   int                   stabsect;
1050   int                   stabstrsect;
1051
1052
1053   /*
1054    * Make sure we can stat and open this file.
1055    */
1056   if( filename == NULL )
1057       goto leave;
1058
1059   status = stat(filename, &statbuf);
1060   if( status == -1 )
1061     {
1062       char *s,*t,*fn,*paths;
1063       if (strchr(filename,'/'))
1064         goto leave;
1065       paths = DBG_strdup(getenv("PATH"));
1066       s = paths;
1067       while (s && *s) {
1068         t = strchr(s,':');
1069         if (t) *t='\0';
1070         fn = (char*)DBG_alloc(strlen(filename)+1+strlen(s)+1);
1071         strcpy(fn,s);
1072         strcat(fn,"/");
1073         strcat(fn,filename);
1074         if ((rtn = DEBUG_ProcessElfObject(fn,load_offset))) {
1075                 DBG_free(fn);
1076                 DBG_free(paths);
1077                 goto leave;
1078         }
1079         DBG_free(fn);
1080         if (t) s = t+1; else break;
1081       }
1082       if (!s || !*s) fprintf(stderr," not found");
1083       DBG_free(paths);
1084       goto leave;
1085     }
1086
1087   /*
1088    * Now open the file, so that we can mmap() it.
1089    */
1090   fd = open(filename, O_RDONLY);
1091   if( fd == -1 )
1092       goto leave;
1093
1094
1095   /*
1096    * Now mmap() the file.
1097    */
1098   addr = mmap(0, statbuf.st_size, PROT_READ, 
1099               MAP_PRIVATE, fd, 0);
1100   if( addr == (char *) 0xffffffff )
1101       goto leave;
1102
1103   /*
1104    * Next, we need to find a few of the internal ELF headers within
1105    * this thing.  We need the main executable header, and the section
1106    * table.
1107    */
1108   ehptr = (Elf32_Ehdr *) addr;
1109
1110   if( load_offset == 0 )
1111       DEBUG_RegisterELFDebugInfo(ehptr->e_entry, statbuf.st_size, filename);
1112   else
1113       DEBUG_RegisterELFDebugInfo(load_offset, statbuf.st_size, filename);
1114
1115   spnt = (Elf32_Shdr *) (addr + ehptr->e_shoff);
1116   nsect = ehptr->e_shnum;
1117   shstrtab = (addr + spnt[ehptr->e_shstrndx].sh_offset);
1118
1119   stabsect = stabstrsect = -1;
1120
1121   for(i=0; i < nsect; i++)
1122     {
1123       if( strcmp(shstrtab + spnt[i].sh_name, ".stab") == 0 )
1124           stabsect = i;
1125
1126       if( strcmp(shstrtab + spnt[i].sh_name, ".stabstr") == 0 )
1127           stabstrsect = i;
1128     }
1129
1130   if( stabsect == -1 || stabstrsect == -1 )
1131       goto leave;
1132
1133   /*
1134    * OK, now just parse all of the stabs.
1135    */
1136   rtn = DEBUG_ParseStabs(addr, load_offset, 
1137                          spnt[stabsect].sh_offset,
1138                          spnt[stabsect].sh_size,
1139                          spnt[stabstrsect].sh_offset,
1140                          spnt[stabstrsect].sh_size);
1141
1142   if( rtn != TRUE )
1143       goto leave;
1144
1145   for(i=0; i < nsect; i++)
1146     {
1147       if(    (strcmp(shstrtab + spnt[i].sh_name, ".symtab") == 0)
1148           && (spnt[i].sh_type == SHT_SYMTAB) )
1149           DEBUG_ProcessElfSymtab(addr, load_offset, 
1150                                  spnt + i, spnt + spnt[i].sh_link);
1151
1152       if(    (strcmp(shstrtab + spnt[i].sh_name, ".dynsym") == 0)
1153           && (spnt[i].sh_type == SHT_DYNSYM) )
1154           DEBUG_ProcessElfSymtab(addr, load_offset, 
1155                                  spnt + i, spnt + spnt[i].sh_link);
1156     }
1157
1158 leave:
1159
1160   if( addr != (char *) 0xffffffff )
1161       munmap(addr, statbuf.st_size);
1162
1163   if( fd != -1 )
1164       close(fd);
1165
1166   return (rtn);
1167
1168 }
1169
1170 int
1171 DEBUG_ReadExecutableDbgInfo(void)
1172 {
1173   Elf32_Ehdr          * ehdr;
1174   char                * exe_name;
1175   Elf32_Dyn           * dynpnt;
1176   struct r_debug      * dbg_hdr;
1177   struct link_map     * lpnt = NULL;
1178   extern Elf32_Dyn      _DYNAMIC[];
1179   int                   rtn = FALSE;
1180   int                   rowcount;
1181
1182   exe_name = DEBUG_argv0;
1183
1184   /*
1185    * Make sure we can stat and open this file.
1186    */
1187   if( exe_name == NULL )
1188       goto leave;
1189
1190   fprintf( stderr, "Loading symbols: %s", exe_name );
1191   rowcount = 17 + strlen(exe_name);
1192   DEBUG_ProcessElfObject(exe_name, 0);
1193
1194   /*
1195    * Finally walk the tables that the dynamic loader maintains to find all
1196    * of the other shared libraries which might be loaded.  Perform the
1197    * same step for all of these.
1198    */
1199   dynpnt = _DYNAMIC;
1200   if( dynpnt == NULL )
1201       goto leave;
1202
1203   /*
1204    * Now walk the dynamic section (of the executable, looking for a DT_DEBUG
1205    * entry.
1206    */
1207   for(; dynpnt->d_tag != DT_NULL; dynpnt++)
1208       if( dynpnt->d_tag == DT_DEBUG )
1209           break;
1210
1211   if(    (dynpnt->d_tag != DT_DEBUG)
1212       || (dynpnt->d_un.d_ptr == 0) )
1213       goto leave;
1214
1215   /*
1216    * OK, now dig into the actual tables themselves.
1217    */
1218   dbg_hdr = (struct r_debug *) dynpnt->d_un.d_ptr;
1219   lpnt = dbg_hdr->r_map;
1220
1221   /*
1222    * Now walk the linked list.  In all known ELF implementations,
1223    * the dynamic loader maintains this linked list for us.  In some
1224    * cases the first entry doesn't appear with a name, in other cases it
1225    * does.
1226    */
1227   for(; lpnt; lpnt = lpnt->l_next )
1228     {
1229       /*
1230        * We already got the stuff for the executable using the
1231        * argv[0] entry above.  Here we only need to concentrate on any
1232        * shared libraries which may be loaded.
1233        */
1234       ehdr = (Elf32_Ehdr *) lpnt->l_addr;
1235       if( (lpnt->l_addr == 0) || (ehdr->e_type != ET_DYN) )
1236           continue;
1237
1238       if( lpnt->l_name != NULL )
1239       {
1240           if (rowcount + strlen(lpnt->l_name) > 76)
1241           {
1242               fprintf( stderr, "\n   " );
1243               rowcount = 3;
1244           }
1245           fprintf( stderr, " %s", lpnt->l_name );
1246           rowcount += strlen(lpnt->l_name) + 1;
1247           DEBUG_ProcessElfObject(lpnt->l_name, lpnt->l_addr);
1248       }
1249     }
1250
1251   rtn = TRUE;
1252
1253 leave:
1254   fprintf( stderr, "\n" );
1255   return (rtn);
1256
1257 }
1258
1259 #else   /* !__ELF__ */
1260
1261 #ifdef linux
1262 /*
1263  * a.out linux.
1264  */
1265 int
1266 DEBUG_ReadExecutableDbgInfo(void)
1267 {
1268   char                * addr = (char *) 0xffffffff;
1269   char                * exe_name;
1270   struct exec         * ahdr;
1271   int                   fd = -1;
1272   int                   rtn = FALSE;
1273   unsigned int          staboff;
1274   struct stat           statbuf;
1275   int                   status;
1276   unsigned int          stroff;
1277
1278   exe_name = DEBUG_argv0;
1279
1280   /*
1281    * Make sure we can stat and open this file.
1282    */
1283   if( exe_name == NULL )
1284       goto leave;
1285
1286   status = stat(exe_name, &statbuf);
1287   if( status == -1 )
1288       goto leave;
1289
1290   /*
1291    * Now open the file, so that we can mmap() it.
1292    */
1293   fd = open(exe_name, O_RDONLY);
1294   if( fd == -1 )
1295       goto leave;
1296
1297
1298   /*
1299    * Now mmap() the file.
1300    */
1301   addr = mmap(0, statbuf.st_size, PROT_READ, 
1302               MAP_PRIVATE, fd, 0);
1303   if( addr == (char *) 0xffffffff )
1304       goto leave;
1305
1306   ahdr = (struct exec *) addr;
1307
1308   staboff = N_SYMOFF(*ahdr);
1309   stroff = N_STROFF(*ahdr);
1310   rtn = DEBUG_ParseStabs(addr, 0, 
1311                          staboff, 
1312                          ahdr->a_syms,
1313                          stroff,
1314                          statbuf.st_size - stroff);
1315
1316   /*
1317    * Give a nice status message here...
1318    */
1319   fprintf( stderr, "Loading symbols: %s", exe_name );
1320
1321   rtn = TRUE;
1322
1323 leave:
1324
1325   if( addr != (char *) 0xffffffff )
1326       munmap(addr, statbuf.st_size);
1327
1328   if( fd != -1 )
1329       close(fd);
1330
1331   return (rtn);
1332
1333 }
1334 #else
1335 /*
1336  * Non-linux, non-ELF platforms.
1337  */
1338 int
1339 DEBUG_ReadExecutableDbgInfo(void)
1340 {
1341 return FALSE;
1342 }
1343 #endif
1344
1345 #endif  /* __ELF__ */