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