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