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