Call the equivalent delegate function for all of the simple
[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
40 WINE_DEFAULT_DEBUG_CHANNEL(dbghelp);
41 WINE_DECLARE_DEBUG_CHANNEL(dbghelp_symt);
42
43 inline static int cmp_addr(ULONG64 a1, ULONG64 a2)
44 {
45     if (a1 > a2) return 1;
46     if (a1 < a2) return -1;
47     return 0;
48 }
49
50 inline static int cmp_sorttab_addr(const struct module* module, int idx, ULONG64 addr)
51 {
52     ULONG64     ref;
53
54     symt_get_info(&module->addr_sorttab[idx]->symt, TI_GET_ADDRESS, &ref);
55     return cmp_addr(ref, addr);
56 }
57
58 int symt_cmp_addr(const void* p1, const void* p2)
59 {
60     const struct symt*  sym1 = *(const struct symt* const *)p1;
61     const struct symt*  sym2 = *(const struct symt* const *)p2;
62     ULONG64     a1, a2;
63
64     symt_get_info(sym1, TI_GET_ADDRESS, &a1);
65     symt_get_info(sym2, TI_GET_ADDRESS, &a2);
66     return cmp_addr(a1, a2);
67 }
68
69 static inline void re_append(char** mask, unsigned* len, char ch)
70 {
71     *mask = HeapReAlloc(GetProcessHeap(), 0, *mask, ++(*len));
72     (*mask)[*len - 2] = ch;
73 }
74
75 /* transforms a dbghelp's regular expression into a POSIX one
76  * Here are the valid dbghelp reg ex characters:
77  *      *       0 or more characters
78  *      ?       a single character
79  *      []      list
80  *      #       0 or more of preceding char
81  *      +       1 or more of preceding char
82  *      escapes \ on #, ?, [, ], *, +. don't work on -
83  */
84 static void compile_regex(const char* str, int numchar, regex_t* re)
85 {
86     char*       mask = HeapAlloc(GetProcessHeap(), 0, 1);
87     unsigned    len = 1;
88     BOOL        in_escape = FALSE;
89
90     re_append(&mask, &len, '^');
91
92     while (*str && numchar--)
93     {
94         /* FIXME: this shouldn't be valid on '-' */
95         if (in_escape)
96         {
97             re_append(&mask, &len, '\\');
98             re_append(&mask, &len, *str);
99             in_escape = FALSE;
100         }
101         else switch (*str)
102         {
103         case '\\': in_escape = TRUE; break;
104         case '*':  re_append(&mask, &len, '.'); re_append(&mask, &len, '*'); break;
105         case '?':  re_append(&mask, &len, '.'); break;
106         case '#':  re_append(&mask, &len, '*'); break;
107         /* escape some valid characters in dbghelp reg exp:s */
108         case '$':  re_append(&mask, &len, '\\'); re_append(&mask, &len, '$'); break;
109         /* +, [, ], - are the same in dbghelp & POSIX, use them as any other char */
110         default:   re_append(&mask, &len, *str); break;
111         }
112         str++;
113     }
114     if (in_escape)
115     {
116         re_append(&mask, &len, '\\');
117         re_append(&mask, &len, '\\');
118     }
119     re_append(&mask, &len, '$');
120     mask[len - 1] = '\0';
121     if (regcomp(re, mask, REG_NOSUB)) FIXME("Couldn't compile %s\n", mask);
122     HeapFree(GetProcessHeap(), 0, mask);
123 }
124
125 struct symt_compiland* symt_new_compiland(struct module* module, const char* name)
126 {
127     struct symt_compiland*    sym;
128
129     TRACE_(dbghelp_symt)("Adding compiland symbol %s:%s\n", 
130                          module->module.ModuleName, name);
131     if ((sym = pool_alloc(&module->pool, sizeof(*sym))))
132     {
133         sym->symt.tag = SymTagCompiland;
134         sym->source   = source_new(module, name);
135         vector_init(&sym->vchildren, sizeof(struct symt*), 32);
136     }
137     return sym;
138 }
139
140 struct symt_public* symt_new_public(struct module* module, 
141                                     struct symt_compiland* compiland,
142                                     const char* name,
143                                     unsigned long address, unsigned size,
144                                     BOOL in_code, BOOL is_func)
145 {
146     struct symt_public* sym;
147     struct symt**       p;
148
149     TRACE_(dbghelp_symt)("Adding public symbol %s:%s @%lx\n", 
150                          module->module.ModuleName, name, address);
151     if ((dbghelp_options & SYMOPT_AUTO_PUBLICS) && 
152         symt_find_nearest(module, address) != -1)
153         return NULL;
154     if ((sym = pool_alloc(&module->pool, sizeof(*sym))))
155     {
156         sym->symt.tag      = SymTagPublicSymbol;
157         sym->hash_elt.name = pool_strdup(&module->pool, name);
158         hash_table_add(&module->ht_symbols, &sym->hash_elt);
159         module->sortlist_valid = FALSE;
160         sym->container     = compiland ? &compiland->symt : NULL;
161         sym->address       = address;
162         sym->size          = size;
163         sym->in_code       = in_code;
164         sym->is_function   = is_func;
165         if (compiland)
166         {
167             p = vector_add(&compiland->vchildren, &module->pool);
168             *p = &sym->symt;
169         }
170     }
171     return sym;
172 }
173
174 struct symt_data* symt_new_global_variable(struct module* module, 
175                                            struct symt_compiland* compiland, 
176                                            const char* name, unsigned is_static,
177                                            unsigned long addr, unsigned long size,
178                                            struct symt* type)
179 {
180     struct symt_data*   sym;
181     struct symt**       p;
182     DWORD64             tsz;
183
184     TRACE_(dbghelp_symt)("Adding global symbol %s:%s @%lx %p\n", 
185                          module->module.ModuleName, name, addr, type);
186     if ((sym = pool_alloc(&module->pool, sizeof(*sym))))
187     {
188         sym->symt.tag      = SymTagData;
189         sym->hash_elt.name = pool_strdup(&module->pool, name);
190         hash_table_add(&module->ht_symbols, &sym->hash_elt);
191         module->sortlist_valid = FALSE;
192         sym->kind          = is_static ? DataIsFileStatic : DataIsGlobal;
193         sym->container     = compiland ? &compiland->symt : NULL;
194         sym->type          = type;
195         sym->u.address     = addr;
196         if (type && size && symt_get_info(type, TI_GET_LENGTH, &tsz))
197         {
198             if (tsz != size)
199                 FIXME("Size mismatch for %s.%s between type (%s) and src (%lu)\n",
200                       module->module.ModuleName, name, 
201                       wine_dbgstr_longlong(tsz), size);
202         }
203         if (compiland)
204         {
205             p = vector_add(&compiland->vchildren, &module->pool);
206             *p = &sym->symt;
207         }
208     }
209     return sym;
210 }
211
212 struct symt_function* symt_new_function(struct module* module, 
213                                         struct symt_compiland* compiland, 
214                                         const char* name,
215                                         unsigned long addr, unsigned long size,
216                                         struct symt* sig_type)
217 {
218     struct symt_function*       sym;
219     struct symt**               p;
220
221     TRACE_(dbghelp_symt)("Adding global function %s:%s @%lx-%lx\n", 
222                          module->module.ModuleName, name, addr, addr + size - 1);
223
224     assert(!sig_type || sig_type->tag == SymTagFunctionType);
225     if ((sym = pool_alloc(&module->pool, sizeof(*sym))))
226     {
227         sym->symt.tag  = SymTagFunction;
228         sym->hash_elt.name = pool_strdup(&module->pool, name);
229         hash_table_add(&module->ht_symbols, &sym->hash_elt);
230         module->sortlist_valid = FALSE;
231         sym->container = &compiland->symt;
232         sym->address   = addr;
233         sym->type      = sig_type;
234         sym->size      = size;
235         vector_init(&sym->vlines,  sizeof(struct line_info), 64);
236         vector_init(&sym->vchildren, sizeof(struct symt*), 8);
237         if (compiland)
238         {
239             p = vector_add(&compiland->vchildren, &module->pool);
240             *p = &sym->symt;
241         }
242     }
243     return sym;
244 }
245
246 void symt_add_func_line(struct module* module, struct symt_function* func,
247                         unsigned source_idx, int line_num, unsigned long offset)
248 {
249     struct line_info*   dli;
250     BOOL                last_matches = FALSE;
251
252     if (func == NULL || !(dbghelp_options & SYMOPT_LOAD_LINES)) return;
253
254     TRACE_(dbghelp_symt)("(%p)%s:%lx %s:%u\n", 
255                          func, func->hash_elt.name, offset, 
256                          source_get(module, source_idx), line_num);
257
258     assert(func->symt.tag == SymTagFunction);
259
260     dli = NULL;
261     while ((dli = vector_iter_down(&func->vlines, dli)))
262     {
263         if (dli->is_source_file)
264         {
265             last_matches = (source_idx == dli->u.source_file);
266             break;
267         }
268     }
269
270     if (!last_matches)
271     {
272         /* we shouldn't have line changes on first line of function */
273         dli = vector_add(&func->vlines, &module->pool);
274         dli->is_source_file = 1;
275         dli->is_first       = dli->is_last = 0;
276         dli->line_number    = 0;
277         dli->u.source_file  = source_idx;
278     }
279     dli = vector_add(&func->vlines, &module->pool);
280     dli->is_source_file = 0;
281     dli->is_first       = dli->is_last = 0;
282     dli->line_number    = line_num;
283     dli->u.pc_offset    = func->address + offset;
284 }
285
286 struct symt_data* symt_add_func_local(struct module* module, 
287                                       struct symt_function* func, 
288                                       int regno, int offset, 
289                                       struct symt_block* block, 
290                                       struct symt* type, const char* name)
291 {
292     struct symt_data*   locsym;
293     struct symt**       p;
294
295     assert(func);
296     assert(func->symt.tag == SymTagFunction);
297
298     TRACE_(dbghelp_symt)("Adding local symbol (%s:%s): %s %p\n", 
299                          module->module.ModuleName, func->hash_elt.name, 
300                          name, type);
301     locsym = pool_alloc(&module->pool, sizeof(*locsym));
302     locsym->symt.tag      = SymTagData;
303     locsym->hash_elt.name = pool_strdup(&module->pool, name);
304     locsym->hash_elt.next = NULL;
305     locsym->kind          = (offset < 0) ? DataIsParam : DataIsLocal;
306     locsym->container     = &block->symt;
307     locsym->type          = type;
308     if (regno)
309     {
310         locsym->u.s.reg_id = regno;
311         locsym->u.s.offset = 0;
312         locsym->u.s.length = 0;
313     }
314     else
315     {
316         locsym->u.s.reg_id = 0;
317         locsym->u.s.offset = offset * 8;
318         locsym->u.s.length = 0;
319     }
320     if (block)
321         p = vector_add(&block->vchildren, &module->pool);
322     else
323         p = vector_add(&func->vchildren, &module->pool);
324     *p = &locsym->symt;
325     return locsym;
326 }
327
328 struct symt_block* symt_open_func_block(struct module* module, 
329                                         struct symt_function* func,
330                                         struct symt_block* parent_block, 
331                                         unsigned pc, unsigned len)
332 {
333     struct symt_block*  block;
334     struct symt**       p;
335
336     assert(func);
337     assert(func->symt.tag == SymTagFunction);
338
339     assert(!parent_block || parent_block->symt.tag == SymTagBlock);
340     block = pool_alloc(&module->pool, sizeof(*block));
341     block->symt.tag = SymTagBlock;
342     block->address  = func->address + pc;
343     block->size     = len;
344     block->container = parent_block ? &parent_block->symt : &func->symt;
345     vector_init(&block->vchildren, sizeof(struct symt*), 4);
346     if (parent_block)
347         p = vector_add(&parent_block->vchildren, &module->pool);
348     else
349         p = vector_add(&func->vchildren, &module->pool);
350     *p = &block->symt;
351
352     return block;
353 }
354
355 struct symt_block* symt_close_func_block(struct module* module, 
356                                          struct symt_function* func,
357                                          struct symt_block* block, unsigned pc)
358 {
359     assert(func->symt.tag == SymTagFunction);
360
361     if (pc) block->size = func->address + pc - block->address;
362     return (block->container->tag == SymTagBlock) ? 
363         GET_ENTRY(block->container, struct symt_block, symt) : NULL;
364 }
365
366 struct symt_function_point* symt_add_function_point(struct module* module, 
367                                                     struct symt_function* func,
368                                                     enum SymTagEnum point, 
369                                                     unsigned offset, const char* name)
370 {
371     struct symt_function_point* sym;
372     struct symt**               p;
373
374     if ((sym = pool_alloc(&module->pool, sizeof(*sym))))
375     {
376         sym->symt.tag = point;
377         sym->parent   = func;
378         sym->offset   = offset;
379         sym->name     = name ? pool_strdup(&module->pool, name) : NULL;
380         p = vector_add(&func->vchildren, &module->pool);
381         *p = &sym->symt;
382     }
383     return sym;
384 }
385
386 BOOL symt_normalize_function(struct module* module, struct symt_function* func)
387 {
388     unsigned            len;
389     struct line_info*   dli;
390
391     assert(func);
392     /* We aren't adding any more locals or line numbers to this function.
393      * Free any spare memory that we might have allocated.
394      */
395     assert(func->symt.tag == SymTagFunction);
396
397 /* EPP     vector_pool_normalize(&func->vlines,    &module->pool); */
398 /* EPP     vector_pool_normalize(&func->vchildren, &module->pool); */
399
400     len = vector_length(&func->vlines);
401     if (len--)
402     {
403         dli = vector_at(&func->vlines,   0);  dli->is_first = 1;
404         dli = vector_at(&func->vlines, len);  dli->is_last  = 1;
405     }
406     return TRUE;
407 }
408
409 struct symt_thunk* symt_new_thunk(struct module* module, 
410                                   struct symt_compiland* compiland, 
411                                   const char* name, THUNK_ORDINAL ord,
412                                   unsigned long addr, unsigned long size)
413 {
414     struct symt_thunk*  sym;
415
416     TRACE_(dbghelp_symt)("Adding global thunk %s:%s @%lx-%lx\n", 
417                          module->module.ModuleName, name, addr, addr + size - 1);
418
419     if ((sym = pool_alloc(&module->pool, sizeof(*sym))))
420     {
421         sym->symt.tag  = SymTagThunk;
422         sym->hash_elt.name = pool_strdup(&module->pool, name);
423         hash_table_add(&module->ht_symbols, &sym->hash_elt);
424         module->sortlist_valid = FALSE;
425         sym->container = &compiland->symt;
426         sym->address   = addr;
427         sym->size      = size;
428         sym->ordinal   = ord;
429         if (compiland)
430         {
431             struct symt**       p;
432             p = vector_add(&compiland->vchildren, &module->pool);
433             *p = &sym->symt;
434         }
435     }
436     return sym;
437 }
438
439 /* expect sym_info->MaxNameLen to be set before being called */
440 static void symt_fill_sym_info(const struct module* module, 
441                                const struct symt* sym, SYMBOL_INFO* sym_info)
442 {
443     const char* name;
444     DWORD64 size;
445
446     sym_info->TypeIndex = (DWORD)sym;
447     sym_info->info = 0; /* TBD */
448     symt_get_info(sym, TI_GET_LENGTH, &size);
449     sym_info->Size = (DWORD)size;
450     sym_info->ModBase = module->module.BaseOfImage;
451     sym_info->Flags = 0;
452     switch (sym->tag)
453     {
454     case SymTagData:
455         {
456             const struct symt_data*  data = (const struct symt_data*)sym;
457             switch (data->kind)
458             {
459             case DataIsLocal:
460             case DataIsParam:
461                 if (data->u.s.reg_id)
462                 {
463                     sym_info->Flags |= SYMFLAG_REGISTER;
464                     sym_info->Register = data->u.s.reg_id;
465                     sym_info->Address = 0;
466                 }
467                 else
468                 {
469                     if (data->u.s.offset < 0)
470                         sym_info->Flags |= SYMFLAG_LOCAL | SYMFLAG_FRAMEREL;
471                     else
472                         sym_info->Flags |= SYMFLAG_LOCAL | SYMFLAG_PARAMETER | SYMFLAG_FRAMEREL;
473                     /* FIXME: needed ? moreover, it's i386 dependent !!! */
474                     sym_info->Register = CV_REG_EBP;
475                     sym_info->Address = data->u.s.offset / 8;
476                 }
477                 break;
478             case DataIsGlobal:
479             case DataIsFileStatic:
480                 symt_get_info(sym, TI_GET_ADDRESS, &sym_info->Address);
481                 sym_info->Register = 0;
482                 break;
483             case DataIsConstant:
484                 sym_info->Flags |= SYMFLAG_VALUEPRESENT;
485                 switch (data->u.value.n1.n2.vt)
486                 {
487                 case VT_I4:  sym_info->Value = (ULONG)data->u.value.n1.n2.n3.lVal; break;
488                 case VT_I2:  sym_info->Value = (ULONG)(long)data->u.value.n1.n2.n3.iVal; break;
489                 case VT_I1:  sym_info->Value = (ULONG)(long)data->u.value.n1.n2.n3.cVal; break;
490                 case VT_UI4: sym_info->Value = (ULONG)data->u.value.n1.n2.n3.ulVal; break;
491                 case VT_UI2: sym_info->Value = (ULONG)data->u.value.n1.n2.n3.uiVal; break;
492                 case VT_UI1: sym_info->Value = (ULONG)data->u.value.n1.n2.n3.bVal; break;
493                 default:        
494                     FIXME("Unsupported variant type (%u)\n", data->u.value.n1.n2.vt);
495                 }
496                 break;
497             default:
498                 FIXME("Unhandled kind (%u) in sym data\n", data->kind);
499             }
500         }
501         break;
502     case SymTagPublicSymbol:
503         sym_info->Flags |= SYMFLAG_EXPORT;
504         symt_get_info(sym, TI_GET_ADDRESS, &sym_info->Address);
505         break;
506     case SymTagFunction:
507         sym_info->Flags |= SYMFLAG_FUNCTION;
508         symt_get_info(sym, TI_GET_ADDRESS, &sym_info->Address);
509         break;
510     case SymTagThunk:
511         sym_info->Flags |= SYMFLAG_THUNK;
512         symt_get_info(sym, TI_GET_ADDRESS, &sym_info->Address);
513         break;
514     default:
515         symt_get_info(sym, TI_GET_ADDRESS, &sym_info->Address);
516         sym_info->Register = 0;
517         break;
518     }
519     sym_info->Scope = 0; /* FIXME */
520     sym_info->Tag = sym->tag;
521     name = symt_get_name(sym);
522     if (sym_info->MaxNameLen)
523     {
524         if (sym->tag != SymTagPublicSymbol || !(dbghelp_options & SYMOPT_UNDNAME) ||
525             (sym_info->NameLen = UnDecorateSymbolName(name, sym_info->Name, 
526                                                       sym_info->MaxNameLen, UNDNAME_COMPLETE) == 0))
527         {
528             sym_info->NameLen = min(strlen(name), sym_info->MaxNameLen - 1);
529             memcpy(sym_info->Name, name, sym_info->NameLen);
530             sym_info->Name[sym_info->NameLen] = '\0';
531         }
532     }
533     TRACE_(dbghelp_symt)("%p => %s %lu %s\n",
534                          sym, sym_info->Name, sym_info->Size,
535                          wine_dbgstr_longlong(sym_info->Address));
536 }
537
538 static BOOL symt_enum_module(struct module* module, regex_t* regex,
539                              PSYM_ENUMERATESYMBOLS_CALLBACK cb, PVOID user)
540 {
541     char                        buffer[sizeof(SYMBOL_INFO) + 256];
542     SYMBOL_INFO*                sym_info = (SYMBOL_INFO*)buffer;
543     void*                       ptr;
544     struct symt_ht*             sym = NULL;
545     struct hash_table_iter      hti;
546
547     hash_table_iter_init(&module->ht_symbols, &hti, NULL);
548     while ((ptr = hash_table_iter_up(&hti)))
549     {
550         sym = GET_ENTRY(ptr, struct symt_ht, hash_elt);
551         if (sym->hash_elt.name &&
552             regexec(regex, sym->hash_elt.name, 0, NULL, 0) == 0)
553         {
554             sym_info->SizeOfStruct = sizeof(SYMBOL_INFO);
555             sym_info->MaxNameLen = sizeof(buffer) - sizeof(SYMBOL_INFO);
556             symt_fill_sym_info(module, &sym->symt, sym_info);
557             if (!cb(sym_info, sym_info->Size, user)) return TRUE;
558         }
559     }   
560     return FALSE;
561 }
562
563 /***********************************************************************
564  *              resort_symbols
565  *
566  * Rebuild sorted list of symbols for a module.
567  */
568 static BOOL resort_symbols(struct module* module)
569 {
570     int                         nsym = 0;
571     void*                       ptr;
572     struct symt_ht*             sym;
573     struct hash_table_iter      hti;
574
575     hash_table_iter_init(&module->ht_symbols, &hti, NULL);
576     while ((ptr = hash_table_iter_up(&hti)))
577         nsym++;
578
579     if (!(module->module.NumSyms = nsym)) return FALSE;
580     
581     if (module->addr_sorttab)
582         module->addr_sorttab = HeapReAlloc(GetProcessHeap(), 0,
583                                            module->addr_sorttab, 
584                                            nsym * sizeof(struct symt_ht*));
585     else
586         module->addr_sorttab = HeapAlloc(GetProcessHeap(), 0,
587                                          nsym * sizeof(struct symt_ht*));
588     if (!module->addr_sorttab) return FALSE;
589
590     nsym = 0;
591     hash_table_iter_init(&module->ht_symbols, &hti, NULL);
592     while ((ptr = hash_table_iter_up(&hti)))
593     {
594         sym = GET_ENTRY(ptr, struct symt_ht, hash_elt);
595         assert(sym);
596         module->addr_sorttab[nsym++] = sym;
597     }
598     
599     qsort(module->addr_sorttab, nsym, sizeof(struct symt_ht*), symt_cmp_addr);
600     return module->sortlist_valid = TRUE;
601 }
602
603 /* assume addr is in module */
604 int symt_find_nearest(struct module* module, DWORD addr)
605 {
606     int         mid, high, low;
607     ULONG64     ref_addr, ref_size;
608
609     if (!module->sortlist_valid || !module->addr_sorttab)
610     {
611         if (!resort_symbols(module)) return -1;
612     }
613
614     /*
615      * Binary search to find closest symbol.
616      */
617     low = 0;
618     high = module->module.NumSyms;
619
620     symt_get_info(&module->addr_sorttab[0]->symt, TI_GET_ADDRESS, &ref_addr);
621     if (addr < ref_addr) return -1;
622     if (high)
623     {
624         symt_get_info(&module->addr_sorttab[high - 1]->symt, TI_GET_ADDRESS, &ref_addr);
625         if (!symt_get_info(&module->addr_sorttab[high - 1]->symt,  TI_GET_LENGTH, &ref_size) || !ref_size)
626             ref_size = 0x1000; /* arbitrary value */
627         if (addr >= ref_addr + ref_size) return -1;
628     }
629     
630     while (high > low + 1)
631     {
632         mid = (high + low) / 2;
633         if (cmp_sorttab_addr(module, mid, addr) < 0)
634             low = mid;
635         else
636             high = mid;
637     }
638     if (low != high && high != module->module.NumSyms && 
639         cmp_sorttab_addr(module, high, addr) <= 0)
640         low = high;
641
642     /* If found symbol is a public symbol, check if there are any other entries that
643      * might also have the same address, but would get better information
644      */
645     if (module->addr_sorttab[low]->symt.tag == SymTagPublicSymbol)
646     {   
647         symt_get_info(&module->addr_sorttab[low]->symt, TI_GET_ADDRESS, &ref_addr);
648         if (low > 0 &&
649             module->addr_sorttab[low - 1]->symt.tag != SymTagPublicSymbol &&
650             !cmp_sorttab_addr(module, low - 1, ref_addr))
651             low--;
652         else if (low < module->module.NumSyms - 1 && 
653                  module->addr_sorttab[low + 1]->symt.tag != SymTagPublicSymbol &&
654                  !cmp_sorttab_addr(module, low + 1, ref_addr))
655             low++;
656     }
657     /* finally check that we fit into the found symbol */
658     symt_get_info(&module->addr_sorttab[low]->symt, TI_GET_ADDRESS, &ref_addr);
659     if (addr < ref_addr) return -1;
660     if (!symt_get_info(&module->addr_sorttab[high - 1]->symt, TI_GET_LENGTH, &ref_size) || !ref_size)
661         ref_size = 0x1000; /* arbitrary value */
662     if (addr >= ref_addr + ref_size) return -1;
663
664     return low;
665 }
666
667 static BOOL symt_enum_locals_helper(struct process* pcs, struct module* module,
668                                     regex_t* preg, PSYM_ENUMERATESYMBOLS_CALLBACK cb,
669                                     PVOID user, SYMBOL_INFO* sym_info,
670                                     struct vector* v)
671 {
672     struct symt**       plsym = NULL;
673     struct symt*        lsym = NULL;
674     DWORD               pc = pcs->ctx_frame.InstructionOffset;
675
676     while ((plsym = vector_iter_up(v, plsym)))
677     {
678         lsym = *plsym;
679         switch (lsym->tag)
680         {
681         case SymTagBlock:
682             {
683                 struct symt_block*  block = (struct symt_block*)lsym;
684                 if (pc < block->address || block->address + block->size <= pc)
685                     continue;
686                 if (!symt_enum_locals_helper(pcs, module, preg, cb, user, 
687                                              sym_info, &block->vchildren))
688                     return FALSE;
689             }
690             break;
691         case SymTagData:
692             if (regexec(preg, symt_get_name(lsym), 0, NULL, 0) == 0)
693             {
694                 symt_fill_sym_info(module, lsym, sym_info);
695                 if (!cb(sym_info, sym_info->Size, user))
696                     return FALSE;
697             }
698             break;
699         case SymTagLabel:
700         case SymTagFuncDebugStart:
701         case SymTagFuncDebugEnd:
702             break;
703         default:
704             FIXME("Unknown type: %u (%x)\n", lsym->tag, lsym->tag);
705             assert(0);
706         }
707     }
708     return TRUE;
709 }
710
711 static BOOL symt_enum_locals(struct process* pcs, const char* mask,
712                              PSYM_ENUMERATESYMBOLS_CALLBACK EnumSymbolsCallback,
713                              PVOID UserContext)
714 {
715     struct module*      module;
716     struct symt_ht*     sym;
717     char                buffer[sizeof(SYMBOL_INFO) + 256];
718     SYMBOL_INFO*        sym_info = (SYMBOL_INFO*)buffer;
719     DWORD               pc = pcs->ctx_frame.InstructionOffset;
720     int                 idx;
721
722     sym_info->SizeOfStruct = sizeof(*sym_info);
723     sym_info->MaxNameLen = sizeof(buffer) - sizeof(SYMBOL_INFO);
724
725     module = module_find_by_addr(pcs, pc, DMT_UNKNOWN);
726     if (!(module = module_get_debug(pcs, module))) return FALSE;
727     if ((idx = symt_find_nearest(module, pc)) == -1) return FALSE;
728
729     sym = module->addr_sorttab[idx];
730     if (sym->symt.tag == SymTagFunction)
731     {
732         BOOL            ret;
733         regex_t         preg;
734
735         compile_regex(mask ? mask : "*", -1, &preg);
736         ret = symt_enum_locals_helper(pcs, module, &preg, EnumSymbolsCallback, 
737                                       UserContext, sym_info, 
738                                       &((struct symt_function*)sym)->vchildren);
739         regfree(&preg);
740         return ret;
741         
742     }
743     symt_fill_sym_info(module, &sym->symt, sym_info);
744     return EnumSymbolsCallback(sym_info, sym_info->Size, UserContext);
745 }
746
747 /******************************************************************
748  *              SymEnumSymbols (DBGHELP.@)
749  *
750  * cases BaseOfDll = 0
751  *      !foo fails always (despite what MSDN states)
752  *      RE1!RE2 looks up all modules matching RE1, and in all these modules, lookup RE2
753  *      no ! in Mask, lookup in local Context
754  * cases BaseOfDll != 0
755  *      !foo fails always (despite what MSDN states)
756  *      RE1!RE2 gets RE2 from BaseOfDll (whatever RE1 is)
757  */
758 BOOL WINAPI SymEnumSymbols(HANDLE hProcess, ULONG64 BaseOfDll, PCSTR Mask,
759                            PSYM_ENUMERATESYMBOLS_CALLBACK EnumSymbolsCallback,
760                            PVOID UserContext)
761 {
762     struct process*     pcs = process_find_by_handle(hProcess);
763     struct module*      module;
764     struct module*      dbg_module;
765     const char*         bang;
766     regex_t             mod_regex, sym_regex;
767
768     TRACE("(%p %s %s %p %p)\n", 
769           hProcess, wine_dbgstr_longlong(BaseOfDll), debugstr_a(Mask),
770           EnumSymbolsCallback, UserContext);
771
772     if (!pcs) return FALSE;
773
774     if (BaseOfDll == 0)
775     {
776         /* do local variables ? */
777         if (!Mask || !(bang = strchr(Mask, '!')))
778             return symt_enum_locals(pcs, Mask, EnumSymbolsCallback, UserContext);
779
780         if (bang == Mask) return FALSE;
781
782         compile_regex(Mask, bang - Mask, &mod_regex);
783         compile_regex(bang + 1, -1, &sym_regex);
784         
785         for (module = pcs->lmodules; module; module = module->next)
786         {
787             if (module->type == DMT_PE && (dbg_module = module_get_debug(pcs, module)))
788             {
789                 if (regexec(&mod_regex, module->module.ModuleName, 0, NULL, 0) == 0 &&
790                     symt_enum_module(dbg_module, &sym_regex, 
791                                      EnumSymbolsCallback, UserContext))
792                     break;
793             }
794         }
795         /* not found in PE modules, retry on the ELF ones
796          */
797         if (!module && (dbghelp_options & SYMOPT_WINE_WITH_ELF_MODULES))
798         {
799             for (module = pcs->lmodules; module; module = module->next)
800             {
801                 if (module->type == DMT_ELF &&
802                     !module_get_containee(pcs, module) &&
803                     (dbg_module = module_get_debug(pcs, module)))
804                 {
805                     if (regexec(&mod_regex, module->module.ModuleName, 0, NULL, 0) == 0 &&
806                         symt_enum_module(dbg_module, &sym_regex, EnumSymbolsCallback, UserContext))
807                     break;
808                 }
809             }
810         }
811         regfree(&mod_regex);
812         regfree(&sym_regex);
813         return TRUE;
814     }
815     module = module_find_by_addr(pcs, BaseOfDll, DMT_UNKNOWN);
816     if (!(module = module_get_debug(pcs, module)))
817         return FALSE;
818
819     /* we always ignore module name from Mask when BaseOfDll is defined */
820     if (Mask && (bang = strchr(Mask, '!')))
821     {
822         if (bang == Mask) return FALSE;
823         Mask = bang + 1;
824     }
825
826     compile_regex(Mask ? Mask : "*", -1, &sym_regex);
827     symt_enum_module(module, &sym_regex, EnumSymbolsCallback, UserContext);
828     regfree(&sym_regex);
829
830     return TRUE;
831 }
832
833 struct sym_enumerate
834 {
835     void*                       ctx;
836     PSYM_ENUMSYMBOLS_CALLBACK   cb;
837 };
838
839 static BOOL CALLBACK sym_enumerate_cb(PSYMBOL_INFO syminfo, ULONG size, void* ctx)
840 {
841     struct sym_enumerate*       se = (struct sym_enumerate*)ctx;
842     return (se->cb)(syminfo->Name, syminfo->Address, syminfo->Size, se->ctx);
843 }
844
845 /***********************************************************************
846  *              SymEnumerateSymbols (DBGHELP.@)
847  */
848 BOOL WINAPI SymEnumerateSymbols(HANDLE hProcess, DWORD BaseOfDll,
849                                 PSYM_ENUMSYMBOLS_CALLBACK EnumSymbolsCallback, 
850                                 PVOID UserContext)
851 {
852     struct sym_enumerate        se;
853
854     se.ctx = UserContext;
855     se.cb  = EnumSymbolsCallback;
856     
857     return SymEnumSymbols(hProcess, BaseOfDll, NULL, sym_enumerate_cb, &se);
858 }
859
860 /******************************************************************
861  *              SymFromAddr (DBGHELP.@)
862  *
863  */
864 BOOL WINAPI SymFromAddr(HANDLE hProcess, DWORD64 Address, 
865                         DWORD64* Displacement, PSYMBOL_INFO Symbol)
866 {
867     struct process*     pcs = process_find_by_handle(hProcess);
868     struct module*      module;
869     struct symt_ht*     sym;
870     int                 idx;
871
872     if (!pcs) return FALSE;
873     module = module_find_by_addr(pcs, Address, DMT_UNKNOWN);
874     if (!(module = module_get_debug(pcs, module))) return FALSE;
875     if ((idx = symt_find_nearest(module, Address)) == -1) return FALSE;
876
877     sym = module->addr_sorttab[idx];
878
879     symt_fill_sym_info(module, &sym->symt, Symbol);
880     *Displacement = Address - Symbol->Address;
881     return TRUE;
882 }
883
884 /******************************************************************
885  *              SymGetSymFromAddr (DBGHELP.@)
886  *
887  */
888 BOOL WINAPI SymGetSymFromAddr(HANDLE hProcess, DWORD Address,
889                               PDWORD Displacement, PIMAGEHLP_SYMBOL Symbol)
890 {
891     char        buffer[sizeof(SYMBOL_INFO) + 256];
892     SYMBOL_INFO*si = (SYMBOL_INFO*)buffer;
893     size_t      len;
894     DWORD64     Displacement64;
895
896     if (Symbol->SizeOfStruct < sizeof(*Symbol)) return FALSE;
897     si->SizeOfStruct = sizeof(*si);
898     si->MaxNameLen = 256;
899     if (!SymFromAddr(hProcess, Address, &Displacement64, si))
900         return FALSE;
901
902     if (Displacement)
903         *Displacement = Displacement64;
904     Symbol->Address = si->Address;
905     Symbol->Size    = si->Size;
906     Symbol->Flags   = si->Flags;
907     len = min(Symbol->MaxNameLength, si->MaxNameLen);
908     lstrcpynA(Symbol->Name, si->Name, len);
909     return TRUE;
910 }
911
912 /******************************************************************
913  *              SymFromName (DBGHELP.@)
914  *
915  */
916 BOOL WINAPI SymFromName(HANDLE hProcess, LPSTR Name, PSYMBOL_INFO Symbol)
917 {
918     struct process*             pcs = process_find_by_handle(hProcess);
919     struct module*              module;
920     struct hash_table_iter      hti;
921     void*                       ptr;
922     struct symt_ht*             sym = NULL;
923     const char*                 name;
924
925     TRACE("(%p, %s, %p)\n", hProcess, Name, Symbol);
926     if (!pcs) return FALSE;
927     if (Symbol->SizeOfStruct < sizeof(*Symbol)) return FALSE;
928     name = strchr(Name, '!');
929     if (name)
930     {
931         char    tmp[128];
932         assert(name - Name < sizeof(tmp));
933         memcpy(tmp, Name, name - Name);
934         tmp[name - Name] = '\0';
935         module = module_find_by_name(pcs, tmp, DMT_UNKNOWN);
936         if (!module) return FALSE;
937         Name = (char*)(name + 1);
938     }
939     else module = pcs->lmodules;
940
941     /* FIXME: Name could be made out of a regular expression */
942     for (; module; module = (name) ? NULL : module->next)
943     {
944         if (module->module.SymType == SymNone) continue;
945         if (module->module.SymType == SymDeferred)
946         {
947             struct module*      xmodule = module_get_debug(pcs, module);
948             if (!xmodule || xmodule != module) continue;
949         }
950         hash_table_iter_init(&module->ht_symbols, &hti, Name);
951         while ((ptr = hash_table_iter_up(&hti)))
952         {
953             sym = GET_ENTRY(ptr, struct symt_ht, hash_elt);
954
955             if (!strcmp(sym->hash_elt.name, Name))
956             {
957                 symt_fill_sym_info(module, &sym->symt, Symbol);
958                 return TRUE;
959             }
960         }
961     }
962     return FALSE;
963 }
964
965 /***********************************************************************
966  *              SymGetSymFromName (DBGHELP.@)
967  */
968 BOOL WINAPI SymGetSymFromName(HANDLE hProcess, LPSTR Name, PIMAGEHLP_SYMBOL Symbol)
969 {
970     char        buffer[sizeof(SYMBOL_INFO) + 256];
971     SYMBOL_INFO*si = (SYMBOL_INFO*)buffer;
972     size_t      len;
973
974     if (Symbol->SizeOfStruct < sizeof(*Symbol)) return FALSE;
975     si->SizeOfStruct = sizeof(*si);
976     si->MaxNameLen = 256;
977     if (!SymFromName(hProcess, Name, si)) return FALSE;
978
979     Symbol->Address = si->Address;
980     Symbol->Size    = si->Size;
981     Symbol->Flags   = si->Flags;
982     len = min(Symbol->MaxNameLength, si->MaxNameLen);
983     lstrcpynA(Symbol->Name, si->Name, len);
984     return TRUE;
985 }
986
987 /******************************************************************
988  *              sym_fill_func_line_info
989  *
990  * fills information about a file
991  */
992 BOOL symt_fill_func_line_info(struct module* module, struct symt_function* func, 
993                               DWORD addr, IMAGEHLP_LINE* line)
994 {
995     struct line_info*   dli = NULL;
996     BOOL                found = FALSE;
997
998     assert(func->symt.tag == SymTagFunction);
999
1000     while ((dli = vector_iter_down(&func->vlines, dli)))
1001     {
1002         if (!dli->is_source_file)
1003         {
1004             if (found || dli->u.pc_offset > addr) continue;
1005             line->LineNumber = dli->line_number;
1006             line->Address    = dli->u.pc_offset;
1007             line->Key        = dli;
1008             found = TRUE;
1009             continue;
1010         }
1011         if (found)
1012         {
1013             line->FileName = (char*)source_get(module, dli->u.source_file);
1014             return TRUE;
1015         }
1016     }
1017     return FALSE;
1018 }
1019
1020 /***********************************************************************
1021  *              SymGetSymNext (DBGHELP.@)
1022  */
1023 BOOL WINAPI SymGetSymNext(HANDLE hProcess, PIMAGEHLP_SYMBOL Symbol)
1024 {
1025     /* algo:
1026      * get module from Symbol.Address
1027      * get index in module.addr_sorttab of Symbol.Address
1028      * increment index
1029      * if out of module bounds, move to next module in process address space
1030      */
1031     FIXME("(%p, %p): stub\n", hProcess, Symbol);
1032     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1033     return FALSE;
1034 }
1035
1036 /***********************************************************************
1037  *              SymGetSymPrev (DBGHELP.@)
1038  */
1039
1040 BOOL WINAPI SymGetSymPrev(HANDLE hProcess, PIMAGEHLP_SYMBOL Symbol)
1041 {
1042     FIXME("(%p, %p): stub\n", hProcess, Symbol);
1043     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1044     return FALSE;
1045 }
1046
1047 /******************************************************************
1048  *              SymGetLineFromAddr (DBGHELP.@)
1049  *
1050  */
1051 BOOL WINAPI SymGetLineFromAddr(HANDLE hProcess, DWORD dwAddr, 
1052                                PDWORD pdwDisplacement, PIMAGEHLP_LINE Line)
1053 {
1054     struct process*     pcs = process_find_by_handle(hProcess);
1055     struct module*      module;
1056     int                 idx;
1057
1058     TRACE("%p %08lx %p %p\n", hProcess, dwAddr, pdwDisplacement, Line);
1059
1060     if (Line->SizeOfStruct < sizeof(*Line)) return FALSE;
1061
1062     if (!pcs) return FALSE;
1063     module = module_find_by_addr(pcs, dwAddr, DMT_UNKNOWN);
1064     if (!(module = module_get_debug(pcs, module))) return FALSE;
1065     if ((idx = symt_find_nearest(module, dwAddr)) == -1) return FALSE;
1066
1067     if (module->addr_sorttab[idx]->symt.tag != SymTagFunction) return FALSE;
1068     if (!symt_fill_func_line_info(module, 
1069                                   (struct symt_function*)module->addr_sorttab[idx],
1070                                   dwAddr, Line)) return FALSE;
1071     *pdwDisplacement = dwAddr - Line->Address;
1072     return TRUE;
1073 }
1074
1075 /******************************************************************
1076  *              SymGetLinePrev (DBGHELP.@)
1077  *
1078  */
1079 BOOL WINAPI SymGetLinePrev(HANDLE hProcess, PIMAGEHLP_LINE Line)
1080 {
1081     struct process*     pcs = process_find_by_handle(hProcess);
1082     struct module*      module;
1083     struct line_info*   li;
1084     BOOL                in_search = FALSE;
1085
1086     TRACE("(%p %p)\n", hProcess, Line);
1087
1088     if (Line->SizeOfStruct < sizeof(*Line)) return FALSE;
1089
1090     if (!pcs) return FALSE;
1091     module = module_find_by_addr(pcs, Line->Address, DMT_UNKNOWN);
1092     if (!(module = module_get_debug(pcs, module))) return FALSE;
1093
1094     if (Line->Key == 0) return FALSE;
1095     li = (struct line_info*)Line->Key;
1096     /* things are a bit complicated because when we encounter a DLIT_SOURCEFILE
1097      * element we have to go back until we find the prev one to get the real
1098      * source file name for the DLIT_OFFSET element just before 
1099      * the first DLIT_SOURCEFILE
1100      */
1101     while (!li->is_first)
1102     {
1103         li--;
1104         if (!li->is_source_file)
1105         {
1106             Line->LineNumber = li->line_number;
1107             Line->Address    = li->u.pc_offset;
1108             Line->Key        = li;
1109             if (!in_search) return TRUE;
1110         }
1111         else
1112         {
1113             if (in_search)
1114             {
1115                 Line->FileName = (char*)source_get(module, li->u.source_file);
1116                 return TRUE;
1117             }
1118             in_search = TRUE;
1119         }
1120     }
1121     SetLastError(ERROR_NO_MORE_ITEMS); /* FIXME */
1122     return FALSE;
1123 }
1124
1125 BOOL symt_get_func_line_next(struct module* module, PIMAGEHLP_LINE line)
1126 {
1127     struct line_info*   li;
1128
1129     if (line->Key == 0) return FALSE;
1130     li = (struct line_info*)line->Key;
1131     while (!li->is_last)
1132     {
1133         li++;
1134         if (!li->is_source_file)
1135         {
1136             line->LineNumber = li->line_number;
1137             line->Address    = li->u.pc_offset;
1138             line->Key        = li;
1139             return TRUE;
1140         }
1141         line->FileName = (char*)source_get(module, li->u.source_file);
1142     }
1143     return FALSE;
1144 }
1145
1146 /******************************************************************
1147  *              SymGetLineNext (DBGHELP.@)
1148  *
1149  */
1150 BOOL WINAPI SymGetLineNext(HANDLE hProcess, PIMAGEHLP_LINE Line)
1151 {
1152     struct process*     pcs = process_find_by_handle(hProcess);
1153     struct module*      module;
1154
1155     TRACE("(%p %p)\n", hProcess, Line);
1156
1157     if (Line->SizeOfStruct < sizeof(*Line)) return FALSE;
1158     if (!pcs) return FALSE;
1159     module = module_find_by_addr(pcs, Line->Address, DMT_UNKNOWN);
1160     if (!(module = module_get_debug(pcs, module))) return FALSE;
1161
1162     if (symt_get_func_line_next(module, Line)) return TRUE;
1163     SetLastError(ERROR_NO_MORE_ITEMS); /* FIXME */
1164     return FALSE;
1165 }
1166
1167 /***********************************************************************
1168  *              SymFunctionTableAccess (DBGHELP.@)
1169  */
1170 PVOID WINAPI SymFunctionTableAccess(HANDLE hProcess, DWORD AddrBase)
1171 {
1172     FIXME("(%p, 0x%08lx): stub\n", hProcess, AddrBase);
1173     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1174     return FALSE;
1175 }
1176
1177 /***********************************************************************
1178  *              SymUnDName (DBGHELP.@)
1179  */
1180 BOOL WINAPI SymUnDName(PIMAGEHLP_SYMBOL sym, LPSTR UnDecName, DWORD UnDecNameLength)
1181 {
1182     TRACE("(%p %s %lu): stub\n", sym, UnDecName, UnDecNameLength);
1183     return UnDecorateSymbolName(sym->Name, UnDecName, UnDecNameLength, 
1184                                 UNDNAME_COMPLETE) != 0;
1185 }
1186
1187 static void* und_alloc(size_t len) { return HeapAlloc(GetProcessHeap(), 0, len); }
1188 static void  und_free (void* ptr)  { HeapFree(GetProcessHeap(), 0, ptr); }
1189
1190 /***********************************************************************
1191  *              UnDecorateSymbolName (DBGHELP.@)
1192  */
1193 DWORD WINAPI UnDecorateSymbolName(LPCSTR DecoratedName, LPSTR UnDecoratedName,
1194                                   DWORD UndecoratedLength, DWORD Flags)
1195 {
1196     /* undocumented from msvcrt */
1197     static char* (*p_undname)(char*, const char*, int, void* (*)(size_t), void (*)(void*), unsigned short);
1198     static WCHAR szMsvcrt[] = {'m','s','v','c','r','t','.','d','l','l',0};
1199
1200     TRACE("(%s, %p, %ld, 0x%08lx): stub\n",
1201           debugstr_a(DecoratedName), UnDecoratedName, UndecoratedLength, Flags);
1202
1203     if (!p_undname)
1204     {
1205         if (!hMsvcrt) hMsvcrt = LoadLibraryW(szMsvcrt);
1206         if (hMsvcrt) p_undname = (void*)GetProcAddress(hMsvcrt, "__unDName");
1207         if (!p_undname) return 0;
1208     }
1209
1210     if (!UnDecoratedName) return 0;
1211     if (!p_undname(UnDecoratedName, DecoratedName, UndecoratedLength, 
1212                    und_alloc, und_free, Flags))
1213         return 0;
1214     return strlen(UnDecoratedName);
1215 }