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