symbol.c 73.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/*
 * File symbol.c - management of symbols (lexical tree)
 *
 * Copyright (C) 1993, Eric Youngdale.
 *               2004, Eric Pouech
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20 21
 */

22
#define NONAMELESSUNION
23

24
#include "config.h"
25

26 27 28 29 30 31 32
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <limits.h>
#include <sys/types.h>
#include <assert.h>

33
#include "wine/debug.h"
34
#include "dbghelp_private.h"
35
#include "winnls.h"
36 37

WINE_DEFAULT_DEBUG_CHANNEL(dbghelp);
38
WINE_DECLARE_DEBUG_CHANNEL(dbghelp_symt);
39

40
static const WCHAR starW[] = {'*','\0'};
41

42
static inline int cmp_addr(ULONG64 a1, ULONG64 a2)
43 44 45 46 47 48
{
    if (a1 > a2) return 1;
    if (a1 < a2) return -1;
    return 0;
}

49
static inline int cmp_sorttab_addr(struct module* module, int idx, ULONG64 addr)
50
{
51
    ULONG64     ref;
52
    symt_get_address(&module->addr_sorttab[idx]->symt, &ref);
53 54 55 56 57
    return cmp_addr(ref, addr);
}

int symt_cmp_addr(const void* p1, const void* p2)
{
58 59
    const struct symt*  sym1 = *(const struct symt* const *)p1;
    const struct symt*  sym2 = *(const struct symt* const *)p2;
60
    ULONG64     a1, a2;
61

62 63
    symt_get_address(sym1, &a1);
    symt_get_address(sym2, &a2);
64 65 66
    return cmp_addr(a1, a2);
}

67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
DWORD             symt_ptr2index(struct module* module, const struct symt* sym)
{
#ifdef _WIN64
    const struct symt** c;
    int                 len = vector_length(&module->vsymt), i;

    /* FIXME: this is inefficient */
    for (i = 0; i < len; i++)
    {
        if (*(struct symt**)vector_at(&module->vsymt, i) == sym)
            return i + 1;
    }
    /* not found */
    c = vector_add(&module->vsymt, &module->pool);
    if (c) *c = sym;
    return len + 1;
#else
    return (DWORD)sym;
#endif
}

struct symt*      symt_index2ptr(struct module* module, DWORD id)
{
#ifdef _WIN64
    if (!id-- || id >= vector_length(&module->vsymt)) return NULL;
    return *(struct symt**)vector_at(&module->vsymt, id);
#else
    return (struct symt*)id;
#endif
}

98 99 100
static BOOL symt_grow_sorttab(struct module* module, unsigned sz)
{
    struct symt_ht**    new;
101
    unsigned int size;
102

103
    if (sz <= module->sorttab_size) return TRUE;
104
    if (module->addr_sorttab)
105 106
    {
        size = module->sorttab_size * 2;
107
        new = HeapReAlloc(GetProcessHeap(), 0, module->addr_sorttab,
108 109
                          size * sizeof(struct symt_ht*));
    }
110
    else
111 112 113 114
    {
        size = 64;
        new = HeapAlloc(GetProcessHeap(), 0, size * sizeof(struct symt_ht*));
    }
115
    if (!new) return FALSE;
116
    module->sorttab_size = size;
117 118 119 120
    module->addr_sorttab = new;
    return TRUE;
}

121 122
static void symt_add_module_ht(struct module* module, struct symt_ht* ht)
{
123 124
    ULONG64             addr;

125
    hash_table_add(&module->ht_symbols, &ht->hash_elt);
126 127 128
    /* Don't store in sorttab a symbol without address, they are of
     * no use here (e.g. constant values)
     */
129
    if (symt_get_address(&ht->symt, &addr) &&
130 131 132 133 134
        symt_grow_sorttab(module, module->num_symbols + 1))
    {
        module->addr_sorttab[module->num_symbols++] = ht;
        module->sortlist_valid = FALSE;
    }
135 136
}

137
static WCHAR* file_regex(const char* srcfile)
138
{
139 140
    WCHAR* mask;
    WCHAR* p;
141

142
    if (!srcfile || !*srcfile)
143
    {
144 145 146
        if (!(p = mask = HeapAlloc(GetProcessHeap(), 0, 3 * sizeof(WCHAR)))) return NULL;
        *p++ = '?';
        *p++ = '#';
147
    }
148
    else
149
    {
150 151
        DWORD  sz = MultiByteToWideChar(CP_ACP, 0, srcfile, -1, NULL, 0);
        WCHAR* srcfileW;
152

153 154 155 156 157
        /* FIXME: we use here the largest conversion for every char... could be optimized */
        p = mask = HeapAlloc(GetProcessHeap(), 0, (5 * strlen(srcfile) + 1 + sz) * sizeof(WCHAR));
        if (!mask) return NULL;
        srcfileW = mask + 5 * strlen(srcfile) + 1;
        MultiByteToWideChar(CP_ACP, 0, srcfile, -1, srcfileW, sz);
158

159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
        while (*srcfileW)
        {
            switch (*srcfileW)
            {
            case '\\':
            case '/':
                *p++ = '[';
                *p++ = '\\';
                *p++ = '\\';
                *p++ = '/';
                *p++ = ']';
                break;
            case '.':
                *p++ = '?';
                break;
            default:
                *p++ = *srcfileW;
                break;
            }
            srcfileW++;
        }
    }
    *p = 0;
    return mask;
183 184
}

185 186
struct symt_compiland* symt_new_compiland(struct module* module, 
                                          unsigned long address, unsigned src_idx)
187 188 189
{
    struct symt_compiland*    sym;

190
    TRACE_(dbghelp_symt)("Adding compiland symbol %s:%s\n",
191
                         debugstr_w(module->module.ModuleName), source_get(module, src_idx));
192 193 194
    if ((sym = pool_alloc(&module->pool, sizeof(*sym))))
    {
        sym->symt.tag = SymTagCompiland;
195
        sym->address  = address;
196
        sym->source   = src_idx;
197 198 199 200 201 202 203 204
        vector_init(&sym->vchildren, sizeof(struct symt*), 32);
    }
    return sym;
}

struct symt_public* symt_new_public(struct module* module, 
                                    struct symt_compiland* compiland,
                                    const char* name,
205
                                    unsigned long address, unsigned size)
206 207 208 209
{
    struct symt_public* sym;
    struct symt**       p;

210
    TRACE_(dbghelp_symt)("Adding public symbol %s:%s @%lx\n",
211
                         debugstr_w(module->module.ModuleName), name, address);
212
    if ((dbghelp_options & SYMOPT_AUTO_PUBLICS) &&
213
        symt_find_nearest(module, address) != NULL)
214
        return NULL;
215 216 217 218 219 220 221
    if ((sym = pool_alloc(&module->pool, sizeof(*sym))))
    {
        sym->symt.tag      = SymTagPublicSymbol;
        sym->hash_elt.name = pool_strdup(&module->pool, name);
        sym->container     = compiland ? &compiland->symt : NULL;
        sym->address       = address;
        sym->size          = size;
222
        symt_add_module_ht(module, (struct symt_ht*)sym);
223 224 225 226 227 228 229 230 231 232 233 234
        if (compiland)
        {
            p = vector_add(&compiland->vchildren, &module->pool);
            *p = &sym->symt;
        }
    }
    return sym;
}

struct symt_data* symt_new_global_variable(struct module* module, 
                                           struct symt_compiland* compiland, 
                                           const char* name, unsigned is_static,
235
                                           struct location loc, unsigned long size,
236 237 238 239
                                           struct symt* type)
{
    struct symt_data*   sym;
    struct symt**       p;
240
    DWORD64             tsz;
241

242 243
    TRACE_(dbghelp_symt)("Adding global symbol %s:%s %d@%lx %p\n",
                         debugstr_w(module->module.ModuleName), name, loc.kind, loc.offset, type);
244 245 246 247 248 249 250
    if ((sym = pool_alloc(&module->pool, sizeof(*sym))))
    {
        sym->symt.tag      = SymTagData;
        sym->hash_elt.name = pool_strdup(&module->pool, name);
        sym->kind          = is_static ? DataIsFileStatic : DataIsGlobal;
        sym->container     = compiland ? &compiland->symt : NULL;
        sym->type          = type;
251
        sym->u.var         = loc;
252
        if (type && size && symt_get_info(module, type, TI_GET_LENGTH, &tsz))
253 254
        {
            if (tsz != size)
255
                FIXME("Size mismatch for %s.%s between type (%s) and src (%lu)\n",
256
                      debugstr_w(module->module.ModuleName), name,
257
                      wine_dbgstr_longlong(tsz), size);
258
        }
259
        symt_add_module_ht(module, (struct symt_ht*)sym);
260 261 262 263 264 265 266 267 268 269 270 271 272
        if (compiland)
        {
            p = vector_add(&compiland->vchildren, &module->pool);
            *p = &sym->symt;
        }
    }
    return sym;
}

struct symt_function* symt_new_function(struct module* module, 
                                        struct symt_compiland* compiland, 
                                        const char* name,
                                        unsigned long addr, unsigned long size,
273
                                        struct symt* sig_type)
274 275 276 277
{
    struct symt_function*       sym;
    struct symt**               p;

278
    TRACE_(dbghelp_symt)("Adding global function %s:%s @%lx-%lx\n",
279
                         debugstr_w(module->module.ModuleName), name, addr, addr + size - 1);
280 281

    assert(!sig_type || sig_type->tag == SymTagFunctionType);
282 283 284 285 286
    if ((sym = pool_alloc(&module->pool, sizeof(*sym))))
    {
        sym->symt.tag  = SymTagFunction;
        sym->hash_elt.name = pool_strdup(&module->pool, name);
        sym->container = &compiland->symt;
287
        sym->address   = addr;
288
        sym->type      = sig_type;
289 290 291
        sym->size      = size;
        vector_init(&sym->vlines,  sizeof(struct line_info), 64);
        vector_init(&sym->vchildren, sizeof(struct symt*), 8);
292
        symt_add_module_ht(module, (struct symt_ht*)sym);
293 294 295 296 297 298 299 300 301 302 303 304 305 306
        if (compiland)
        {
            p = vector_add(&compiland->vchildren, &module->pool);
            *p = &sym->symt;
        }
    }
    return sym;
}

void symt_add_func_line(struct module* module, struct symt_function* func,
                        unsigned source_idx, int line_num, unsigned long offset)
{
    struct line_info*   dli;
    BOOL                last_matches = FALSE;
307
    int                 i;
308 309 310

    if (func == NULL || !(dbghelp_options & SYMOPT_LOAD_LINES)) return;

311 312 313
    TRACE_(dbghelp_symt)("(%p)%s:%lx %s:%u\n", 
                         func, func->hash_elt.name, offset, 
                         source_get(module, source_idx), line_num);
314 315 316

    assert(func->symt.tag == SymTagFunction);

317
    for (i=vector_length(&func->vlines)-1; i>=0; i--)
318
    {
319
        dli = vector_at(&func->vlines, i);
320
        if (dli->is_source_file)
321 322 323 324 325 326 327 328 329 330
        {
            last_matches = (source_idx == dli->u.source_file);
            break;
        }
    }

    if (!last_matches)
    {
        /* we shouldn't have line changes on first line of function */
        dli = vector_add(&func->vlines, &module->pool);
331 332 333 334
        dli->is_source_file = 1;
        dli->is_first       = dli->is_last = 0;
        dli->line_number    = 0;
        dli->u.source_file  = source_idx;
335 336
    }
    dli = vector_add(&func->vlines, &module->pool);
337 338 339
    dli->is_source_file = 0;
    dli->is_first       = dli->is_last = 0;
    dli->line_number    = line_num;
340
    dli->u.pc_offset    = func->address + offset;
341 342
}

343
/******************************************************************
344
 *             symt_add_func_local
345 346
 *
 * Adds a new local/parameter to a given function:
347
 * In any cases, dt tells whether it's a local variable or a parameter
348 349
 * If regno it's not 0:
 *      - then variable is stored in a register
350
 *      - otherwise, value is referenced by register + offset
351
 * Otherwise, the variable is stored on the stack:
352
 *      - offset is then the offset from the frame register
353
 */
354 355
struct symt_data* symt_add_func_local(struct module* module, 
                                      struct symt_function* func, 
356
                                      enum DataKind dt,
357
                                      const struct location* loc,
358 359 360 361 362 363
                                      struct symt_block* block, 
                                      struct symt* type, const char* name)
{
    struct symt_data*   locsym;
    struct symt**       p;

364
    TRACE_(dbghelp_symt)("Adding local symbol (%s:%s): %s %p\n",
365
                         debugstr_w(module->module.ModuleName), func->hash_elt.name,
366
                         name, type);
367 368 369 370 371

    assert(func);
    assert(func->symt.tag == SymTagFunction);
    assert(dt == DataIsParam || dt == DataIsLocal);

372 373 374 375
    locsym = pool_alloc(&module->pool, sizeof(*locsym));
    locsym->symt.tag      = SymTagData;
    locsym->hash_elt.name = pool_strdup(&module->pool, name);
    locsym->hash_elt.next = NULL;
376
    locsym->kind          = dt;
377
    locsym->container     = block ? &block->symt : &func->symt;
378
    locsym->type          = type;
379
    locsym->u.var         = *loc;
380 381 382 383 384 385 386 387
    if (block)
        p = vector_add(&block->vchildren, &module->pool);
    else
        p = vector_add(&func->vchildren, &module->pool);
    *p = &locsym->symt;
    return locsym;
}

388

389 390 391
struct symt_block* symt_open_func_block(struct module* module, 
                                        struct symt_function* func,
                                        struct symt_block* parent_block, 
392
                                        unsigned pc, unsigned len)
393 394 395 396 397 398 399 400 401
{
    struct symt_block*  block;
    struct symt**       p;

    assert(func);
    assert(func->symt.tag == SymTagFunction);

    assert(!parent_block || parent_block->symt.tag == SymTagBlock);
    block = pool_alloc(&module->pool, sizeof(*block));
402
    block->symt.tag = SymTagBlock;
403
    block->address  = func->address + pc;
404
    block->size     = len;
405 406 407 408 409 410 411 412 413 414 415 416
    block->container = parent_block ? &parent_block->symt : &func->symt;
    vector_init(&block->vchildren, sizeof(struct symt*), 4);
    if (parent_block)
        p = vector_add(&parent_block->vchildren, &module->pool);
    else
        p = vector_add(&func->vchildren, &module->pool);
    *p = &block->symt;

    return block;
}

struct symt_block* symt_close_func_block(struct module* module, 
417
                                         const struct symt_function* func,
418 419
                                         struct symt_block* block, unsigned pc)
{
420
    assert(func);
421 422
    assert(func->symt.tag == SymTagFunction);

423
    if (pc) block->size = func->address + pc - block->address;
424
    return (block->container->tag == SymTagBlock) ? 
425
        CONTAINING_RECORD(block->container, struct symt_block, symt) : NULL;
426 427
}

428 429 430 431 432
struct symt_hierarchy_point* symt_add_function_point(struct module* module,
                                                     struct symt_function* func,
                                                     enum SymTagEnum point,
                                                     const struct location* loc,
                                                     const char* name)
433
{
434
    struct symt_hierarchy_point*sym;
435 436 437 438 439
    struct symt**               p;

    if ((sym = pool_alloc(&module->pool, sizeof(*sym))))
    {
        sym->symt.tag = point;
440
        sym->parent   = &func->symt;
441
        sym->loc      = *loc;
442
        sym->hash_elt.name = name ? pool_strdup(&module->pool, name) : NULL;
443 444 445 446 447 448
        p = vector_add(&func->vchildren, &module->pool);
        *p = &sym->symt;
    }
    return sym;
}

449
BOOL symt_normalize_function(struct module* module, const struct symt_function* func)
450 451 452 453
{
    unsigned            len;
    struct line_info*   dli;

454
    assert(func);
455 456 457 458 459 460 461 462 463 464 465
    /* We aren't adding any more locals or line numbers to this function.
     * Free any spare memory that we might have allocated.
     */
    assert(func->symt.tag == SymTagFunction);

/* EPP     vector_pool_normalize(&func->vlines,    &module->pool); */
/* EPP     vector_pool_normalize(&func->vchildren, &module->pool); */

    len = vector_length(&func->vlines);
    if (len--)
    {
466 467
        dli = vector_at(&func->vlines,   0);  dli->is_first = 1;
        dli = vector_at(&func->vlines, len);  dli->is_last  = 1;
468 469 470 471
    }
    return TRUE;
}

472 473 474 475 476 477 478
struct symt_thunk* symt_new_thunk(struct module* module, 
                                  struct symt_compiland* compiland, 
                                  const char* name, THUNK_ORDINAL ord,
                                  unsigned long addr, unsigned long size)
{
    struct symt_thunk*  sym;

479
    TRACE_(dbghelp_symt)("Adding global thunk %s:%s @%lx-%lx\n",
480
                         debugstr_w(module->module.ModuleName), name, addr, addr + size - 1);
481 482 483 484 485 486 487 488 489

    if ((sym = pool_alloc(&module->pool, sizeof(*sym))))
    {
        sym->symt.tag  = SymTagThunk;
        sym->hash_elt.name = pool_strdup(&module->pool, name);
        sym->container = &compiland->symt;
        sym->address   = addr;
        sym->size      = size;
        sym->ordinal   = ord;
490
        symt_add_module_ht(module, (struct symt_ht*)sym);
491 492 493 494 495 496 497 498 499 500
        if (compiland)
        {
            struct symt**       p;
            p = vector_add(&compiland->vchildren, &module->pool);
            *p = &sym->symt;
        }
    }
    return sym;
}

501 502 503 504 505 506 507 508
struct symt_data* symt_new_constant(struct module* module,
                                    struct symt_compiland* compiland,
                                    const char* name, struct symt* type,
                                    const VARIANT* v)
{
    struct symt_data*  sym;

    TRACE_(dbghelp_symt)("Adding constant value %s:%s\n",
509
                         debugstr_w(module->module.ModuleName), name);
510 511 512 513 514 515 516 517 518

    if ((sym = pool_alloc(&module->pool, sizeof(*sym))))
    {
        sym->symt.tag      = SymTagData;
        sym->hash_elt.name = pool_strdup(&module->pool, name);
        sym->kind          = DataIsConstant;
        sym->container     = compiland ? &compiland->symt : NULL;
        sym->type          = type;
        sym->u.value       = *v;
519
        symt_add_module_ht(module, (struct symt_ht*)sym);
520 521 522
        if (compiland)
        {
            struct symt**       p;
523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
            p = vector_add(&compiland->vchildren, &module->pool);
            *p = &sym->symt;
        }
    }
    return sym;
}

struct symt_hierarchy_point* symt_new_label(struct module* module,
                                            struct symt_compiland* compiland,
                                            const char* name, unsigned long address)
{
    struct symt_hierarchy_point*        sym;

    TRACE_(dbghelp_symt)("Adding global label value %s:%s\n",
                         debugstr_w(module->module.ModuleName), name);

    if ((sym = pool_alloc(&module->pool, sizeof(*sym))))
    {
        sym->symt.tag      = SymTagLabel;
        sym->hash_elt.name = pool_strdup(&module->pool, name);
        sym->loc.kind      = loc_absolute;
        sym->loc.offset    = address;
        sym->parent        = compiland ? &compiland->symt : NULL;
546
        symt_add_module_ht(module, (struct symt_ht*)sym);
547 548 549
        if (compiland)
        {
            struct symt**       p;
550 551 552 553 554 555 556
            p = vector_add(&compiland->vchildren, &module->pool);
            *p = &sym->symt;
        }
    }
    return sym;
}

557
/* expect sym_info->MaxNameLen to be set before being called */
558
static void symt_fill_sym_info(struct module_pair* pair,
559
                               const struct symt_function* func,
560 561 562
                               const struct symt* sym, SYMBOL_INFO* sym_info)
{
    const char* name;
563
    DWORD64 size;
564

565
    if (!symt_get_info(pair->effective, sym, TI_GET_TYPE, &sym_info->TypeIndex))
566
        sym_info->TypeIndex = 0;
567
    sym_info->Index = symt_ptr2index(pair->effective, sym);
Eric Pouech's avatar
Eric Pouech committed
568
    sym_info->Reserved[0] = sym_info->Reserved[1] = 0;
569
    if (!symt_get_info(pair->effective, sym, TI_GET_LENGTH, &size) &&
Eric Pouech's avatar
Eric Pouech committed
570
        (!sym_info->TypeIndex ||
571 572
         !symt_get_info(pair->effective, symt_index2ptr(pair->effective, sym_info->TypeIndex),
                         TI_GET_LENGTH, &size)))
573
        size = 0;
574
    sym_info->Size = (DWORD)size;
Eric Pouech's avatar
Eric Pouech committed
575
    sym_info->ModBase = pair->requested->module.BaseOfImage;
576
    sym_info->Flags = 0;
Eric Pouech's avatar
Eric Pouech committed
577 578
    sym_info->Value = 0;

579 580 581 582
    switch (sym->tag)
    {
    case SymTagData:
        {
583
            const struct symt_data*  data = (const struct symt_data*)sym;
584
            switch (data->kind)
585
            {
586
            case DataIsParam:
587 588
                sym_info->Flags |= SYMFLAG_PARAMETER;
                /* fall through */
589
            case DataIsLocal:
590
                sym_info->Flags |= SYMFLAG_LOCAL;
591
                {
592 593 594
                    struct location loc = data->u.var;

                    if (loc.kind >= loc_user)
595 596 597 598 599 600 601 602 603 604 605 606 607 608
                    {
                        unsigned                i;
                        struct module_format*   modfmt;

                        for (i = 0; i < DFI_LAST; i++)
                        {
                            modfmt = pair->effective->format_info[i];
                            if (modfmt && modfmt->loc_compute)
                            {
                                modfmt->loc_compute(pair->pcs, modfmt, func, &loc);
                                break;
                            }
                        }
                    }
609 610 611 612 613 614 615 616 617 618 619
                    switch (loc.kind)
                    {
                    case loc_error:
                        /* for now we report error cases as a negative register number */
                        /* fall through */
                    case loc_register:
                        sym_info->Flags |= SYMFLAG_REGISTER;
                        sym_info->Register = loc.reg;
                        sym_info->Address = 0;
                        break;
                    case loc_regrel:
620
                        sym_info->Flags |= SYMFLAG_REGREL;
621 622 623
                        sym_info->Register = loc.reg;
                        if (loc.reg == CV_REG_NONE || (int)loc.reg < 0 /* error */)
                            FIXME("suspicious register value %x\n", loc.reg);
624 625
                        sym_info->Address = loc.offset;
                        break;
626 627 628 629
                    case loc_absolute:
                        sym_info->Flags |= SYMFLAG_VALUEPRESENT;
                        sym_info->Value = loc.offset;
                        break;
630 631 632 633
                    default:
                        FIXME("Shouldn't happen (kind=%d), debug reader backend is broken\n", loc.kind);
                        assert(0);
                    }
634
                }
635
                break;
636 637
            case DataIsGlobal:
            case DataIsFileStatic:
638 639 640 641 642 643
                switch (data->u.var.kind)
                {
                case loc_tlsrel:
                    sym_info->Flags |= SYMFLAG_TLSREL;
                    /* fall through */
                case loc_absolute:
644
                    symt_get_address(sym, &sym_info->Address);
645 646 647 648 649 650
                    sym_info->Register = 0;
                    break;
                default:
                    FIXME("Shouldn't happen (kind=%d), debug reader backend is broken\n", data->u.var.kind);
                    assert(0);
                }
651
                break;
652
            case DataIsConstant:
653
                sym_info->Flags |= SYMFLAG_VALUEPRESENT;
654 655 656 657 658 659 660 661
                switch (data->u.value.n1.n2.vt)
                {
                case VT_I4:  sym_info->Value = (ULONG)data->u.value.n1.n2.n3.lVal; break;
                case VT_I2:  sym_info->Value = (ULONG)(long)data->u.value.n1.n2.n3.iVal; break;
                case VT_I1:  sym_info->Value = (ULONG)(long)data->u.value.n1.n2.n3.cVal; break;
                case VT_UI4: sym_info->Value = (ULONG)data->u.value.n1.n2.n3.ulVal; break;
                case VT_UI2: sym_info->Value = (ULONG)data->u.value.n1.n2.n3.uiVal; break;
                case VT_UI1: sym_info->Value = (ULONG)data->u.value.n1.n2.n3.bVal; break;
662
                case VT_I1 | VT_BYREF: sym_info->Value = (ULONG64)(DWORD_PTR)data->u.value.n1.n2.n3.byref; break;
663
                case VT_EMPTY: sym_info->Value = 0; break;
664
                default:
665
                    FIXME("Unsupported variant type (%u)\n", data->u.value.n1.n2.vt);
666 667
                    sym_info->Value = 0;
                    break;
668
                }
669 670
                break;
            default:
671
                FIXME("Unhandled kind (%u) in sym data\n", data->kind);
672 673 674 675 676
            }
        }
        break;
    case SymTagPublicSymbol:
        sym_info->Flags |= SYMFLAG_EXPORT;
677
        symt_get_address(sym, &sym_info->Address);
678 679 680
        break;
    case SymTagFunction:
        sym_info->Flags |= SYMFLAG_FUNCTION;
681
        symt_get_address(sym, &sym_info->Address);
682
        break;
683 684
    case SymTagThunk:
        sym_info->Flags |= SYMFLAG_THUNK;
685
        symt_get_address(sym, &sym_info->Address);
686
        break;
687
    default:
688
        symt_get_address(sym, &sym_info->Address);
689 690 691 692 693 694 695 696
        sym_info->Register = 0;
        break;
    }
    sym_info->Scope = 0; /* FIXME */
    sym_info->Tag = sym->tag;
    name = symt_get_name(sym);
    if (sym_info->MaxNameLen)
    {
697
        if (sym->tag != SymTagPublicSymbol || !(dbghelp_options & SYMOPT_UNDNAME) ||
698 699
            ((sym_info->NameLen = UnDecorateSymbolName(name, sym_info->Name,
                                                       sym_info->MaxNameLen, UNDNAME_NAME_ONLY)) == 0))
700 701
        {
            sym_info->NameLen = min(strlen(name), sym_info->MaxNameLen - 1);
702
            memcpy(sym_info->Name, name, sym_info->NameLen);
703 704
            sym_info->Name[sym_info->NameLen] = '\0';
        }
705
    }
706
    TRACE_(dbghelp_symt)("%p => %s %u %s\n",
707 708
                         sym, sym_info->Name, sym_info->Size,
                         wine_dbgstr_longlong(sym_info->Address));
709 710
}

711 712 713 714 715
struct sym_enum
{
    PSYM_ENUMERATESYMBOLS_CALLBACK      cb;
    PVOID                               user;
    SYMBOL_INFO*                        sym_info;
716 717 718
    DWORD                               index;
    DWORD                               tag;
    DWORD64                             addr;
719 720
    char                                buffer[sizeof(SYMBOL_INFO) + MAX_SYM_NAME];
};
721

722
static BOOL send_symbol(const struct sym_enum* se, struct module_pair* pair,
723
                        const struct symt_function* func, const struct symt* sym)
724
{
725
    symt_fill_sym_info(pair, func, sym, se->sym_info);
726
    if (se->index && se->sym_info->Index != se->index) return FALSE;
727 728 729 730 731
    if (se->tag && se->sym_info->Tag != se->tag) return FALSE;
    if (se->addr && !(se->addr >= se->sym_info->Address && se->addr < se->sym_info->Address + se->sym_info->Size)) return FALSE;
    return !se->cb(se->sym_info, se->sym_info->Size, se->user);
}

732
static BOOL symt_enum_module(struct module_pair* pair, const WCHAR* match,
733
                             const struct sym_enum* se)
734 735 736 737
{
    void*                       ptr;
    struct symt_ht*             sym = NULL;
    struct hash_table_iter      hti;
738 739
    WCHAR*                      nameW;
    BOOL                        ret;
740

Eric Pouech's avatar
Eric Pouech committed
741
    hash_table_iter_init(&pair->effective->ht_symbols, &hti, NULL);
742 743
    while ((ptr = hash_table_iter_up(&hti)))
    {
744
        sym = CONTAINING_RECORD(ptr, struct symt_ht, hash_elt);
745 746 747 748
        nameW = symt_get_nameW(&sym->symt);
        ret = SymMatchStringW(nameW, match, FALSE);
        HeapFree(GetProcessHeap(), 0, nameW);
        if (ret)
749
        {
750 751
            se->sym_info->SizeOfStruct = sizeof(SYMBOL_INFO);
            se->sym_info->MaxNameLen = sizeof(se->buffer) - sizeof(SYMBOL_INFO);
752
            if (send_symbol(se, pair, NULL, &sym->symt)) return TRUE;
753
        }
754
    }
755
    return FALSE;
756 757
}

758
static inline unsigned where_to_insert(struct module* module, unsigned high, const struct symt_ht* elt)
759 760 761 762 763
{
    unsigned    low = 0, mid = high / 2;
    ULONG64     addr;

    if (!high) return 0;
764
    symt_get_address(&elt->symt, &addr);
765 766 767 768 769 770 771 772 773 774 775 776 777
    do
    {
        switch (cmp_sorttab_addr(module, mid, addr))
        {
        case 0: return mid;
        case -1: low = mid + 1; break;
        case 1: high = mid; break;
        }
        mid = low + (high - low) / 2;
    } while (low < high);
    return mid;
}

778 779 780 781 782 783 784
/***********************************************************************
 *              resort_symbols
 *
 * Rebuild sorted list of symbols for a module.
 */
static BOOL resort_symbols(struct module* module)
{
785 786
    int delta;

787
    if (!(module->module.NumSyms = module->num_symbols))
788
        return FALSE;
789

790 791 792 793 794 795 796
    /* we know that set from 0 up to num_sorttab is already sorted
     * so sort the remaining (new) symbols, and merge the two sets
     * (unless the first set is empty)
     */
    delta = module->num_symbols - module->num_sorttab;
    qsort(&module->addr_sorttab[module->num_sorttab], delta, sizeof(struct symt_ht*), symt_cmp_addr);
    if (module->num_sorttab)
797
    {
798 799 800
        int     i, ins_idx = module->num_sorttab, prev_ins_idx;
        static struct symt_ht** tmp;
        static unsigned num_tmp;
801

802 803 804 805 806 807 808 809 810 811 812 813 814 815 816
        if (num_tmp < delta)
        {
            static struct symt_ht** new;
            if (tmp)
                new = HeapReAlloc(GetProcessHeap(), 0, tmp, delta * sizeof(struct symt_ht*));
            else
                new = HeapAlloc(GetProcessHeap(), 0, delta * sizeof(struct symt_ht*));
            if (!new)
            {
                module->num_sorttab = 0;
                return resort_symbols(module);
            }
            tmp = new;
            num_tmp = delta;
        }
817 818 819 820 821 822
        memcpy(tmp, &module->addr_sorttab[module->num_sorttab], delta * sizeof(struct symt_ht*));
        qsort(tmp, delta, sizeof(struct symt_ht*), symt_cmp_addr);

        for (i = delta - 1; i >= 0; i--)
        {
            prev_ins_idx = ins_idx;
823
            ins_idx = where_to_insert(module, ins_idx, tmp[i]);
824 825 826 827 828 829
            memmove(&module->addr_sorttab[ins_idx + i + 1],
                    &module->addr_sorttab[ins_idx],
                    (prev_ins_idx - ins_idx) * sizeof(struct symt_ht*));
            module->addr_sorttab[ins_idx + i] = tmp[i];
        }
    }
830
    module->num_sorttab = module->num_symbols;
831 832 833
    return module->sortlist_valid = TRUE;
}

834
static void symt_get_length(struct module* module, const struct symt* symt, ULONG64* size)
835 836 837
{
    DWORD       type_index;

838
    if (symt_get_info(module,  symt, TI_GET_LENGTH, size) && *size)
839 840
        return;

841 842
    if (symt_get_info(module, symt, TI_GET_TYPE, &type_index) &&
        symt_get_info(module, symt_index2ptr(module, type_index), TI_GET_LENGTH, size)) return;
843 844 845
    *size = 0x1000; /* arbitrary value */
}

846
/* assume addr is in module */
847
struct symt_ht* symt_find_nearest(struct module* module, DWORD_PTR addr)
848 849
{
    int         mid, high, low;
850
    ULONG64     ref_addr, ref_size;
851

852 853
    if (!module->sortlist_valid || !module->addr_sorttab)
    {
854
        if (!resort_symbols(module)) return NULL;
855
    }
856 857 858 859 860

    /*
     * Binary search to find closest symbol.
     */
    low = 0;
861
    high = module->num_sorttab;
862

863
    symt_get_address(&module->addr_sorttab[0]->symt, &ref_addr);
864
    if (addr < ref_addr) return NULL;
865 866
    if (high)
    {
867
        symt_get_address(&module->addr_sorttab[high - 1]->symt, &ref_addr);
868
        symt_get_length(module, &module->addr_sorttab[high - 1]->symt, &ref_size);
869
        if (addr >= ref_addr + ref_size) return NULL;
870
    }
871 872 873 874 875 876 877 878 879
    
    while (high > low + 1)
    {
        mid = (high + low) / 2;
        if (cmp_sorttab_addr(module, mid, addr) < 0)
            low = mid;
        else
            high = mid;
    }
880
    if (low != high && high != module->num_sorttab &&
881 882 883 884 885 886 887
        cmp_sorttab_addr(module, high, addr) <= 0)
        low = high;

    /* If found symbol is a public symbol, check if there are any other entries that
     * might also have the same address, but would get better information
     */
    if (module->addr_sorttab[low]->symt.tag == SymTagPublicSymbol)
888 889
    {
        symt_get_address(&module->addr_sorttab[low]->symt, &ref_addr);
890 891
        if (low > 0 &&
            module->addr_sorttab[low - 1]->symt.tag != SymTagPublicSymbol &&
892
            !cmp_sorttab_addr(module, low - 1, ref_addr))
893
            low--;
894
        else if (low < module->num_sorttab - 1 &&
895
                 module->addr_sorttab[low + 1]->symt.tag != SymTagPublicSymbol &&
896
                 !cmp_sorttab_addr(module, low + 1, ref_addr))
897 898
            low++;
    }
899
    /* finally check that we fit into the found symbol */
900
    symt_get_address(&module->addr_sorttab[low]->symt, &ref_addr);
901
    if (addr < ref_addr) return NULL;
902
    symt_get_length(module, &module->addr_sorttab[low]->symt, &ref_size);
903
    if (addr >= ref_addr + ref_size) return NULL;
904

905
    return module->addr_sorttab[low];
906 907
}

908
static BOOL symt_enum_locals_helper(struct module_pair* pair,
909
                                    const WCHAR* match, const struct sym_enum* se,
910
                                    struct symt_function* func, const struct vector* v)
911 912
{
    struct symt*        lsym = NULL;
913
    DWORD               pc = pair->pcs->ctx_frame.InstructionOffset;
914
    unsigned int        i;
915 916
    WCHAR*              nameW;
    BOOL                ret;
917

918
    for (i=0; i<vector_length(v); i++)
919
    {
920
        lsym = *(struct symt**)vector_at(v, i);
921 922 923 924 925 926 927
        switch (lsym->tag)
        {
        case SymTagBlock:
            {
                struct symt_block*  block = (struct symt_block*)lsym;
                if (pc < block->address || block->address + block->size <= pc)
                    continue;
928
                if (!symt_enum_locals_helper(pair, match, se, func, &block->vchildren))
929 930 931 932
                    return FALSE;
            }
            break;
        case SymTagData:
933 934 935 936 937
            nameW = symt_get_nameW(lsym);
            ret = SymMatchStringW(nameW, match,
                                  !(dbghelp_options & SYMOPT_CASE_INSENSITIVE));
            HeapFree(GetProcessHeap(), 0, nameW);
            if (ret)
938
            {
939
                if (send_symbol(se, pair, func, lsym)) return FALSE;
940 941
            }
            break;
942 943 944
        case SymTagLabel:
        case SymTagFuncDebugStart:
        case SymTagFuncDebugEnd:
945
        case SymTagCustom:
946
            break;
947 948 949 950 951 952 953 954
        default:
            FIXME("Unknown type: %u (%x)\n", lsym->tag, lsym->tag);
            assert(0);
        }
    }
    return TRUE;
}

955
static BOOL symt_enum_locals(struct process* pcs, const WCHAR* mask,
956
                             const struct sym_enum* se)
957
{
Eric Pouech's avatar
Eric Pouech committed
958
    struct module_pair  pair;
959
    struct symt_ht*     sym;
960
    DWORD_PTR           pc = pcs->ctx_frame.InstructionOffset;
961

962 963
    se->sym_info->SizeOfStruct = sizeof(*se->sym_info);
    se->sym_info->MaxNameLen = sizeof(se->buffer) - sizeof(SYMBOL_INFO);
964

965 966 967
    pair.pcs = pcs;
    pair.requested = module_find_by_addr(pair.pcs, pc, DMT_UNKNOWN);
    if (!module_get_debug(&pair)) return FALSE;
968
    if ((sym = symt_find_nearest(pair.effective, pc)) == NULL) return FALSE;
969 970 971

    if (sym->symt.tag == SymTagFunction)
    {
972 973
        return symt_enum_locals_helper(&pair, mask ? mask : starW, se, (struct symt_function*)sym,
                                       &((struct symt_function*)sym)->vchildren);
974
    }
975
    return FALSE;
976 977
}

978 979 980
/******************************************************************
 *		copy_symbolW
 *
981
 * Helper for transforming an ANSI symbol info into a UNICODE one.
982 983
 * Assume that MaxNameLen is the same for both version (A & W).
 */
984
void copy_symbolW(SYMBOL_INFOW* siw, const SYMBOL_INFO* si)
985 986 987 988 989
{
    siw->SizeOfStruct = si->SizeOfStruct;
    siw->TypeIndex = si->TypeIndex; 
    siw->Reserved[0] = si->Reserved[0];
    siw->Reserved[1] = si->Reserved[1];
990
    siw->Index = si->Index;
991 992 993 994 995 996 997 998 999 1000 1001 1002
    siw->Size = si->Size;
    siw->ModBase = si->ModBase;
    siw->Flags = si->Flags;
    siw->Value = si->Value;
    siw->Address = si->Address;
    siw->Register = si->Register;
    siw->Scope = si->Scope;
    siw->Tag = si->Tag;
    siw->NameLen = si->NameLen;
    siw->MaxNameLen = si->MaxNameLen;
    MultiByteToWideChar(CP_ACP, 0, si->Name, -1, siw->Name, siw->MaxNameLen);
}
1003

1004
/******************************************************************
1005
 *		sym_enum
1006
 *
1007
 * Core routine for most of the enumeration of symbols
1008
 */
1009
static BOOL sym_enum(HANDLE hProcess, ULONG64 BaseOfDll, PCWSTR Mask,
1010
                     const struct sym_enum* se)
1011
{
Eric Pouech's avatar
Eric Pouech committed
1012
    struct module_pair  pair;
1013 1014
    const WCHAR*        bang;
    WCHAR*              mod;
1015

1016
    pair.pcs = process_find_by_handle(hProcess);
1017
    if (!pair.pcs) return FALSE;
1018 1019
    if (BaseOfDll == 0)
    {
1020
        /* do local variables ? */
1021
        if (!Mask || !(bang = strchrW(Mask, '!')))
1022
            return symt_enum_locals(pair.pcs, Mask, se);
1023 1024 1025

        if (bang == Mask) return FALSE;

1026 1027 1028 1029 1030
        mod = HeapAlloc(GetProcessHeap(), 0, (bang - Mask + 1) * sizeof(WCHAR));
        if (!mod) return FALSE;
        memcpy(mod, Mask, (bang - Mask) * sizeof(WCHAR));
        mod[bang - Mask] = 0;

1031
        for (pair.requested = pair.pcs->lmodules; pair.requested; pair.requested = pair.requested->next)
1032
        {
1033
            if (pair.requested->type == DMT_PE && module_get_debug(&pair))
1034
            {
1035 1036
                if (SymMatchStringW(pair.requested->module.ModuleName, mod, FALSE) &&
                    symt_enum_module(&pair, bang + 1, se))
1037 1038 1039 1040 1041
                    break;
            }
        }
        /* not found in PE modules, retry on the ELF ones
         */
1042
        if (!pair.requested && (dbghelp_options & SYMOPT_WINE_WITH_NATIVE_MODULES))
1043
        {
1044
            for (pair.requested = pair.pcs->lmodules; pair.requested; pair.requested = pair.requested->next)
1045
            {
1046
                if ((pair.requested->type == DMT_ELF || pair.requested->type == DMT_MACHO) &&
1047 1048
                    !module_get_containee(pair.pcs, pair.requested) &&
                    module_get_debug(&pair))
1049
                {
1050 1051
                    if (SymMatchStringW(pair.requested->module.ModuleName, mod, FALSE) &&
                        symt_enum_module(&pair, bang + 1, se))
1052 1053
                    break;
                }
1054 1055
            }
        }
1056
        HeapFree(GetProcessHeap(), 0, mod);
1057
        return TRUE;
1058
    }
1059 1060
    pair.requested = module_find_by_addr(pair.pcs, BaseOfDll, DMT_UNKNOWN);
    if (!module_get_debug(&pair))
1061 1062 1063
        return FALSE;

    /* we always ignore module name from Mask when BaseOfDll is defined */
1064
    if (Mask && (bang = strchrW(Mask, '!')))
1065
    {
1066 1067
        if (bang == Mask) return FALSE;
        Mask = bang + 1;
1068
    }
1069

1070
    symt_enum_module(&pair, Mask ? Mask : starW, se);
1071

1072 1073 1074
    return TRUE;
}

1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
static inline BOOL doSymEnumSymbols(HANDLE hProcess, ULONG64 BaseOfDll, PCWSTR Mask,
                                    PSYM_ENUMERATESYMBOLS_CALLBACK EnumSymbolsCallback,
                                    PVOID UserContext)
{
    struct sym_enum     se;

    se.cb = EnumSymbolsCallback;
    se.user = UserContext;
    se.index = 0;
    se.tag = 0;
    se.addr = 0;
    se.sym_info = (PSYMBOL_INFO)se.buffer;

    return sym_enum(hProcess, BaseOfDll, Mask, &se);
}

1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
/******************************************************************
 *		SymEnumSymbols (DBGHELP.@)
 *
 * cases BaseOfDll = 0
 *      !foo fails always (despite what MSDN states)
 *      RE1!RE2 looks up all modules matching RE1, and in all these modules, lookup RE2
 *      no ! in Mask, lookup in local Context
 * cases BaseOfDll != 0
 *      !foo fails always (despite what MSDN states)
 *      RE1!RE2 gets RE2 from BaseOfDll (whatever RE1 is)
 */
BOOL WINAPI SymEnumSymbols(HANDLE hProcess, ULONG64 BaseOfDll, PCSTR Mask,
                           PSYM_ENUMERATESYMBOLS_CALLBACK EnumSymbolsCallback,
                           PVOID UserContext)
{
1106 1107
    BOOL                ret;
    PWSTR               maskW = NULL;
1108

1109
    TRACE("(%p %s %s %p %p)\n",
1110 1111 1112
          hProcess, wine_dbgstr_longlong(BaseOfDll), debugstr_a(Mask),
          EnumSymbolsCallback, UserContext);

1113 1114 1115 1116 1117 1118 1119 1120 1121 1122
    if (Mask)
    {
        DWORD sz = MultiByteToWideChar(CP_ACP, 0, Mask, -1, NULL, 0);
        if (!(maskW = HeapAlloc(GetProcessHeap(), 0, sz * sizeof(WCHAR))))
            return FALSE;
        MultiByteToWideChar(CP_ACP, 0, Mask, -1, maskW, sz);
    }
    ret = doSymEnumSymbols(hProcess, BaseOfDll, maskW, EnumSymbolsCallback, UserContext);
    HeapFree(GetProcessHeap(), 0, maskW);
    return ret;
1123 1124
}

1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
struct sym_enumW
{
    PSYM_ENUMERATESYMBOLS_CALLBACKW     cb;
    void*                               ctx;
    PSYMBOL_INFOW                       sym_info;
    char                                buffer[sizeof(SYMBOL_INFOW) + MAX_SYM_NAME];

};
    
static BOOL CALLBACK sym_enumW(PSYMBOL_INFO si, ULONG size, PVOID ctx)
{
    struct sym_enumW*   sew = ctx;

    copy_symbolW(sew->sym_info, si);

    return (sew->cb)(sew->sym_info, size, sew->ctx);
}

/******************************************************************
 *		SymEnumSymbolsW (DBGHELP.@)
 *
 */
BOOL WINAPI SymEnumSymbolsW(HANDLE hProcess, ULONG64 BaseOfDll, PCWSTR Mask,
                            PSYM_ENUMERATESYMBOLS_CALLBACKW EnumSymbolsCallback,
                            PVOID UserContext)
{
    struct sym_enumW    sew;

    sew.ctx = UserContext;
    sew.cb = EnumSymbolsCallback;
    sew.sym_info = (PSYMBOL_INFOW)sew.buffer;

1157
    return doSymEnumSymbols(hProcess, BaseOfDll, Mask, sym_enumW, &sew);
1158 1159
}

1160 1161 1162 1163 1164 1165 1166 1167
struct sym_enumerate
{
    void*                       ctx;
    PSYM_ENUMSYMBOLS_CALLBACK   cb;
};

static BOOL CALLBACK sym_enumerate_cb(PSYMBOL_INFO syminfo, ULONG size, void* ctx)
{
1168
    struct sym_enumerate*       se = ctx;
1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
    return (se->cb)(syminfo->Name, syminfo->Address, syminfo->Size, se->ctx);
}

/***********************************************************************
 *		SymEnumerateSymbols (DBGHELP.@)
 */
BOOL WINAPI SymEnumerateSymbols(HANDLE hProcess, DWORD BaseOfDll,
                                PSYM_ENUMSYMBOLS_CALLBACK EnumSymbolsCallback, 
                                PVOID UserContext)
{
    struct sym_enumerate        se;

    se.ctx = UserContext;
    se.cb  = EnumSymbolsCallback;
    
    return SymEnumSymbols(hProcess, BaseOfDll, NULL, sym_enumerate_cb, &se);
}

1187 1188 1189 1190 1191 1192 1193 1194
struct sym_enumerate64
{
    void*                       ctx;
    PSYM_ENUMSYMBOLS_CALLBACK64 cb;
};

static BOOL CALLBACK sym_enumerate_cb64(PSYMBOL_INFO syminfo, ULONG size, void* ctx)
{
1195
    struct sym_enumerate64*     se = ctx;
1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213
    return (se->cb)(syminfo->Name, syminfo->Address, syminfo->Size, se->ctx);
}

/***********************************************************************
 *              SymEnumerateSymbols64 (DBGHELP.@)
 */
BOOL WINAPI SymEnumerateSymbols64(HANDLE hProcess, DWORD64 BaseOfDll,
                                  PSYM_ENUMSYMBOLS_CALLBACK64 EnumSymbolsCallback,
                                  PVOID UserContext)
{
    struct sym_enumerate64      se;

    se.ctx = UserContext;
    se.cb  = EnumSymbolsCallback;

    return SymEnumSymbols(hProcess, BaseOfDll, NULL, sym_enumerate_cb64, &se);
}

1214 1215 1216 1217
/******************************************************************
 *		SymFromAddr (DBGHELP.@)
 *
 */
1218 1219
BOOL WINAPI SymFromAddr(HANDLE hProcess, DWORD64 Address, 
                        DWORD64* Displacement, PSYMBOL_INFO Symbol)
1220
{
Eric Pouech's avatar
Eric Pouech committed
1221
    struct module_pair  pair;
1222 1223
    struct symt_ht*     sym;

1224 1225 1226 1227
    pair.pcs = process_find_by_handle(hProcess);
    if (!pair.pcs) return FALSE;
    pair.requested = module_find_by_addr(pair.pcs, Address, DMT_UNKNOWN);
    if (!module_get_debug(&pair)) return FALSE;
1228
    if ((sym = symt_find_nearest(pair.effective, Address)) == NULL) return FALSE;
1229

1230
    symt_fill_sym_info(&pair, NULL, &sym->symt, Symbol);
1231 1232
    if (Displacement)
        *Displacement = Address - Symbol->Address;
1233 1234 1235
    return TRUE;
}

1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260
/******************************************************************
 *		SymFromAddrW (DBGHELP.@)
 *
 */
BOOL WINAPI SymFromAddrW(HANDLE hProcess, DWORD64 Address, 
                         DWORD64* Displacement, PSYMBOL_INFOW Symbol)
{
    PSYMBOL_INFO        si;
    unsigned            len;
    BOOL                ret;

    len = sizeof(*si) + Symbol->MaxNameLen * sizeof(WCHAR);
    si = HeapAlloc(GetProcessHeap(), 0, len);
    if (!si) return FALSE;

    si->SizeOfStruct = sizeof(*si);
    si->MaxNameLen = Symbol->MaxNameLen;
    if ((ret = SymFromAddr(hProcess, Address, Displacement, si)))
    {
        copy_symbolW(Symbol, si);
    }
    HeapFree(GetProcessHeap(), 0, si);
    return ret;
}

1261 1262 1263 1264 1265 1266 1267
/******************************************************************
 *		SymGetSymFromAddr (DBGHELP.@)
 *
 */
BOOL WINAPI SymGetSymFromAddr(HANDLE hProcess, DWORD Address,
                              PDWORD Displacement, PIMAGEHLP_SYMBOL Symbol)
{
Eric Pouech's avatar
Eric Pouech committed
1268
    char        buffer[sizeof(SYMBOL_INFO) + MAX_SYM_NAME];
1269 1270
    SYMBOL_INFO*si = (SYMBOL_INFO*)buffer;
    size_t      len;
1271
    DWORD64     Displacement64;
1272 1273 1274

    if (Symbol->SizeOfStruct < sizeof(*Symbol)) return FALSE;
    si->SizeOfStruct = sizeof(*si);
Eric Pouech's avatar
Eric Pouech committed
1275
    si->MaxNameLen = MAX_SYM_NAME;
1276
    if (!SymFromAddr(hProcess, Address, &Displacement64, si))
1277 1278
        return FALSE;

1279 1280
    if (Displacement)
        *Displacement = Displacement64;
1281 1282 1283 1284
    Symbol->Address = si->Address;
    Symbol->Size    = si->Size;
    Symbol->Flags   = si->Flags;
    len = min(Symbol->MaxNameLength, si->MaxNameLen);
1285
    lstrcpynA(Symbol->Name, si->Name, len);
1286 1287 1288
    return TRUE;
}

1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316
/******************************************************************
 *		SymGetSymFromAddr64 (DBGHELP.@)
 *
 */
BOOL WINAPI SymGetSymFromAddr64(HANDLE hProcess, DWORD64 Address,
                                PDWORD64 Displacement, PIMAGEHLP_SYMBOL64 Symbol)
{
    char        buffer[sizeof(SYMBOL_INFO) + MAX_SYM_NAME];
    SYMBOL_INFO*si = (SYMBOL_INFO*)buffer;
    size_t      len;
    DWORD64     Displacement64;

    if (Symbol->SizeOfStruct < sizeof(*Symbol)) return FALSE;
    si->SizeOfStruct = sizeof(*si);
    si->MaxNameLen = MAX_SYM_NAME;
    if (!SymFromAddr(hProcess, Address, &Displacement64, si))
        return FALSE;

    if (Displacement)
        *Displacement = Displacement64;
    Symbol->Address = si->Address;
    Symbol->Size    = si->Size;
    Symbol->Flags   = si->Flags;
    len = min(Symbol->MaxNameLength, si->MaxNameLen);
    lstrcpynA(Symbol->Name, si->Name, len);
    return TRUE;
}

Eric Pouech's avatar
Eric Pouech committed
1317 1318 1319 1320 1321 1322 1323 1324
static BOOL find_name(struct process* pcs, struct module* module, const char* name,
                      SYMBOL_INFO* symbol)
{
    struct hash_table_iter      hti;
    void*                       ptr;
    struct symt_ht*             sym = NULL;
    struct module_pair          pair;

1325
    pair.pcs = pcs;
Eric Pouech's avatar
Eric Pouech committed
1326
    if (!(pair.requested = module)) return FALSE;
1327
    if (!module_get_debug(&pair)) return FALSE;
Eric Pouech's avatar
Eric Pouech committed
1328 1329 1330 1331

    hash_table_iter_init(&pair.effective->ht_symbols, &hti, name);
    while ((ptr = hash_table_iter_up(&hti)))
    {
1332
        sym = CONTAINING_RECORD(ptr, struct symt_ht, hash_elt);
Eric Pouech's avatar
Eric Pouech committed
1333 1334 1335

        if (!strcmp(sym->hash_elt.name, name))
        {
1336
            symt_fill_sym_info(&pair, NULL, &sym->symt, symbol);
Eric Pouech's avatar
Eric Pouech committed
1337 1338 1339 1340 1341 1342
            return TRUE;
        }
    }
    return FALSE;

}
1343 1344 1345 1346
/******************************************************************
 *		SymFromName (DBGHELP.@)
 *
 */
1347
BOOL WINAPI SymFromName(HANDLE hProcess, PCSTR Name, PSYMBOL_INFO Symbol)
1348 1349 1350
{
    struct process*             pcs = process_find_by_handle(hProcess);
    struct module*              module;
1351
    const char*                 name;
1352 1353 1354 1355

    TRACE("(%p, %s, %p)\n", hProcess, Name, Symbol);
    if (!pcs) return FALSE;
    if (Symbol->SizeOfStruct < sizeof(*Symbol)) return FALSE;
1356 1357 1358 1359 1360 1361 1362
    name = strchr(Name, '!');
    if (name)
    {
        char    tmp[128];
        assert(name - Name < sizeof(tmp));
        memcpy(tmp, Name, name - Name);
        tmp[name - Name] = '\0';
1363
        module = module_find_by_nameA(pcs, tmp);
1364
        return find_name(pcs, module, name + 1, Symbol);
1365
    }
Eric Pouech's avatar
Eric Pouech committed
1366
    for (module = pcs->lmodules; module; module = module->next)
1367
    {
Eric Pouech's avatar
Eric Pouech committed
1368 1369 1370 1371 1372
        if (module->type == DMT_PE && find_name(pcs, module, Name, Symbol))
            return TRUE;
    }
    /* not found in PE modules, retry on the ELF ones
     */
1373
    if (dbghelp_options & SYMOPT_WINE_WITH_NATIVE_MODULES)
Eric Pouech's avatar
Eric Pouech committed
1374 1375
    {
        for (module = pcs->lmodules; module; module = module->next)
1376
        {
1377 1378
            if ((module->type == DMT_ELF || module->type == DMT_MACHO) &&
                !module_get_containee(pcs, module) &&
Eric Pouech's avatar
Eric Pouech committed
1379
                find_name(pcs, module, Name, Symbol))
1380
                return TRUE;
1381 1382 1383 1384 1385
        }
    }
    return FALSE;
}

1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407
/***********************************************************************
 *		SymGetSymFromName64 (DBGHELP.@)
 */
BOOL WINAPI SymGetSymFromName64(HANDLE hProcess, PCSTR Name, PIMAGEHLP_SYMBOL64 Symbol)
{
    char        buffer[sizeof(SYMBOL_INFO) + MAX_SYM_NAME];
    SYMBOL_INFO*si = (SYMBOL_INFO*)buffer;
    size_t      len;

    if (Symbol->SizeOfStruct < sizeof(*Symbol)) return FALSE;
    si->SizeOfStruct = sizeof(*si);
    si->MaxNameLen = MAX_SYM_NAME;
    if (!SymFromName(hProcess, Name, si)) return FALSE;

    Symbol->Address = si->Address;
    Symbol->Size    = si->Size;
    Symbol->Flags   = si->Flags;
    len = min(Symbol->MaxNameLength, si->MaxNameLen);
    lstrcpynA(Symbol->Name, si->Name, len);
    return TRUE;
}

1408 1409 1410
/***********************************************************************
 *		SymGetSymFromName (DBGHELP.@)
 */
1411
BOOL WINAPI SymGetSymFromName(HANDLE hProcess, PCSTR Name, PIMAGEHLP_SYMBOL Symbol)
1412
{
Eric Pouech's avatar
Eric Pouech committed
1413
    char        buffer[sizeof(SYMBOL_INFO) + MAX_SYM_NAME];
1414 1415 1416 1417 1418
    SYMBOL_INFO*si = (SYMBOL_INFO*)buffer;
    size_t      len;

    if (Symbol->SizeOfStruct < sizeof(*Symbol)) return FALSE;
    si->SizeOfStruct = sizeof(*si);
Eric Pouech's avatar
Eric Pouech committed
1419
    si->MaxNameLen = MAX_SYM_NAME;
1420 1421 1422 1423 1424 1425
    if (!SymFromName(hProcess, Name, si)) return FALSE;

    Symbol->Address = si->Address;
    Symbol->Size    = si->Size;
    Symbol->Flags   = si->Flags;
    len = min(Symbol->MaxNameLength, si->MaxNameLen);
1426
    lstrcpynA(Symbol->Name, si->Name, len);
1427 1428 1429 1430
    return TRUE;
}

/******************************************************************
1431
 *		sym_fill_func_line_info
1432 1433 1434
 *
 * fills information about a file
 */
1435
BOOL symt_fill_func_line_info(const struct module* module, const struct symt_function* func,
1436
                              DWORD64 addr, IMAGEHLP_LINE64* line)
1437 1438 1439
{
    struct line_info*   dli = NULL;
    BOOL                found = FALSE;
1440
    int                 i;
1441 1442 1443

    assert(func->symt.tag == SymTagFunction);

1444
    for (i=vector_length(&func->vlines)-1; i>=0; i--)
1445
    {
1446
        dli = vector_at(&func->vlines, i);
1447
        if (!dli->is_source_file)
1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465
        {
            if (found || dli->u.pc_offset > addr) continue;
            line->LineNumber = dli->line_number;
            line->Address    = dli->u.pc_offset;
            line->Key        = dli;
            found = TRUE;
            continue;
        }
        if (found)
        {
            line->FileName = (char*)source_get(module, dli->u.source_file);
            return TRUE;
        }
    }
    return FALSE;
}

/***********************************************************************
1466
 *		SymGetSymNext64 (DBGHELP.@)
1467
 */
1468
BOOL WINAPI SymGetSymNext64(HANDLE hProcess, PIMAGEHLP_SYMBOL64 Symbol)
1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481
{
    /* algo:
     * get module from Symbol.Address
     * get index in module.addr_sorttab of Symbol.Address
     * increment index
     * if out of module bounds, move to next module in process address space
     */
    FIXME("(%p, %p): stub\n", hProcess, Symbol);
    SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
    return FALSE;
}

/***********************************************************************
1482
 *		SymGetSymNext (DBGHELP.@)
1483
 */
1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499
BOOL WINAPI SymGetSymNext(HANDLE hProcess, PIMAGEHLP_SYMBOL Symbol)
{
    FIXME("(%p, %p): stub\n", hProcess, Symbol);
    SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
    return FALSE;
}

/***********************************************************************
 *		SymGetSymPrev64 (DBGHELP.@)
 */
BOOL WINAPI SymGetSymPrev64(HANDLE hProcess, PIMAGEHLP_SYMBOL64 Symbol)
{
    FIXME("(%p, %p): stub\n", hProcess, Symbol);
    SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
    return FALSE;
}
1500

1501 1502 1503
/***********************************************************************
 *		SymGetSymPrev (DBGHELP.@)
 */
1504 1505 1506 1507 1508 1509 1510
BOOL WINAPI SymGetSymPrev(HANDLE hProcess, PIMAGEHLP_SYMBOL Symbol)
{
    FIXME("(%p, %p): stub\n", hProcess, Symbol);
    SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
    return FALSE;
}

1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523
/******************************************************************
 *		copy_line_64_from_32 (internal)
 *
 */
static void copy_line_64_from_32(IMAGEHLP_LINE64* l64, const IMAGEHLP_LINE* l32)

{
    l64->Key = l32->Key;
    l64->LineNumber = l32->LineNumber;
    l64->FileName = l32->FileName;
    l64->Address = l32->Address;
}

1524 1525 1526 1527
/******************************************************************
 *		copy_line_W64_from_32 (internal)
 *
 */
1528
static void copy_line_W64_from_64(struct process* pcs, IMAGEHLP_LINEW64* l64w, const IMAGEHLP_LINE64* l64)
1529 1530 1531
{
    unsigned len;

1532 1533 1534 1535 1536 1537
    l64w->Key = l64->Key;
    l64w->LineNumber = l64->LineNumber;
    len = MultiByteToWideChar(CP_ACP, 0, l64->FileName, -1, NULL, 0);
    if ((l64w->FileName = fetch_buffer(pcs, len * sizeof(WCHAR))))
        MultiByteToWideChar(CP_ACP, 0, l64->FileName, -1, l64w->FileName, len);
    l64w->Address = l64->Address;
1538 1539
}

1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552
/******************************************************************
 *		copy_line_32_from_64 (internal)
 *
 */
static void copy_line_32_from_64(IMAGEHLP_LINE* l32, const IMAGEHLP_LINE64* l64)

{
    l32->Key = l64->Key;
    l32->LineNumber = l64->LineNumber;
    l32->FileName = l64->FileName;
    l32->Address = l64->Address;
}

1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568
/******************************************************************
 *		SymGetLineFromAddr (DBGHELP.@)
 *
 */
BOOL WINAPI SymGetLineFromAddr(HANDLE hProcess, DWORD dwAddr,
                               PDWORD pdwDisplacement, PIMAGEHLP_LINE Line)
{
    IMAGEHLP_LINE64     il64;

    il64.SizeOfStruct = sizeof(il64);
    if (!SymGetLineFromAddr64(hProcess, dwAddr, pdwDisplacement, &il64))
        return FALSE;
    copy_line_32_from_64(Line, &il64);
    return TRUE;
}

1569 1570 1571 1572 1573 1574 1575
/******************************************************************
 *		SymGetLineFromAddr64 (DBGHELP.@)
 *
 */
BOOL WINAPI SymGetLineFromAddr64(HANDLE hProcess, DWORD64 dwAddr, 
                                 PDWORD pdwDisplacement, PIMAGEHLP_LINE64 Line)
{
1576 1577 1578 1579
    struct module_pair  pair;
    struct symt_ht*     symt;

    TRACE("%p %s %p %p\n", hProcess, wine_dbgstr_longlong(dwAddr), pdwDisplacement, Line);
1580 1581

    if (Line->SizeOfStruct < sizeof(*Line)) return FALSE;
1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592

    pair.pcs = process_find_by_handle(hProcess);
    if (!pair.pcs) return FALSE;
    pair.requested = module_find_by_addr(pair.pcs, dwAddr, DMT_UNKNOWN);
    if (!module_get_debug(&pair)) return FALSE;
    if ((symt = symt_find_nearest(pair.effective, dwAddr)) == NULL) return FALSE;

    if (symt->symt.tag != SymTagFunction) return FALSE;
    if (!symt_fill_func_line_info(pair.effective, (struct symt_function*)symt,
                                  dwAddr, Line)) return FALSE;
    *pdwDisplacement = dwAddr - Line->Address;
1593 1594 1595
    return TRUE;
}

1596 1597 1598 1599 1600 1601 1602
/******************************************************************
 *		SymGetLineFromAddrW64 (DBGHELP.@)
 *
 */
BOOL WINAPI SymGetLineFromAddrW64(HANDLE hProcess, DWORD64 dwAddr, 
                                  PDWORD pdwDisplacement, PIMAGEHLP_LINEW64 Line)
{
1603
    IMAGEHLP_LINE64     il64;
1604

1605 1606
    il64.SizeOfStruct = sizeof(il64);
    if (!SymGetLineFromAddr64(hProcess, dwAddr, pdwDisplacement, &il64))
1607
        return FALSE;
1608
    copy_line_W64_from_64(process_find_by_handle(hProcess), Line, &il64);
1609 1610 1611
    return TRUE;
}

1612
/******************************************************************
1613
 *		SymGetLinePrev64 (DBGHELP.@)
1614 1615
 *
 */
1616
BOOL WINAPI SymGetLinePrev64(HANDLE hProcess, PIMAGEHLP_LINE64 Line)
1617
{
Eric Pouech's avatar
Eric Pouech committed
1618
    struct module_pair  pair;
1619 1620 1621 1622 1623 1624 1625
    struct line_info*   li;
    BOOL                in_search = FALSE;

    TRACE("(%p %p)\n", hProcess, Line);

    if (Line->SizeOfStruct < sizeof(*Line)) return FALSE;

1626 1627 1628 1629
    pair.pcs = process_find_by_handle(hProcess);
    if (!pair.pcs) return FALSE;
    pair.requested = module_find_by_addr(pair.pcs, Line->Address, DMT_UNKNOWN);
    if (!module_get_debug(&pair)) return FALSE;
1630 1631

    if (Line->Key == 0) return FALSE;
1632
    li = Line->Key;
1633 1634 1635 1636 1637
    /* things are a bit complicated because when we encounter a DLIT_SOURCEFILE
     * element we have to go back until we find the prev one to get the real
     * source file name for the DLIT_OFFSET element just before 
     * the first DLIT_SOURCEFILE
     */
1638
    while (!li->is_first)
1639 1640
    {
        li--;
1641
        if (!li->is_source_file)
1642 1643 1644 1645 1646 1647 1648 1649 1650 1651
        {
            Line->LineNumber = li->line_number;
            Line->Address    = li->u.pc_offset;
            Line->Key        = li;
            if (!in_search) return TRUE;
        }
        else
        {
            if (in_search)
            {
Eric Pouech's avatar
Eric Pouech committed
1652
                Line->FileName = (char*)source_get(pair.effective, li->u.source_file);
1653 1654 1655 1656 1657 1658 1659 1660 1661
                return TRUE;
            }
            in_search = TRUE;
        }
    }
    SetLastError(ERROR_NO_MORE_ITEMS); /* FIXME */
    return FALSE;
}

1662
/******************************************************************
1663
 *		SymGetLinePrev (DBGHELP.@)
1664 1665
 *
 */
1666
BOOL WINAPI SymGetLinePrev(HANDLE hProcess, PIMAGEHLP_LINE Line)
1667
{
1668
    IMAGEHLP_LINE64     line64;
1669

1670 1671 1672 1673
    line64.SizeOfStruct = sizeof(line64);
    copy_line_64_from_32(&line64, Line);
    if (!SymGetLinePrev64(hProcess, &line64)) return FALSE;
    copy_line_32_from_64(Line, &line64);
1674 1675
    return TRUE;
}
1676 1677

BOOL symt_get_func_line_next(const struct module* module, PIMAGEHLP_LINE64 line)
1678 1679 1680 1681
{
    struct line_info*   li;

    if (line->Key == 0) return FALSE;
1682
    li = line->Key;
1683
    while (!li->is_last)
1684 1685
    {
        li++;
1686
        if (!li->is_source_file)
1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697
        {
            line->LineNumber = li->line_number;
            line->Address    = li->u.pc_offset;
            line->Key        = li;
            return TRUE;
        }
        line->FileName = (char*)source_get(module, li->u.source_file);
    }
    return FALSE;
}

1698
/******************************************************************
1699
 *		SymGetLineNext64 (DBGHELP.@)
1700 1701
 *
 */
1702
BOOL WINAPI SymGetLineNext64(HANDLE hProcess, PIMAGEHLP_LINE64 Line)
1703
{
Eric Pouech's avatar
Eric Pouech committed
1704
    struct module_pair  pair;
1705 1706 1707 1708

    TRACE("(%p %p)\n", hProcess, Line);

    if (Line->SizeOfStruct < sizeof(*Line)) return FALSE;
1709 1710 1711 1712
    pair.pcs = process_find_by_handle(hProcess);
    if (!pair.pcs) return FALSE;
    pair.requested = module_find_by_addr(pair.pcs, Line->Address, DMT_UNKNOWN);
    if (!module_get_debug(&pair)) return FALSE;
1713

Eric Pouech's avatar
Eric Pouech committed
1714
    if (symt_get_func_line_next(pair.effective, Line)) return TRUE;
1715 1716 1717 1718
    SetLastError(ERROR_NO_MORE_ITEMS); /* FIXME */
    return FALSE;
}

1719
/******************************************************************
1720
 *		SymGetLineNext (DBGHELP.@)
1721 1722
 *
 */
1723
BOOL WINAPI SymGetLineNext(HANDLE hProcess, PIMAGEHLP_LINE Line)
1724
{
1725
    IMAGEHLP_LINE64     line64;
1726

1727 1728 1729 1730
    line64.SizeOfStruct = sizeof(line64);
    copy_line_64_from_32(&line64, Line);
    if (!SymGetLineNext64(hProcess, &line64)) return FALSE;
    copy_line_32_from_64(Line, &line64);
1731 1732
    return TRUE;
}
1733

1734 1735 1736
/***********************************************************************
 *		SymUnDName (DBGHELP.@)
 */
1737
BOOL WINAPI SymUnDName(PIMAGEHLP_SYMBOL sym, PSTR UnDecName, DWORD UnDecNameLength)
1738
{
1739 1740 1741 1742 1743 1744 1745 1746 1747
    return UnDecorateSymbolName(sym->Name, UnDecName, UnDecNameLength,
                                UNDNAME_COMPLETE) != 0;
}

/***********************************************************************
 *		SymUnDName64 (DBGHELP.@)
 */
BOOL WINAPI SymUnDName64(PIMAGEHLP_SYMBOL64 sym, PSTR UnDecName, DWORD UnDecNameLength)
{
1748
    return UnDecorateSymbolName(sym->Name, UnDecName, UnDecNameLength,
1749
                                UNDNAME_COMPLETE) != 0;
1750 1751
}

1752 1753
static void * CDECL und_alloc(size_t len) { return HeapAlloc(GetProcessHeap(), 0, len); }
static void   CDECL und_free (void* ptr)  { HeapFree(GetProcessHeap(), 0, ptr); }
1754

1755
static char *und_name(char *buffer, const char *mangled, int buflen, unsigned short flags)
1756
{
1757
    /* undocumented from msvcrt */
1758
    static HANDLE hMsvcrt;
1759
    static char* (CDECL *p_undname)(char*, const char*, int, void* (CDECL*)(size_t), void (CDECL*)(void*), unsigned short);
1760
    static const WCHAR szMsvcrt[] = {'m','s','v','c','r','t','.','d','l','l',0};
1761 1762 1763 1764 1765

    if (!p_undname)
    {
        if (!hMsvcrt) hMsvcrt = LoadLibraryW(szMsvcrt);
        if (hMsvcrt) p_undname = (void*)GetProcAddress(hMsvcrt, "__unDName");
1766
        if (!p_undname) return NULL;
1767 1768
    }

1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800
    return p_undname(buffer, mangled, buflen, und_alloc, und_free, flags);
}

/***********************************************************************
 *		UnDecorateSymbolName (DBGHELP.@)
 */
DWORD WINAPI UnDecorateSymbolName(const char *decorated_name, char *undecorated_name,
                                  DWORD undecorated_length, DWORD flags)
{
    TRACE("(%s, %p, %d, 0x%08x)\n",
          debugstr_a(decorated_name), undecorated_name, undecorated_length, flags);

    if (!undecorated_name || !undecorated_length)
        return 0;
    if (!und_name(undecorated_name, decorated_name, undecorated_length, flags))
        return 0;
    return strlen(undecorated_name);
}

/***********************************************************************
 *		UnDecorateSymbolNameW (DBGHELP.@)
 */
DWORD WINAPI UnDecorateSymbolNameW(const WCHAR *decorated_name, WCHAR *undecorated_name,
                                   DWORD undecorated_length, DWORD flags)
{
    char *buf, *ptr;
    int len, ret = 0;

    TRACE("(%s, %p, %d, 0x%08x)\n",
          debugstr_w(decorated_name), undecorated_name, undecorated_length, flags);

    if (!undecorated_name || !undecorated_length)
1801
        return 0;
1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817

    len = WideCharToMultiByte(CP_ACP, 0, decorated_name, -1, NULL, 0, NULL, NULL);
    if ((buf = HeapAlloc(GetProcessHeap(), 0, len)))
    {
        WideCharToMultiByte(CP_ACP, 0, decorated_name, -1, buf, len, NULL, NULL);
        if ((ptr = und_name(NULL, buf, 0, flags)))
        {
            MultiByteToWideChar(CP_ACP, 0, ptr, -1, undecorated_name, undecorated_length);
            undecorated_name[undecorated_length - 1] = 0;
            ret = strlenW(undecorated_name);
            und_free(ptr);
        }
        HeapFree(GetProcessHeap(), 0, buf);
    }

    return ret;
1818
}
1819

1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945
#define WILDCHAR(x)      (-(x))

static  int     re_fetch_char(const WCHAR** re)
{
    switch (**re)
    {
    case '\\': (*re)++; return *(*re)++;
    case '*': case '[': case '?': case '+': case '#': case ']': return WILDCHAR(*(*re)++);
    default: return *(*re)++;
    }
}

static inline int  re_match_char(WCHAR ch1, WCHAR ch2, BOOL _case)
{
    return _case ? ch1 - ch2 : toupperW(ch1) - toupperW(ch2);
}

static const WCHAR* re_match_one(const WCHAR* string, const WCHAR* elt, BOOL _case)
{
    int         ch1, prev = 0;
    unsigned    state = 0;

    switch (ch1 = re_fetch_char(&elt))
    {
    default:
        return (ch1 >= 0 && re_match_char(*string, ch1, _case) == 0) ? ++string : NULL;
    case WILDCHAR('?'): return *string ? ++string : NULL;
    case WILDCHAR('*'): assert(0);
    case WILDCHAR('['): break;
    }

    for (;;)
    {
        ch1 = re_fetch_char(&elt);
        if (ch1 == WILDCHAR(']')) return NULL;
        if (state == 1 && ch1 == '-') state = 2;
        else
        {
            if (re_match_char(*string, ch1, _case) == 0) return ++string;
            switch (state)
            {
            case 0:
                state = 1;
                prev = ch1;
                break;
            case 1:
                state = 0;
                break;
            case 2:
                if (prev >= 0 && ch1 >= 0 && re_match_char(prev, *string, _case) <= 0 &&
                    re_match_char(*string, ch1, _case) <= 0)
                    return ++string;
                state = 0;
                break;
            }
        }
    }
}

/******************************************************************
 *		re_match_multi
 *
 * match a substring of *pstring according to *pre regular expression
 * pstring and pre are only updated in case of successful match
 */
static BOOL re_match_multi(const WCHAR** pstring, const WCHAR** pre, BOOL _case)
{
    const WCHAR* re_end = *pre;
    const WCHAR* string_end = *pstring;
    const WCHAR* re_beg;
    const WCHAR* string_beg;
    const WCHAR* next;
    int          ch;

    while (*re_end && *string_end)
    {
        string_beg = string_end;
        re_beg = re_end;
        switch (ch = re_fetch_char(&re_end))
        {
        case WILDCHAR(']'): case WILDCHAR('+'): case WILDCHAR('#'): return FALSE;
        case WILDCHAR('*'):
            /* transform '*' into '?#' */
            {static const WCHAR qmW[] = {'?',0}; re_beg = qmW;}
            goto closure;
        case WILDCHAR('['):
            do
            {
                if (!(ch = re_fetch_char(&re_end))) return FALSE;
            } while (ch != WILDCHAR(']'));
            /* fall through */
        case WILDCHAR('?'):
        default:
            break;
        }

        switch (*re_end)
        {
        case '+':
            if (!(next = re_match_one(string_end, re_beg, _case))) return FALSE;
            string_beg++;
            /* fall through */
        case '#':
            re_end++;
        closure:
            while ((next = re_match_one(string_end, re_beg, _case))) string_end = next;
            for ( ; string_end >= string_beg; string_end--)
            {
                if (re_match_multi(&string_end, &re_end, _case)) goto found;
            }
            return FALSE;
        default:
            if (!(next = re_match_one(string_end, re_beg, _case))) return FALSE;
            string_end = next;
        }
        re_beg = re_end;
    }

    if (*re_end || *string_end) return FALSE;

found:
    *pre = re_end;
    *pstring = string_end;
    return TRUE;
}

1946
/******************************************************************
1947
 *		SymMatchStringA (DBGHELP.@)
1948 1949
 *
 */
1950
BOOL WINAPI SymMatchStringA(PCSTR string, PCSTR re, BOOL _case)
1951
{
1952 1953 1954 1955
    WCHAR*      strW;
    WCHAR*      reW;
    BOOL        ret = FALSE;
    DWORD       sz;
1956

1957 1958 1959 1960 1961
    if (!string || !re)
    {
        SetLastError(ERROR_INVALID_HANDLE);
        return FALSE;
    }
1962 1963
    TRACE("%s %s %c\n", string, re, _case ? 'Y' : 'N');

1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974
    sz = MultiByteToWideChar(CP_ACP, 0, string, -1, NULL, 0);
    if ((strW = HeapAlloc(GetProcessHeap(), 0, sz * sizeof(WCHAR))))
        MultiByteToWideChar(CP_ACP, 0, string, -1, strW, sz);
    sz = MultiByteToWideChar(CP_ACP, 0, re, -1, NULL, 0);
    if ((reW = HeapAlloc(GetProcessHeap(), 0, sz * sizeof(WCHAR))))
        MultiByteToWideChar(CP_ACP, 0, re, -1, reW, sz);

    if (strW && reW)
        ret = SymMatchStringW(strW, reW, _case);
    HeapFree(GetProcessHeap(), 0, strW);
    HeapFree(GetProcessHeap(), 0, reW);
1975 1976 1977
    return ret;
}

1978 1979 1980 1981 1982 1983 1984 1985
/******************************************************************
 *		SymMatchStringW (DBGHELP.@)
 *
 */
BOOL WINAPI SymMatchStringW(PCWSTR string, PCWSTR re, BOOL _case)
{
    TRACE("%s %s %c\n", debugstr_w(string), debugstr_w(re), _case ? 'Y' : 'N');

1986 1987 1988 1989 1990 1991
    if (!string || !re)
    {
        SetLastError(ERROR_INVALID_HANDLE);
        return FALSE;
    }
    return re_match_multi(&string, &re, _case);
1992 1993
}

1994 1995 1996 1997
static inline BOOL doSymSearch(HANDLE hProcess, ULONG64 BaseOfDll, DWORD Index,
                               DWORD SymTag, PCWSTR Mask, DWORD64 Address,
                               PSYM_ENUMERATESYMBOLS_CALLBACK EnumSymbolsCallback,
                               PVOID UserContext, DWORD Options)
1998
{
1999 2000
    struct sym_enum     se;

2001 2002
    if (Options != SYMSEARCH_GLOBALSONLY)
    {
2003
        FIXME("Unsupported searching with options (%x)\n", Options);
2004 2005 2006
        SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }
2007 2008 2009 2010 2011 2012 2013 2014 2015

    se.cb = EnumSymbolsCallback;
    se.user = UserContext;
    se.index = Index;
    se.tag = SymTag;
    se.addr = Address;
    se.sym_info = (PSYMBOL_INFO)se.buffer;

    return sym_enum(hProcess, BaseOfDll, Mask, &se);
2016
}
2017

2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047
/******************************************************************
 *		SymSearch (DBGHELP.@)
 */
BOOL WINAPI SymSearch(HANDLE hProcess, ULONG64 BaseOfDll, DWORD Index,
                      DWORD SymTag, PCSTR Mask, DWORD64 Address,
                      PSYM_ENUMERATESYMBOLS_CALLBACK EnumSymbolsCallback,
                      PVOID UserContext, DWORD Options)
{
    LPWSTR      maskW = NULL;
    BOOLEAN     ret;

    TRACE("(%p %s %u %u %s %s %p %p %x)\n",
          hProcess, wine_dbgstr_longlong(BaseOfDll), Index, SymTag, Mask,
          wine_dbgstr_longlong(Address), EnumSymbolsCallback,
          UserContext, Options);

    if (Mask)
    {
        DWORD sz = MultiByteToWideChar(CP_ACP, 0, Mask, -1, NULL, 0);

        if (!(maskW = HeapAlloc(GetProcessHeap(), 0, sz * sizeof(WCHAR))))
            return FALSE;
        MultiByteToWideChar(CP_ACP, 0, Mask, -1, maskW, sz);
    }
    ret = doSymSearch(hProcess, BaseOfDll, Index, SymTag, maskW, Address,
                      EnumSymbolsCallback, UserContext, Options);
    HeapFree(GetProcessHeap(), 0, maskW);
    return ret;
}

2048 2049 2050 2051 2052 2053 2054 2055 2056 2057
/******************************************************************
 *		SymSearchW (DBGHELP.@)
 */
BOOL WINAPI SymSearchW(HANDLE hProcess, ULONG64 BaseOfDll, DWORD Index,
                       DWORD SymTag, PCWSTR Mask, DWORD64 Address,
                       PSYM_ENUMERATESYMBOLS_CALLBACKW EnumSymbolsCallback,
                       PVOID UserContext, DWORD Options)
{
    struct sym_enumW    sew;

2058 2059
    TRACE("(%p %s %u %u %s %s %p %p %x)\n",
          hProcess, wine_dbgstr_longlong(BaseOfDll), Index, SymTag, debugstr_w(Mask),
2060 2061 2062 2063 2064 2065 2066
          wine_dbgstr_longlong(Address), EnumSymbolsCallback,
          UserContext, Options);

    sew.ctx = UserContext;
    sew.cb = EnumSymbolsCallback;
    sew.sym_info = (PSYMBOL_INFOW)sew.buffer;

2067 2068
    return doSymSearch(hProcess, BaseOfDll, Index, SymTag, Mask, Address,
                       sym_enumW, &sew, Options);
2069
}
2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103

/******************************************************************
 *		SymAddSymbol (DBGHELP.@)
 *
 */
BOOL WINAPI SymAddSymbol(HANDLE hProcess, ULONG64 BaseOfDll, PCSTR name,
                         DWORD64 addr, DWORD size, DWORD flags)
{
    WCHAR       nameW[MAX_SYM_NAME];

    MultiByteToWideChar(CP_ACP, 0, name, -1, nameW, sizeof(nameW) / sizeof(WCHAR));
    return SymAddSymbolW(hProcess, BaseOfDll, nameW, addr, size, flags);
}

/******************************************************************
 *		SymAddSymbolW (DBGHELP.@)
 *
 */
BOOL WINAPI SymAddSymbolW(HANDLE hProcess, ULONG64 BaseOfDll, PCWSTR name,
                          DWORD64 addr, DWORD size, DWORD flags)
{
    struct module_pair  pair;

    TRACE("(%p %s %s %u)\n", hProcess, wine_dbgstr_w(name), wine_dbgstr_longlong(addr), size);

    pair.pcs = process_find_by_handle(hProcess);
    if (!pair.pcs) return FALSE;
    pair.requested = module_find_by_addr(pair.pcs, BaseOfDll, DMT_UNKNOWN);
    if (!module_get_debug(&pair)) return FALSE;

    SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
    return FALSE;
}

2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115
/******************************************************************
 *		SymSetScopeFromAddr (DBGHELP.@)
 */
BOOL WINAPI SymSetScopeFromAddr(HANDLE hProcess, ULONG64 addr)
{
    struct process*     pcs;

    FIXME("(%p %s): stub\n", hProcess, wine_dbgstr_longlong(addr));

    if (!(pcs = process_find_by_handle(hProcess))) return FALSE;
    return TRUE;
}
2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126

/******************************************************************
 *		SymEnumLines (DBGHELP.@)
 *
 */
BOOL WINAPI SymEnumLines(HANDLE hProcess, ULONG64 base, PCSTR compiland,
                         PCSTR srcfile, PSYM_ENUMLINES_CALLBACK cb, PVOID user)
{
    struct module_pair          pair;
    struct hash_table_iter      hti;
    struct symt_ht*             sym;
2127
    WCHAR*                      srcmask;
2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140
    struct line_info*           dli;
    void*                       ptr;
    SRCCODEINFO                 sci;
    const char*                 file;

    if (!cb) return FALSE;
    if (!(dbghelp_options & SYMOPT_LOAD_LINES)) return TRUE;

    pair.pcs = process_find_by_handle(hProcess);
    if (!pair.pcs) return FALSE;
    if (compiland) FIXME("Unsupported yet (filtering on compiland %s)\n", compiland);
    pair.requested = module_find_by_addr(pair.pcs, base, DMT_UNKNOWN);
    if (!module_get_debug(&pair)) return FALSE;
2141
    if (!(srcmask = file_regex(srcfile))) return FALSE;
2142 2143 2144 2145 2146 2147 2148 2149 2150

    sci.SizeOfStruct = sizeof(sci);
    sci.ModBase      = base;

    hash_table_iter_init(&pair.effective->ht_symbols, &hti, NULL);
    while ((ptr = hash_table_iter_up(&hti)))
    {
        unsigned int    i;

2151
        sym = CONTAINING_RECORD(ptr, struct symt_ht, hash_elt);
2152 2153 2154 2155 2156 2157 2158 2159 2160
        if (sym->symt.tag != SymTagFunction) continue;

        sci.FileName[0] = '\0';
        for (i=0; i<vector_length(&((struct symt_function*)sym)->vlines); i++)
        {
            dli = vector_at(&((struct symt_function*)sym)->vlines, i);
            if (dli->is_source_file)
            {
                file = source_get(pair.effective, dli->u.source_file);
2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174
                if (!file) sci.FileName[0] = '\0';
                else
                {
                    DWORD   sz = MultiByteToWideChar(CP_ACP, 0, file, -1, NULL, 0);
                    WCHAR*  fileW;

                    if ((fileW = HeapAlloc(GetProcessHeap(), 0, sz * sizeof(WCHAR))))
                        MultiByteToWideChar(CP_ACP, 0, file, -1, fileW, sz);
                    if (SymMatchStringW(fileW, srcmask, FALSE))
                        strcpy(sci.FileName, file);
                    else
                        sci.FileName[0] = '\0';
                    HeapFree(GetProcessHeap(), 0, fileW);
                }
2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185
            }
            else if (sci.FileName[0])
            {
                sci.Key = dli;
                sci.Obj[0] = '\0'; /* FIXME */
                sci.LineNumber = dli->line_number;
                sci.Address = dli->u.pc_offset;
                if (!cb(&sci, user)) break;
            }
        }
    }
2186
    HeapFree(GetProcessHeap(), 0, srcmask);
2187 2188
    return TRUE;
}
2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212

BOOL WINAPI SymGetLineFromName(HANDLE hProcess, PCSTR ModuleName, PCSTR FileName,
                DWORD dwLineNumber, PLONG plDisplacement, PIMAGEHLP_LINE Line)
{
    FIXME("(%p) (%s, %s, %d %p %p): stub\n", hProcess, ModuleName, FileName,
                dwLineNumber, plDisplacement, Line);
    return FALSE;
}

BOOL WINAPI SymGetLineFromName64(HANDLE hProcess, PCSTR ModuleName, PCSTR FileName,
                DWORD dwLineNumber, PLONG lpDisplacement, PIMAGEHLP_LINE64 Line)
{
    FIXME("(%p) (%s, %s, %d %p %p): stub\n", hProcess, ModuleName, FileName,
                dwLineNumber, lpDisplacement, Line);
    return FALSE;
}

BOOL WINAPI SymGetLineFromNameW64(HANDLE hProcess, PCWSTR ModuleName, PCWSTR FileName,
                DWORD dwLineNumber, PLONG plDisplacement, PIMAGEHLP_LINEW64 Line)
{
    FIXME("(%p) (%s, %s, %d %p %p): stub\n", hProcess, debugstr_w(ModuleName), debugstr_w(FileName),
                dwLineNumber, plDisplacement, Line);
    return FALSE;
}
2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236

/******************************************************************
 *		SymFromIndex (DBGHELP.@)
 *
 */
BOOL WINAPI SymFromIndex(HANDLE hProcess, ULONG64 BaseOfDll, DWORD index, PSYMBOL_INFO symbol)
{
    FIXME("hProcess = %p, BaseOfDll = %s, index = %d, symbol = %p\n",
          hProcess, wine_dbgstr_longlong(BaseOfDll), index, symbol);

    return FALSE;
}

/******************************************************************
 *		SymFromIndexW (DBGHELP.@)
 *
 */
BOOL WINAPI SymFromIndexW(HANDLE hProcess, ULONG64 BaseOfDll, DWORD index, PSYMBOL_INFOW symbol)
{
    FIXME("hProcess = %p, BaseOfDll = %s, index = %d, symbol = %p\n",
          hProcess, wine_dbgstr_longlong(BaseOfDll), index, symbol);

    return FALSE;
}
2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258

/******************************************************************
 *		SymSetHomeDirectory (DBGHELP.@)
 *
 */
PCHAR WINAPI SymSetHomeDirectory(HANDLE hProcess, PCSTR dir)
{
    FIXME("(%p, %s): stub\n", hProcess, dir);

    return NULL;
}

/******************************************************************
 *		SymSetHomeDirectoryW (DBGHELP.@)
 *
 */
PWSTR WINAPI SymSetHomeDirectoryW(HANDLE hProcess, PCWSTR dir)
{
    FIXME("(%p, %s): stub\n", hProcess, debugstr_w(dir));

    return NULL;
}