dbghelp: Recognize DT_GNU_HASH.
[wine] / dlls / dbghelp / symbol.c
1 /*
2  * File symbol.c - management of symbols (lexical tree)
3  *
4  * Copyright (C) 1993, Eric Youngdale.
5  *               2004, 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 #define NONAMELESSUNION
23 #define NONAMELESSSTRUCT
24
25 #include "config.h"
26
27 #include <stdlib.h>
28 #include <stdio.h>
29 #include <string.h>
30 #include <limits.h>
31 #include <sys/types.h>
32 #include <assert.h>
33 #ifdef HAVE_REGEX_H
34 # include <regex.h>
35 #endif
36
37 #include "wine/debug.h"
38 #include "dbghelp_private.h"
39 #include "winnls.h"
40
41 WINE_DEFAULT_DEBUG_CHANNEL(dbghelp);
42 WINE_DECLARE_DEBUG_CHANNEL(dbghelp_symt);
43
44 inline static int cmp_addr(ULONG64 a1, ULONG64 a2)
45 {
46     if (a1 > a2) return 1;
47     if (a1 < a2) return -1;
48     return 0;
49 }
50
51 inline static int cmp_sorttab_addr(const struct module* module, int idx, ULONG64 addr)
52 {
53     ULONG64     ref;
54
55     symt_get_info(&module->addr_sorttab[idx]->symt, TI_GET_ADDRESS, &ref);
56     return cmp_addr(ref, addr);
57 }
58
59 int symt_cmp_addr(const void* p1, const void* p2)
60 {
61     const struct symt*  sym1 = *(const struct symt* const *)p1;
62     const struct symt*  sym2 = *(const struct symt* const *)p2;
63     ULONG64     a1, a2;
64
65     symt_get_info(sym1, TI_GET_ADDRESS, &a1);
66     symt_get_info(sym2, TI_GET_ADDRESS, &a2);
67     return cmp_addr(a1, a2);
68 }
69
70 static inline void re_append(char** mask, unsigned* len, char ch)
71 {
72     *mask = HeapReAlloc(GetProcessHeap(), 0, *mask, ++(*len));
73     (*mask)[*len - 2] = ch;
74 }
75
76 /* transforms a dbghelp's regular expression into a POSIX one
77  * Here are the valid dbghelp reg ex characters:
78  *      *       0 or more characters
79  *      ?       a single character
80  *      []      list
81  *      #       0 or more of preceding char
82  *      +       1 or more of preceding char
83  *      escapes \ on #, ?, [, ], *, +. don't work on -
84  */
85 static void compile_regex(const char* str, int numchar, regex_t* re, BOOL _case)
86 {
87     char*       mask = HeapAlloc(GetProcessHeap(), 0, 1);
88     unsigned    len = 1;
89     BOOL        in_escape = FALSE;
90     unsigned    flags = REG_NOSUB;
91
92     re_append(&mask, &len, '^');
93
94     while (*str && numchar--)
95     {
96         /* FIXME: this shouldn't be valid on '-' */
97         if (in_escape)
98         {
99             re_append(&mask, &len, '\\');
100             re_append(&mask, &len, *str);
101             in_escape = FALSE;
102         }
103         else switch (*str)
104         {
105         case '\\': in_escape = TRUE; break;
106         case '*':  re_append(&mask, &len, '.'); re_append(&mask, &len, '*'); break;
107         case '?':  re_append(&mask, &len, '.'); break;
108         case '#':  re_append(&mask, &len, '*'); break;
109         /* escape some valid characters in dbghelp reg exp:s */
110         case '$':  re_append(&mask, &len, '\\'); re_append(&mask, &len, '$'); break;
111         /* +, [, ], - are the same in dbghelp & POSIX, use them as any other char */
112         default:   re_append(&mask, &len, *str); break;
113         }
114         str++;
115     }
116     if (in_escape)
117     {
118         re_append(&mask, &len, '\\');
119         re_append(&mask, &len, '\\');
120     }
121     re_append(&mask, &len, '$');
122     mask[len - 1] = '\0';
123     if (_case) flags |= REG_ICASE;
124     if (regcomp(re, mask, flags)) FIXME("Couldn't compile %s\n", mask);
125     HeapFree(GetProcessHeap(), 0, mask);
126 }
127
128 struct symt_compiland* symt_new_compiland(struct module* module, 
129                                           unsigned long address, unsigned src_idx)
130 {
131     struct symt_compiland*    sym;
132
133     TRACE_(dbghelp_symt)("Adding compiland symbol %s:%s\n", 
134                          module->module.ModuleName, source_get(module, src_idx));
135     if ((sym = pool_alloc(&module->pool, sizeof(*sym))))
136     {
137         sym->symt.tag = SymTagCompiland;
138         sym->address  = address;
139         sym->source   = src_idx;
140         vector_init(&sym->vchildren, sizeof(struct symt*), 32);
141     }
142     return sym;
143 }
144
145 struct symt_public* symt_new_public(struct module* module, 
146                                     struct symt_compiland* compiland,
147                                     const char* name,
148                                     unsigned long address, unsigned size,
149                                     BOOL in_code, BOOL is_func)
150 {
151     struct symt_public* sym;
152     struct symt**       p;
153
154     TRACE_(dbghelp_symt)("Adding public symbol %s:%s @%lx\n", 
155                          module->module.ModuleName, name, address);
156     if ((dbghelp_options & SYMOPT_AUTO_PUBLICS) && 
157         symt_find_nearest(module, address) != -1)
158         return NULL;
159     if ((sym = pool_alloc(&module->pool, sizeof(*sym))))
160     {
161         sym->symt.tag      = SymTagPublicSymbol;
162         sym->hash_elt.name = pool_strdup(&module->pool, name);
163         hash_table_add(&module->ht_symbols, &sym->hash_elt);
164         module->sortlist_valid = FALSE;
165         sym->container     = compiland ? &compiland->symt : NULL;
166         sym->address       = address;
167         sym->size          = size;
168         sym->in_code       = in_code;
169         sym->is_function   = is_func;
170         if (compiland)
171         {
172             p = vector_add(&compiland->vchildren, &module->pool);
173             *p = &sym->symt;
174         }
175     }
176     return sym;
177 }
178
179 struct symt_data* symt_new_global_variable(struct module* module, 
180                                            struct symt_compiland* compiland, 
181                                            const char* name, unsigned is_static,
182                                            unsigned long addr, unsigned long size,
183                                            struct symt* type)
184 {
185     struct symt_data*   sym;
186     struct symt**       p;
187     DWORD64             tsz;
188
189     TRACE_(dbghelp_symt)("Adding global symbol %s:%s @%lx %p\n", 
190                          module->module.ModuleName, name, addr, type);
191     if ((sym = pool_alloc(&module->pool, sizeof(*sym))))
192     {
193         sym->symt.tag      = SymTagData;
194         sym->hash_elt.name = pool_strdup(&module->pool, name);
195         hash_table_add(&module->ht_symbols, &sym->hash_elt);
196         module->sortlist_valid = FALSE;
197         sym->kind          = is_static ? DataIsFileStatic : DataIsGlobal;
198         sym->container     = compiland ? &compiland->symt : NULL;
199         sym->type          = type;
200         sym->u.var.offset  = addr;
201         if (type && size && symt_get_info(type, TI_GET_LENGTH, &tsz))
202         {
203             if (tsz != size)
204                 FIXME("Size mismatch for %s.%s between type (%s) and src (%lu)\n",
205                       module->module.ModuleName, name, 
206                       wine_dbgstr_longlong(tsz), size);
207         }
208         if (compiland)
209         {
210             p = vector_add(&compiland->vchildren, &module->pool);
211             *p = &sym->symt;
212         }
213     }
214     return sym;
215 }
216
217 struct symt_function* symt_new_function(struct module* module, 
218                                         struct symt_compiland* compiland, 
219                                         const char* name,
220                                         unsigned long addr, unsigned long size,
221                                         struct symt* sig_type)
222 {
223     struct symt_function*       sym;
224     struct symt**               p;
225
226     TRACE_(dbghelp_symt)("Adding global function %s:%s @%lx-%lx\n", 
227                          module->module.ModuleName, name, addr, addr + size - 1);
228
229     assert(!sig_type || sig_type->tag == SymTagFunctionType);
230     if ((sym = pool_alloc(&module->pool, sizeof(*sym))))
231     {
232         sym->symt.tag  = SymTagFunction;
233         sym->hash_elt.name = pool_strdup(&module->pool, name);
234         hash_table_add(&module->ht_symbols, &sym->hash_elt);
235         module->sortlist_valid = FALSE;
236         sym->container = &compiland->symt;
237         sym->address   = addr;
238         sym->type      = sig_type;
239         sym->size      = size;
240         vector_init(&sym->vlines,  sizeof(struct line_info), 64);
241         vector_init(&sym->vchildren, sizeof(struct symt*), 8);
242         if (compiland)
243         {
244             p = vector_add(&compiland->vchildren, &module->pool);
245             *p = &sym->symt;
246         }
247     }
248     return sym;
249 }
250
251 void symt_add_func_line(struct module* module, struct symt_function* func,
252                         unsigned source_idx, int line_num, unsigned long offset)
253 {
254     struct line_info*   dli;
255     BOOL                last_matches = FALSE;
256
257     if (func == NULL || !(dbghelp_options & SYMOPT_LOAD_LINES)) return;
258
259     TRACE_(dbghelp_symt)("(%p)%s:%lx %s:%u\n", 
260                          func, func->hash_elt.name, offset, 
261                          source_get(module, source_idx), line_num);
262
263     assert(func->symt.tag == SymTagFunction);
264
265     dli = NULL;
266     while ((dli = vector_iter_down(&func->vlines, dli)))
267     {
268         if (dli->is_source_file)
269         {
270             last_matches = (source_idx == dli->u.source_file);
271             break;
272         }
273     }
274
275     if (!last_matches)
276     {
277         /* we shouldn't have line changes on first line of function */
278         dli = vector_add(&func->vlines, &module->pool);
279         dli->is_source_file = 1;
280         dli->is_first       = dli->is_last = 0;
281         dli->line_number    = 0;
282         dli->u.source_file  = source_idx;
283     }
284     dli = vector_add(&func->vlines, &module->pool);
285     dli->is_source_file = 0;
286     dli->is_first       = dli->is_last = 0;
287     dli->line_number    = line_num;
288     dli->u.pc_offset    = func->address + offset;
289 }
290
291 /******************************************************************
292  *             symt_add_func_local
293  *
294  * Adds a new local/parameter to a given function:
295  * In any cases, dt tells whether it's a local variable or a parameter
296  * If regno it's not 0:
297  *      - then variable is stored in a register
298  *      - otherwise, value is referenced by register + offset
299  * Otherwise, the variable is stored on the stack:
300  *      - offset is then the offset from the frame register
301  */
302 struct symt_data* symt_add_func_local(struct module* module, 
303                                       struct symt_function* func, 
304                                       enum DataKind dt,
305                                       const struct location* loc,
306                                       struct symt_block* block, 
307                                       struct symt* type, const char* name)
308 {
309     struct symt_data*   locsym;
310     struct symt**       p;
311
312     TRACE_(dbghelp_symt)("Adding local symbol (%s:%s): %s %p\n", 
313                          module->module.ModuleName, func->hash_elt.name, 
314                          name, type);
315
316     assert(func);
317     assert(func->symt.tag == SymTagFunction);
318     assert(dt == DataIsParam || dt == DataIsLocal);
319
320     locsym = pool_alloc(&module->pool, sizeof(*locsym));
321     locsym->symt.tag      = SymTagData;
322     locsym->hash_elt.name = pool_strdup(&module->pool, name);
323     locsym->hash_elt.next = NULL;
324     locsym->kind          = dt;
325     locsym->container     = &block->symt;
326     locsym->type          = type;
327     locsym->u.var         = *loc;
328     if (block)
329         p = vector_add(&block->vchildren, &module->pool);
330     else
331         p = vector_add(&func->vchildren, &module->pool);
332     *p = &locsym->symt;
333     return locsym;
334 }
335
336
337 struct symt_block* symt_open_func_block(struct module* module, 
338                                         struct symt_function* func,
339                                         struct symt_block* parent_block, 
340                                         unsigned pc, unsigned len)
341 {
342     struct symt_block*  block;
343     struct symt**       p;
344
345     assert(func);
346     assert(func->symt.tag == SymTagFunction);
347
348     assert(!parent_block || parent_block->symt.tag == SymTagBlock);
349     block = pool_alloc(&module->pool, sizeof(*block));
350     block->symt.tag = SymTagBlock;
351     block->address  = func->address + pc;
352     block->size     = len;
353     block->container = parent_block ? &parent_block->symt : &func->symt;
354     vector_init(&block->vchildren, sizeof(struct symt*), 4);
355     if (parent_block)
356         p = vector_add(&parent_block->vchildren, &module->pool);
357     else
358         p = vector_add(&func->vchildren, &module->pool);
359     *p = &block->symt;
360
361     return block;
362 }
363
364 struct symt_block* symt_close_func_block(struct module* module, 
365                                          struct symt_function* func,
366                                          struct symt_block* block, unsigned pc)
367 {
368     assert(func);
369     assert(func->symt.tag == SymTagFunction);
370
371     if (pc) block->size = func->address + pc - block->address;
372     return (block->container->tag == SymTagBlock) ? 
373         GET_ENTRY(block->container, struct symt_block, symt) : NULL;
374 }
375
376 struct symt_function_point* symt_add_function_point(struct module* module, 
377                                                     struct symt_function* func,
378                                                     enum SymTagEnum point, 
379                                                     const struct location* loc,
380                                                     const char* name)
381 {
382     struct symt_function_point* sym;
383     struct symt**               p;
384
385     if ((sym = pool_alloc(&module->pool, sizeof(*sym))))
386     {
387         sym->symt.tag = point;
388         sym->parent   = func;
389         sym->loc      = *loc;
390         sym->name     = name ? pool_strdup(&module->pool, name) : NULL;
391         p = vector_add(&func->vchildren, &module->pool);
392         *p = &sym->symt;
393     }
394     return sym;
395 }
396
397 BOOL symt_normalize_function(struct module* module, struct symt_function* func)
398 {
399     unsigned            len;
400     struct line_info*   dli;
401
402     assert(func);
403     /* We aren't adding any more locals or line numbers to this function.
404      * Free any spare memory that we might have allocated.
405      */
406     assert(func->symt.tag == SymTagFunction);
407
408 /* EPP     vector_pool_normalize(&func->vlines,    &module->pool); */
409 /* EPP     vector_pool_normalize(&func->vchildren, &module->pool); */
410
411     len = vector_length(&func->vlines);
412     if (len--)
413     {
414         dli = vector_at(&func->vlines,   0);  dli->is_first = 1;
415         dli = vector_at(&func->vlines, len);  dli->is_last  = 1;
416     }
417     return TRUE;
418 }
419
420 struct symt_thunk* symt_new_thunk(struct module* module, 
421                                   struct symt_compiland* compiland, 
422                                   const char* name, THUNK_ORDINAL ord,
423                                   unsigned long addr, unsigned long size)
424 {
425     struct symt_thunk*  sym;
426
427     TRACE_(dbghelp_symt)("Adding global thunk %s:%s @%lx-%lx\n", 
428                          module->module.ModuleName, name, addr, addr + size - 1);
429
430     if ((sym = pool_alloc(&module->pool, sizeof(*sym))))
431     {
432         sym->symt.tag  = SymTagThunk;
433         sym->hash_elt.name = pool_strdup(&module->pool, name);
434         hash_table_add(&module->ht_symbols, &sym->hash_elt);
435         module->sortlist_valid = FALSE;
436         sym->container = &compiland->symt;
437         sym->address   = addr;
438         sym->size      = size;
439         sym->ordinal   = ord;
440         if (compiland)
441         {
442             struct symt**       p;
443             p = vector_add(&compiland->vchildren, &module->pool);
444             *p = &sym->symt;
445         }
446     }
447     return sym;
448 }
449
450 /* expect sym_info->MaxNameLen to be set before being called */
451 static void symt_fill_sym_info(const struct module_pair* pair, 
452                                const struct symt_function* func,
453                                const struct symt* sym, SYMBOL_INFO* sym_info)
454 {
455     const char* name;
456     DWORD64 size;
457
458     if (!symt_get_info(sym, TI_GET_TYPE, &sym_info->TypeIndex))
459         sym_info->TypeIndex = 0;
460     sym_info->info = (DWORD)sym;
461     sym_info->Reserved[0] = sym_info->Reserved[1] = 0;
462     if (!symt_get_info(sym, TI_GET_LENGTH, &size) &&
463         (!sym_info->TypeIndex ||
464          !symt_get_info((struct symt*)sym_info->TypeIndex, TI_GET_LENGTH, &size)))
465         size = 0;
466     sym_info->Size = (DWORD)size;
467     sym_info->ModBase = pair->requested->module.BaseOfImage;
468     sym_info->Flags = 0;
469     sym_info->Value = 0;
470
471     switch (sym->tag)
472     {
473     case SymTagData:
474         {
475             const struct symt_data*  data = (const struct symt_data*)sym;
476             switch (data->kind)
477             {
478             case DataIsParam:
479                 sym_info->Flags |= SYMFLAG_PARAMETER;
480                 /* fall through */
481             case DataIsLocal:
482                 {
483                     struct location loc = data->u.var;
484
485                     if (loc.kind >= loc_user)
486                         pair->effective->loc_compute(pair->pcs, pair->effective, func, &loc);
487
488                     switch (loc.kind)
489                     {
490                     case loc_error:
491                         /* for now we report error cases as a negative register number */
492                         sym_info->Flags |= SYMFLAG_LOCAL;
493                         /* fall through */
494                     case loc_register:
495                         sym_info->Flags |= SYMFLAG_REGISTER;
496                         sym_info->Register = loc.reg;
497                         sym_info->Address = 0;
498                         break;
499                     case loc_regrel:
500                         sym_info->Flags |= SYMFLAG_LOCAL | SYMFLAG_REGREL;
501                         /* FIXME: it's i386 dependent !!! */
502                         sym_info->Register = loc.reg ? loc.reg : CV_REG_EBP;
503                         sym_info->Address = loc.offset;
504                         break;
505                     default:
506                         FIXME("Shouldn't happen (kind=%d), debug reader backend is broken\n", loc.kind);
507                         assert(0);
508                     }
509                 }
510                 break;
511             case DataIsGlobal:
512             case DataIsFileStatic:
513                 symt_get_info(sym, TI_GET_ADDRESS, &sym_info->Address);
514                 sym_info->Register = 0;
515                 break;
516             case DataIsConstant:
517                 sym_info->Flags |= SYMFLAG_VALUEPRESENT;
518                 switch (data->u.value.n1.n2.vt)
519                 {
520                 case VT_I4:  sym_info->Value = (ULONG)data->u.value.n1.n2.n3.lVal; break;
521                 case VT_I2:  sym_info->Value = (ULONG)(long)data->u.value.n1.n2.n3.iVal; break;
522                 case VT_I1:  sym_info->Value = (ULONG)(long)data->u.value.n1.n2.n3.cVal; break;
523                 case VT_UI4: sym_info->Value = (ULONG)data->u.value.n1.n2.n3.ulVal; break;
524                 case VT_UI2: sym_info->Value = (ULONG)data->u.value.n1.n2.n3.uiVal; break;
525                 case VT_UI1: sym_info->Value = (ULONG)data->u.value.n1.n2.n3.bVal; break;
526                 default:        
527                     FIXME("Unsupported variant type (%u)\n", data->u.value.n1.n2.vt);
528                 }
529                 break;
530             default:
531                 FIXME("Unhandled kind (%u) in sym data\n", data->kind);
532             }
533         }
534         break;
535     case SymTagPublicSymbol:
536         sym_info->Flags |= SYMFLAG_EXPORT;
537         symt_get_info(sym, TI_GET_ADDRESS, &sym_info->Address);
538         break;
539     case SymTagFunction:
540         sym_info->Flags |= SYMFLAG_FUNCTION;
541         symt_get_info(sym, TI_GET_ADDRESS, &sym_info->Address);
542         break;
543     case SymTagThunk:
544         sym_info->Flags |= SYMFLAG_THUNK;
545         symt_get_info(sym, TI_GET_ADDRESS, &sym_info->Address);
546         break;
547     default:
548         symt_get_info(sym, TI_GET_ADDRESS, &sym_info->Address);
549         sym_info->Register = 0;
550         break;
551     }
552     sym_info->Scope = 0; /* FIXME */
553     sym_info->Tag = sym->tag;
554     name = symt_get_name(sym);
555     if (sym_info->MaxNameLen)
556     {
557         if (sym->tag != SymTagPublicSymbol || !(dbghelp_options & SYMOPT_UNDNAME) ||
558             (sym_info->NameLen = UnDecorateSymbolName(name, sym_info->Name, 
559                                                       sym_info->MaxNameLen, UNDNAME_COMPLETE) == 0))
560         {
561             sym_info->NameLen = min(strlen(name), sym_info->MaxNameLen - 1);
562             memcpy(sym_info->Name, name, sym_info->NameLen);
563             sym_info->Name[sym_info->NameLen] = '\0';
564         }
565     }
566     TRACE_(dbghelp_symt)("%p => %s %u %s\n",
567                          sym, sym_info->Name, sym_info->Size,
568                          wine_dbgstr_longlong(sym_info->Address));
569 }
570
571 struct sym_enum
572 {
573     PSYM_ENUMERATESYMBOLS_CALLBACK      cb;
574     PVOID                               user;
575     SYMBOL_INFO*                        sym_info;
576     DWORD                               index;
577     DWORD                               tag;
578     DWORD64                             addr;
579     char                                buffer[sizeof(SYMBOL_INFO) + MAX_SYM_NAME];
580 };
581
582 static BOOL send_symbol(const struct sym_enum* se, struct module_pair* pair,
583                         const struct symt_function* func, const struct symt* sym)
584 {
585     symt_fill_sym_info(pair, func, sym, se->sym_info);
586     if (se->index && se->sym_info->info != se->index) return FALSE;
587     if (se->tag && se->sym_info->Tag != se->tag) return FALSE;
588     if (se->addr && !(se->addr >= se->sym_info->Address && se->addr < se->sym_info->Address + se->sym_info->Size)) return FALSE;
589     return !se->cb(se->sym_info, se->sym_info->Size, se->user);
590 }
591
592 static BOOL symt_enum_module(struct module_pair* pair, regex_t* regex,
593                              const struct sym_enum* se)
594 {
595     void*                       ptr;
596     struct symt_ht*             sym = NULL;
597     struct hash_table_iter      hti;
598
599     hash_table_iter_init(&pair->effective->ht_symbols, &hti, NULL);
600     while ((ptr = hash_table_iter_up(&hti)))
601     {
602         sym = GET_ENTRY(ptr, struct symt_ht, hash_elt);
603         if (sym->hash_elt.name &&
604             regexec(regex, sym->hash_elt.name, 0, NULL, 0) == 0)
605         {
606             se->sym_info->SizeOfStruct = sizeof(SYMBOL_INFO);
607             se->sym_info->MaxNameLen = sizeof(se->buffer) - sizeof(SYMBOL_INFO);
608             if (send_symbol(se, pair, NULL, &sym->symt)) return TRUE;
609         }
610     }   
611     return FALSE;
612 }
613
614 /***********************************************************************
615  *              resort_symbols
616  *
617  * Rebuild sorted list of symbols for a module.
618  */
619 static BOOL resort_symbols(struct module* module)
620 {
621     int                         nsym;
622     void*                       ptr;
623     struct symt_ht*             sym;
624     struct hash_table_iter      hti;
625
626     if (!module_compute_num_syms(module)) return FALSE;
627     
628     if (module->addr_sorttab)
629         module->addr_sorttab = HeapReAlloc(GetProcessHeap(), 0,
630                                            module->addr_sorttab, 
631                                            module->module.NumSyms * sizeof(struct symt_ht*));
632     else
633         module->addr_sorttab = HeapAlloc(GetProcessHeap(), 0,
634                                          module->module.NumSyms * sizeof(struct symt_ht*));
635     if (!module->addr_sorttab) return FALSE;
636
637     nsym = 0;
638     hash_table_iter_init(&module->ht_symbols, &hti, NULL);
639     while ((ptr = hash_table_iter_up(&hti)))
640     {
641         sym = GET_ENTRY(ptr, struct symt_ht, hash_elt);
642         assert(sym);
643         module->addr_sorttab[nsym++] = sym;
644     }
645     
646     qsort(module->addr_sorttab, nsym, sizeof(struct symt_ht*), symt_cmp_addr);
647     return module->sortlist_valid = TRUE;
648 }
649
650 /* assume addr is in module */
651 int symt_find_nearest(struct module* module, DWORD addr)
652 {
653     int         mid, high, low;
654     ULONG64     ref_addr, ref_size;
655
656     if (!module->sortlist_valid || !module->addr_sorttab)
657     {
658         if (!resort_symbols(module)) return -1;
659     }
660
661     /*
662      * Binary search to find closest symbol.
663      */
664     low = 0;
665     high = module->module.NumSyms;
666
667     symt_get_info(&module->addr_sorttab[0]->symt, TI_GET_ADDRESS, &ref_addr);
668     if (addr < ref_addr) return -1;
669     if (high)
670     {
671         symt_get_info(&module->addr_sorttab[high - 1]->symt, TI_GET_ADDRESS, &ref_addr);
672         if (!symt_get_info(&module->addr_sorttab[high - 1]->symt, TI_GET_LENGTH, &ref_size) || !ref_size)
673             ref_size = 0x1000; /* arbitrary value */
674         if (addr >= ref_addr + ref_size) return -1;
675     }
676     
677     while (high > low + 1)
678     {
679         mid = (high + low) / 2;
680         if (cmp_sorttab_addr(module, mid, addr) < 0)
681             low = mid;
682         else
683             high = mid;
684     }
685     if (low != high && high != module->module.NumSyms && 
686         cmp_sorttab_addr(module, high, addr) <= 0)
687         low = high;
688
689     /* If found symbol is a public symbol, check if there are any other entries that
690      * might also have the same address, but would get better information
691      */
692     if (module->addr_sorttab[low]->symt.tag == SymTagPublicSymbol)
693     {   
694         symt_get_info(&module->addr_sorttab[low]->symt, TI_GET_ADDRESS, &ref_addr);
695         if (low > 0 &&
696             module->addr_sorttab[low - 1]->symt.tag != SymTagPublicSymbol &&
697             !cmp_sorttab_addr(module, low - 1, ref_addr))
698             low--;
699         else if (low < module->module.NumSyms - 1 && 
700                  module->addr_sorttab[low + 1]->symt.tag != SymTagPublicSymbol &&
701                  !cmp_sorttab_addr(module, low + 1, ref_addr))
702             low++;
703     }
704     /* finally check that we fit into the found symbol */
705     symt_get_info(&module->addr_sorttab[low]->symt, TI_GET_ADDRESS, &ref_addr);
706     if (addr < ref_addr) return -1;
707     if (!symt_get_info(&module->addr_sorttab[high - 1]->symt, TI_GET_LENGTH, &ref_size) || !ref_size)
708         ref_size = 0x1000; /* arbitrary value */
709     if (addr >= ref_addr + ref_size) return -1;
710
711     return low;
712 }
713
714 static BOOL symt_enum_locals_helper(struct module_pair* pair,
715                                     regex_t* preg, const struct sym_enum* se,
716                                     struct symt_function* func, struct vector* v)
717 {
718     struct symt**       plsym = NULL;
719     struct symt*        lsym = NULL;
720     DWORD               pc = pair->pcs->ctx_frame.InstructionOffset;
721
722     while ((plsym = vector_iter_up(v, plsym)))
723     {
724         lsym = *plsym;
725         switch (lsym->tag)
726         {
727         case SymTagBlock:
728             {
729                 struct symt_block*  block = (struct symt_block*)lsym;
730                 if (pc < block->address || block->address + block->size <= pc)
731                     continue;
732                 if (!symt_enum_locals_helper(pair, preg, se, func, &block->vchildren))
733                     return FALSE;
734             }
735             break;
736         case SymTagData:
737             if (regexec(preg, symt_get_name(lsym), 0, NULL, 0) == 0)
738             {
739                 if (send_symbol(se, pair, func, lsym)) return FALSE;
740             }
741             break;
742         case SymTagLabel:
743         case SymTagFuncDebugStart:
744         case SymTagFuncDebugEnd:
745         case SymTagCustom:
746             break;
747         default:
748             FIXME("Unknown type: %u (%x)\n", lsym->tag, lsym->tag);
749             assert(0);
750         }
751     }
752     return TRUE;
753 }
754
755 static BOOL symt_enum_locals(struct process* pcs, const char* mask, 
756                              const struct sym_enum* se)
757 {
758     struct module_pair  pair;
759     struct symt_ht*     sym;
760     DWORD               pc = pcs->ctx_frame.InstructionOffset;
761     int                 idx;
762
763     se->sym_info->SizeOfStruct = sizeof(*se->sym_info);
764     se->sym_info->MaxNameLen = sizeof(se->buffer) - sizeof(SYMBOL_INFO);
765
766     pair.pcs = pcs;
767     pair.requested = module_find_by_addr(pair.pcs, pc, DMT_UNKNOWN);
768     if (!module_get_debug(&pair)) return FALSE;
769     if ((idx = symt_find_nearest(pair.effective, pc)) == -1) return FALSE;
770
771     sym = pair.effective->addr_sorttab[idx];
772     if (sym->symt.tag == SymTagFunction)
773     {
774         BOOL            ret;
775         regex_t         preg;
776
777         compile_regex(mask ? mask : "*", -1, &preg,
778                       dbghelp_options & SYMOPT_CASE_INSENSITIVE);
779         ret = symt_enum_locals_helper(&pair, &preg, se, (struct symt_function*)sym,
780                                       &((struct symt_function*)sym)->vchildren);
781         regfree(&preg);
782         return ret;
783         
784     }
785     return send_symbol(se, &pair, NULL, &sym->symt);
786 }
787
788 /******************************************************************
789  *              copy_symbolW
790  *
791  * Helper for transforming an ANSI symbol info into an UNICODE one.
792  * Assume that MaxNameLen is the same for both version (A & W).
793  */
794 static void copy_symbolW(SYMBOL_INFOW* siw, const SYMBOL_INFO* si)
795 {
796     siw->SizeOfStruct = si->SizeOfStruct;
797     siw->TypeIndex = si->TypeIndex; 
798     siw->Reserved[0] = si->Reserved[0];
799     siw->Reserved[1] = si->Reserved[1];
800     siw->Index = si->info; /* FIXME: see dbghelp.h */
801     siw->Size = si->Size;
802     siw->ModBase = si->ModBase;
803     siw->Flags = si->Flags;
804     siw->Value = si->Value;
805     siw->Address = si->Address;
806     siw->Register = si->Register;
807     siw->Scope = si->Scope;
808     siw->Tag = si->Tag;
809     siw->NameLen = si->NameLen;
810     siw->MaxNameLen = si->MaxNameLen;
811     MultiByteToWideChar(CP_ACP, 0, si->Name, -1, siw->Name, siw->MaxNameLen);
812 }
813
814 /******************************************************************
815  *              sym_enum
816  *
817  * Core routine for most of the enumeration of symbols
818  */
819 static BOOL sym_enum(HANDLE hProcess, ULONG64 BaseOfDll, PCSTR Mask,
820                      const struct sym_enum* se)
821 {
822     struct module_pair  pair;
823     const char*         bang;
824     regex_t             mod_regex, sym_regex;
825
826     pair.pcs = process_find_by_handle(hProcess);
827     if (BaseOfDll == 0)
828     {
829         /* do local variables ? */
830         if (!Mask || !(bang = strchr(Mask, '!')))
831             return symt_enum_locals(pair.pcs, Mask, se);
832
833         if (bang == Mask) return FALSE;
834
835         compile_regex(Mask, bang - Mask, &mod_regex, TRUE);
836         compile_regex(bang + 1, -1, &sym_regex, 
837                       dbghelp_options & SYMOPT_CASE_INSENSITIVE);
838         
839         for (pair.requested = pair.pcs->lmodules; pair.requested; pair.requested = pair.requested->next)
840         {
841             if (pair.requested->type == DMT_PE && module_get_debug(&pair))
842             {
843                 if (regexec(&mod_regex, pair.requested->module.ModuleName, 0, NULL, 0) == 0 &&
844                     symt_enum_module(&pair, &sym_regex, se))
845                     break;
846             }
847         }
848         /* not found in PE modules, retry on the ELF ones
849          */
850         if (!pair.requested && (dbghelp_options & SYMOPT_WINE_WITH_ELF_MODULES))
851         {
852             for (pair.requested = pair.pcs->lmodules; pair.requested; pair.requested = pair.requested->next)
853             {
854                 if (pair.requested->type == DMT_ELF &&
855                     !module_get_containee(pair.pcs, pair.requested) &&
856                     module_get_debug(&pair))
857                 {
858                     if (regexec(&mod_regex, pair.requested->module.ModuleName, 0, NULL, 0) == 0 &&
859                         symt_enum_module(&pair, &sym_regex, se))
860                     break;
861                 }
862             }
863         }
864         regfree(&mod_regex);
865         regfree(&sym_regex);
866         return TRUE;
867     }
868     pair.requested = module_find_by_addr(pair.pcs, BaseOfDll, DMT_UNKNOWN);
869     if (!module_get_debug(&pair))
870         return FALSE;
871
872     /* we always ignore module name from Mask when BaseOfDll is defined */
873     if (Mask && (bang = strchr(Mask, '!')))
874     {
875         if (bang == Mask) return FALSE;
876         Mask = bang + 1;
877     }
878
879     compile_regex(Mask ? Mask : "*", -1, &sym_regex, 
880                   dbghelp_options & SYMOPT_CASE_INSENSITIVE);
881     symt_enum_module(&pair, &sym_regex, se);
882     regfree(&sym_regex);
883
884     return TRUE;
885 }
886
887 /******************************************************************
888  *              SymEnumSymbols (DBGHELP.@)
889  *
890  * cases BaseOfDll = 0
891  *      !foo fails always (despite what MSDN states)
892  *      RE1!RE2 looks up all modules matching RE1, and in all these modules, lookup RE2
893  *      no ! in Mask, lookup in local Context
894  * cases BaseOfDll != 0
895  *      !foo fails always (despite what MSDN states)
896  *      RE1!RE2 gets RE2 from BaseOfDll (whatever RE1 is)
897  */
898 BOOL WINAPI SymEnumSymbols(HANDLE hProcess, ULONG64 BaseOfDll, PCSTR Mask,
899                            PSYM_ENUMERATESYMBOLS_CALLBACK EnumSymbolsCallback,
900                            PVOID UserContext)
901 {
902     struct sym_enum     se;
903
904     TRACE("(%p %s %s %p %p)\n", 
905           hProcess, wine_dbgstr_longlong(BaseOfDll), debugstr_a(Mask),
906           EnumSymbolsCallback, UserContext);
907
908     se.cb = EnumSymbolsCallback;
909     se.user = UserContext;
910     se.index = 0;
911     se.tag = 0;
912     se.addr = 0;
913     se.sym_info = (PSYMBOL_INFO)se.buffer;
914
915     return sym_enum(hProcess, BaseOfDll, Mask, &se);
916 }
917
918 struct sym_enumW
919 {
920     PSYM_ENUMERATESYMBOLS_CALLBACKW     cb;
921     void*                               ctx;
922     PSYMBOL_INFOW                       sym_info;
923     char                                buffer[sizeof(SYMBOL_INFOW) + MAX_SYM_NAME];
924
925 };
926     
927 static BOOL CALLBACK sym_enumW(PSYMBOL_INFO si, ULONG size, PVOID ctx)
928 {
929     struct sym_enumW*   sew = ctx;
930
931     copy_symbolW(sew->sym_info, si);
932
933     return (sew->cb)(sew->sym_info, size, sew->ctx);
934 }
935
936 /******************************************************************
937  *              SymEnumSymbolsW (DBGHELP.@)
938  *
939  */
940 BOOL WINAPI SymEnumSymbolsW(HANDLE hProcess, ULONG64 BaseOfDll, PCWSTR Mask,
941                             PSYM_ENUMERATESYMBOLS_CALLBACKW EnumSymbolsCallback,
942                             PVOID UserContext)
943 {
944     struct sym_enumW    sew;
945     BOOL                ret = FALSE;
946     char*               maskA = NULL;
947
948     sew.ctx = UserContext;
949     sew.cb = EnumSymbolsCallback;
950     sew.sym_info = (PSYMBOL_INFOW)sew.buffer;
951
952     if (Mask)
953     {
954         unsigned len = WideCharToMultiByte(CP_ACP, 0, Mask, -1, NULL, 0, NULL, NULL);
955         maskA = HeapAlloc(GetProcessHeap(), 0, len);
956         if (!maskA) return FALSE;
957         WideCharToMultiByte(CP_ACP, 0, Mask, -1, maskA, len, NULL, NULL);
958     }
959     ret = SymEnumSymbols(hProcess, BaseOfDll, maskA, sym_enumW, &sew);
960     HeapFree(GetProcessHeap(), 0, maskA);
961
962     return ret;
963 }
964
965 struct sym_enumerate
966 {
967     void*                       ctx;
968     PSYM_ENUMSYMBOLS_CALLBACK   cb;
969 };
970
971 static BOOL CALLBACK sym_enumerate_cb(PSYMBOL_INFO syminfo, ULONG size, void* ctx)
972 {
973     struct sym_enumerate*       se = (struct sym_enumerate*)ctx;
974     return (se->cb)(syminfo->Name, syminfo->Address, syminfo->Size, se->ctx);
975 }
976
977 /***********************************************************************
978  *              SymEnumerateSymbols (DBGHELP.@)
979  */
980 BOOL WINAPI SymEnumerateSymbols(HANDLE hProcess, DWORD BaseOfDll,
981                                 PSYM_ENUMSYMBOLS_CALLBACK EnumSymbolsCallback, 
982                                 PVOID UserContext)
983 {
984     struct sym_enumerate        se;
985
986     se.ctx = UserContext;
987     se.cb  = EnumSymbolsCallback;
988     
989     return SymEnumSymbols(hProcess, BaseOfDll, NULL, sym_enumerate_cb, &se);
990 }
991
992 /******************************************************************
993  *              SymFromAddr (DBGHELP.@)
994  *
995  */
996 BOOL WINAPI SymFromAddr(HANDLE hProcess, DWORD64 Address, 
997                         DWORD64* Displacement, PSYMBOL_INFO Symbol)
998 {
999     struct module_pair  pair;
1000     struct symt_ht*     sym;
1001     int                 idx;
1002
1003     pair.pcs = process_find_by_handle(hProcess);
1004     if (!pair.pcs) return FALSE;
1005     pair.requested = module_find_by_addr(pair.pcs, Address, DMT_UNKNOWN);
1006     if (!module_get_debug(&pair)) return FALSE;
1007     if ((idx = symt_find_nearest(pair.effective, Address)) == -1) return FALSE;
1008
1009     sym = pair.effective->addr_sorttab[idx];
1010
1011     symt_fill_sym_info(&pair, NULL, &sym->symt, Symbol);
1012     *Displacement = Address - Symbol->Address;
1013     return TRUE;
1014 }
1015
1016 /******************************************************************
1017  *              SymFromAddrW (DBGHELP.@)
1018  *
1019  */
1020 BOOL WINAPI SymFromAddrW(HANDLE hProcess, DWORD64 Address, 
1021                          DWORD64* Displacement, PSYMBOL_INFOW Symbol)
1022 {
1023     PSYMBOL_INFO        si;
1024     unsigned            len;
1025     BOOL                ret;
1026
1027     len = sizeof(*si) + Symbol->MaxNameLen * sizeof(WCHAR);
1028     si = HeapAlloc(GetProcessHeap(), 0, len);
1029     if (!si) return FALSE;
1030
1031     si->SizeOfStruct = sizeof(*si);
1032     si->MaxNameLen = Symbol->MaxNameLen;
1033     if ((ret = SymFromAddr(hProcess, Address, Displacement, si)))
1034     {
1035         copy_symbolW(Symbol, si);
1036     }
1037     HeapFree(GetProcessHeap(), 0, si);
1038     return ret;
1039 }
1040
1041 /******************************************************************
1042  *              SymGetSymFromAddr (DBGHELP.@)
1043  *
1044  */
1045 BOOL WINAPI SymGetSymFromAddr(HANDLE hProcess, DWORD Address,
1046                               PDWORD Displacement, PIMAGEHLP_SYMBOL Symbol)
1047 {
1048     char        buffer[sizeof(SYMBOL_INFO) + MAX_SYM_NAME];
1049     SYMBOL_INFO*si = (SYMBOL_INFO*)buffer;
1050     size_t      len;
1051     DWORD64     Displacement64;
1052
1053     if (Symbol->SizeOfStruct < sizeof(*Symbol)) return FALSE;
1054     si->SizeOfStruct = sizeof(*si);
1055     si->MaxNameLen = MAX_SYM_NAME;
1056     if (!SymFromAddr(hProcess, Address, &Displacement64, si))
1057         return FALSE;
1058
1059     if (Displacement)
1060         *Displacement = Displacement64;
1061     Symbol->Address = si->Address;
1062     Symbol->Size    = si->Size;
1063     Symbol->Flags   = si->Flags;
1064     len = min(Symbol->MaxNameLength, si->MaxNameLen);
1065     lstrcpynA(Symbol->Name, si->Name, len);
1066     return TRUE;
1067 }
1068
1069 /******************************************************************
1070  *              SymGetSymFromAddr64 (DBGHELP.@)
1071  *
1072  */
1073 BOOL WINAPI SymGetSymFromAddr64(HANDLE hProcess, DWORD64 Address,
1074                                 PDWORD64 Displacement, PIMAGEHLP_SYMBOL64 Symbol)
1075 {
1076     char        buffer[sizeof(SYMBOL_INFO) + MAX_SYM_NAME];
1077     SYMBOL_INFO*si = (SYMBOL_INFO*)buffer;
1078     size_t      len;
1079     DWORD64     Displacement64;
1080
1081     if (Symbol->SizeOfStruct < sizeof(*Symbol)) return FALSE;
1082     si->SizeOfStruct = sizeof(*si);
1083     si->MaxNameLen = MAX_SYM_NAME;
1084     if (!SymFromAddr(hProcess, Address, &Displacement64, si))
1085         return FALSE;
1086
1087     if (Displacement)
1088         *Displacement = Displacement64;
1089     Symbol->Address = si->Address;
1090     Symbol->Size    = si->Size;
1091     Symbol->Flags   = si->Flags;
1092     len = min(Symbol->MaxNameLength, si->MaxNameLen);
1093     lstrcpynA(Symbol->Name, si->Name, len);
1094     return TRUE;
1095 }
1096
1097 static BOOL find_name(struct process* pcs, struct module* module, const char* name,
1098                       SYMBOL_INFO* symbol)
1099 {
1100     struct hash_table_iter      hti;
1101     void*                       ptr;
1102     struct symt_ht*             sym = NULL;
1103     struct module_pair          pair;
1104
1105     pair.pcs = pcs;
1106     if (!(pair.requested = module)) return FALSE;
1107     if (!module_get_debug(&pair)) return FALSE;
1108
1109     hash_table_iter_init(&pair.effective->ht_symbols, &hti, name);
1110     while ((ptr = hash_table_iter_up(&hti)))
1111     {
1112         sym = GET_ENTRY(ptr, struct symt_ht, hash_elt);
1113
1114         if (!strcmp(sym->hash_elt.name, name))
1115         {
1116             symt_fill_sym_info(&pair, NULL, &sym->symt, symbol);
1117             return TRUE;
1118         }
1119     }
1120     return FALSE;
1121
1122 }
1123 /******************************************************************
1124  *              SymFromName (DBGHELP.@)
1125  *
1126  */
1127 BOOL WINAPI SymFromName(HANDLE hProcess, PCSTR Name, PSYMBOL_INFO Symbol)
1128 {
1129     struct process*             pcs = process_find_by_handle(hProcess);
1130     struct module*              module;
1131     const char*                 name;
1132
1133     TRACE("(%p, %s, %p)\n", hProcess, Name, Symbol);
1134     if (!pcs) return FALSE;
1135     if (Symbol->SizeOfStruct < sizeof(*Symbol)) return FALSE;
1136     name = strchr(Name, '!');
1137     if (name)
1138     {
1139         char    tmp[128];
1140         assert(name - Name < sizeof(tmp));
1141         memcpy(tmp, Name, name - Name);
1142         tmp[name - Name] = '\0';
1143         module = module_find_by_name(pcs, tmp, DMT_UNKNOWN);
1144         return find_name(pcs, module, name + 1, Symbol);
1145     }
1146     for (module = pcs->lmodules; module; module = module->next)
1147     {
1148         if (module->type == DMT_PE && find_name(pcs, module, Name, Symbol))
1149             return TRUE;
1150     }
1151     /* not found in PE modules, retry on the ELF ones
1152      */
1153     if (dbghelp_options & SYMOPT_WINE_WITH_ELF_MODULES)
1154     {
1155         for (module = pcs->lmodules; module; module = module->next)
1156         {
1157             if (module->type == DMT_ELF && !module_get_containee(pcs, module) &&
1158                 find_name(pcs, module, Name, Symbol))
1159                 return TRUE;
1160         }
1161     }
1162     return FALSE;
1163 }
1164
1165 /***********************************************************************
1166  *              SymGetSymFromName (DBGHELP.@)
1167  */
1168 BOOL WINAPI SymGetSymFromName(HANDLE hProcess, PCSTR Name, PIMAGEHLP_SYMBOL Symbol)
1169 {
1170     char        buffer[sizeof(SYMBOL_INFO) + MAX_SYM_NAME];
1171     SYMBOL_INFO*si = (SYMBOL_INFO*)buffer;
1172     size_t      len;
1173
1174     if (Symbol->SizeOfStruct < sizeof(*Symbol)) return FALSE;
1175     si->SizeOfStruct = sizeof(*si);
1176     si->MaxNameLen = MAX_SYM_NAME;
1177     if (!SymFromName(hProcess, Name, si)) return FALSE;
1178
1179     Symbol->Address = si->Address;
1180     Symbol->Size    = si->Size;
1181     Symbol->Flags   = si->Flags;
1182     len = min(Symbol->MaxNameLength, si->MaxNameLen);
1183     lstrcpynA(Symbol->Name, si->Name, len);
1184     return TRUE;
1185 }
1186
1187 /******************************************************************
1188  *              sym_fill_func_line_info
1189  *
1190  * fills information about a file
1191  */
1192 BOOL symt_fill_func_line_info(struct module* module, struct symt_function* func, 
1193                               DWORD addr, IMAGEHLP_LINE* line)
1194 {
1195     struct line_info*   dli = NULL;
1196     BOOL                found = FALSE;
1197
1198     assert(func->symt.tag == SymTagFunction);
1199
1200     while ((dli = vector_iter_down(&func->vlines, dli)))
1201     {
1202         if (!dli->is_source_file)
1203         {
1204             if (found || dli->u.pc_offset > addr) continue;
1205             line->LineNumber = dli->line_number;
1206             line->Address    = dli->u.pc_offset;
1207             line->Key        = dli;
1208             found = TRUE;
1209             continue;
1210         }
1211         if (found)
1212         {
1213             line->FileName = (char*)source_get(module, dli->u.source_file);
1214             return TRUE;
1215         }
1216     }
1217     return FALSE;
1218 }
1219
1220 /***********************************************************************
1221  *              SymGetSymNext (DBGHELP.@)
1222  */
1223 BOOL WINAPI SymGetSymNext(HANDLE hProcess, PIMAGEHLP_SYMBOL Symbol)
1224 {
1225     /* algo:
1226      * get module from Symbol.Address
1227      * get index in module.addr_sorttab of Symbol.Address
1228      * increment index
1229      * if out of module bounds, move to next module in process address space
1230      */
1231     FIXME("(%p, %p): stub\n", hProcess, Symbol);
1232     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1233     return FALSE;
1234 }
1235
1236 /***********************************************************************
1237  *              SymGetSymPrev (DBGHELP.@)
1238  */
1239
1240 BOOL WINAPI SymGetSymPrev(HANDLE hProcess, PIMAGEHLP_SYMBOL Symbol)
1241 {
1242     FIXME("(%p, %p): stub\n", hProcess, Symbol);
1243     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1244     return FALSE;
1245 }
1246
1247 /******************************************************************
1248  *              SymGetLineFromAddr (DBGHELP.@)
1249  *
1250  */
1251 BOOL WINAPI SymGetLineFromAddr(HANDLE hProcess, DWORD dwAddr, 
1252                                PDWORD pdwDisplacement, PIMAGEHLP_LINE Line)
1253 {
1254     struct module_pair  pair;
1255     int                 idx;
1256
1257     TRACE("%p %08x %p %p\n", hProcess, dwAddr, pdwDisplacement, Line);
1258
1259     if (Line->SizeOfStruct < sizeof(*Line)) return FALSE;
1260
1261     pair.pcs = process_find_by_handle(hProcess);
1262     if (!pair.pcs) return FALSE;
1263     pair.requested = module_find_by_addr(pair.pcs, dwAddr, DMT_UNKNOWN);
1264     if (!module_get_debug(&pair)) return FALSE;
1265     if ((idx = symt_find_nearest(pair.effective, dwAddr)) == -1) return FALSE;
1266
1267     if (pair.effective->addr_sorttab[idx]->symt.tag != SymTagFunction) return FALSE;
1268     if (!symt_fill_func_line_info(pair.effective, 
1269                                   (struct symt_function*)pair.effective->addr_sorttab[idx],
1270                                   dwAddr, Line)) return FALSE;
1271     *pdwDisplacement = dwAddr - Line->Address;
1272     return TRUE;
1273 }
1274
1275 /******************************************************************
1276  *              copy_line_64_from_32 (internal)
1277  *
1278  */
1279 static void copy_line_64_from_32(IMAGEHLP_LINE64* l64, const IMAGEHLP_LINE* l32)
1280
1281 {
1282     l64->Key = l32->Key;
1283     l64->LineNumber = l32->LineNumber;
1284     l64->FileName = l32->FileName;
1285     l64->Address = l32->Address;
1286 }
1287
1288 /******************************************************************
1289  *              copy_line_W64_from_32 (internal)
1290  *
1291  */
1292 static void copy_line_W64_from_32(struct process* pcs, IMAGEHLP_LINEW64* l64, const IMAGEHLP_LINE* l32)
1293 {
1294     unsigned len;
1295
1296     l64->Key = l32->Key;
1297     l64->LineNumber = l32->LineNumber;
1298     len = MultiByteToWideChar(CP_ACP, 0, l32->FileName, -1, NULL, 0);
1299     if ((l64->FileName = fetch_buffer(pcs, len * sizeof(WCHAR))))
1300         MultiByteToWideChar(CP_ACP, 0, l32->FileName, -1, l64->FileName, len);
1301     l64->Address = l32->Address;
1302 }
1303
1304 /******************************************************************
1305  *              copy_line_32_from_64 (internal)
1306  *
1307  */
1308 static void copy_line_32_from_64(IMAGEHLP_LINE* l32, const IMAGEHLP_LINE64* l64)
1309
1310 {
1311     l32->Key = l64->Key;
1312     l32->LineNumber = l64->LineNumber;
1313     l32->FileName = l64->FileName;
1314     l32->Address = l64->Address;
1315 }
1316
1317 /******************************************************************
1318  *              SymGetLineFromAddr64 (DBGHELP.@)
1319  *
1320  */
1321 BOOL WINAPI SymGetLineFromAddr64(HANDLE hProcess, DWORD64 dwAddr, 
1322                                  PDWORD pdwDisplacement, PIMAGEHLP_LINE64 Line)
1323 {
1324     IMAGEHLP_LINE       line32;
1325
1326     if (Line->SizeOfStruct < sizeof(*Line)) return FALSE;
1327     if (!validate_addr64(dwAddr)) return FALSE;
1328     line32.SizeOfStruct = sizeof(line32);
1329     if (!SymGetLineFromAddr(hProcess, (DWORD)dwAddr, pdwDisplacement, &line32))
1330         return FALSE;
1331     copy_line_64_from_32(Line, &line32);
1332     return TRUE;
1333 }
1334
1335 /******************************************************************
1336  *              SymGetLineFromAddrW64 (DBGHELP.@)
1337  *
1338  */
1339 BOOL WINAPI SymGetLineFromAddrW64(HANDLE hProcess, DWORD64 dwAddr, 
1340                                   PDWORD pdwDisplacement, PIMAGEHLP_LINEW64 Line)
1341 {
1342     struct process*     pcs = process_find_by_handle(hProcess);
1343     IMAGEHLP_LINE       line32;
1344
1345     if (!pcs) return FALSE;
1346     if (Line->SizeOfStruct < sizeof(*Line)) return FALSE;
1347     if (!validate_addr64(dwAddr)) return FALSE;
1348     line32.SizeOfStruct = sizeof(line32);
1349     if (!SymGetLineFromAddr(hProcess, (DWORD)dwAddr, pdwDisplacement, &line32))
1350         return FALSE;
1351     copy_line_W64_from_32(pcs, Line, &line32);
1352     return TRUE;
1353 }
1354
1355 /******************************************************************
1356  *              SymGetLinePrev (DBGHELP.@)
1357  *
1358  */
1359 BOOL WINAPI SymGetLinePrev(HANDLE hProcess, PIMAGEHLP_LINE Line)
1360 {
1361     struct module_pair  pair;
1362     struct line_info*   li;
1363     BOOL                in_search = FALSE;
1364
1365     TRACE("(%p %p)\n", hProcess, Line);
1366
1367     if (Line->SizeOfStruct < sizeof(*Line)) return FALSE;
1368
1369     pair.pcs = process_find_by_handle(hProcess);
1370     if (!pair.pcs) return FALSE;
1371     pair.requested = module_find_by_addr(pair.pcs, Line->Address, DMT_UNKNOWN);
1372     if (!module_get_debug(&pair)) return FALSE;
1373
1374     if (Line->Key == 0) return FALSE;
1375     li = (struct line_info*)Line->Key;
1376     /* things are a bit complicated because when we encounter a DLIT_SOURCEFILE
1377      * element we have to go back until we find the prev one to get the real
1378      * source file name for the DLIT_OFFSET element just before 
1379      * the first DLIT_SOURCEFILE
1380      */
1381     while (!li->is_first)
1382     {
1383         li--;
1384         if (!li->is_source_file)
1385         {
1386             Line->LineNumber = li->line_number;
1387             Line->Address    = li->u.pc_offset;
1388             Line->Key        = li;
1389             if (!in_search) return TRUE;
1390         }
1391         else
1392         {
1393             if (in_search)
1394             {
1395                 Line->FileName = (char*)source_get(pair.effective, li->u.source_file);
1396                 return TRUE;
1397             }
1398             in_search = TRUE;
1399         }
1400     }
1401     SetLastError(ERROR_NO_MORE_ITEMS); /* FIXME */
1402     return FALSE;
1403 }
1404
1405 /******************************************************************
1406  *              SymGetLinePrev64 (DBGHELP.@)
1407  *
1408  */
1409 BOOL WINAPI SymGetLinePrev64(HANDLE hProcess, PIMAGEHLP_LINE64 Line)
1410 {
1411     IMAGEHLP_LINE       line32;
1412
1413     line32.SizeOfStruct = sizeof(line32);
1414     copy_line_32_from_64(&line32, Line);
1415     if (!SymGetLinePrev(hProcess, &line32)) return FALSE;
1416     copy_line_64_from_32(Line, &line32);
1417     return TRUE;
1418 }
1419     
1420 BOOL symt_get_func_line_next(struct module* module, PIMAGEHLP_LINE line)
1421 {
1422     struct line_info*   li;
1423
1424     if (line->Key == 0) return FALSE;
1425     li = (struct line_info*)line->Key;
1426     while (!li->is_last)
1427     {
1428         li++;
1429         if (!li->is_source_file)
1430         {
1431             line->LineNumber = li->line_number;
1432             line->Address    = li->u.pc_offset;
1433             line->Key        = li;
1434             return TRUE;
1435         }
1436         line->FileName = (char*)source_get(module, li->u.source_file);
1437     }
1438     return FALSE;
1439 }
1440
1441 /******************************************************************
1442  *              SymGetLineNext (DBGHELP.@)
1443  *
1444  */
1445 BOOL WINAPI SymGetLineNext(HANDLE hProcess, PIMAGEHLP_LINE Line)
1446 {
1447     struct module_pair  pair;
1448
1449     TRACE("(%p %p)\n", hProcess, Line);
1450
1451     if (Line->SizeOfStruct < sizeof(*Line)) return FALSE;
1452     pair.pcs = process_find_by_handle(hProcess);
1453     if (!pair.pcs) return FALSE;
1454     pair.requested = module_find_by_addr(pair.pcs, Line->Address, DMT_UNKNOWN);
1455     if (!module_get_debug(&pair)) return FALSE;
1456
1457     if (symt_get_func_line_next(pair.effective, Line)) return TRUE;
1458     SetLastError(ERROR_NO_MORE_ITEMS); /* FIXME */
1459     return FALSE;
1460 }
1461
1462 /******************************************************************
1463  *              SymGetLineNext64 (DBGHELP.@)
1464  *
1465  */
1466 BOOL WINAPI SymGetLineNext64(HANDLE hProcess, PIMAGEHLP_LINE64 Line)
1467 {
1468     IMAGEHLP_LINE       line32;
1469
1470     line32.SizeOfStruct = sizeof(line32);
1471     copy_line_32_from_64(&line32, Line);
1472     if (!SymGetLineNext(hProcess, &line32)) return FALSE;
1473     copy_line_64_from_32(Line, &line32);
1474     return TRUE;
1475 }
1476     
1477 /***********************************************************************
1478  *              SymFunctionTableAccess (DBGHELP.@)
1479  */
1480 PVOID WINAPI SymFunctionTableAccess(HANDLE hProcess, DWORD AddrBase)
1481 {
1482     WARN("(%p, 0x%08x): stub\n", hProcess, AddrBase);
1483     return NULL;
1484 }
1485
1486 /***********************************************************************
1487  *              SymFunctionTableAccess64 (DBGHELP.@)
1488  */
1489 PVOID WINAPI SymFunctionTableAccess64(HANDLE hProcess, DWORD64 AddrBase)
1490 {
1491     WARN("(%p, %s): stub\n", hProcess, wine_dbgstr_longlong(AddrBase));
1492     return NULL;
1493 }
1494
1495 /***********************************************************************
1496  *              SymUnDName (DBGHELP.@)
1497  */
1498 BOOL WINAPI SymUnDName(PIMAGEHLP_SYMBOL sym, LPSTR UnDecName, DWORD UnDecNameLength)
1499 {
1500     TRACE("(%p %s %u)\n", sym, UnDecName, UnDecNameLength);
1501     return UnDecorateSymbolName(sym->Name, UnDecName, UnDecNameLength,
1502                                 UNDNAME_COMPLETE) != 0;
1503 }
1504
1505 static void* und_alloc(size_t len) { return HeapAlloc(GetProcessHeap(), 0, len); }
1506 static void  und_free (void* ptr)  { HeapFree(GetProcessHeap(), 0, ptr); }
1507
1508 /***********************************************************************
1509  *              UnDecorateSymbolName (DBGHELP.@)
1510  */
1511 DWORD WINAPI UnDecorateSymbolName(LPCSTR DecoratedName, LPSTR UnDecoratedName,
1512                                   DWORD UndecoratedLength, DWORD Flags)
1513 {
1514     /* undocumented from msvcrt */
1515     static char* (*p_undname)(char*, const char*, int, void* (*)(size_t), void (*)(void*), unsigned short);
1516     static const WCHAR szMsvcrt[] = {'m','s','v','c','r','t','.','d','l','l',0};
1517
1518     TRACE("(%s, %p, %d, 0x%08x)\n",
1519           debugstr_a(DecoratedName), UnDecoratedName, UndecoratedLength, Flags);
1520
1521     if (!p_undname)
1522     {
1523         if (!hMsvcrt) hMsvcrt = LoadLibraryW(szMsvcrt);
1524         if (hMsvcrt) p_undname = (void*)GetProcAddress(hMsvcrt, "__unDName");
1525         if (!p_undname) return 0;
1526     }
1527
1528     if (!UnDecoratedName) return 0;
1529     if (!p_undname(UnDecoratedName, DecoratedName, UndecoratedLength, 
1530                    und_alloc, und_free, Flags))
1531         return 0;
1532     return strlen(UnDecoratedName);
1533 }
1534
1535 /******************************************************************
1536  *              SymMatchString (DBGHELP.@)
1537  *
1538  */
1539 BOOL WINAPI SymMatchString(PCSTR string, PCSTR re, BOOL _case)
1540 {
1541     regex_t     preg;
1542     BOOL        ret;
1543
1544     TRACE("%s %s %c\n", string, re, _case ? 'Y' : 'N');
1545
1546     compile_regex(re, -1, &preg, _case);
1547     ret = regexec(&preg, string, 0, NULL, 0) == 0;
1548     regfree(&preg);
1549     return ret;
1550 }
1551
1552 /******************************************************************
1553  *              SymSearch (DBGHELP.@)
1554  */
1555 BOOL WINAPI SymSearch(HANDLE hProcess, ULONG64 BaseOfDll, DWORD Index,
1556                       DWORD SymTag, PCSTR Mask, DWORD64 Address,
1557                       PSYM_ENUMERATESYMBOLS_CALLBACK EnumSymbolsCallback,
1558                       PVOID UserContext, DWORD Options)
1559 {
1560     struct sym_enum     se;
1561
1562     TRACE("(%p %s %u %u %s %s %p %p %x)\n",
1563           hProcess, wine_dbgstr_longlong(BaseOfDll), Index, SymTag, Mask,
1564           wine_dbgstr_longlong(Address), EnumSymbolsCallback,
1565           UserContext, Options);
1566
1567     if (Options != SYMSEARCH_GLOBALSONLY)
1568     {
1569         FIXME("Unsupported searching with options (%x)\n", Options);
1570         SetLastError(ERROR_INVALID_PARAMETER);
1571         return FALSE;
1572     }
1573
1574     se.cb = EnumSymbolsCallback;
1575     se.user = UserContext;
1576     se.index = Index;
1577     se.tag = SymTag;
1578     se.addr = Address;
1579     se.sym_info = (PSYMBOL_INFO)se.buffer;
1580
1581     return sym_enum(hProcess, BaseOfDll, Mask, &se);
1582 }
1583
1584 /******************************************************************
1585  *              SymSearchW (DBGHELP.@)
1586  */
1587 BOOL WINAPI SymSearchW(HANDLE hProcess, ULONG64 BaseOfDll, DWORD Index,
1588                        DWORD SymTag, PCWSTR Mask, DWORD64 Address,
1589                        PSYM_ENUMERATESYMBOLS_CALLBACKW EnumSymbolsCallback,
1590                        PVOID UserContext, DWORD Options)
1591 {
1592     struct sym_enumW    sew;
1593     BOOL                ret = FALSE;
1594     char*               maskA = NULL;
1595
1596     TRACE("(%p %s %u %u %s %s %p %p %x)\n",
1597           hProcess, wine_dbgstr_longlong(BaseOfDll), Index, SymTag, debugstr_w(Mask),
1598           wine_dbgstr_longlong(Address), EnumSymbolsCallback,
1599           UserContext, Options);
1600
1601     sew.ctx = UserContext;
1602     sew.cb = EnumSymbolsCallback;
1603     sew.sym_info = (PSYMBOL_INFOW)sew.buffer;
1604
1605     if (Mask)
1606     {
1607         unsigned len = WideCharToMultiByte(CP_ACP, 0, Mask, -1, NULL, 0, NULL, NULL);
1608         maskA = HeapAlloc(GetProcessHeap(), 0, len);
1609         if (!maskA) return FALSE;
1610         WideCharToMultiByte(CP_ACP, 0, Mask, -1, maskA, len, NULL, NULL);
1611     }
1612     ret = SymSearch(hProcess, BaseOfDll, Index, SymTag, maskA, Address,
1613                     sym_enumW, &sew, Options);
1614     HeapFree(GetProcessHeap(), 0, maskA);
1615
1616     return ret;
1617 }