ole32: Fix memory leaks in the storage test.
[wine] / dlls / dbghelp / elf_module.c
1 /*
2  * File elf.c - processing of ELF files
3  *
4  * Copyright (C) 1996, Eric Youngdale.
5  *               1999-2007 Eric Pouech
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20  */
21
22 #include "config.h"
23 #include "wine/port.h"
24
25 #if defined(__svr4__) || defined(__sun)
26 #define __ELF__ 1
27 /* large files are not supported by libelf */
28 #undef _FILE_OFFSET_BITS
29 #define _FILE_OFFSET_BITS 32
30 #endif
31
32 #include <assert.h>
33 #include <stdio.h>
34 #include <stdlib.h>
35 #ifdef HAVE_SYS_STAT_H
36 # include <sys/stat.h>
37 #endif
38 #include <fcntl.h>
39 #ifdef HAVE_SYS_MMAN_H
40 #include <sys/mman.h>
41 #endif
42 #ifdef HAVE_UNISTD_H
43 # include <unistd.h>
44 #endif
45 #ifndef PATH_MAX
46 #define PATH_MAX MAX_PATH
47 #endif
48
49 #include "dbghelp_private.h"
50
51 #ifdef HAVE_ELF_H
52 # include <elf.h>
53 #endif
54 #ifdef HAVE_SYS_ELF32_H
55 # include <sys/elf32.h>
56 #endif
57 #ifdef HAVE_SYS_EXEC_ELF_H
58 # include <sys/exec_elf.h>
59 #endif
60 #if !defined(DT_NUM)
61 # if defined(DT_COUNT)
62 #  define DT_NUM DT_COUNT
63 # else
64 /* this seems to be a satisfactory value on Solaris, which doesn't support this AFAICT */
65 #  define DT_NUM 24
66 # endif
67 #endif
68 #ifdef HAVE_LINK_H
69 # include <link.h>
70 #endif
71 #ifdef HAVE_SYS_LINK_H
72 # include <sys/link.h>
73 #endif
74
75 #include "wine/library.h"
76 #include "wine/debug.h"
77
78 struct elf_module_info
79 {
80     DWORD_PTR                   elf_addr;
81     unsigned short              elf_mark : 1,
82                                 elf_loader : 1;
83 };
84
85 #ifdef __ELF__
86
87 #define ELF_INFO_DEBUG_HEADER   0x0001
88 #define ELF_INFO_MODULE         0x0002
89 #define ELF_INFO_NAME           0x0004
90
91 WINE_DEFAULT_DEBUG_CHANNEL(dbghelp);
92
93 struct elf_info
94 {
95     unsigned                    flags;          /* IN  one (or several) of the ELF_INFO constants */
96     DWORD_PTR                   dbg_hdr_addr;   /* OUT address of debug header (if ELF_INFO_DEBUG_HEADER is set) */
97     struct module*              module;         /* OUT loaded module (if ELF_INFO_MODULE is set) */
98     const WCHAR*                module_name;    /* OUT found module name (if ELF_INFO_NAME is set) */
99 };
100
101 #ifdef _WIN64
102 #define         Elf_Ehdr        Elf64_Ehdr
103 #define         Elf_Shdr        Elf64_Shdr
104 #define         Elf_Phdr        Elf64_Phdr
105 #define         Elf_Dyn         Elf64_Dyn
106 #define         Elf_Sym         Elf64_Sym
107 #else
108 #define         Elf_Ehdr        Elf32_Ehdr
109 #define         Elf_Shdr        Elf32_Shdr
110 #define         Elf_Phdr        Elf32_Phdr
111 #define         Elf_Dyn         Elf32_Dyn
112 #define         Elf_Sym         Elf32_Sym
113 #endif
114
115 /* structure holding information while handling an ELF image
116  * allows one by one section mapping for memory savings
117  */
118 struct elf_file_map
119 {
120     Elf_Ehdr                    elfhdr;
121     size_t                      elf_size;
122     size_t                      elf_start;
123     struct
124     {
125         Elf_Shdr                        shdr;
126         const char*                     mapped;
127     }*                          sect;
128     int                         fd;
129     const char*                 shstrtab;
130     struct elf_file_map*        alternate;      /* another ELF file (linked to this one) */
131 };
132
133 struct elf_section_map
134 {
135     struct elf_file_map*        fmap;
136     long                        sidx;
137 };
138
139 struct symtab_elt
140 {
141     struct hash_table_elt       ht_elt;
142     const Elf_Sym*              symp;
143     struct symt_compiland*      compiland;
144     unsigned                    used;
145 };
146
147 struct elf_thunk_area
148 {
149     const char*                 symname;
150     THUNK_ORDINAL               ordinal;
151     unsigned long               rva_start;
152     unsigned long               rva_end;
153 };
154
155 /******************************************************************
156  *              elf_map_section
157  *
158  * Maps a single section into memory from an ELF file
159  */
160 static const char* elf_map_section(struct elf_section_map* esm)
161 {
162     unsigned pgsz = getpagesize();
163     unsigned ofst, size;
164
165     if (esm->sidx < 0 || esm->sidx >= esm->fmap->elfhdr.e_shnum ||
166         esm->fmap->sect[esm->sidx].shdr.sh_type == SHT_NOBITS)
167         return ELF_NO_MAP;
168
169     /* align required information on page size (we assume pagesize is a power of 2) */
170     ofst = esm->fmap->sect[esm->sidx].shdr.sh_offset & ~(pgsz - 1);
171     size = ((esm->fmap->sect[esm->sidx].shdr.sh_offset +
172              esm->fmap->sect[esm->sidx].shdr.sh_size + pgsz - 1) & ~(pgsz - 1)) - ofst;
173     esm->fmap->sect[esm->sidx].mapped = mmap(NULL, size, PROT_READ, MAP_PRIVATE,
174                                              esm->fmap->fd, ofst);
175     if (esm->fmap->sect[esm->sidx].mapped == ELF_NO_MAP) return ELF_NO_MAP;
176     return esm->fmap->sect[esm->sidx].mapped + (esm->fmap->sect[esm->sidx].shdr.sh_offset & (pgsz - 1));
177 }
178
179 /******************************************************************
180  *              elf_find_section
181  *
182  * Finds a section by name (and type) into memory from an ELF file
183  * or its alternate if any
184  */
185 static BOOL elf_find_section(struct elf_file_map* fmap, const char* name,
186                              unsigned sht, struct elf_section_map* esm)
187 {
188     unsigned i;
189
190     while (fmap)
191     {
192         if (fmap->shstrtab == ELF_NO_MAP)
193         {
194             struct elf_section_map  hdr_esm = {fmap, fmap->elfhdr.e_shstrndx};
195             if ((fmap->shstrtab = elf_map_section(&hdr_esm)) == ELF_NO_MAP) break;
196         }
197         for (i = 0; i < fmap->elfhdr.e_shnum; i++)
198         {
199             if (strcmp(fmap->shstrtab + fmap->sect[i].shdr.sh_name, name) == 0 &&
200                 (sht == SHT_NULL || sht == fmap->sect[i].shdr.sh_type))
201             {
202                 esm->fmap = fmap;
203                 esm->sidx = i;
204                 return TRUE;
205             }
206         }
207         fmap = fmap->alternate;
208     }
209     esm->fmap = NULL;
210     esm->sidx = -1;
211     return FALSE;
212 }
213
214 /******************************************************************
215  *              elf_unmap_section
216  *
217  * Unmaps a single section from memory
218  */
219 static void elf_unmap_section(struct elf_section_map* esm)
220 {
221     if (esm->sidx >= 0 && esm->sidx < esm->fmap->elfhdr.e_shnum && esm->fmap->sect[esm->sidx].mapped != ELF_NO_MAP)
222     {
223         unsigned pgsz = getpagesize();
224         unsigned ofst, size;
225
226         ofst = esm->fmap->sect[esm->sidx].shdr.sh_offset & ~(pgsz - 1);
227         size = ((esm->fmap->sect[esm->sidx].shdr.sh_offset +
228              esm->fmap->sect[esm->sidx].shdr.sh_size + pgsz - 1) & ~(pgsz - 1)) - ofst;
229         if (munmap((char*)esm->fmap->sect[esm->sidx].mapped, size) < 0)
230             WARN("Couldn't unmap the section\n");
231         esm->fmap->sect[esm->sidx].mapped = ELF_NO_MAP;
232     }
233 }
234
235 static void elf_end_find(struct elf_file_map* fmap)
236 {
237     struct elf_section_map      esm;
238
239     while (fmap)
240     {
241         esm.fmap = fmap;
242         esm.sidx = fmap->elfhdr.e_shstrndx;
243         elf_unmap_section(&esm);
244         fmap->shstrtab = ELF_NO_MAP;
245         fmap = fmap->alternate;
246     }
247 }
248
249 /******************************************************************
250  *              elf_get_map_size
251  *
252  * Get the size of an ELF section
253  */
254 static inline unsigned elf_get_map_size(const struct elf_section_map* esm)
255 {
256     if (esm->sidx < 0 || esm->sidx >= esm->fmap->elfhdr.e_shnum)
257         return 0;
258     return esm->fmap->sect[esm->sidx].shdr.sh_size;
259 }
260
261 /******************************************************************
262  *              elf_map_file
263  *
264  * Maps an ELF file into memory (and checks it's a real ELF file)
265  */
266 static BOOL elf_map_file(const WCHAR* filenameW, struct elf_file_map* fmap)
267 {
268     static const BYTE   elf_signature[4] = { ELFMAG0, ELFMAG1, ELFMAG2, ELFMAG3 };
269     struct stat         statbuf;
270     int                 i;
271     Elf_Phdr            phdr;
272     unsigned            tmp, page_mask = getpagesize() - 1;
273     char*               filename;
274     unsigned            len;
275     BOOL                ret = FALSE;
276
277     len = WideCharToMultiByte(CP_UNIXCP, 0, filenameW, -1, NULL, 0, NULL, NULL);
278     if (!(filename = HeapAlloc(GetProcessHeap(), 0, len))) return FALSE;
279     WideCharToMultiByte(CP_UNIXCP, 0, filenameW, -1, filename, len, NULL, NULL);
280
281     fmap->fd = -1;
282     fmap->shstrtab = ELF_NO_MAP;
283     fmap->alternate = NULL;
284
285     /* check that the file exists, and that the module hasn't been loaded yet */
286     if (stat(filename, &statbuf) == -1 || S_ISDIR(statbuf.st_mode)) goto done;
287
288     /* Now open the file, so that we can mmap() it. */
289     if ((fmap->fd = open(filename, O_RDONLY)) == -1) goto done;
290
291     if (read(fmap->fd, &fmap->elfhdr, sizeof(fmap->elfhdr)) != sizeof(fmap->elfhdr))
292         goto done;
293     /* and check for an ELF header */
294     if (memcmp(fmap->elfhdr.e_ident, 
295                elf_signature, sizeof(elf_signature))) goto done;
296     /* and check 32 vs 64 size according to current machine */
297 #ifdef _WIN64
298     if (fmap->elfhdr.e_ident[EI_CLASS] != ELFCLASS64) goto done;
299 #else
300     if (fmap->elfhdr.e_ident[EI_CLASS] != ELFCLASS32) goto done;
301 #endif
302     fmap->sect = HeapAlloc(GetProcessHeap(), 0,
303                            fmap->elfhdr.e_shnum * sizeof(fmap->sect[0]));
304     if (!fmap->sect) goto done;
305
306     lseek(fmap->fd, fmap->elfhdr.e_shoff, SEEK_SET);
307     for (i = 0; i < fmap->elfhdr.e_shnum; i++)
308     {
309         read(fmap->fd, &fmap->sect[i].shdr, sizeof(fmap->sect[i].shdr));
310         fmap->sect[i].mapped = ELF_NO_MAP;
311     }
312
313     /* grab size of module once loaded in memory */
314     lseek(fmap->fd, fmap->elfhdr.e_phoff, SEEK_SET);
315     fmap->elf_size = 0; 
316     fmap->elf_start = ~0L;
317     for (i = 0; i < fmap->elfhdr.e_phnum; i++)
318     {
319         if (read(fmap->fd, &phdr, sizeof(phdr)) == sizeof(phdr) && 
320             phdr.p_type == PT_LOAD)
321         {
322             tmp = (phdr.p_vaddr + phdr.p_memsz + page_mask) & ~page_mask;
323             if (fmap->elf_size < tmp) fmap->elf_size = tmp;
324             if (phdr.p_vaddr < fmap->elf_start) fmap->elf_start = phdr.p_vaddr;
325         }
326     }
327     /* if non relocatable ELF, then remove fixed address from computation
328      * otherwise, all addresses are zero based and start has no effect
329      */
330     fmap->elf_size -= fmap->elf_start;
331     ret = TRUE;
332 done:
333     HeapFree(GetProcessHeap(), 0, filename);
334     return ret;
335 }
336
337 /******************************************************************
338  *              elf_unmap_file
339  *
340  * Unmaps an ELF file from memory (previously mapped with elf_map_file)
341  */
342 static void elf_unmap_file(struct elf_file_map* fmap)
343 {
344     while (fmap)
345     {
346         if (fmap->fd != -1)
347         {
348             struct elf_section_map  esm;
349             esm.fmap = fmap;
350             for (esm.sidx = 0; esm.sidx < fmap->elfhdr.e_shnum; esm.sidx++)
351             {
352                 elf_unmap_section(&esm);
353             }
354             HeapFree(GetProcessHeap(), 0, fmap->sect);
355             close(fmap->fd);
356         }
357         fmap = fmap->alternate;
358     }
359 }
360
361 /******************************************************************
362  *              elf_is_in_thunk_area
363  *
364  * Check whether an address lies within one of the thunk area we
365  * know of.
366  */
367 int elf_is_in_thunk_area(unsigned long addr,
368                          const struct elf_thunk_area* thunks)
369 {
370     unsigned i;
371
372     for (i = 0; thunks[i].symname; i++)
373     {
374         if (addr >= thunks[i].rva_start && addr < thunks[i].rva_end)
375             return i;
376     }
377     return -1;
378 }
379
380 /******************************************************************
381  *              elf_hash_symtab
382  *
383  * creating an internal hash table to ease use ELF symtab information lookup
384  */
385 static void elf_hash_symtab(struct module* module, struct pool* pool, 
386                             struct hash_table* ht_symtab, struct elf_file_map* fmap,
387                             struct elf_thunk_area* thunks)
388 {
389     int                         i, j, nsym;
390     const char*                 strp;
391     const char*                 symname;
392     struct symt_compiland*      compiland = NULL;
393     const char*                 ptr;
394     const Elf_Sym*              symp;
395     struct symtab_elt*          ste;
396     struct elf_section_map      esm, esm_str;
397
398     if (!elf_find_section(fmap, ".symtab", SHT_SYMTAB, &esm) &&
399         !elf_find_section(fmap, ".dynsym", SHT_DYNSYM, &esm)) return;
400     if ((symp = (const Elf_Sym*)elf_map_section(&esm)) == ELF_NO_MAP) return;
401     esm_str.fmap = fmap;
402     esm_str.sidx = fmap->sect[esm.sidx].shdr.sh_link;
403     if ((strp = elf_map_section(&esm_str)) == ELF_NO_MAP) return;
404
405     nsym = elf_get_map_size(&esm) / sizeof(*symp);
406
407     for (j = 0; thunks[j].symname; j++)
408         thunks[j].rva_start = thunks[j].rva_end = 0;
409
410     for (i = 0; i < nsym; i++, symp++)
411     {
412         /* Ignore certain types of entries which really aren't of that much
413          * interest.
414          */
415         if ((ELF32_ST_TYPE(symp->st_info) != STT_NOTYPE &&
416              ELF32_ST_TYPE(symp->st_info) != STT_FILE &&
417              ELF32_ST_TYPE(symp->st_info) != STT_OBJECT &&
418              ELF32_ST_TYPE(symp->st_info) != STT_FUNC) ||
419             symp->st_shndx == SHN_UNDEF)
420         {
421             continue;
422         }
423
424         symname = strp + symp->st_name;
425
426         /* handle some specific symtab (that we'll throw away when done) */
427         switch (ELF32_ST_TYPE(symp->st_info))
428         {
429         case STT_FILE:
430             if (symname)
431                 compiland = symt_new_compiland(module, symp->st_value,
432                                                source_new(module, NULL, symname));
433             else
434                 compiland = NULL;
435             continue;
436         case STT_NOTYPE:
437             /* we are only interested in wine markers inserted by winebuild */
438             for (j = 0; thunks[j].symname; j++)
439             {
440                 if (!strcmp(symname, thunks[j].symname))
441                 {
442                     thunks[j].rva_start = symp->st_value;
443                     thunks[j].rva_end   = symp->st_value + symp->st_size;
444                     break;
445                 }
446             }
447             continue;
448         }
449
450         /* FIXME: we don't need to handle them (GCC internals)
451          * Moreover, they screw up our symbol lookup :-/
452          */
453         if (symname[0] == '.' && symname[1] == 'L' && isdigit(symname[2]))
454             continue;
455
456         ste = pool_alloc(pool, sizeof(*ste));
457         ste->ht_elt.name = symname;
458         /* GCC emits, in some cases, a .<digit>+ suffix.
459          * This is used for static variable inside functions, so
460          * that we can have several such variables with same name in
461          * the same compilation unit
462          * We simply ignore that suffix when present (we also get rid
463          * of it in stabs parsing)
464          */
465         ptr = symname + strlen(symname) - 1;
466         if (isdigit(*ptr))
467         {
468             while (isdigit(*ptr) && ptr >= symname) ptr--;
469             if (ptr > symname && *ptr == '.')
470             {
471                 char* n = pool_alloc(pool, ptr - symname + 1);
472                 memcpy(n, symname, ptr - symname + 1);
473                 n[ptr - symname] = '\0';
474                 ste->ht_elt.name = n;
475             }
476         }
477         ste->symp        = symp;
478         ste->compiland   = compiland;
479         ste->used        = 0;
480         hash_table_add(ht_symtab, &ste->ht_elt);
481     }
482     /* as we added in the ht_symtab pointers to the symbols themselves,
483      * we cannot unmap yet the sections, it will be done when we're over
484      * with this ELF file
485      */
486 }
487
488 /******************************************************************
489  *              elf_lookup_symtab
490  *
491  * lookup a symbol by name in our internal hash table for the symtab
492  */
493 static const Elf_Sym* elf_lookup_symtab(const struct module* module,
494                                           const struct hash_table* ht_symtab,
495                                           const char* name, const struct symt* compiland)
496 {
497     struct symtab_elt*          weak_result = NULL; /* without compiland name */
498     struct symtab_elt*          result = NULL;
499     struct hash_table_iter      hti;
500     struct symtab_elt*          ste;
501     const char*                 compiland_name;
502     const char*                 compiland_basename;
503     const char*                 base;
504
505     /* we need weak match up (at least) when symbols of same name, 
506      * defined several times in different compilation units,
507      * are merged in a single one (hence a different filename for c.u.)
508      */
509     if (compiland)
510     {
511         compiland_name = source_get(module,
512                                     ((const struct symt_compiland*)compiland)->source);
513         compiland_basename = strrchr(compiland_name, '/');
514         if (!compiland_basename++) compiland_basename = compiland_name;
515     }
516     else compiland_name = compiland_basename = NULL;
517     
518     hash_table_iter_init(ht_symtab, &hti, name);
519     while ((ste = hash_table_iter_up(&hti)))
520     {
521         if (ste->used || strcmp(ste->ht_elt.name, name)) continue;
522
523         weak_result = ste;
524         if ((ste->compiland && !compiland_name) || (!ste->compiland && compiland_name))
525             continue;
526         if (ste->compiland && compiland_name)
527         {
528             const char* filename = source_get(module, ste->compiland->source);
529             if (strcmp(filename, compiland_name))
530             {
531                 base = strrchr(filename, '/');
532                 if (!base++) base = filename;
533                 if (strcmp(base, compiland_basename)) continue;
534             }
535         }
536         if (result)
537         {
538             FIXME("Already found symbol %s (%s) in symtab %s @%08x and %s @%08x\n",
539                   name, compiland_name,
540                   source_get(module, result->compiland->source), (unsigned int)result->symp->st_value,
541                   source_get(module, ste->compiland->source), (unsigned int)ste->symp->st_value);
542         }
543         else
544         {
545             result = ste;
546             ste->used = 1;
547         }
548     }
549     if (!result && !(result = weak_result))
550     {
551         FIXME("Couldn't find symbol %s!%s in symtab\n",
552               debugstr_w(module->module.ModuleName), name);
553         return NULL;
554     }
555     return result->symp;
556 }
557
558 /******************************************************************
559  *              elf_finish_stabs_info
560  *
561  * - get any relevant information (address & size) from the bits we got from the
562  *   stabs debugging information
563  */
564 static void elf_finish_stabs_info(struct module* module, const struct hash_table* symtab)
565 {
566     struct hash_table_iter      hti;
567     void*                       ptr;
568     struct symt_ht*             sym;
569     const Elf_Sym*              symp;
570
571     hash_table_iter_init(&module->ht_symbols, &hti, NULL);
572     while ((ptr = hash_table_iter_up(&hti)))
573     {
574         sym = GET_ENTRY(ptr, struct symt_ht, hash_elt);
575         switch (sym->symt.tag)
576         {
577         case SymTagFunction:
578             if (((struct symt_function*)sym)->address != module->elf_info->elf_addr &&
579                 ((struct symt_function*)sym)->size)
580             {
581                 break;
582             }
583             symp = elf_lookup_symtab(module, symtab, sym->hash_elt.name, 
584                                      ((struct symt_function*)sym)->container);
585             if (symp)
586             {
587                 if (((struct symt_function*)sym)->address != module->elf_info->elf_addr &&
588                     ((struct symt_function*)sym)->address != module->elf_info->elf_addr + symp->st_value)
589                     FIXME("Changing address for %p/%s!%s from %08lx to %08lx\n",
590                           sym, debugstr_w(module->module.ModuleName), sym->hash_elt.name,
591                           ((struct symt_function*)sym)->address, module->elf_info->elf_addr + symp->st_value);
592                 if (((struct symt_function*)sym)->size && ((struct symt_function*)sym)->size != symp->st_size)
593                     FIXME("Changing size for %p/%s!%s from %08lx to %08x\n",
594                           sym, debugstr_w(module->module.ModuleName), sym->hash_elt.name,
595                           ((struct symt_function*)sym)->size, (unsigned int)symp->st_size);
596
597                 ((struct symt_function*)sym)->address = module->elf_info->elf_addr +
598                                                         symp->st_value;
599                 ((struct symt_function*)sym)->size    = symp->st_size;
600             } else
601                 FIXME("Couldn't find %s!%s\n",
602                       debugstr_w(module->module.ModuleName), sym->hash_elt.name);
603             break;
604         case SymTagData:
605             switch (((struct symt_data*)sym)->kind)
606             {
607             case DataIsGlobal:
608             case DataIsFileStatic:
609                 if (((struct symt_data*)sym)->u.var.offset != module->elf_info->elf_addr)
610                     break;
611                 symp = elf_lookup_symtab(module, symtab, sym->hash_elt.name, 
612                                          ((struct symt_data*)sym)->container);
613                 if (symp)
614                 {
615                 if (((struct symt_data*)sym)->u.var.offset != module->elf_info->elf_addr &&
616                     ((struct symt_data*)sym)->u.var.offset != module->elf_info->elf_addr + symp->st_value)
617                     FIXME("Changing address for %p/%s!%s from %08lx to %08lx\n",
618                           sym, debugstr_w(module->module.ModuleName), sym->hash_elt.name,
619                           ((struct symt_function*)sym)->address, module->elf_info->elf_addr + symp->st_value);
620                     ((struct symt_data*)sym)->u.var.offset = module->elf_info->elf_addr +
621                                                           symp->st_value;
622                     ((struct symt_data*)sym)->kind = (ELF32_ST_BIND(symp->st_info) == STB_LOCAL) ?
623                         DataIsFileStatic : DataIsGlobal;
624                 } else
625                     FIXME("Couldn't find %s!%s\n",
626                           debugstr_w(module->module.ModuleName), sym->hash_elt.name);
627                 break;
628             default:;
629             }
630             break;
631         default:
632             FIXME("Unsupported tag %u\n", sym->symt.tag);
633             break;
634         }
635     }
636     /* since we may have changed some addresses & sizes, mark the module to be resorted */
637     module->sortlist_valid = FALSE;
638 }
639
640 /******************************************************************
641  *              elf_load_wine_thunks
642  *
643  * creating the thunk objects for a wine native DLL
644  */
645 static int elf_new_wine_thunks(struct module* module, const struct hash_table* ht_symtab,
646                                const struct elf_thunk_area* thunks)
647 {
648     int                         j;
649     struct hash_table_iter      hti;
650     struct symtab_elt*          ste;
651     DWORD_PTR                   addr;
652     struct symt_ht*             symt;
653
654     hash_table_iter_init(ht_symtab, &hti, NULL);
655     while ((ste = hash_table_iter_up(&hti)))
656     {
657         if (ste->used) continue;
658
659         addr = module->elf_info->elf_addr + ste->symp->st_value;
660
661         j = elf_is_in_thunk_area(ste->symp->st_value, thunks);
662         if (j >= 0) /* thunk found */
663         {
664             symt_new_thunk(module, ste->compiland, ste->ht_elt.name, thunks[j].ordinal,
665                            addr, ste->symp->st_size);
666         }
667         else
668         {
669             ULONG64     ref_addr;
670
671             symt = symt_find_nearest(module, addr);
672             if (symt && !symt_get_info(module, &symt->symt, TI_GET_ADDRESS, &ref_addr))
673                 ref_addr = addr;
674             if (!symt || addr != ref_addr)
675             {
676                 /* creating public symbols for all the ELF symbols which haven't been
677                  * used yet (ie we have no debug information on them)
678                  * That's the case, for example, of the .spec.c files
679                  */
680                 switch (ELF32_ST_TYPE(ste->symp->st_info))
681                 {
682                 case STT_FUNC:
683                     symt_new_function(module, ste->compiland, ste->ht_elt.name,
684                                       addr, ste->symp->st_size, NULL);
685                     break;
686                 case STT_OBJECT:
687                     symt_new_global_variable(module, ste->compiland, ste->ht_elt.name,
688                                              ELF32_ST_BIND(ste->symp->st_info) == STB_LOCAL,
689                                              addr, ste->symp->st_size, NULL);
690                     break;
691                 default:
692                     FIXME("Shouldn't happen\n");
693                     break;
694                 }
695                 /* FIXME: this is a hack !!!
696                  * we are adding new symbols, but as we're parsing a symbol table
697                  * (hopefully without duplicate symbols) we delay rebuilding the sorted
698                  * module table until we're done with the symbol table
699                  * Otherwise, as we intertwine symbols's add and lookup, performance
700                  * is rather bad
701                  */
702                 module->sortlist_valid = TRUE;
703             }
704             else if (strcmp(ste->ht_elt.name, symt->hash_elt.name))
705             {
706                 ULONG64 xaddr = 0, xsize = 0;
707                 DWORD   kind = -1;
708
709                 symt_get_info(module, &symt->symt, TI_GET_ADDRESS,  &xaddr);
710                 symt_get_info(module, &symt->symt, TI_GET_LENGTH,   &xsize);
711                 symt_get_info(module, &symt->symt, TI_GET_DATAKIND, &kind);
712
713                 /* If none of symbols has a correct size, we consider they are both markers
714                  * Hence, we can silence this warning
715                  * Also, we check that we don't have two symbols, one local, the other 
716                  * global which is legal
717                  */
718                 if ((xsize || ste->symp->st_size) &&
719                     (kind == (ELF32_ST_BIND(ste->symp->st_info) == STB_LOCAL) ? DataIsFileStatic : DataIsGlobal))
720                     FIXME("Duplicate in %s: %s<%08lx-%08x> %s<%s-%s>\n",
721                           debugstr_w(module->module.ModuleName),
722                           ste->ht_elt.name, addr, (unsigned int)ste->symp->st_size,
723                           symt->hash_elt.name,
724                           wine_dbgstr_longlong(xaddr), wine_dbgstr_longlong(xsize));
725             }
726         }
727     }
728     /* see comment above */
729     module->sortlist_valid = FALSE;
730     return TRUE;
731 }
732
733 /******************************************************************
734  *              elf_new_public_symbols
735  *
736  * Creates a set of public symbols from an ELF symtab
737  */
738 static int elf_new_public_symbols(struct module* module, const struct hash_table* symtab)
739 {
740     struct hash_table_iter      hti;
741     struct symtab_elt*          ste;
742
743     if (dbghelp_options & SYMOPT_NO_PUBLICS) return TRUE;
744
745     /* FIXME: we're missing the ELF entry point here */
746
747     hash_table_iter_init(symtab, &hti, NULL);
748     while ((ste = hash_table_iter_up(&hti)))
749     {
750         symt_new_public(module, ste->compiland, ste->ht_elt.name,
751                         module->elf_info->elf_addr + ste->symp->st_value,
752                         ste->symp->st_size, TRUE /* FIXME */, 
753                         ELF32_ST_TYPE(ste->symp->st_info) == STT_FUNC);
754     }
755     return TRUE;
756 }
757
758 static BOOL elf_check_debug_link(const WCHAR* file, struct elf_file_map* fmap, DWORD crc)
759 {
760     BOOL        ret;
761     if (!elf_map_file(file, fmap)) return FALSE;
762     if (!(ret = crc == calc_crc32(fmap->fd)))
763     {
764         WARN("Bad CRC for file %s (got %08x while expecting %08x)\n",
765              debugstr_w(file), calc_crc32(fmap->fd), crc);
766         elf_unmap_file(fmap);
767     }
768     return ret;
769 }
770
771 /******************************************************************
772  *              elf_locate_debug_link
773  *
774  * Locate a filename from a .gnu_debuglink section, using the same
775  * strategy as gdb:
776  * "If the full name of the directory containing the executable is
777  * execdir, and the executable has a debug link that specifies the
778  * name debugfile, then GDB will automatically search for the
779  * debugging information file in three places:
780  *  - the directory containing the executable file (that is, it
781  *    will look for a file named `execdir/debugfile',
782  *  - a subdirectory of that directory named `.debug' (that is, the
783  *    file `execdir/.debug/debugfile', and
784  *  - a subdirectory of the global debug file directory that includes
785  *    the executable's full path, and the name from the link (that is,
786  *    the file `globaldebugdir/execdir/debugfile', where globaldebugdir
787  *    is the global debug file directory, and execdir has been turned
788  *    into a relative path)." (from GDB manual)
789  */
790 static BOOL elf_locate_debug_link(struct elf_file_map* fmap, const char* filename,
791                                   const WCHAR* loaded_file, DWORD crc)
792 {
793     static const WCHAR globalDebugDirW[] = {'/','u','s','r','/','l','i','b','/','d','e','b','u','g','/'};
794     static const WCHAR dotDebugW[] = {'.','d','e','b','u','g','/'};
795     const size_t globalDebugDirLen = sizeof(globalDebugDirW) / sizeof(WCHAR);
796     size_t filename_len;
797     WCHAR* p = NULL;
798     WCHAR* slash;
799     struct elf_file_map* fmap_link = NULL;
800
801     fmap_link = HeapAlloc(GetProcessHeap(), 0, sizeof(*fmap_link));
802     if (!fmap_link) return FALSE;
803
804     filename_len = MultiByteToWideChar(CP_UNIXCP, 0, filename, -1, NULL, 0);
805     p = HeapAlloc(GetProcessHeap(), 0,
806                   (globalDebugDirLen + strlenW(loaded_file) + 6 + 1 + filename_len + 1) * sizeof(WCHAR));
807     if (!p) goto found;
808
809     /* we prebuild the string with "execdir" */
810     strcpyW(p, loaded_file);
811     slash = strrchrW(p, '/');
812     if (slash == NULL) slash = p; else slash++;
813
814     /* testing execdir/filename */
815     MultiByteToWideChar(CP_UNIXCP, 0, filename, -1, slash, filename_len);
816     if (elf_check_debug_link(p, fmap_link, crc)) goto found;
817
818     /* testing execdir/.debug/filename */
819     memcpy(slash, dotDebugW, sizeof(dotDebugW));
820     MultiByteToWideChar(CP_UNIXCP, 0, filename, -1, slash + sizeof(dotDebugW) / sizeof(WCHAR), filename_len);
821     if (elf_check_debug_link(p, fmap_link, crc)) goto found;
822
823     /* testing globaldebugdir/execdir/filename */
824     memmove(p + globalDebugDirLen, p, (slash - p) * sizeof(WCHAR));
825     memcpy(p, globalDebugDirW, globalDebugDirLen * sizeof(WCHAR));
826     slash += globalDebugDirLen;
827     MultiByteToWideChar(CP_UNIXCP, 0, filename, -1, slash, filename_len);
828     if (elf_check_debug_link(p, fmap_link, crc)) goto found;
829
830     /* finally testing filename */
831     if (elf_check_debug_link(slash, fmap_link, crc)) goto found;
832
833
834     WARN("Couldn't locate or map %s\n", filename);
835     HeapFree(GetProcessHeap(), 0, p);
836     HeapFree(GetProcessHeap(), 0, fmap_link);
837     return FALSE;
838
839 found:
840     TRACE("Located debug information file %s at %s\n", filename, debugstr_w(p));
841     HeapFree(GetProcessHeap(), 0, p);
842     fmap->alternate = fmap_link;
843     return TRUE;
844 }
845
846 /******************************************************************
847  *              elf_debuglink_parse
848  *
849  * Parses a .gnu_debuglink section and loads the debug info from
850  * the external file specified there.
851  */
852 static BOOL elf_debuglink_parse(struct elf_file_map* fmap, const struct module* module,
853                                 const BYTE* debuglink)
854 {
855     /* The content of a debug link section is:
856      * 1/ a NULL terminated string, containing the file name for the
857      *    debug info
858      * 2/ padding on 4 byte boundary
859      * 3/ CRC of the linked ELF file
860      */
861     const char* dbg_link = (const char*)debuglink;
862     DWORD crc;
863
864     crc = *(const DWORD*)(dbg_link + ((DWORD_PTR)(strlen(dbg_link) + 4) & ~3));
865     return elf_locate_debug_link(fmap, dbg_link, module->module.LoadedImageName, crc);
866 }
867
868 /******************************************************************
869  *              elf_load_debug_info_from_map
870  *
871  * Loads the symbolic information from ELF module which mapping is described
872  * in fmap
873  * the module has been loaded at 'load_offset' address, so symbols' address
874  * relocation is performed.
875  * CRC is checked if fmap->with_crc is TRUE
876  * returns
877  *      0 if the file doesn't contain symbolic info (or this info cannot be
878  *      read or parsed)
879  *      1 on success
880  */
881 static BOOL elf_load_debug_info_from_map(struct module* module, 
882                                          struct elf_file_map* fmap,
883                                          struct pool* pool,
884                                          struct hash_table* ht_symtab)
885 {
886     BOOL                ret = FALSE, lret;
887     struct elf_thunk_area thunks[] = 
888     {
889         {"__wine_spec_import_thunks",           THUNK_ORDINAL_NOTYPE, 0, 0},    /* inter DLL calls */
890         {"__wine_spec_delayed_import_loaders",  THUNK_ORDINAL_LOAD,   0, 0},    /* delayed inter DLL calls */
891         {"__wine_spec_delayed_import_thunks",   THUNK_ORDINAL_LOAD,   0, 0},    /* delayed inter DLL calls */
892         {"__wine_delay_load",                   THUNK_ORDINAL_LOAD,   0, 0},    /* delayed inter DLL calls */
893         {"__wine_spec_thunk_text_16",           -16,                  0, 0},    /* 16 => 32 thunks */
894         {"__wine_spec_thunk_text_32",           -32,                  0, 0},    /* 32 => 16 thunks */
895         {NULL,                                  0,                    0, 0}
896     };
897
898     module->module.SymType = SymExport;
899
900     /* create a hash table for the symtab */
901     elf_hash_symtab(module, pool, ht_symtab, fmap, thunks);
902
903     if (!(dbghelp_options & SYMOPT_PUBLICS_ONLY))
904     {
905         struct elf_section_map  stab_sect, stabstr_sect;
906         struct elf_section_map  debug_sect, debug_str_sect, debug_abbrev_sect,
907                                 debug_line_sect, debug_loclist_sect;
908         struct elf_section_map  debuglink_sect;
909
910         /* if present, add the .gnu_debuglink file as an alternate to current one */
911         if (elf_find_section(fmap, ".gnu_debuglink", SHT_NULL, &debuglink_sect))
912         {
913             const BYTE* dbg_link;
914
915             dbg_link = (const BYTE*)elf_map_section(&debuglink_sect);
916             if (dbg_link != ELF_NO_MAP)
917             {
918                 lret = elf_debuglink_parse(fmap, module, dbg_link);
919                 if (!lret)
920                     WARN("Couldn't load linked debug file for %s\n",
921                          debugstr_w(module->module.ModuleName));
922                 ret = ret || lret;
923             }
924             elf_unmap_section(&debuglink_sect);
925         }
926         if (elf_find_section(fmap, ".stab", SHT_NULL, &stab_sect) &&
927             elf_find_section(fmap, ".stabstr", SHT_NULL, &stabstr_sect))
928         {
929             const char* stab;
930             const char* stabstr;
931
932             stab = elf_map_section(&stab_sect);
933             stabstr = elf_map_section(&stabstr_sect);
934             if (stab != ELF_NO_MAP && stabstr != ELF_NO_MAP)
935             {
936                 /* OK, now just parse all of the stabs. */
937                 lret = stabs_parse(module, module->elf_info->elf_addr,
938                                    stab, elf_get_map_size(&stab_sect),
939                                    stabstr, elf_get_map_size(&stabstr_sect),
940                                    NULL, NULL);
941                 if (lret)
942                     /* and fill in the missing information for stabs */
943                     elf_finish_stabs_info(module, ht_symtab);
944                 else
945                     WARN("Couldn't correctly read stabs\n");
946                 ret = ret || lret;
947             }
948             else lret = FALSE;
949             elf_unmap_section(&stab_sect);
950             elf_unmap_section(&stabstr_sect);
951         }
952         if (elf_find_section(fmap, ".debug_info", SHT_NULL, &debug_sect))
953         {
954             /* Dwarf 2 debug information */
955             const BYTE* dw2_debug;
956             const BYTE* dw2_debug_abbrev;
957             const BYTE* dw2_debug_str;
958             const BYTE* dw2_debug_line;
959             const BYTE* dw2_debug_loclist;
960
961             /* debug info might have a different base address than .so file
962              * when elf file is prelinked after splitting off debug info
963              * adjust symbol base addresses accordingly
964              */
965             unsigned long load_offset = module->elf_info->elf_addr +
966                           fmap->elf_start - debug_sect.fmap->elf_start;
967
968             TRACE("Loading Dwarf2 information for %s\n", debugstr_w(module->module.ModuleName));
969
970             elf_find_section(fmap, ".debug_str", SHT_NULL, &debug_str_sect);
971             elf_find_section(fmap, ".debug_abbrev", SHT_NULL, &debug_abbrev_sect);
972             elf_find_section(fmap, ".debug_line", SHT_NULL, &debug_line_sect);
973             elf_find_section(fmap, ".debug_loc", SHT_NULL, &debug_loclist_sect);
974
975             dw2_debug = (const BYTE*)elf_map_section(&debug_sect);
976             dw2_debug_abbrev = (const BYTE*)elf_map_section(&debug_abbrev_sect);
977             dw2_debug_str = (const BYTE*)elf_map_section(&debug_str_sect);
978             dw2_debug_line = (const BYTE*)elf_map_section(&debug_line_sect);
979             dw2_debug_loclist = (const BYTE*)elf_map_section(&debug_loclist_sect);
980             if (dw2_debug != ELF_NO_MAP && dw2_debug_abbrev != ELF_NO_MAP && dw2_debug_str != ELF_NO_MAP)
981             {
982                 /* OK, now just parse dwarf2 debug infos. */
983                 lret = dwarf2_parse(module, load_offset, thunks,
984                                     dw2_debug, elf_get_map_size(&debug_sect),
985                                     dw2_debug_abbrev, elf_get_map_size(&debug_abbrev_sect),
986                                     dw2_debug_str, elf_get_map_size(&debug_str_sect),
987                                     dw2_debug_line, elf_get_map_size(&debug_line_sect),
988                                     dw2_debug_loclist, elf_get_map_size(&debug_loclist_sect));
989
990                 if (!lret)
991                     WARN("Couldn't correctly read dwarf2\n");
992                 ret = ret || lret;
993             }
994             elf_unmap_section(&debug_sect);
995             elf_unmap_section(&debug_abbrev_sect);
996             elf_unmap_section(&debug_str_sect);
997             elf_unmap_section(&debug_line_sect);
998             elf_unmap_section(&debug_loclist_sect);
999         }
1000     }
1001     if (strstrW(module->module.ModuleName, S_ElfW) ||
1002         !strcmpW(module->module.ModuleName, S_WineLoaderW))
1003     {
1004         /* add the thunks for native libraries */
1005         if (!(dbghelp_options & SYMOPT_PUBLICS_ONLY))
1006             elf_new_wine_thunks(module, ht_symtab, thunks);
1007     }
1008     /* add all the public symbols from symtab */
1009     if (elf_new_public_symbols(module, ht_symtab) && !ret) ret = TRUE;
1010
1011     return ret;
1012 }
1013
1014 /******************************************************************
1015  *              elf_load_debug_info
1016  *
1017  * Loads ELF debugging information from the module image file.
1018  */
1019 BOOL elf_load_debug_info(struct module* module, struct elf_file_map* fmap)
1020 {
1021     BOOL                ret = TRUE;
1022     struct pool         pool;
1023     struct hash_table   ht_symtab;
1024     struct elf_file_map my_fmap;
1025
1026     if (module->type != DMT_ELF || !module->elf_info)
1027     {
1028         ERR("Bad elf module '%s'\n", debugstr_w(module->module.LoadedImageName));
1029         return FALSE;
1030     }
1031
1032     pool_init(&pool, 65536);
1033     hash_table_init(&pool, &ht_symtab, 256);
1034
1035     if (!fmap)
1036     {
1037         fmap = &my_fmap;
1038         ret = elf_map_file(module->module.LoadedImageName, fmap);
1039     }
1040     if (ret)
1041         ret = elf_load_debug_info_from_map(module, fmap, &pool, &ht_symtab);
1042
1043     pool_destroy(&pool);
1044     if (fmap == &my_fmap) elf_unmap_file(fmap);
1045     return ret;
1046 }
1047
1048 /******************************************************************
1049  *              elf_fetch_file_info
1050  *
1051  * Gathers some more information for an ELF module from a given file
1052  */
1053 BOOL elf_fetch_file_info(const WCHAR* name, DWORD* base,
1054                          DWORD* size, DWORD* checksum)
1055 {
1056     struct elf_file_map fmap;
1057
1058     if (!elf_map_file(name, &fmap)) return FALSE;
1059     if (base) *base = fmap.elf_start;
1060     *size = fmap.elf_size;
1061     *checksum = calc_crc32(fmap.fd);
1062     elf_unmap_file(&fmap);
1063     return TRUE;
1064 }
1065
1066 /******************************************************************
1067  *              elf_load_file
1068  *
1069  * Loads the information for ELF module stored in 'filename'
1070  * the module has been loaded at 'load_offset' address
1071  * returns
1072  *      -1 if the file cannot be found/opened
1073  *      0 if the file doesn't contain symbolic info (or this info cannot be
1074  *      read or parsed)
1075  *      1 on success
1076  */
1077 static BOOL elf_load_file(struct process* pcs, const WCHAR* filename,
1078                           unsigned long load_offset, struct elf_info* elf_info)
1079 {
1080     BOOL                ret = FALSE;
1081     struct elf_file_map fmap;
1082
1083     TRACE("Processing elf file '%s' at %08lx\n", debugstr_w(filename), load_offset);
1084
1085     if (!elf_map_file(filename, &fmap)) return ret;
1086
1087     /* Next, we need to find a few of the internal ELF headers within
1088      * this thing.  We need the main executable header, and the section
1089      * table.
1090      */
1091     if (!fmap.elf_start && !load_offset)
1092         ERR("Relocatable ELF %s, but no load address. Loading at 0x0000000\n",
1093             debugstr_w(filename));
1094     if (fmap.elf_start && load_offset)
1095     {
1096         WARN("Non-relocatable ELF %s, but load address of 0x%08lx supplied. "
1097              "Assuming load address is corrupt\n", debugstr_w(filename), load_offset);
1098         load_offset = 0;
1099     }
1100
1101     if (elf_info->flags & ELF_INFO_DEBUG_HEADER)
1102     {
1103         struct elf_section_map  esm;
1104
1105         if (elf_find_section(&fmap, ".dynamic", SHT_DYNAMIC, &esm))
1106         {
1107             Elf_Dyn         dyn;
1108             char*           ptr = (char*)fmap.sect[esm.sidx].shdr.sh_addr;
1109             unsigned long   len;
1110
1111             do
1112             {
1113                 if (!ReadProcessMemory(pcs->handle, ptr, &dyn, sizeof(dyn), &len) ||
1114                     len != sizeof(dyn))
1115                     goto leave;
1116                 if (dyn.d_tag == DT_DEBUG)
1117                 {
1118                     elf_info->dbg_hdr_addr = dyn.d_un.d_ptr;
1119                     break;
1120                 }
1121                 ptr += sizeof(dyn);
1122             } while (dyn.d_tag != DT_NULL);
1123             if (dyn.d_tag == DT_NULL) goto leave;
1124         }
1125         elf_end_find(&fmap);
1126     }
1127
1128     if (elf_info->flags & ELF_INFO_MODULE)
1129     {
1130         struct elf_module_info *elf_module_info =
1131             HeapAlloc(GetProcessHeap(), 0, sizeof(struct elf_module_info));
1132         if (!elf_module_info) goto leave;
1133         elf_info->module = module_new(pcs, filename, DMT_ELF, FALSE,
1134                                       (load_offset) ? load_offset : fmap.elf_start,
1135                                       fmap.elf_size, 0, calc_crc32(fmap.fd));
1136         if (!elf_info->module)
1137         {
1138             HeapFree(GetProcessHeap(), 0, elf_module_info);
1139             goto leave;
1140         }
1141         elf_info->module->elf_info = elf_module_info;
1142         elf_info->module->elf_info->elf_addr = load_offset;
1143
1144         if (dbghelp_options & SYMOPT_DEFERRED_LOADS)
1145         {
1146             elf_info->module->module.SymType = SymDeferred;
1147             ret = TRUE;
1148         }
1149         else ret = elf_load_debug_info(elf_info->module, &fmap);
1150
1151         elf_info->module->elf_info->elf_mark = 1;
1152         elf_info->module->elf_info->elf_loader = 0;
1153     } else ret = TRUE;
1154
1155     if (elf_info->flags & ELF_INFO_NAME)
1156     {
1157         WCHAR*  ptr;
1158         ptr = HeapAlloc(GetProcessHeap(), 0, (lstrlenW(filename) + 1) * sizeof(WCHAR));
1159         if (ptr)
1160         {
1161             strcpyW(ptr, filename);
1162             elf_info->module_name = ptr;
1163         }
1164         else ret = FALSE;
1165     }
1166 leave:
1167     elf_unmap_file(&fmap);
1168
1169     return ret;
1170 }
1171
1172 /******************************************************************
1173  *              elf_load_file_from_path
1174  * tries to load an ELF file from a set of paths (separated by ':')
1175  */
1176 static BOOL elf_load_file_from_path(HANDLE hProcess,
1177                                     const WCHAR* filename,
1178                                     unsigned long load_offset,
1179                                     const char* path,
1180                                     struct elf_info* elf_info)
1181 {
1182     BOOL                ret = FALSE;
1183     WCHAR               *s, *t, *fn;
1184     WCHAR*              pathW = NULL;
1185     unsigned            len;
1186
1187     if (!path) return FALSE;
1188
1189     len = MultiByteToWideChar(CP_UNIXCP, 0, path, -1, NULL, 0);
1190     pathW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1191     if (!pathW) return FALSE;
1192     MultiByteToWideChar(CP_UNIXCP, 0, path, -1, pathW, len);
1193
1194     for (s = pathW; s && *s; s = (t) ? (t+1) : NULL)
1195     {
1196         t = strchrW(s, ':');
1197         if (t) *t = '\0';
1198         fn = HeapAlloc(GetProcessHeap(), 0, (lstrlenW(filename) + 1 + lstrlenW(s) + 1) * sizeof(WCHAR));
1199         if (!fn) break;
1200         strcpyW(fn, s);
1201         strcatW(fn, S_SlashW);
1202         strcatW(fn, filename);
1203         ret = elf_load_file(hProcess, fn, load_offset, elf_info);
1204         HeapFree(GetProcessHeap(), 0, fn);
1205         if (ret) break;
1206         s = (t) ? (t+1) : NULL;
1207     }
1208
1209     HeapFree(GetProcessHeap(), 0, pathW);
1210     return ret;
1211 }
1212
1213 /******************************************************************
1214  *              elf_load_file_from_dll_path
1215  *
1216  * Tries to load an ELF file from the dll path
1217  */
1218 static BOOL elf_load_file_from_dll_path(HANDLE hProcess,
1219                                         const WCHAR* filename,
1220                                         unsigned long load_offset,
1221                                         struct elf_info* elf_info)
1222 {
1223     BOOL ret = FALSE;
1224     unsigned int index = 0;
1225     const char *path;
1226
1227     while (!ret && (path = wine_dll_enum_load_path( index++ )))
1228     {
1229         WCHAR *name;
1230         unsigned len;
1231
1232         len = MultiByteToWideChar(CP_UNIXCP, 0, path, -1, NULL, 0);
1233
1234         name = HeapAlloc( GetProcessHeap(), 0,
1235                           (len + lstrlenW(filename) + 2) * sizeof(WCHAR) );
1236
1237         if (!name) break;
1238         MultiByteToWideChar(CP_UNIXCP, 0, path, -1, name, len);
1239         strcatW( name, S_SlashW );
1240         strcatW( name, filename );
1241         ret = elf_load_file(hProcess, name, load_offset, elf_info);
1242         HeapFree( GetProcessHeap(), 0, name );
1243     }
1244     return ret;
1245 }
1246
1247 /******************************************************************
1248  *              elf_search_and_load_file
1249  *
1250  * lookup a file in standard ELF locations, and if found, load it
1251  */
1252 static BOOL elf_search_and_load_file(struct process* pcs, const WCHAR* filename,
1253                                      unsigned long load_offset,
1254                                      struct elf_info* elf_info)
1255 {
1256     BOOL                ret = FALSE;
1257     struct module*      module;
1258     static WCHAR        S_libstdcPPW[] = {'l','i','b','s','t','d','c','+','+','\0'};
1259
1260     if (filename == NULL || *filename == '\0') return FALSE;
1261     if ((module = module_is_already_loaded(pcs, filename)))
1262     {
1263         elf_info->module = module;
1264         module->elf_info->elf_mark = 1;
1265         return module->module.SymType;
1266     }
1267
1268     if (strstrW(filename, S_libstdcPPW)) return FALSE; /* We know we can't do it */
1269     ret = elf_load_file(pcs, filename, load_offset, elf_info);
1270     /* if relative pathname, try some absolute base dirs */
1271     if (!ret && !strchrW(filename, '/'))
1272     {
1273         ret = elf_load_file_from_path(pcs, filename, load_offset,
1274                                       getenv("PATH"), elf_info) ||
1275             elf_load_file_from_path(pcs, filename, load_offset,
1276                                     getenv("LD_LIBRARY_PATH"), elf_info);
1277         if (!ret) ret = elf_load_file_from_dll_path(pcs, filename, load_offset, elf_info);
1278     }
1279     
1280     return ret;
1281 }
1282
1283 /******************************************************************
1284  *              elf_enum_modules_internal
1285  *
1286  * Enumerate ELF modules from a running process
1287  */
1288 static BOOL elf_enum_modules_internal(const struct process* pcs,
1289                                       const WCHAR* main_name,
1290                                       enum_modules_cb cb, void* user)
1291 {
1292     struct r_debug      dbg_hdr;
1293     void*               lm_addr;
1294     struct link_map     lm;
1295     char                bufstr[256];
1296     WCHAR               bufstrW[MAX_PATH];
1297
1298     if (!pcs->dbg_hdr_addr ||
1299         !ReadProcessMemory(pcs->handle, (void*)pcs->dbg_hdr_addr,
1300                            &dbg_hdr, sizeof(dbg_hdr), NULL))
1301         return FALSE;
1302
1303     /* Now walk the linked list.  In all known ELF implementations,
1304      * the dynamic loader maintains this linked list for us.  In some
1305      * cases the first entry doesn't appear with a name, in other cases it
1306      * does.
1307      */
1308     for (lm_addr = (void*)dbg_hdr.r_map; lm_addr; lm_addr = (void*)lm.l_next)
1309     {
1310         if (!ReadProcessMemory(pcs->handle, lm_addr, &lm, sizeof(lm), NULL))
1311             return FALSE;
1312
1313         if (lm.l_prev != NULL && /* skip first entry, normally debuggee itself */
1314             lm.l_name != NULL &&
1315             ReadProcessMemory(pcs->handle, lm.l_name, bufstr, sizeof(bufstr), NULL))
1316         {
1317             bufstr[sizeof(bufstr) - 1] = '\0';
1318             MultiByteToWideChar(CP_UNIXCP, 0, bufstr, -1, bufstrW, sizeof(bufstrW) / sizeof(WCHAR));
1319             if (main_name && !bufstrW[0]) strcpyW(bufstrW, main_name);
1320             if (!cb(bufstrW, (unsigned long)lm.l_addr, user)) break;
1321         }
1322     }
1323     return TRUE;
1324 }
1325
1326 struct elf_sync
1327 {
1328     struct process*     pcs;
1329     struct elf_info     elf_info;
1330 };
1331
1332 static BOOL elf_enum_sync_cb(const WCHAR* name, unsigned long addr, void* user)
1333 {
1334     struct elf_sync*    es = user;
1335
1336     elf_search_and_load_file(es->pcs, name, addr, &es->elf_info);
1337     return TRUE;
1338 }
1339
1340 /******************************************************************
1341  *              elf_synchronize_module_list
1342  *
1343  * this functions rescans the debuggee module's list and synchronizes it with
1344  * the one from 'pcs', ie:
1345  * - if a module is in debuggee and not in pcs, it's loaded into pcs
1346  * - if a module is in pcs and not in debuggee, it's unloaded from pcs
1347  */
1348 BOOL    elf_synchronize_module_list(struct process* pcs)
1349 {
1350     struct module*      module;
1351     struct elf_sync     es;
1352
1353     for (module = pcs->lmodules; module; module = module->next)
1354     {
1355         if (module->type == DMT_ELF && !module->is_virtual)
1356             module->elf_info->elf_mark = 0;
1357     }
1358
1359     es.pcs = pcs;
1360     es.elf_info.flags = ELF_INFO_MODULE;
1361     if (!elf_enum_modules_internal(pcs, NULL, elf_enum_sync_cb, &es))
1362         return FALSE;
1363
1364     module = pcs->lmodules;
1365     while (module)
1366     {
1367         if (module->type == DMT_ELF && !module->is_virtual &&
1368             !module->elf_info->elf_mark && !module->elf_info->elf_loader)
1369         {
1370             module_remove(pcs, module);
1371             /* restart all over */
1372             module = pcs->lmodules;
1373         }
1374         else module = module->next;
1375     }
1376     return TRUE;
1377 }
1378
1379 /******************************************************************
1380  *              elf_search_loader
1381  *
1382  * Lookup in a running ELF process the loader, and sets its ELF link
1383  * address (for accessing the list of loaded .so libs) in pcs.
1384  * If flags is ELF_INFO_MODULE, the module for the loader is also
1385  * added as a module into pcs.
1386  */
1387 static BOOL elf_search_loader(struct process* pcs, struct elf_info* elf_info)
1388 {
1389     BOOL                ret;
1390     const char*         ptr;
1391
1392     /* All binaries are loaded with WINELOADER (if run from tree) or by the
1393      * main executable
1394      */
1395     if ((ptr = getenv("WINELOADER")))
1396     {
1397         WCHAR   tmp[MAX_PATH];
1398         MultiByteToWideChar(CP_ACP, 0, ptr, -1, tmp, sizeof(tmp) / sizeof(WCHAR));
1399         ret = elf_search_and_load_file(pcs, tmp, 0, elf_info);
1400     }
1401     else
1402     {
1403         ret = elf_search_and_load_file(pcs, S_WineW, 0, elf_info);
1404     }
1405     return ret;
1406 }
1407
1408 /******************************************************************
1409  *              elf_read_wine_loader_dbg_info
1410  *
1411  * Try to find a decent wine executable which could have loaded the debuggee
1412  */
1413 BOOL elf_read_wine_loader_dbg_info(struct process* pcs)
1414 {
1415     struct elf_info     elf_info;
1416
1417     elf_info.flags = ELF_INFO_DEBUG_HEADER | ELF_INFO_MODULE;
1418     if (!elf_search_loader(pcs, &elf_info)) return FALSE;
1419     elf_info.module->elf_info->elf_loader = 1;
1420     module_set_module(elf_info.module, S_WineLoaderW);
1421     return (pcs->dbg_hdr_addr = elf_info.dbg_hdr_addr) != 0;
1422 }
1423
1424 /******************************************************************
1425  *              elf_enum_modules
1426  *
1427  * Enumerates the ELF loaded modules from a running target (hProc)
1428  * This function doesn't require that someone has called SymInitialize
1429  * on this very process.
1430  */
1431 BOOL elf_enum_modules(HANDLE hProc, enum_modules_cb cb, void* user)
1432 {
1433     struct process      pcs;
1434     struct elf_info     elf_info;
1435     BOOL                ret;
1436
1437     memset(&pcs, 0, sizeof(pcs));
1438     pcs.handle = hProc;
1439     elf_info.flags = ELF_INFO_DEBUG_HEADER | ELF_INFO_NAME;
1440     if (!elf_search_loader(&pcs, &elf_info)) return FALSE;
1441     pcs.dbg_hdr_addr = elf_info.dbg_hdr_addr;
1442     ret = elf_enum_modules_internal(&pcs, elf_info.module_name, cb, user);
1443     HeapFree(GetProcessHeap(), 0, (char*)elf_info.module_name);
1444     return ret;
1445 }
1446
1447 struct elf_load
1448 {
1449     struct process*     pcs;
1450     struct elf_info     elf_info;
1451     const WCHAR*        name;
1452     BOOL                ret;
1453 };
1454
1455 /******************************************************************
1456  *              elf_load_cb
1457  *
1458  * Callback for elf_load_module, used to walk the list of loaded
1459  * modules.
1460  */
1461 static BOOL elf_load_cb(const WCHAR* name, unsigned long addr, void* user)
1462 {
1463     struct elf_load*    el = user;
1464     const WCHAR*        p;
1465
1466     /* memcmp is needed for matches when bufstr contains also version information
1467      * el->name: libc.so, name: libc.so.6.0
1468      */
1469     p = strrchrW(name, '/');
1470     if (!p++) p = name;
1471     if (!memcmp(p, el->name, lstrlenW(el->name) * sizeof(WCHAR)))
1472     {
1473         el->ret = elf_search_and_load_file(el->pcs, name, addr, &el->elf_info);
1474         return FALSE;
1475     }
1476     return TRUE;
1477 }
1478
1479 /******************************************************************
1480  *              elf_load_module
1481  *
1482  * loads an ELF module and stores it in process' module list
1483  * Also, find module real name and load address from
1484  * the real loaded modules list in pcs address space
1485  */
1486 struct module*  elf_load_module(struct process* pcs, const WCHAR* name, unsigned long addr)
1487 {
1488     struct elf_load     el;
1489
1490     TRACE("(%p %s %08lx)\n", pcs, debugstr_w(name), addr);
1491
1492     el.elf_info.flags = ELF_INFO_MODULE;
1493     el.ret = FALSE;
1494
1495     if (pcs->dbg_hdr_addr) /* we're debugging a life target */
1496     {
1497         el.pcs = pcs;
1498         /* do only the lookup from the filename, not the path (as we lookup module
1499          * name in the process' loaded module list)
1500          */
1501         el.name = strrchrW(name, '/');
1502         if (!el.name++) el.name = name;
1503         el.ret = FALSE;
1504
1505         if (!elf_enum_modules_internal(pcs, NULL, elf_load_cb, &el))
1506             return NULL;
1507     }
1508     else if (addr)
1509     {
1510         el.name = name;
1511         el.ret = elf_search_and_load_file(pcs, el.name, addr, &el.elf_info);
1512     }
1513     if (!el.ret) return NULL;
1514     assert(el.elf_info.module);
1515     return el.elf_info.module;
1516 }
1517
1518 #else   /* !__ELF__ */
1519
1520 BOOL    elf_synchronize_module_list(struct process* pcs)
1521 {
1522     return FALSE;
1523 }
1524
1525 BOOL elf_fetch_file_info(const WCHAR* name, DWORD* base,
1526                          DWORD* size, DWORD* checksum)
1527 {
1528     return FALSE;
1529 }
1530
1531 BOOL elf_read_wine_loader_dbg_info(struct process* pcs)
1532 {
1533     return FALSE;
1534 }
1535
1536 BOOL elf_enum_modules(HANDLE hProc, enum_modules_cb cb, void* user)
1537 {
1538     return FALSE;
1539 }
1540
1541 struct module*  elf_load_module(struct process* pcs, const WCHAR* name, unsigned long addr)
1542 {
1543     return NULL;
1544 }
1545
1546 BOOL elf_load_debug_info(struct module* module, struct elf_file_map* fmap)
1547 {
1548     return FALSE;
1549 }
1550
1551 int elf_is_in_thunk_area(unsigned long addr,
1552                          const struct elf_thunk_area* thunks)
1553 {
1554     return -1;
1555 }
1556 #endif  /* __ELF__ */