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