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