mshtml: Implement IHTMLTextContainer get_scrollLeft.
[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 static void symt_get_length(struct symt* symt, ULONG64* size)
719 {
720     DWORD       type_index;
721
722     if (symt_get_info(symt, TI_GET_LENGTH, size) && *size)
723         return;
724
725     if (symt_get_info(symt, TI_GET_TYPE, &type_index) &&
726         symt_get_info((struct symt*)type_index, TI_GET_LENGTH, size)) return;
727     *size = 0x1000; /* arbitrary value */
728 }
729
730 /* assume addr is in module */
731 struct symt_ht* symt_find_nearest(struct module* module, DWORD addr)
732 {
733     int         mid, high, low;
734     ULONG64     ref_addr, ref_size;
735
736     if (!module->sortlist_valid || !module->addr_sorttab)
737     {
738         if (!resort_symbols(module)) return NULL;
739     }
740
741     /*
742      * Binary search to find closest symbol.
743      */
744     low = 0;
745     high = module->num_sorttab;
746
747     symt_get_info(&module->addr_sorttab[0]->symt, TI_GET_ADDRESS, &ref_addr);
748     if (addr < ref_addr) return NULL;
749     if (high)
750     {
751         symt_get_info(&module->addr_sorttab[high - 1]->symt, TI_GET_ADDRESS, &ref_addr);
752         symt_get_length(&module->addr_sorttab[high - 1]->symt, &ref_size);
753         if (addr >= ref_addr + ref_size) return NULL;
754     }
755     
756     while (high > low + 1)
757     {
758         mid = (high + low) / 2;
759         if (cmp_sorttab_addr(module, mid, addr) < 0)
760             low = mid;
761         else
762             high = mid;
763     }
764     if (low != high && high != module->num_sorttab &&
765         cmp_sorttab_addr(module, high, addr) <= 0)
766         low = high;
767
768     /* If found symbol is a public symbol, check if there are any other entries that
769      * might also have the same address, but would get better information
770      */
771     if (module->addr_sorttab[low]->symt.tag == SymTagPublicSymbol)
772     {   
773         symt_get_info(&module->addr_sorttab[low]->symt, TI_GET_ADDRESS, &ref_addr);
774         if (low > 0 &&
775             module->addr_sorttab[low - 1]->symt.tag != SymTagPublicSymbol &&
776             !cmp_sorttab_addr(module, low - 1, ref_addr))
777             low--;
778         else if (low < module->num_sorttab - 1 &&
779                  module->addr_sorttab[low + 1]->symt.tag != SymTagPublicSymbol &&
780                  !cmp_sorttab_addr(module, low + 1, ref_addr))
781             low++;
782     }
783     /* finally check that we fit into the found symbol */
784     symt_get_info(&module->addr_sorttab[low]->symt, TI_GET_ADDRESS, &ref_addr);
785     if (addr < ref_addr) return NULL;
786     symt_get_length(&module->addr_sorttab[low]->symt, &ref_size);
787     if (addr >= ref_addr + ref_size) return NULL;
788
789     return module->addr_sorttab[low];
790 }
791
792 static BOOL symt_enum_locals_helper(struct module_pair* pair,
793                                     regex_t* preg, const struct sym_enum* se,
794                                     struct symt_function* func, const struct vector* v)
795 {
796     struct symt*        lsym = NULL;
797     DWORD               pc = pair->pcs->ctx_frame.InstructionOffset;
798     int                 i;
799
800     for (i=0; i<vector_length(v); i++)
801     {
802         lsym = *(struct symt**)vector_at(v, i);
803         switch (lsym->tag)
804         {
805         case SymTagBlock:
806             {
807                 struct symt_block*  block = (struct symt_block*)lsym;
808                 if (pc < block->address || block->address + block->size <= pc)
809                     continue;
810                 if (!symt_enum_locals_helper(pair, preg, se, func, &block->vchildren))
811                     return FALSE;
812             }
813             break;
814         case SymTagData:
815             if (regexec(preg, symt_get_name(lsym), 0, NULL, 0) == 0)
816             {
817                 if (send_symbol(se, pair, func, lsym)) return FALSE;
818             }
819             break;
820         case SymTagLabel:
821         case SymTagFuncDebugStart:
822         case SymTagFuncDebugEnd:
823         case SymTagCustom:
824             break;
825         default:
826             FIXME("Unknown type: %u (%x)\n", lsym->tag, lsym->tag);
827             assert(0);
828         }
829     }
830     return TRUE;
831 }
832
833 static BOOL symt_enum_locals(struct process* pcs, const char* mask, 
834                              const struct sym_enum* se)
835 {
836     struct module_pair  pair;
837     struct symt_ht*     sym;
838     DWORD               pc = pcs->ctx_frame.InstructionOffset;
839
840     se->sym_info->SizeOfStruct = sizeof(*se->sym_info);
841     se->sym_info->MaxNameLen = sizeof(se->buffer) - sizeof(SYMBOL_INFO);
842
843     pair.pcs = pcs;
844     pair.requested = module_find_by_addr(pair.pcs, pc, DMT_UNKNOWN);
845     if (!module_get_debug(&pair)) return FALSE;
846     if ((sym = symt_find_nearest(pair.effective, pc)) == NULL) return FALSE;
847
848     if (sym->symt.tag == SymTagFunction)
849     {
850         BOOL            ret;
851         regex_t         preg;
852
853         compile_regex(mask ? mask : "*", -1, &preg,
854                       dbghelp_options & SYMOPT_CASE_INSENSITIVE);
855         ret = symt_enum_locals_helper(&pair, &preg, se, (struct symt_function*)sym,
856                                       &((struct symt_function*)sym)->vchildren);
857         regfree(&preg);
858         return ret;
859         
860     }
861     return send_symbol(se, &pair, NULL, &sym->symt);
862 }
863
864 /******************************************************************
865  *              copy_symbolW
866  *
867  * Helper for transforming an ANSI symbol info into an UNICODE one.
868  * Assume that MaxNameLen is the same for both version (A & W).
869  */
870 void copy_symbolW(SYMBOL_INFOW* siw, const SYMBOL_INFO* si)
871 {
872     siw->SizeOfStruct = si->SizeOfStruct;
873     siw->TypeIndex = si->TypeIndex; 
874     siw->Reserved[0] = si->Reserved[0];
875     siw->Reserved[1] = si->Reserved[1];
876     siw->Index = si->info; /* FIXME: see dbghelp.h */
877     siw->Size = si->Size;
878     siw->ModBase = si->ModBase;
879     siw->Flags = si->Flags;
880     siw->Value = si->Value;
881     siw->Address = si->Address;
882     siw->Register = si->Register;
883     siw->Scope = si->Scope;
884     siw->Tag = si->Tag;
885     siw->NameLen = si->NameLen;
886     siw->MaxNameLen = si->MaxNameLen;
887     MultiByteToWideChar(CP_ACP, 0, si->Name, -1, siw->Name, siw->MaxNameLen);
888 }
889
890 /******************************************************************
891  *              sym_enum
892  *
893  * Core routine for most of the enumeration of symbols
894  */
895 static BOOL sym_enum(HANDLE hProcess, ULONG64 BaseOfDll, PCSTR Mask,
896                      const struct sym_enum* se)
897 {
898     struct module_pair  pair;
899     const char*         bang;
900     regex_t             mod_regex, sym_regex;
901
902     pair.pcs = process_find_by_handle(hProcess);
903     if (BaseOfDll == 0)
904     {
905         /* do local variables ? */
906         if (!Mask || !(bang = strchr(Mask, '!')))
907             return symt_enum_locals(pair.pcs, Mask, se);
908
909         if (bang == Mask) return FALSE;
910
911         compile_regex(Mask, bang - Mask, &mod_regex, TRUE);
912         compile_regex(bang + 1, -1, &sym_regex, 
913                       dbghelp_options & SYMOPT_CASE_INSENSITIVE);
914         
915         for (pair.requested = pair.pcs->lmodules; pair.requested; pair.requested = pair.requested->next)
916         {
917             if (pair.requested->type == DMT_PE && module_get_debug(&pair))
918             {
919                 if (regexec(&mod_regex, pair.requested->module_name, 0, NULL, 0) == 0 &&
920                     symt_enum_module(&pair, &sym_regex, se))
921                     break;
922             }
923         }
924         /* not found in PE modules, retry on the ELF ones
925          */
926         if (!pair.requested && (dbghelp_options & SYMOPT_WINE_WITH_ELF_MODULES))
927         {
928             for (pair.requested = pair.pcs->lmodules; pair.requested; pair.requested = pair.requested->next)
929             {
930                 if (pair.requested->type == DMT_ELF &&
931                     !module_get_containee(pair.pcs, pair.requested) &&
932                     module_get_debug(&pair))
933                 {
934                     if (regexec(&mod_regex, pair.requested->module_name, 0, NULL, 0) == 0 &&
935                         symt_enum_module(&pair, &sym_regex, se))
936                     break;
937                 }
938             }
939         }
940         regfree(&mod_regex);
941         regfree(&sym_regex);
942         return TRUE;
943     }
944     pair.requested = module_find_by_addr(pair.pcs, BaseOfDll, DMT_UNKNOWN);
945     if (!module_get_debug(&pair))
946         return FALSE;
947
948     /* we always ignore module name from Mask when BaseOfDll is defined */
949     if (Mask && (bang = strchr(Mask, '!')))
950     {
951         if (bang == Mask) return FALSE;
952         Mask = bang + 1;
953     }
954
955     compile_regex(Mask ? Mask : "*", -1, &sym_regex, 
956                   dbghelp_options & SYMOPT_CASE_INSENSITIVE);
957     symt_enum_module(&pair, &sym_regex, se);
958     regfree(&sym_regex);
959
960     return TRUE;
961 }
962
963 /******************************************************************
964  *              SymEnumSymbols (DBGHELP.@)
965  *
966  * cases BaseOfDll = 0
967  *      !foo fails always (despite what MSDN states)
968  *      RE1!RE2 looks up all modules matching RE1, and in all these modules, lookup RE2
969  *      no ! in Mask, lookup in local Context
970  * cases BaseOfDll != 0
971  *      !foo fails always (despite what MSDN states)
972  *      RE1!RE2 gets RE2 from BaseOfDll (whatever RE1 is)
973  */
974 BOOL WINAPI SymEnumSymbols(HANDLE hProcess, ULONG64 BaseOfDll, PCSTR Mask,
975                            PSYM_ENUMERATESYMBOLS_CALLBACK EnumSymbolsCallback,
976                            PVOID UserContext)
977 {
978     struct sym_enum     se;
979
980     TRACE("(%p %s %s %p %p)\n", 
981           hProcess, wine_dbgstr_longlong(BaseOfDll), debugstr_a(Mask),
982           EnumSymbolsCallback, UserContext);
983
984     se.cb = EnumSymbolsCallback;
985     se.user = UserContext;
986     se.index = 0;
987     se.tag = 0;
988     se.addr = 0;
989     se.sym_info = (PSYMBOL_INFO)se.buffer;
990
991     return sym_enum(hProcess, BaseOfDll, Mask, &se);
992 }
993
994 struct sym_enumW
995 {
996     PSYM_ENUMERATESYMBOLS_CALLBACKW     cb;
997     void*                               ctx;
998     PSYMBOL_INFOW                       sym_info;
999     char                                buffer[sizeof(SYMBOL_INFOW) + MAX_SYM_NAME];
1000
1001 };
1002     
1003 static BOOL CALLBACK sym_enumW(PSYMBOL_INFO si, ULONG size, PVOID ctx)
1004 {
1005     struct sym_enumW*   sew = ctx;
1006
1007     copy_symbolW(sew->sym_info, si);
1008
1009     return (sew->cb)(sew->sym_info, size, sew->ctx);
1010 }
1011
1012 /******************************************************************
1013  *              SymEnumSymbolsW (DBGHELP.@)
1014  *
1015  */
1016 BOOL WINAPI SymEnumSymbolsW(HANDLE hProcess, ULONG64 BaseOfDll, PCWSTR Mask,
1017                             PSYM_ENUMERATESYMBOLS_CALLBACKW EnumSymbolsCallback,
1018                             PVOID UserContext)
1019 {
1020     struct sym_enumW    sew;
1021     BOOL                ret = FALSE;
1022     char*               maskA = NULL;
1023
1024     sew.ctx = UserContext;
1025     sew.cb = EnumSymbolsCallback;
1026     sew.sym_info = (PSYMBOL_INFOW)sew.buffer;
1027
1028     if (Mask)
1029     {
1030         unsigned len = WideCharToMultiByte(CP_ACP, 0, Mask, -1, NULL, 0, NULL, NULL);
1031         maskA = HeapAlloc(GetProcessHeap(), 0, len);
1032         if (!maskA) return FALSE;
1033         WideCharToMultiByte(CP_ACP, 0, Mask, -1, maskA, len, NULL, NULL);
1034     }
1035     ret = SymEnumSymbols(hProcess, BaseOfDll, maskA, sym_enumW, &sew);
1036     HeapFree(GetProcessHeap(), 0, maskA);
1037
1038     return ret;
1039 }
1040
1041 struct sym_enumerate
1042 {
1043     void*                       ctx;
1044     PSYM_ENUMSYMBOLS_CALLBACK   cb;
1045 };
1046
1047 static BOOL CALLBACK sym_enumerate_cb(PSYMBOL_INFO syminfo, ULONG size, void* ctx)
1048 {
1049     struct sym_enumerate*       se = (struct sym_enumerate*)ctx;
1050     return (se->cb)(syminfo->Name, syminfo->Address, syminfo->Size, se->ctx);
1051 }
1052
1053 /***********************************************************************
1054  *              SymEnumerateSymbols (DBGHELP.@)
1055  */
1056 BOOL WINAPI SymEnumerateSymbols(HANDLE hProcess, DWORD BaseOfDll,
1057                                 PSYM_ENUMSYMBOLS_CALLBACK EnumSymbolsCallback, 
1058                                 PVOID UserContext)
1059 {
1060     struct sym_enumerate        se;
1061
1062     se.ctx = UserContext;
1063     se.cb  = EnumSymbolsCallback;
1064     
1065     return SymEnumSymbols(hProcess, BaseOfDll, NULL, sym_enumerate_cb, &se);
1066 }
1067
1068 struct sym_enumerate64
1069 {
1070     void*                       ctx;
1071     PSYM_ENUMSYMBOLS_CALLBACK64 cb;
1072 };
1073
1074 static BOOL CALLBACK sym_enumerate_cb64(PSYMBOL_INFO syminfo, ULONG size, void* ctx)
1075 {
1076     struct sym_enumerate64*     se = (struct sym_enumerate64*)ctx;
1077     return (se->cb)(syminfo->Name, syminfo->Address, syminfo->Size, se->ctx);
1078 }
1079
1080 /***********************************************************************
1081  *              SymEnumerateSymbols64 (DBGHELP.@)
1082  */
1083 BOOL WINAPI SymEnumerateSymbols64(HANDLE hProcess, DWORD64 BaseOfDll,
1084                                   PSYM_ENUMSYMBOLS_CALLBACK64 EnumSymbolsCallback,
1085                                   PVOID UserContext)
1086 {
1087     struct sym_enumerate64      se;
1088
1089     se.ctx = UserContext;
1090     se.cb  = EnumSymbolsCallback;
1091
1092     return SymEnumSymbols(hProcess, BaseOfDll, NULL, sym_enumerate_cb64, &se);
1093 }
1094
1095 /******************************************************************
1096  *              SymFromAddr (DBGHELP.@)
1097  *
1098  */
1099 BOOL WINAPI SymFromAddr(HANDLE hProcess, DWORD64 Address, 
1100                         DWORD64* Displacement, PSYMBOL_INFO Symbol)
1101 {
1102     struct module_pair  pair;
1103     struct symt_ht*     sym;
1104
1105     pair.pcs = process_find_by_handle(hProcess);
1106     if (!pair.pcs) return FALSE;
1107     pair.requested = module_find_by_addr(pair.pcs, Address, DMT_UNKNOWN);
1108     if (!module_get_debug(&pair)) return FALSE;
1109     if ((sym = symt_find_nearest(pair.effective, Address)) == NULL) return FALSE;
1110
1111     symt_fill_sym_info(&pair, NULL, &sym->symt, Symbol);
1112     *Displacement = Address - Symbol->Address;
1113     return TRUE;
1114 }
1115
1116 /******************************************************************
1117  *              SymFromAddrW (DBGHELP.@)
1118  *
1119  */
1120 BOOL WINAPI SymFromAddrW(HANDLE hProcess, DWORD64 Address, 
1121                          DWORD64* Displacement, PSYMBOL_INFOW Symbol)
1122 {
1123     PSYMBOL_INFO        si;
1124     unsigned            len;
1125     BOOL                ret;
1126
1127     len = sizeof(*si) + Symbol->MaxNameLen * sizeof(WCHAR);
1128     si = HeapAlloc(GetProcessHeap(), 0, len);
1129     if (!si) return FALSE;
1130
1131     si->SizeOfStruct = sizeof(*si);
1132     si->MaxNameLen = Symbol->MaxNameLen;
1133     if ((ret = SymFromAddr(hProcess, Address, Displacement, si)))
1134     {
1135         copy_symbolW(Symbol, si);
1136     }
1137     HeapFree(GetProcessHeap(), 0, si);
1138     return ret;
1139 }
1140
1141 /******************************************************************
1142  *              SymGetSymFromAddr (DBGHELP.@)
1143  *
1144  */
1145 BOOL WINAPI SymGetSymFromAddr(HANDLE hProcess, DWORD Address,
1146                               PDWORD Displacement, PIMAGEHLP_SYMBOL Symbol)
1147 {
1148     char        buffer[sizeof(SYMBOL_INFO) + MAX_SYM_NAME];
1149     SYMBOL_INFO*si = (SYMBOL_INFO*)buffer;
1150     size_t      len;
1151     DWORD64     Displacement64;
1152
1153     if (Symbol->SizeOfStruct < sizeof(*Symbol)) return FALSE;
1154     si->SizeOfStruct = sizeof(*si);
1155     si->MaxNameLen = MAX_SYM_NAME;
1156     if (!SymFromAddr(hProcess, Address, &Displacement64, si))
1157         return FALSE;
1158
1159     if (Displacement)
1160         *Displacement = Displacement64;
1161     Symbol->Address = si->Address;
1162     Symbol->Size    = si->Size;
1163     Symbol->Flags   = si->Flags;
1164     len = min(Symbol->MaxNameLength, si->MaxNameLen);
1165     lstrcpynA(Symbol->Name, si->Name, len);
1166     return TRUE;
1167 }
1168
1169 /******************************************************************
1170  *              SymGetSymFromAddr64 (DBGHELP.@)
1171  *
1172  */
1173 BOOL WINAPI SymGetSymFromAddr64(HANDLE hProcess, DWORD64 Address,
1174                                 PDWORD64 Displacement, PIMAGEHLP_SYMBOL64 Symbol)
1175 {
1176     char        buffer[sizeof(SYMBOL_INFO) + MAX_SYM_NAME];
1177     SYMBOL_INFO*si = (SYMBOL_INFO*)buffer;
1178     size_t      len;
1179     DWORD64     Displacement64;
1180
1181     if (Symbol->SizeOfStruct < sizeof(*Symbol)) return FALSE;
1182     si->SizeOfStruct = sizeof(*si);
1183     si->MaxNameLen = MAX_SYM_NAME;
1184     if (!SymFromAddr(hProcess, Address, &Displacement64, si))
1185         return FALSE;
1186
1187     if (Displacement)
1188         *Displacement = Displacement64;
1189     Symbol->Address = si->Address;
1190     Symbol->Size    = si->Size;
1191     Symbol->Flags   = si->Flags;
1192     len = min(Symbol->MaxNameLength, si->MaxNameLen);
1193     lstrcpynA(Symbol->Name, si->Name, len);
1194     return TRUE;
1195 }
1196
1197 static BOOL find_name(struct process* pcs, struct module* module, const char* name,
1198                       SYMBOL_INFO* symbol)
1199 {
1200     struct hash_table_iter      hti;
1201     void*                       ptr;
1202     struct symt_ht*             sym = NULL;
1203     struct module_pair          pair;
1204
1205     pair.pcs = pcs;
1206     if (!(pair.requested = module)) return FALSE;
1207     if (!module_get_debug(&pair)) return FALSE;
1208
1209     hash_table_iter_init(&pair.effective->ht_symbols, &hti, name);
1210     while ((ptr = hash_table_iter_up(&hti)))
1211     {
1212         sym = GET_ENTRY(ptr, struct symt_ht, hash_elt);
1213
1214         if (!strcmp(sym->hash_elt.name, name))
1215         {
1216             symt_fill_sym_info(&pair, NULL, &sym->symt, symbol);
1217             return TRUE;
1218         }
1219     }
1220     return FALSE;
1221
1222 }
1223 /******************************************************************
1224  *              SymFromName (DBGHELP.@)
1225  *
1226  */
1227 BOOL WINAPI SymFromName(HANDLE hProcess, PCSTR Name, PSYMBOL_INFO Symbol)
1228 {
1229     struct process*             pcs = process_find_by_handle(hProcess);
1230     struct module*              module;
1231     const char*                 name;
1232
1233     TRACE("(%p, %s, %p)\n", hProcess, Name, Symbol);
1234     if (!pcs) return FALSE;
1235     if (Symbol->SizeOfStruct < sizeof(*Symbol)) return FALSE;
1236     name = strchr(Name, '!');
1237     if (name)
1238     {
1239         char    tmp[128];
1240         assert(name - Name < sizeof(tmp));
1241         memcpy(tmp, Name, name - Name);
1242         tmp[name - Name] = '\0';
1243         module = module_find_by_nameA(pcs, tmp);
1244         return find_name(pcs, module, name + 1, Symbol);
1245     }
1246     for (module = pcs->lmodules; module; module = module->next)
1247     {
1248         if (module->type == DMT_PE && find_name(pcs, module, Name, Symbol))
1249             return TRUE;
1250     }
1251     /* not found in PE modules, retry on the ELF ones
1252      */
1253     if (dbghelp_options & SYMOPT_WINE_WITH_ELF_MODULES)
1254     {
1255         for (module = pcs->lmodules; module; module = module->next)
1256         {
1257             if (module->type == DMT_ELF && !module_get_containee(pcs, module) &&
1258                 find_name(pcs, module, Name, Symbol))
1259                 return TRUE;
1260         }
1261     }
1262     return FALSE;
1263 }
1264
1265 /***********************************************************************
1266  *              SymGetSymFromName (DBGHELP.@)
1267  */
1268 BOOL WINAPI SymGetSymFromName(HANDLE hProcess, PCSTR Name, PIMAGEHLP_SYMBOL Symbol)
1269 {
1270     char        buffer[sizeof(SYMBOL_INFO) + MAX_SYM_NAME];
1271     SYMBOL_INFO*si = (SYMBOL_INFO*)buffer;
1272     size_t      len;
1273
1274     if (Symbol->SizeOfStruct < sizeof(*Symbol)) return FALSE;
1275     si->SizeOfStruct = sizeof(*si);
1276     si->MaxNameLen = MAX_SYM_NAME;
1277     if (!SymFromName(hProcess, Name, si)) return FALSE;
1278
1279     Symbol->Address = si->Address;
1280     Symbol->Size    = si->Size;
1281     Symbol->Flags   = si->Flags;
1282     len = min(Symbol->MaxNameLength, si->MaxNameLen);
1283     lstrcpynA(Symbol->Name, si->Name, len);
1284     return TRUE;
1285 }
1286
1287 /******************************************************************
1288  *              sym_fill_func_line_info
1289  *
1290  * fills information about a file
1291  */
1292 BOOL symt_fill_func_line_info(const struct module* module, const struct symt_function* func,
1293                               DWORD addr, IMAGEHLP_LINE* line)
1294 {
1295     struct line_info*   dli = NULL;
1296     BOOL                found = FALSE;
1297     int                 i;
1298
1299     assert(func->symt.tag == SymTagFunction);
1300
1301     for (i=vector_length(&func->vlines)-1; i>=0; i--)
1302     {
1303         dli = vector_at(&func->vlines, i);
1304         if (!dli->is_source_file)
1305         {
1306             if (found || dli->u.pc_offset > addr) continue;
1307             line->LineNumber = dli->line_number;
1308             line->Address    = dli->u.pc_offset;
1309             line->Key        = dli;
1310             found = TRUE;
1311             continue;
1312         }
1313         if (found)
1314         {
1315             line->FileName = (char*)source_get(module, dli->u.source_file);
1316             return TRUE;
1317         }
1318     }
1319     return FALSE;
1320 }
1321
1322 /***********************************************************************
1323  *              SymGetSymNext (DBGHELP.@)
1324  */
1325 BOOL WINAPI SymGetSymNext(HANDLE hProcess, PIMAGEHLP_SYMBOL Symbol)
1326 {
1327     /* algo:
1328      * get module from Symbol.Address
1329      * get index in module.addr_sorttab of Symbol.Address
1330      * increment index
1331      * if out of module bounds, move to next module in process address space
1332      */
1333     FIXME("(%p, %p): stub\n", hProcess, Symbol);
1334     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1335     return FALSE;
1336 }
1337
1338 /***********************************************************************
1339  *              SymGetSymPrev (DBGHELP.@)
1340  */
1341
1342 BOOL WINAPI SymGetSymPrev(HANDLE hProcess, PIMAGEHLP_SYMBOL Symbol)
1343 {
1344     FIXME("(%p, %p): stub\n", hProcess, Symbol);
1345     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1346     return FALSE;
1347 }
1348
1349 /******************************************************************
1350  *              SymGetLineFromAddr (DBGHELP.@)
1351  *
1352  */
1353 BOOL WINAPI SymGetLineFromAddr(HANDLE hProcess, DWORD dwAddr, 
1354                                PDWORD pdwDisplacement, PIMAGEHLP_LINE Line)
1355 {
1356     struct module_pair  pair;
1357     struct symt_ht*     symt;
1358
1359     TRACE("%p %08x %p %p\n", hProcess, dwAddr, pdwDisplacement, Line);
1360
1361     if (Line->SizeOfStruct < sizeof(*Line)) return FALSE;
1362
1363     pair.pcs = process_find_by_handle(hProcess);
1364     if (!pair.pcs) return FALSE;
1365     pair.requested = module_find_by_addr(pair.pcs, dwAddr, DMT_UNKNOWN);
1366     if (!module_get_debug(&pair)) return FALSE;
1367     if ((symt = symt_find_nearest(pair.effective, dwAddr)) == NULL) return FALSE;
1368
1369     if (symt->symt.tag != SymTagFunction) return FALSE;
1370     if (!symt_fill_func_line_info(pair.effective, (struct symt_function*)symt,
1371                                   dwAddr, Line)) return FALSE;
1372     *pdwDisplacement = dwAddr - Line->Address;
1373     return TRUE;
1374 }
1375
1376 /******************************************************************
1377  *              copy_line_64_from_32 (internal)
1378  *
1379  */
1380 static void copy_line_64_from_32(IMAGEHLP_LINE64* l64, const IMAGEHLP_LINE* l32)
1381
1382 {
1383     l64->Key = l32->Key;
1384     l64->LineNumber = l32->LineNumber;
1385     l64->FileName = l32->FileName;
1386     l64->Address = l32->Address;
1387 }
1388
1389 /******************************************************************
1390  *              copy_line_W64_from_32 (internal)
1391  *
1392  */
1393 static void copy_line_W64_from_32(struct process* pcs, IMAGEHLP_LINEW64* l64, const IMAGEHLP_LINE* l32)
1394 {
1395     unsigned len;
1396
1397     l64->Key = l32->Key;
1398     l64->LineNumber = l32->LineNumber;
1399     len = MultiByteToWideChar(CP_ACP, 0, l32->FileName, -1, NULL, 0);
1400     if ((l64->FileName = fetch_buffer(pcs, len * sizeof(WCHAR))))
1401         MultiByteToWideChar(CP_ACP, 0, l32->FileName, -1, l64->FileName, len);
1402     l64->Address = l32->Address;
1403 }
1404
1405 /******************************************************************
1406  *              copy_line_32_from_64 (internal)
1407  *
1408  */
1409 static void copy_line_32_from_64(IMAGEHLP_LINE* l32, const IMAGEHLP_LINE64* l64)
1410
1411 {
1412     l32->Key = l64->Key;
1413     l32->LineNumber = l64->LineNumber;
1414     l32->FileName = l64->FileName;
1415     l32->Address = l64->Address;
1416 }
1417
1418 /******************************************************************
1419  *              SymGetLineFromAddr64 (DBGHELP.@)
1420  *
1421  */
1422 BOOL WINAPI SymGetLineFromAddr64(HANDLE hProcess, DWORD64 dwAddr, 
1423                                  PDWORD pdwDisplacement, PIMAGEHLP_LINE64 Line)
1424 {
1425     IMAGEHLP_LINE       line32;
1426
1427     if (Line->SizeOfStruct < sizeof(*Line)) return FALSE;
1428     if (!validate_addr64(dwAddr)) return FALSE;
1429     line32.SizeOfStruct = sizeof(line32);
1430     if (!SymGetLineFromAddr(hProcess, (DWORD)dwAddr, pdwDisplacement, &line32))
1431         return FALSE;
1432     copy_line_64_from_32(Line, &line32);
1433     return TRUE;
1434 }
1435
1436 /******************************************************************
1437  *              SymGetLineFromAddrW64 (DBGHELP.@)
1438  *
1439  */
1440 BOOL WINAPI SymGetLineFromAddrW64(HANDLE hProcess, DWORD64 dwAddr, 
1441                                   PDWORD pdwDisplacement, PIMAGEHLP_LINEW64 Line)
1442 {
1443     struct process*     pcs = process_find_by_handle(hProcess);
1444     IMAGEHLP_LINE       line32;
1445
1446     if (!pcs) return FALSE;
1447     if (Line->SizeOfStruct < sizeof(*Line)) return FALSE;
1448     if (!validate_addr64(dwAddr)) return FALSE;
1449     line32.SizeOfStruct = sizeof(line32);
1450     if (!SymGetLineFromAddr(hProcess, (DWORD)dwAddr, pdwDisplacement, &line32))
1451         return FALSE;
1452     copy_line_W64_from_32(pcs, Line, &line32);
1453     return TRUE;
1454 }
1455
1456 /******************************************************************
1457  *              SymGetLinePrev (DBGHELP.@)
1458  *
1459  */
1460 BOOL WINAPI SymGetLinePrev(HANDLE hProcess, PIMAGEHLP_LINE Line)
1461 {
1462     struct module_pair  pair;
1463     struct line_info*   li;
1464     BOOL                in_search = FALSE;
1465
1466     TRACE("(%p %p)\n", hProcess, Line);
1467
1468     if (Line->SizeOfStruct < sizeof(*Line)) return FALSE;
1469
1470     pair.pcs = process_find_by_handle(hProcess);
1471     if (!pair.pcs) return FALSE;
1472     pair.requested = module_find_by_addr(pair.pcs, Line->Address, DMT_UNKNOWN);
1473     if (!module_get_debug(&pair)) return FALSE;
1474
1475     if (Line->Key == 0) return FALSE;
1476     li = (struct line_info*)Line->Key;
1477     /* things are a bit complicated because when we encounter a DLIT_SOURCEFILE
1478      * element we have to go back until we find the prev one to get the real
1479      * source file name for the DLIT_OFFSET element just before 
1480      * the first DLIT_SOURCEFILE
1481      */
1482     while (!li->is_first)
1483     {
1484         li--;
1485         if (!li->is_source_file)
1486         {
1487             Line->LineNumber = li->line_number;
1488             Line->Address    = li->u.pc_offset;
1489             Line->Key        = li;
1490             if (!in_search) return TRUE;
1491         }
1492         else
1493         {
1494             if (in_search)
1495             {
1496                 Line->FileName = (char*)source_get(pair.effective, li->u.source_file);
1497                 return TRUE;
1498             }
1499             in_search = TRUE;
1500         }
1501     }
1502     SetLastError(ERROR_NO_MORE_ITEMS); /* FIXME */
1503     return FALSE;
1504 }
1505
1506 /******************************************************************
1507  *              SymGetLinePrev64 (DBGHELP.@)
1508  *
1509  */
1510 BOOL WINAPI SymGetLinePrev64(HANDLE hProcess, PIMAGEHLP_LINE64 Line)
1511 {
1512     IMAGEHLP_LINE       line32;
1513
1514     line32.SizeOfStruct = sizeof(line32);
1515     copy_line_32_from_64(&line32, Line);
1516     if (!SymGetLinePrev(hProcess, &line32)) return FALSE;
1517     copy_line_64_from_32(Line, &line32);
1518     return TRUE;
1519 }
1520     
1521 BOOL symt_get_func_line_next(const struct module* module, PIMAGEHLP_LINE line)
1522 {
1523     struct line_info*   li;
1524
1525     if (line->Key == 0) return FALSE;
1526     li = (struct line_info*)line->Key;
1527     while (!li->is_last)
1528     {
1529         li++;
1530         if (!li->is_source_file)
1531         {
1532             line->LineNumber = li->line_number;
1533             line->Address    = li->u.pc_offset;
1534             line->Key        = li;
1535             return TRUE;
1536         }
1537         line->FileName = (char*)source_get(module, li->u.source_file);
1538     }
1539     return FALSE;
1540 }
1541
1542 /******************************************************************
1543  *              SymGetLineNext (DBGHELP.@)
1544  *
1545  */
1546 BOOL WINAPI SymGetLineNext(HANDLE hProcess, PIMAGEHLP_LINE Line)
1547 {
1548     struct module_pair  pair;
1549
1550     TRACE("(%p %p)\n", hProcess, Line);
1551
1552     if (Line->SizeOfStruct < sizeof(*Line)) return FALSE;
1553     pair.pcs = process_find_by_handle(hProcess);
1554     if (!pair.pcs) return FALSE;
1555     pair.requested = module_find_by_addr(pair.pcs, Line->Address, DMT_UNKNOWN);
1556     if (!module_get_debug(&pair)) return FALSE;
1557
1558     if (symt_get_func_line_next(pair.effective, Line)) return TRUE;
1559     SetLastError(ERROR_NO_MORE_ITEMS); /* FIXME */
1560     return FALSE;
1561 }
1562
1563 /******************************************************************
1564  *              SymGetLineNext64 (DBGHELP.@)
1565  *
1566  */
1567 BOOL WINAPI SymGetLineNext64(HANDLE hProcess, PIMAGEHLP_LINE64 Line)
1568 {
1569     IMAGEHLP_LINE       line32;
1570
1571     line32.SizeOfStruct = sizeof(line32);
1572     copy_line_32_from_64(&line32, Line);
1573     if (!SymGetLineNext(hProcess, &line32)) return FALSE;
1574     copy_line_64_from_32(Line, &line32);
1575     return TRUE;
1576 }
1577     
1578 /***********************************************************************
1579  *              SymFunctionTableAccess (DBGHELP.@)
1580  */
1581 PVOID WINAPI SymFunctionTableAccess(HANDLE hProcess, DWORD AddrBase)
1582 {
1583     WARN("(%p, 0x%08x): stub\n", hProcess, AddrBase);
1584     return NULL;
1585 }
1586
1587 /***********************************************************************
1588  *              SymFunctionTableAccess64 (DBGHELP.@)
1589  */
1590 PVOID WINAPI SymFunctionTableAccess64(HANDLE hProcess, DWORD64 AddrBase)
1591 {
1592     WARN("(%p, %s): stub\n", hProcess, wine_dbgstr_longlong(AddrBase));
1593     return NULL;
1594 }
1595
1596 /***********************************************************************
1597  *              SymUnDName (DBGHELP.@)
1598  */
1599 BOOL WINAPI SymUnDName(PIMAGEHLP_SYMBOL sym, PSTR UnDecName, DWORD UnDecNameLength)
1600 {
1601     TRACE("(%p %s %u)\n", sym, UnDecName, UnDecNameLength);
1602     return UnDecorateSymbolName(sym->Name, UnDecName, UnDecNameLength,
1603                                 UNDNAME_COMPLETE) != 0;
1604 }
1605
1606 static void* und_alloc(size_t len) { return HeapAlloc(GetProcessHeap(), 0, len); }
1607 static void  und_free (void* ptr)  { HeapFree(GetProcessHeap(), 0, ptr); }
1608
1609 /***********************************************************************
1610  *              UnDecorateSymbolName (DBGHELP.@)
1611  */
1612 DWORD WINAPI UnDecorateSymbolName(PCSTR DecoratedName, PSTR UnDecoratedName,
1613                                   DWORD UndecoratedLength, DWORD Flags)
1614 {
1615     /* undocumented from msvcrt */
1616     static char* (*p_undname)(char*, const char*, int, void* (*)(size_t), void (*)(void*), unsigned short);
1617     static const WCHAR szMsvcrt[] = {'m','s','v','c','r','t','.','d','l','l',0};
1618
1619     TRACE("(%s, %p, %d, 0x%08x)\n",
1620           debugstr_a(DecoratedName), UnDecoratedName, UndecoratedLength, Flags);
1621
1622     if (!p_undname)
1623     {
1624         if (!hMsvcrt) hMsvcrt = LoadLibraryW(szMsvcrt);
1625         if (hMsvcrt) p_undname = (void*)GetProcAddress(hMsvcrt, "__unDName");
1626         if (!p_undname) return 0;
1627     }
1628
1629     if (!UnDecoratedName) return 0;
1630     if (!p_undname(UnDecoratedName, DecoratedName, UndecoratedLength, 
1631                    und_alloc, und_free, Flags))
1632         return 0;
1633     return strlen(UnDecoratedName);
1634 }
1635
1636 /******************************************************************
1637  *              SymMatchString (DBGHELP.@)
1638  *
1639  */
1640 BOOL WINAPI SymMatchString(PCSTR string, PCSTR re, BOOL _case)
1641 {
1642     regex_t     preg;
1643     BOOL        ret;
1644
1645     TRACE("%s %s %c\n", string, re, _case ? 'Y' : 'N');
1646
1647     compile_regex(re, -1, &preg, _case);
1648     ret = regexec(&preg, string, 0, NULL, 0) == 0;
1649     regfree(&preg);
1650     return ret;
1651 }
1652
1653 /******************************************************************
1654  *              SymSearch (DBGHELP.@)
1655  */
1656 BOOL WINAPI SymSearch(HANDLE hProcess, ULONG64 BaseOfDll, DWORD Index,
1657                       DWORD SymTag, PCSTR Mask, DWORD64 Address,
1658                       PSYM_ENUMERATESYMBOLS_CALLBACK EnumSymbolsCallback,
1659                       PVOID UserContext, DWORD Options)
1660 {
1661     struct sym_enum     se;
1662
1663     TRACE("(%p %s %u %u %s %s %p %p %x)\n",
1664           hProcess, wine_dbgstr_longlong(BaseOfDll), Index, SymTag, Mask,
1665           wine_dbgstr_longlong(Address), EnumSymbolsCallback,
1666           UserContext, Options);
1667
1668     if (Options != SYMSEARCH_GLOBALSONLY)
1669     {
1670         FIXME("Unsupported searching with options (%x)\n", Options);
1671         SetLastError(ERROR_INVALID_PARAMETER);
1672         return FALSE;
1673     }
1674
1675     se.cb = EnumSymbolsCallback;
1676     se.user = UserContext;
1677     se.index = Index;
1678     se.tag = SymTag;
1679     se.addr = Address;
1680     se.sym_info = (PSYMBOL_INFO)se.buffer;
1681
1682     return sym_enum(hProcess, BaseOfDll, Mask, &se);
1683 }
1684
1685 /******************************************************************
1686  *              SymSearchW (DBGHELP.@)
1687  */
1688 BOOL WINAPI SymSearchW(HANDLE hProcess, ULONG64 BaseOfDll, DWORD Index,
1689                        DWORD SymTag, PCWSTR Mask, DWORD64 Address,
1690                        PSYM_ENUMERATESYMBOLS_CALLBACKW EnumSymbolsCallback,
1691                        PVOID UserContext, DWORD Options)
1692 {
1693     struct sym_enumW    sew;
1694     BOOL                ret = FALSE;
1695     char*               maskA = NULL;
1696
1697     TRACE("(%p %s %u %u %s %s %p %p %x)\n",
1698           hProcess, wine_dbgstr_longlong(BaseOfDll), Index, SymTag, debugstr_w(Mask),
1699           wine_dbgstr_longlong(Address), EnumSymbolsCallback,
1700           UserContext, Options);
1701
1702     sew.ctx = UserContext;
1703     sew.cb = EnumSymbolsCallback;
1704     sew.sym_info = (PSYMBOL_INFOW)sew.buffer;
1705
1706     if (Mask)
1707     {
1708         unsigned len = WideCharToMultiByte(CP_ACP, 0, Mask, -1, NULL, 0, NULL, NULL);
1709         maskA = HeapAlloc(GetProcessHeap(), 0, len);
1710         if (!maskA) return FALSE;
1711         WideCharToMultiByte(CP_ACP, 0, Mask, -1, maskA, len, NULL, NULL);
1712     }
1713     ret = SymSearch(hProcess, BaseOfDll, Index, SymTag, maskA, Address,
1714                     sym_enumW, &sew, Options);
1715     HeapFree(GetProcessHeap(), 0, maskA);
1716
1717     return ret;
1718 }