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