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