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