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