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