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