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