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