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