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