Spelling fixes.
[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 /******************************************************************
1059  *              SymFromAddr (DBGHELP.@)
1060  *
1061  */
1062 BOOL WINAPI SymFromAddr(HANDLE hProcess, DWORD64 Address, 
1063                         DWORD64* Displacement, PSYMBOL_INFO Symbol)
1064 {
1065     struct module_pair  pair;
1066     struct symt_ht*     sym;
1067
1068     pair.pcs = process_find_by_handle(hProcess);
1069     if (!pair.pcs) return FALSE;
1070     pair.requested = module_find_by_addr(pair.pcs, Address, DMT_UNKNOWN);
1071     if (!module_get_debug(&pair)) return FALSE;
1072     if ((sym = symt_find_nearest(pair.effective, Address)) == NULL) return FALSE;
1073
1074     symt_fill_sym_info(&pair, NULL, &sym->symt, Symbol);
1075     *Displacement = Address - Symbol->Address;
1076     return TRUE;
1077 }
1078
1079 /******************************************************************
1080  *              SymFromAddrW (DBGHELP.@)
1081  *
1082  */
1083 BOOL WINAPI SymFromAddrW(HANDLE hProcess, DWORD64 Address, 
1084                          DWORD64* Displacement, PSYMBOL_INFOW Symbol)
1085 {
1086     PSYMBOL_INFO        si;
1087     unsigned            len;
1088     BOOL                ret;
1089
1090     len = sizeof(*si) + Symbol->MaxNameLen * sizeof(WCHAR);
1091     si = HeapAlloc(GetProcessHeap(), 0, len);
1092     if (!si) return FALSE;
1093
1094     si->SizeOfStruct = sizeof(*si);
1095     si->MaxNameLen = Symbol->MaxNameLen;
1096     if ((ret = SymFromAddr(hProcess, Address, Displacement, si)))
1097     {
1098         copy_symbolW(Symbol, si);
1099     }
1100     HeapFree(GetProcessHeap(), 0, si);
1101     return ret;
1102 }
1103
1104 /******************************************************************
1105  *              SymGetSymFromAddr (DBGHELP.@)
1106  *
1107  */
1108 BOOL WINAPI SymGetSymFromAddr(HANDLE hProcess, DWORD Address,
1109                               PDWORD Displacement, PIMAGEHLP_SYMBOL Symbol)
1110 {
1111     char        buffer[sizeof(SYMBOL_INFO) + MAX_SYM_NAME];
1112     SYMBOL_INFO*si = (SYMBOL_INFO*)buffer;
1113     size_t      len;
1114     DWORD64     Displacement64;
1115
1116     if (Symbol->SizeOfStruct < sizeof(*Symbol)) return FALSE;
1117     si->SizeOfStruct = sizeof(*si);
1118     si->MaxNameLen = MAX_SYM_NAME;
1119     if (!SymFromAddr(hProcess, Address, &Displacement64, si))
1120         return FALSE;
1121
1122     if (Displacement)
1123         *Displacement = Displacement64;
1124     Symbol->Address = si->Address;
1125     Symbol->Size    = si->Size;
1126     Symbol->Flags   = si->Flags;
1127     len = min(Symbol->MaxNameLength, si->MaxNameLen);
1128     lstrcpynA(Symbol->Name, si->Name, len);
1129     return TRUE;
1130 }
1131
1132 /******************************************************************
1133  *              SymGetSymFromAddr64 (DBGHELP.@)
1134  *
1135  */
1136 BOOL WINAPI SymGetSymFromAddr64(HANDLE hProcess, DWORD64 Address,
1137                                 PDWORD64 Displacement, PIMAGEHLP_SYMBOL64 Symbol)
1138 {
1139     char        buffer[sizeof(SYMBOL_INFO) + MAX_SYM_NAME];
1140     SYMBOL_INFO*si = (SYMBOL_INFO*)buffer;
1141     size_t      len;
1142     DWORD64     Displacement64;
1143
1144     if (Symbol->SizeOfStruct < sizeof(*Symbol)) return FALSE;
1145     si->SizeOfStruct = sizeof(*si);
1146     si->MaxNameLen = MAX_SYM_NAME;
1147     if (!SymFromAddr(hProcess, Address, &Displacement64, si))
1148         return FALSE;
1149
1150     if (Displacement)
1151         *Displacement = Displacement64;
1152     Symbol->Address = si->Address;
1153     Symbol->Size    = si->Size;
1154     Symbol->Flags   = si->Flags;
1155     len = min(Symbol->MaxNameLength, si->MaxNameLen);
1156     lstrcpynA(Symbol->Name, si->Name, len);
1157     return TRUE;
1158 }
1159
1160 static BOOL find_name(struct process* pcs, struct module* module, const char* name,
1161                       SYMBOL_INFO* symbol)
1162 {
1163     struct hash_table_iter      hti;
1164     void*                       ptr;
1165     struct symt_ht*             sym = NULL;
1166     struct module_pair          pair;
1167
1168     pair.pcs = pcs;
1169     if (!(pair.requested = module)) return FALSE;
1170     if (!module_get_debug(&pair)) return FALSE;
1171
1172     hash_table_iter_init(&pair.effective->ht_symbols, &hti, name);
1173     while ((ptr = hash_table_iter_up(&hti)))
1174     {
1175         sym = GET_ENTRY(ptr, struct symt_ht, hash_elt);
1176
1177         if (!strcmp(sym->hash_elt.name, name))
1178         {
1179             symt_fill_sym_info(&pair, NULL, &sym->symt, symbol);
1180             return TRUE;
1181         }
1182     }
1183     return FALSE;
1184
1185 }
1186 /******************************************************************
1187  *              SymFromName (DBGHELP.@)
1188  *
1189  */
1190 BOOL WINAPI SymFromName(HANDLE hProcess, PCSTR Name, PSYMBOL_INFO Symbol)
1191 {
1192     struct process*             pcs = process_find_by_handle(hProcess);
1193     struct module*              module;
1194     const char*                 name;
1195
1196     TRACE("(%p, %s, %p)\n", hProcess, Name, Symbol);
1197     if (!pcs) return FALSE;
1198     if (Symbol->SizeOfStruct < sizeof(*Symbol)) return FALSE;
1199     name = strchr(Name, '!');
1200     if (name)
1201     {
1202         char    tmp[128];
1203         assert(name - Name < sizeof(tmp));
1204         memcpy(tmp, Name, name - Name);
1205         tmp[name - Name] = '\0';
1206         module = module_find_by_nameA(pcs, tmp);
1207         return find_name(pcs, module, name + 1, Symbol);
1208     }
1209     for (module = pcs->lmodules; module; module = module->next)
1210     {
1211         if (module->type == DMT_PE && find_name(pcs, module, Name, Symbol))
1212             return TRUE;
1213     }
1214     /* not found in PE modules, retry on the ELF ones
1215      */
1216     if (dbghelp_options & SYMOPT_WINE_WITH_ELF_MODULES)
1217     {
1218         for (module = pcs->lmodules; module; module = module->next)
1219         {
1220             if (module->type == DMT_ELF && !module_get_containee(pcs, module) &&
1221                 find_name(pcs, module, Name, Symbol))
1222                 return TRUE;
1223         }
1224     }
1225     return FALSE;
1226 }
1227
1228 /***********************************************************************
1229  *              SymGetSymFromName (DBGHELP.@)
1230  */
1231 BOOL WINAPI SymGetSymFromName(HANDLE hProcess, PCSTR Name, PIMAGEHLP_SYMBOL Symbol)
1232 {
1233     char        buffer[sizeof(SYMBOL_INFO) + MAX_SYM_NAME];
1234     SYMBOL_INFO*si = (SYMBOL_INFO*)buffer;
1235     size_t      len;
1236
1237     if (Symbol->SizeOfStruct < sizeof(*Symbol)) return FALSE;
1238     si->SizeOfStruct = sizeof(*si);
1239     si->MaxNameLen = MAX_SYM_NAME;
1240     if (!SymFromName(hProcess, Name, si)) return FALSE;
1241
1242     Symbol->Address = si->Address;
1243     Symbol->Size    = si->Size;
1244     Symbol->Flags   = si->Flags;
1245     len = min(Symbol->MaxNameLength, si->MaxNameLen);
1246     lstrcpynA(Symbol->Name, si->Name, len);
1247     return TRUE;
1248 }
1249
1250 /******************************************************************
1251  *              sym_fill_func_line_info
1252  *
1253  * fills information about a file
1254  */
1255 BOOL symt_fill_func_line_info(const struct module* module, const struct symt_function* func,
1256                               DWORD addr, IMAGEHLP_LINE* line)
1257 {
1258     struct line_info*   dli = NULL;
1259     BOOL                found = FALSE;
1260     int                 i;
1261
1262     assert(func->symt.tag == SymTagFunction);
1263
1264     for (i=vector_length(&func->vlines)-1; i>=0; i--)
1265     {
1266         dli = vector_at(&func->vlines, i);
1267         if (!dli->is_source_file)
1268         {
1269             if (found || dli->u.pc_offset > addr) continue;
1270             line->LineNumber = dli->line_number;
1271             line->Address    = dli->u.pc_offset;
1272             line->Key        = dli;
1273             found = TRUE;
1274             continue;
1275         }
1276         if (found)
1277         {
1278             line->FileName = (char*)source_get(module, dli->u.source_file);
1279             return TRUE;
1280         }
1281     }
1282     return FALSE;
1283 }
1284
1285 /***********************************************************************
1286  *              SymGetSymNext (DBGHELP.@)
1287  */
1288 BOOL WINAPI SymGetSymNext(HANDLE hProcess, PIMAGEHLP_SYMBOL Symbol)
1289 {
1290     /* algo:
1291      * get module from Symbol.Address
1292      * get index in module.addr_sorttab of Symbol.Address
1293      * increment index
1294      * if out of module bounds, move to next module in process address space
1295      */
1296     FIXME("(%p, %p): stub\n", hProcess, Symbol);
1297     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1298     return FALSE;
1299 }
1300
1301 /***********************************************************************
1302  *              SymGetSymPrev (DBGHELP.@)
1303  */
1304
1305 BOOL WINAPI SymGetSymPrev(HANDLE hProcess, PIMAGEHLP_SYMBOL Symbol)
1306 {
1307     FIXME("(%p, %p): stub\n", hProcess, Symbol);
1308     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1309     return FALSE;
1310 }
1311
1312 /******************************************************************
1313  *              SymGetLineFromAddr (DBGHELP.@)
1314  *
1315  */
1316 BOOL WINAPI SymGetLineFromAddr(HANDLE hProcess, DWORD dwAddr, 
1317                                PDWORD pdwDisplacement, PIMAGEHLP_LINE Line)
1318 {
1319     struct module_pair  pair;
1320     struct symt_ht*     symt;
1321
1322     TRACE("%p %08x %p %p\n", hProcess, dwAddr, pdwDisplacement, Line);
1323
1324     if (Line->SizeOfStruct < sizeof(*Line)) return FALSE;
1325
1326     pair.pcs = process_find_by_handle(hProcess);
1327     if (!pair.pcs) return FALSE;
1328     pair.requested = module_find_by_addr(pair.pcs, dwAddr, DMT_UNKNOWN);
1329     if (!module_get_debug(&pair)) return FALSE;
1330     if ((symt = symt_find_nearest(pair.effective, dwAddr)) == NULL) return FALSE;
1331
1332     if (symt->symt.tag != SymTagFunction) return FALSE;
1333     if (!symt_fill_func_line_info(pair.effective, (struct symt_function*)symt,
1334                                   dwAddr, Line)) return FALSE;
1335     *pdwDisplacement = dwAddr - Line->Address;
1336     return TRUE;
1337 }
1338
1339 /******************************************************************
1340  *              copy_line_64_from_32 (internal)
1341  *
1342  */
1343 static void copy_line_64_from_32(IMAGEHLP_LINE64* l64, const IMAGEHLP_LINE* l32)
1344
1345 {
1346     l64->Key = l32->Key;
1347     l64->LineNumber = l32->LineNumber;
1348     l64->FileName = l32->FileName;
1349     l64->Address = l32->Address;
1350 }
1351
1352 /******************************************************************
1353  *              copy_line_W64_from_32 (internal)
1354  *
1355  */
1356 static void copy_line_W64_from_32(struct process* pcs, IMAGEHLP_LINEW64* l64, const IMAGEHLP_LINE* l32)
1357 {
1358     unsigned len;
1359
1360     l64->Key = l32->Key;
1361     l64->LineNumber = l32->LineNumber;
1362     len = MultiByteToWideChar(CP_ACP, 0, l32->FileName, -1, NULL, 0);
1363     if ((l64->FileName = fetch_buffer(pcs, len * sizeof(WCHAR))))
1364         MultiByteToWideChar(CP_ACP, 0, l32->FileName, -1, l64->FileName, len);
1365     l64->Address = l32->Address;
1366 }
1367
1368 /******************************************************************
1369  *              copy_line_32_from_64 (internal)
1370  *
1371  */
1372 static void copy_line_32_from_64(IMAGEHLP_LINE* l32, const IMAGEHLP_LINE64* l64)
1373
1374 {
1375     l32->Key = l64->Key;
1376     l32->LineNumber = l64->LineNumber;
1377     l32->FileName = l64->FileName;
1378     l32->Address = l64->Address;
1379 }
1380
1381 /******************************************************************
1382  *              SymGetLineFromAddr64 (DBGHELP.@)
1383  *
1384  */
1385 BOOL WINAPI SymGetLineFromAddr64(HANDLE hProcess, DWORD64 dwAddr, 
1386                                  PDWORD pdwDisplacement, PIMAGEHLP_LINE64 Line)
1387 {
1388     IMAGEHLP_LINE       line32;
1389
1390     if (Line->SizeOfStruct < sizeof(*Line)) return FALSE;
1391     if (!validate_addr64(dwAddr)) return FALSE;
1392     line32.SizeOfStruct = sizeof(line32);
1393     if (!SymGetLineFromAddr(hProcess, (DWORD)dwAddr, pdwDisplacement, &line32))
1394         return FALSE;
1395     copy_line_64_from_32(Line, &line32);
1396     return TRUE;
1397 }
1398
1399 /******************************************************************
1400  *              SymGetLineFromAddrW64 (DBGHELP.@)
1401  *
1402  */
1403 BOOL WINAPI SymGetLineFromAddrW64(HANDLE hProcess, DWORD64 dwAddr, 
1404                                   PDWORD pdwDisplacement, PIMAGEHLP_LINEW64 Line)
1405 {
1406     struct process*     pcs = process_find_by_handle(hProcess);
1407     IMAGEHLP_LINE       line32;
1408
1409     if (!pcs) return FALSE;
1410     if (Line->SizeOfStruct < sizeof(*Line)) return FALSE;
1411     if (!validate_addr64(dwAddr)) return FALSE;
1412     line32.SizeOfStruct = sizeof(line32);
1413     if (!SymGetLineFromAddr(hProcess, (DWORD)dwAddr, pdwDisplacement, &line32))
1414         return FALSE;
1415     copy_line_W64_from_32(pcs, Line, &line32);
1416     return TRUE;
1417 }
1418
1419 /******************************************************************
1420  *              SymGetLinePrev (DBGHELP.@)
1421  *
1422  */
1423 BOOL WINAPI SymGetLinePrev(HANDLE hProcess, PIMAGEHLP_LINE Line)
1424 {
1425     struct module_pair  pair;
1426     struct line_info*   li;
1427     BOOL                in_search = FALSE;
1428
1429     TRACE("(%p %p)\n", hProcess, Line);
1430
1431     if (Line->SizeOfStruct < sizeof(*Line)) return FALSE;
1432
1433     pair.pcs = process_find_by_handle(hProcess);
1434     if (!pair.pcs) return FALSE;
1435     pair.requested = module_find_by_addr(pair.pcs, Line->Address, DMT_UNKNOWN);
1436     if (!module_get_debug(&pair)) return FALSE;
1437
1438     if (Line->Key == 0) return FALSE;
1439     li = (struct line_info*)Line->Key;
1440     /* things are a bit complicated because when we encounter a DLIT_SOURCEFILE
1441      * element we have to go back until we find the prev one to get the real
1442      * source file name for the DLIT_OFFSET element just before 
1443      * the first DLIT_SOURCEFILE
1444      */
1445     while (!li->is_first)
1446     {
1447         li--;
1448         if (!li->is_source_file)
1449         {
1450             Line->LineNumber = li->line_number;
1451             Line->Address    = li->u.pc_offset;
1452             Line->Key        = li;
1453             if (!in_search) return TRUE;
1454         }
1455         else
1456         {
1457             if (in_search)
1458             {
1459                 Line->FileName = (char*)source_get(pair.effective, li->u.source_file);
1460                 return TRUE;
1461             }
1462             in_search = TRUE;
1463         }
1464     }
1465     SetLastError(ERROR_NO_MORE_ITEMS); /* FIXME */
1466     return FALSE;
1467 }
1468
1469 /******************************************************************
1470  *              SymGetLinePrev64 (DBGHELP.@)
1471  *
1472  */
1473 BOOL WINAPI SymGetLinePrev64(HANDLE hProcess, PIMAGEHLP_LINE64 Line)
1474 {
1475     IMAGEHLP_LINE       line32;
1476
1477     line32.SizeOfStruct = sizeof(line32);
1478     copy_line_32_from_64(&line32, Line);
1479     if (!SymGetLinePrev(hProcess, &line32)) return FALSE;
1480     copy_line_64_from_32(Line, &line32);
1481     return TRUE;
1482 }
1483     
1484 BOOL symt_get_func_line_next(const struct module* module, PIMAGEHLP_LINE line)
1485 {
1486     struct line_info*   li;
1487
1488     if (line->Key == 0) return FALSE;
1489     li = (struct line_info*)line->Key;
1490     while (!li->is_last)
1491     {
1492         li++;
1493         if (!li->is_source_file)
1494         {
1495             line->LineNumber = li->line_number;
1496             line->Address    = li->u.pc_offset;
1497             line->Key        = li;
1498             return TRUE;
1499         }
1500         line->FileName = (char*)source_get(module, li->u.source_file);
1501     }
1502     return FALSE;
1503 }
1504
1505 /******************************************************************
1506  *              SymGetLineNext (DBGHELP.@)
1507  *
1508  */
1509 BOOL WINAPI SymGetLineNext(HANDLE hProcess, PIMAGEHLP_LINE Line)
1510 {
1511     struct module_pair  pair;
1512
1513     TRACE("(%p %p)\n", hProcess, Line);
1514
1515     if (Line->SizeOfStruct < sizeof(*Line)) return FALSE;
1516     pair.pcs = process_find_by_handle(hProcess);
1517     if (!pair.pcs) return FALSE;
1518     pair.requested = module_find_by_addr(pair.pcs, Line->Address, DMT_UNKNOWN);
1519     if (!module_get_debug(&pair)) return FALSE;
1520
1521     if (symt_get_func_line_next(pair.effective, Line)) return TRUE;
1522     SetLastError(ERROR_NO_MORE_ITEMS); /* FIXME */
1523     return FALSE;
1524 }
1525
1526 /******************************************************************
1527  *              SymGetLineNext64 (DBGHELP.@)
1528  *
1529  */
1530 BOOL WINAPI SymGetLineNext64(HANDLE hProcess, PIMAGEHLP_LINE64 Line)
1531 {
1532     IMAGEHLP_LINE       line32;
1533
1534     line32.SizeOfStruct = sizeof(line32);
1535     copy_line_32_from_64(&line32, Line);
1536     if (!SymGetLineNext(hProcess, &line32)) return FALSE;
1537     copy_line_64_from_32(Line, &line32);
1538     return TRUE;
1539 }
1540     
1541 /***********************************************************************
1542  *              SymFunctionTableAccess (DBGHELP.@)
1543  */
1544 PVOID WINAPI SymFunctionTableAccess(HANDLE hProcess, DWORD AddrBase)
1545 {
1546     WARN("(%p, 0x%08x): stub\n", hProcess, AddrBase);
1547     return NULL;
1548 }
1549
1550 /***********************************************************************
1551  *              SymFunctionTableAccess64 (DBGHELP.@)
1552  */
1553 PVOID WINAPI SymFunctionTableAccess64(HANDLE hProcess, DWORD64 AddrBase)
1554 {
1555     WARN("(%p, %s): stub\n", hProcess, wine_dbgstr_longlong(AddrBase));
1556     return NULL;
1557 }
1558
1559 /***********************************************************************
1560  *              SymUnDName (DBGHELP.@)
1561  */
1562 BOOL WINAPI SymUnDName(PIMAGEHLP_SYMBOL sym, PSTR UnDecName, DWORD UnDecNameLength)
1563 {
1564     TRACE("(%p %s %u)\n", sym, UnDecName, UnDecNameLength);
1565     return UnDecorateSymbolName(sym->Name, UnDecName, UnDecNameLength,
1566                                 UNDNAME_COMPLETE) != 0;
1567 }
1568
1569 static void* und_alloc(size_t len) { return HeapAlloc(GetProcessHeap(), 0, len); }
1570 static void  und_free (void* ptr)  { HeapFree(GetProcessHeap(), 0, ptr); }
1571
1572 /***********************************************************************
1573  *              UnDecorateSymbolName (DBGHELP.@)
1574  */
1575 DWORD WINAPI UnDecorateSymbolName(PCSTR DecoratedName, PSTR UnDecoratedName,
1576                                   DWORD UndecoratedLength, DWORD Flags)
1577 {
1578     /* undocumented from msvcrt */
1579     static char* (*p_undname)(char*, const char*, int, void* (*)(size_t), void (*)(void*), unsigned short);
1580     static const WCHAR szMsvcrt[] = {'m','s','v','c','r','t','.','d','l','l',0};
1581
1582     TRACE("(%s, %p, %d, 0x%08x)\n",
1583           debugstr_a(DecoratedName), UnDecoratedName, UndecoratedLength, Flags);
1584
1585     if (!p_undname)
1586     {
1587         if (!hMsvcrt) hMsvcrt = LoadLibraryW(szMsvcrt);
1588         if (hMsvcrt) p_undname = (void*)GetProcAddress(hMsvcrt, "__unDName");
1589         if (!p_undname) return 0;
1590     }
1591
1592     if (!UnDecoratedName) return 0;
1593     if (!p_undname(UnDecoratedName, DecoratedName, UndecoratedLength, 
1594                    und_alloc, und_free, Flags))
1595         return 0;
1596     return strlen(UnDecoratedName);
1597 }
1598
1599 /******************************************************************
1600  *              SymMatchString (DBGHELP.@)
1601  *
1602  */
1603 BOOL WINAPI SymMatchString(PCSTR string, PCSTR re, BOOL _case)
1604 {
1605     regex_t     preg;
1606     BOOL        ret;
1607
1608     TRACE("%s %s %c\n", string, re, _case ? 'Y' : 'N');
1609
1610     compile_regex(re, -1, &preg, _case);
1611     ret = regexec(&preg, string, 0, NULL, 0) == 0;
1612     regfree(&preg);
1613     return ret;
1614 }
1615
1616 /******************************************************************
1617  *              SymSearch (DBGHELP.@)
1618  */
1619 BOOL WINAPI SymSearch(HANDLE hProcess, ULONG64 BaseOfDll, DWORD Index,
1620                       DWORD SymTag, PCSTR Mask, DWORD64 Address,
1621                       PSYM_ENUMERATESYMBOLS_CALLBACK EnumSymbolsCallback,
1622                       PVOID UserContext, DWORD Options)
1623 {
1624     struct sym_enum     se;
1625
1626     TRACE("(%p %s %u %u %s %s %p %p %x)\n",
1627           hProcess, wine_dbgstr_longlong(BaseOfDll), Index, SymTag, Mask,
1628           wine_dbgstr_longlong(Address), EnumSymbolsCallback,
1629           UserContext, Options);
1630
1631     if (Options != SYMSEARCH_GLOBALSONLY)
1632     {
1633         FIXME("Unsupported searching with options (%x)\n", Options);
1634         SetLastError(ERROR_INVALID_PARAMETER);
1635         return FALSE;
1636     }
1637
1638     se.cb = EnumSymbolsCallback;
1639     se.user = UserContext;
1640     se.index = Index;
1641     se.tag = SymTag;
1642     se.addr = Address;
1643     se.sym_info = (PSYMBOL_INFO)se.buffer;
1644
1645     return sym_enum(hProcess, BaseOfDll, Mask, &se);
1646 }
1647
1648 /******************************************************************
1649  *              SymSearchW (DBGHELP.@)
1650  */
1651 BOOL WINAPI SymSearchW(HANDLE hProcess, ULONG64 BaseOfDll, DWORD Index,
1652                        DWORD SymTag, PCWSTR Mask, DWORD64 Address,
1653                        PSYM_ENUMERATESYMBOLS_CALLBACKW EnumSymbolsCallback,
1654                        PVOID UserContext, DWORD Options)
1655 {
1656     struct sym_enumW    sew;
1657     BOOL                ret = FALSE;
1658     char*               maskA = NULL;
1659
1660     TRACE("(%p %s %u %u %s %s %p %p %x)\n",
1661           hProcess, wine_dbgstr_longlong(BaseOfDll), Index, SymTag, debugstr_w(Mask),
1662           wine_dbgstr_longlong(Address), EnumSymbolsCallback,
1663           UserContext, Options);
1664
1665     sew.ctx = UserContext;
1666     sew.cb = EnumSymbolsCallback;
1667     sew.sym_info = (PSYMBOL_INFOW)sew.buffer;
1668
1669     if (Mask)
1670     {
1671         unsigned len = WideCharToMultiByte(CP_ACP, 0, Mask, -1, NULL, 0, NULL, NULL);
1672         maskA = HeapAlloc(GetProcessHeap(), 0, len);
1673         if (!maskA) return FALSE;
1674         WideCharToMultiByte(CP_ACP, 0, Mask, -1, maskA, len, NULL, NULL);
1675     }
1676     ret = SymSearch(hProcess, BaseOfDll, Index, SymTag, maskA, Address,
1677                     sym_enumW, &sew, Options);
1678     HeapFree(GetProcessHeap(), 0, maskA);
1679
1680     return ret;
1681 }