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