undname.c 57.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/*
 *  Demangle VC++ symbols into C function prototypes
 *
 *  Copyright 2000 Jon Griffiths
 *            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
 */

#include <assert.h>
23
#include <stdio.h>
24
#include <stdlib.h>
25 26 27 28 29 30 31
#include "msvcrt.h"

#include "wine/debug.h"

WINE_DEFAULT_DEBUG_CHANNEL(msvcrt);

/* TODO:
32
 * - document a bit (grammar + functions)
33 34 35
 * - back-port this new code into tools/winedump/msmangle.c
 */

36 37
/* How data types qualifiers are stored:
 * M (in the following definitions) is defined for
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
 * 'A', 'B', 'C' and 'D' as follows
 *      {<A>}:  ""
 *      {<B>}:  "const "
 *      {<C>}:  "volatile "
 *      {<D>}:  "const volatile "
 *
 *      in arguments:
 *              P<M>x   {<M>}x*
 *              Q<M>x   {<M>}x* const
 *              A<M>x   {<M>}x&
 *      in data fields:
 *              same as for arguments and also the following
 *              ?<M>x   {<M>}x
 *              
 */

struct array
{
    unsigned            start;          /* first valid reference in array */
    unsigned            num;            /* total number of used elts */
    unsigned            max;
59 60
    unsigned            alloc;
    char**              elts;
61 62 63 64 65 66 67 68 69 70 71 72
};

/* Structure holding a parsed symbol */
struct parsed_symbol
{
    unsigned            flags;          /* the UNDNAME_ flags used for demangling */
    malloc_func_t       mem_alloc_ptr;  /* internal allocator */
    free_func_t         mem_free_ptr;   /* internal deallocator */

    const char*         current;        /* pointer in input (mangled) string */
    char*               result;         /* demangled string */

73
    struct array        names;          /* array of names for back reference */
74 75 76 77 78 79
    struct array        stack;          /* stack of parsed strings */

    void*               alloc_list;     /* linked list of allocated blocks */
    unsigned            avail_in_first; /* number of available bytes in head block */
};

80 81 82
enum datatype_e
{
    DT_NO_LEADING_WS = 0x01,
83
    DT_NO_LRSEP_WS = 0x02,
84 85
};

86 87 88 89 90
/* Type for parsing mangled types */
struct datatype_t
{
    const char*         left;
    const char*         right;
91
    enum datatype_e     flags;
92 93
};

94
static BOOL symbol_demangle(struct parsed_symbol* sym);
95
static char* get_class_name(struct parsed_symbol* sym);
96

97 98 99 100 101 102 103
/******************************************************************
 *		und_alloc
 *
 * Internal allocator. Uses a simple linked list of large blocks
 * where we use a poor-man allocator. It's fast, and since all
 * allocation is pool, memory management is easy (esp. freeing).
 */
104
static void*    und_alloc(struct parsed_symbol* sym, unsigned int len)
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
{
    void*       ptr;

#define BLOCK_SIZE      1024
#define AVAIL_SIZE      (1024 - sizeof(void*))

    if (len > AVAIL_SIZE)
    {
        /* allocate a specific block */
        ptr = sym->mem_alloc_ptr(sizeof(void*) + len);
        if (!ptr) return NULL;
        *(void**)ptr = sym->alloc_list;
        sym->alloc_list = ptr;
        sym->avail_in_first = 0;
        ptr = (char*)sym->alloc_list + sizeof(void*);
    }
    else 
    {
        if (len > sym->avail_in_first)
        {
            /* add a new block */
            ptr = sym->mem_alloc_ptr(BLOCK_SIZE);
            if (!ptr) return NULL;
            *(void**)ptr = sym->alloc_list;
            sym->alloc_list = ptr;
            sym->avail_in_first = AVAIL_SIZE;
        }
        /* grab memory from head block */
        ptr = (char*)sym->alloc_list + BLOCK_SIZE - sym->avail_in_first;
        sym->avail_in_first -= len;
    }
    return ptr;
#undef BLOCK_SIZE
#undef AVAIL_SIZE
}

/******************************************************************
 *		und_free
 * Frees all the blocks in the list of large blocks allocated by
 * und_alloc.
 */
static void und_free_all(struct parsed_symbol* sym)
{
    void*       next;

    while (sym->alloc_list)
    {
        next = *(void**)sym->alloc_list;
153
        if(sym->mem_free_ptr) sym->mem_free_ptr(sym->alloc_list);
154 155 156 157 158 159 160 161 162 163 164
        sym->alloc_list = next;
    }
    sym->avail_in_first = 0;
}

/******************************************************************
 *		str_array_init
 * Initialises an array of strings
 */
static void str_array_init(struct array* a)
{
165 166
    a->start = a->num = a->max = a->alloc = 0;
    a->elts = NULL;
167 168 169 170 171 172
}

/******************************************************************
 *		str_array_push
 * Adding a new string to an array
 */
173
static BOOL str_array_push(struct parsed_symbol* sym, const char* ptr, int len,
174 175
                           struct array* a)
{
176 177
    char**      new;

178 179
    assert(ptr);
    assert(a);
180

181 182 183 184 185 186 187 188 189 190 191 192 193 194
    if (!a->alloc)
    {
        new = und_alloc(sym, (a->alloc = 32) * sizeof(a->elts[0]));
        if (!new) return FALSE;
        a->elts = new;
    }
    else if (a->max >= a->alloc)
    {
        new = und_alloc(sym, (a->alloc * 2) * sizeof(a->elts[0]));
        if (!new) return FALSE;
        memcpy(new, a->elts, a->alloc * sizeof(a->elts[0]));
        a->alloc *= 2;
        a->elts = new;
    }
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
    if (len == -1) len = strlen(ptr);
    a->elts[a->num] = und_alloc(sym, len + 1);
    assert(a->elts[a->num]);
    memcpy(a->elts[a->num], ptr, len);
    a->elts[a->num][len] = '\0'; 
    if (++a->num >= a->max) a->max = a->num;
    {
        int i;
        char c;

        for (i = a->max - 1; i >= 0; i--)
        {
            c = '>';
            if (i < a->start) c = '-';
            else if (i >= a->num) c = '}';
210
            TRACE("%p\t%d%c %s\n", a, i, c, debugstr_a(a->elts[i]));
211 212
        }
    }
213 214

    return TRUE;
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
}

/******************************************************************
 *		str_array_get_ref
 * Extracts a reference from an existing array (doing proper type
 * checking)
 */
static char* str_array_get_ref(struct array* cref, unsigned idx)
{
    assert(cref);
    if (cref->start + idx >= cref->max)
    {
        WARN("Out of bounds: %p %d + %d >= %d\n", 
              cref, cref->start, idx, cref->max);
        return NULL;
    }
    TRACE("Returning %p[%d] => %s\n", 
232
          cref, idx, debugstr_a(cref->elts[cref->start + idx]));
233 234 235 236 237 238 239 240
    return cref->elts[cref->start + idx];
}

/******************************************************************
 *		str_printf
 * Helper for printf type of command (only %s and %c are implemented) 
 * while dynamically allocating the buffer
 */
241
static char* WINAPIV str_printf(struct parsed_symbol* sym, const char* format, ...)
242
{
243 244 245 246 247
    va_list      args;
    unsigned int len = 1, i, sz;
    char*        tmp;
    char*        p;
    char*        t;
248 249 250 251 252 253 254 255 256 257

    va_start(args, format);
    for (i = 0; format[i]; i++)
    {
        if (format[i] == '%')
        {
            switch (format[++i])
            {
            case 's': t = va_arg(args, char*); if (t) len += strlen(t); break;
            case 'c': (void)va_arg(args, int); len++; break;
258
            default: i--; /* fall through */
259 260 261 262 263 264
            case '%': len++; break;
            }
        }
        else len++;
    }
    va_end(args);
265
    if (!(tmp = und_alloc(sym, len))) return NULL;
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
    va_start(args, format);
    for (p = tmp, i = 0; format[i]; i++)
    {
        if (format[i] == '%')
        {
            switch (format[++i])
            {
            case 's':
                t = va_arg(args, char*);
                if (t)
                {
                    sz = strlen(t);
                    memcpy(p, t, sz);
                    p += sz;
                }
                break;
            case 'c':
                *p++ = (char)va_arg(args, int);
                break;
285
            default: i--; /* fall through */
286 287 288 289 290 291 292 293 294 295
            case '%': *p++ = '%'; break;
            }
        }
        else *p++ = format[i];
    }
    va_end(args);
    *p = '\0';
    return tmp;
}

296 297 298 299 300 301
enum datatype_flags
{
    IN_ARGS = 0x01,
    WS_AFTER_QUAL_IF = 0x02,
};

302 303
/* forward declaration */
static BOOL demangle_datatype(struct parsed_symbol* sym, struct datatype_t* ct,
304
                              struct array* pmt, enum datatype_flags flags);
305

306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
static const char* get_number(struct parsed_symbol* sym)
{
    char*       ptr;
    BOOL        sgn = FALSE;

    if (*sym->current == '?')
    {
        sgn = TRUE;
        sym->current++;
    }
    if (*sym->current >= '0' && *sym->current <= '8')
    {
        ptr = und_alloc(sym, 3);
        if (sgn) ptr[0] = '-';
        ptr[sgn ? 1 : 0] = *sym->current + 1;
        ptr[sgn ? 2 : 1] = '\0';
        sym->current++;
    }
    else if (*sym->current == '9')
    {
        ptr = und_alloc(sym, 4);
        if (sgn) ptr[0] = '-';
        ptr[sgn ? 1 : 0] = '1';
        ptr[sgn ? 2 : 1] = '0';
        ptr[sgn ? 3 : 2] = '\0';
        sym->current++;
    }
    else if (*sym->current >= 'A' && *sym->current <= 'P')
    {
335
        int ret = 0;
336 337 338 339 340 341 342 343 344

        while (*sym->current >= 'A' && *sym->current <= 'P')
        {
            ret *= 16;
            ret += *sym->current++ - 'A';
        }
        if (*sym->current != '@') return NULL;

        ptr = und_alloc(sym, 17);
345
        sprintf(ptr, "%s%u", sgn ? "-" : "", ret);
346 347 348 349 350 351
        sym->current++;
    }
    else return NULL;
    return ptr;
}

352 353 354 355 356 357 358 359 360 361 362 363
/******************************************************************
 *		get_args
 * Parses a list of function/method arguments, creates a string corresponding
 * to the arguments' list.
 */
static char* get_args(struct parsed_symbol* sym, struct array* pmt_ref, BOOL z_term, 
                      char open_char, char close_char)

{
    struct datatype_t   ct;
    struct array        arg_collect;
    char*               args_str = NULL;
364
    char*               last;
365
    unsigned int        i;
366 367 368 369 370 371 372 373 374 375 376 377

    str_array_init(&arg_collect);

    /* Now come the function arguments */
    while (*sym->current)
    {
        /* Decode each data type and append it to the argument list */
        if (*sym->current == '@')
        {
            sym->current++;
            break;
        }
378
        if (!demangle_datatype(sym, &ct, pmt_ref, IN_ARGS))
379
            return NULL;
380 381
        /* 'void' terminates an argument list in a function */
        if (z_term && !strcmp(ct.left, "void")) break;
382 383 384
        if (!str_array_push(sym, str_printf(sym, "%s%s", ct.left, ct.right), -1,
                            &arg_collect))
            return NULL;
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
        if (!strcmp(ct.left, "...")) break;
    }
    /* Functions are always terminated by 'Z'. If we made it this far and
     * don't find it, we have incorrectly identified a data type.
     */
    if (z_term && *sym->current++ != 'Z') return NULL;

    if (arg_collect.num == 0 || 
        (arg_collect.num == 1 && !strcmp(arg_collect.elts[0], "void")))        
        return str_printf(sym, "%cvoid%c", open_char, close_char);
    for (i = 1; i < arg_collect.num; i++)
    {
        args_str = str_printf(sym, "%s,%s", args_str, arg_collect.elts[i]);
    }

400 401
    last = args_str ? args_str : arg_collect.elts[0];
    if (close_char == '>' && last[strlen(last) - 1] == '>')
402 403 404 405 406 407 408 409 410
        args_str = str_printf(sym, "%c%s%s %c", 
                              open_char, arg_collect.elts[0], args_str, close_char);
    else
        args_str = str_printf(sym, "%c%s%s%c", 
                              open_char, arg_collect.elts[0], args_str, close_char);
    
    return args_str;
}

411 412
static void append_extended_qualifier(struct parsed_symbol *sym, const char **where,
                                      const char *str, BOOL is_ms_keyword)
413
{
414
    if (!is_ms_keyword || !(sym->flags & UNDNAME_NO_MS_KEYWORDS))
415
    {
416
        if (is_ms_keyword && (sym->flags & UNDNAME_NO_LEADING_UNDERSCORES))
417
            str += 2;
418 419
        *where = *where ? str_printf(sym, "%s%s%s%s", *where, is_ms_keyword ? " " : "", str, is_ms_keyword ? "" : " ") :
            str_printf(sym, "%s%s", str, is_ms_keyword ? "" : " ");
420 421 422
    }
}

423
static void get_extended_qualifier(struct parsed_symbol *sym, struct datatype_t *xdt)
424
{
425
    unsigned fl = 0;
426
    xdt->left = xdt->right = NULL;
427
    xdt->flags = 0;
428
    for (;;)
429
    {
430
        switch (*sym->current)
431
        {
432 433 434 435 436 437 438 439
        case 'E': append_extended_qualifier(sym, &xdt->right, "__ptr64", TRUE);     fl |= 2; break;
        case 'F': append_extended_qualifier(sym, &xdt->left,  "__unaligned", TRUE); fl |= 2; break;
#ifdef _UCRT
        case 'G': append_extended_qualifier(sym, &xdt->right, "&", FALSE);          fl |= 1; break;
        case 'H': append_extended_qualifier(sym, &xdt->right, "&&", FALSE);         fl |= 1; break;
#endif
        case 'I': append_extended_qualifier(sym, &xdt->right, "__restrict", TRUE);  fl |= 2; break;
        default: if (fl == 1 || (fl == 3 && (sym->flags & UNDNAME_NO_MS_KEYWORDS))) xdt->flags = DT_NO_LRSEP_WS; return;
440
        }
441 442
        sym->current++;
    }
443 444 445
}

/******************************************************************
446 447
 *		get_qualifier
 * Parses the type qualifier. Always returns static strings.
448
 */
449
static BOOL get_qualifier(struct parsed_symbol *sym, struct datatype_t *xdt, const char** pclass)
450
{
451
    char ch;
452
    const char* qualif;
453

454
    get_extended_qualifier(sym, xdt);
455
    switch (ch = *sym->current++)
456
    {
457 458 459 460 461 462 463 464
    case 'A': qualif = NULL; break;
    case 'B': qualif = "const"; break;
    case 'C': qualif = "volatile"; break;
    case 'D': qualif = "const volatile"; break;
    case 'Q': qualif = NULL; break;
    case 'R': qualif = "const"; break;
    case 'S': qualif = "volatile"; break;
    case 'T': qualif = "const volatile"; break;
465 466
    default: return FALSE;
    }
467
    if (qualif)
468 469
    {
        xdt->flags &= ~DT_NO_LRSEP_WS;
470
        xdt->left = xdt->left ? str_printf(sym, "%s %s", qualif, xdt->left) : qualif;
471
    }
472 473 474 475 476 477 478 479 480 481 482 483
    if (ch >= 'Q' && ch <= 'T') /* pointer to member, fetch class */
    {
        const char* class = get_class_name(sym);
        if (!class) return FALSE;
        if (!pclass)
        {
            FIXME("Got pointer to class %s member without storage\n", class);
            return FALSE;
        }
        *pclass = class;
    }
    else if (pclass) *pclass = NULL;
484 485 486
    return TRUE;
}

487 488 489 490 491 492 493 494 495 496
static BOOL get_function_qualifier(struct parsed_symbol *sym, const char** qualif)
{
    struct datatype_t   xdt;

    if (!get_qualifier(sym, &xdt, NULL)) return FALSE;
    *qualif = (xdt.left || xdt.right) ?
        str_printf(sym, "%s%s%s", xdt.left, (xdt.flags & DT_NO_LRSEP_WS) ? "" : " ", xdt.right) : NULL;
    return TRUE;
}

497 498
static BOOL get_qualified_type(struct datatype_t *ct, struct parsed_symbol* sym,
                              struct array *pmt_ref, char qualif, enum datatype_flags flags)
499
{
500 501
    struct datatype_t xdt1;
    struct datatype_t xdt2;
502
    const char* ref;
503
    const char* str_qualif;
504
    const char* class;
505

506
    get_extended_qualifier(sym, &xdt1);
507

508
    switch (qualif)
509
    {
510 511 512 513 514 515 516 517
    case 'A': ref = " &";  str_qualif = NULL;              break;
    case 'B': ref = " &";  str_qualif = " volatile";       break;
    case 'P': ref = " *";  str_qualif = NULL;              break;
    case 'Q': ref = " *";  str_qualif = " const";          break;
    case 'R': ref = " *";  str_qualif = " volatile";       break;
    case 'S': ref = " *";  str_qualif = " const volatile"; break;
    case '?': ref = NULL;  str_qualif = NULL;              break;
    case '$': ref = " &&"; str_qualif = NULL;              break;
518
    default: return FALSE;
519
    }
520
    ct->right = NULL;
521
    ct->flags = 0;
522

523
    if (get_qualifier(sym, &xdt2, &class))
524 525 526 527
    {
        unsigned            mark = sym->stack.num;
        struct datatype_t   sub_ct;

528
        if (ref || str_qualif || xdt1.left || xdt1.right)
529 530 531 532 533
        {
            if (class)
                ct->left = str_printf(sym, "%s%s%s%s::%s%s%s",
                                      xdt1.left ? " " : NULL, xdt1.left,
                                      class ? " " : NULL, class, ref ? ref + 1 : NULL,
534
                                      xdt1.right ? " " : NULL, xdt1.right, str_qualif);
535 536 537
            else
                ct->left = str_printf(sym, "%s%s%s%s%s%s",
                                      xdt1.left ? " " : NULL, xdt1.left, ref,
538
                                      xdt1.right ? " " : NULL, xdt1.right, str_qualif);
539 540 541
        }
        else
            ct->left = NULL;
542 543 544 545 546 547 548 549
        /* multidimensional arrays */
        if (*sym->current == 'Y')
        {
            const char* n1;
            int num;

            sym->current++;
            if (!(n1 = get_number(sym))) return FALSE;
550
            num = atoi(n1);
551

552
            ct->left = str_printf(sym, " (%s%s", xdt2.left, ct->left && !xdt2.left ? ct->left + 1 : ct->left);
553
            ct->right = ")";
554
            xdt2.left = NULL;
555 556

            while (num--)
557
                ct->right = str_printf(sym, "%s[%s]", ct->right, get_number(sym));
558 559
        }

560
        /* Recurse to get the referred-to type */
561
        if (!demangle_datatype(sym, &sub_ct, pmt_ref, 0))
562
            return FALSE;
563 564
        if (sub_ct.flags & DT_NO_LEADING_WS)
            ct->left++;
565 566
        ct->left = str_printf(sym, "%s%s%s%s%s", sub_ct.left, xdt2.left ? " " : NULL,
                              xdt2.left, ct->left,
567
                              ((xdt2.left || str_qualif) && (flags & WS_AFTER_QUAL_IF)) ? " " : NULL);
568
        if (sub_ct.right) ct->right = str_printf(sym, "%s%s", ct->right, sub_ct.right);
569 570
        sym->stack.num = mark;
    }
571
    else if (ref || str_qualif || xdt1.left || xdt1.right)
572 573
        ct->left = str_printf(sym, "%s%s%s%s%s%s",
                              xdt1.left ? " " : NULL, xdt1.left, ref,
574
                              xdt1.right ? " " : NULL, xdt1.right, str_qualif);
575 576
    else
        ct->left = NULL;
577
    return TRUE;
578 579
}

580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595
/******************************************************************
 *             get_literal_string
 * Gets the literal name from the current position in the mangled
 * symbol to the first '@' character. It pushes the parsed name to
 * the symbol names stack and returns a pointer to it or NULL in
 * case of an error.
 */
static char* get_literal_string(struct parsed_symbol* sym)
{
    const char *ptr = sym->current;

    do {
        if (!((*sym->current >= 'A' && *sym->current <= 'Z') ||
              (*sym->current >= 'a' && *sym->current <= 'z') ||
              (*sym->current >= '0' && *sym->current <= '9') ||
              *sym->current == '_' || *sym->current == '$')) {
596
            TRACE("Failed at '%c' in %s\n", *sym->current, debugstr_a(ptr));
597 598 599 600
            return NULL;
        }
    } while (*++sym->current != '@');
    sym->current++;
601 602
    if (!str_array_push(sym, ptr, sym->current - 1 - ptr, &sym->names))
        return NULL;
603

604
    return str_array_get_ref(&sym->names, sym->names.num - sym->names.start - 1);
605 606
}

607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
/******************************************************************
 *		get_template_name
 * Parses a name with a template argument list and returns it as
 * a string.
 * In a template argument list the back reference to the names
 * table is separately created. '0' points to the class component
 * name with the template arguments.  We use the same stack array
 * to hold the names but save/restore the stack state before/after
 * parsing the template argument list.
 */
static char* get_template_name(struct parsed_symbol* sym)
{
    char *name, *args;
    unsigned num_mark = sym->names.num;
    unsigned start_mark = sym->names.start;
    unsigned stack_mark = sym->stack.num;
623
    struct array array_pmt;
624 625

    sym->names.start = sym->names.num;
626 627
    if (!(name = get_literal_string(sym))) {
        sym->names.start = start_mark;
628
        return FALSE;
629
    }
630 631
    str_array_init(&array_pmt);
    args = get_args(sym, &array_pmt, FALSE, '<', '>');
632 633 634 635 636 637 638 639
    if (args != NULL)
        name = str_printf(sym, "%s%s", name, args);
    sym->names.num = num_mark;
    sym->names.start = start_mark;
    sym->stack.num = stack_mark;
    return name;
}

640 641
/******************************************************************
 *		get_class
642 643 644 645 646 647 648 649
 * Parses class as a list of parent-classes, terminated by '@' and stores the
 * result in 'a' array. Each parent-classes, as well as the inner element
 * (either field/method name or class name), are represented in the mangled
 * name by a literal name ([a-zA-Z0-9_]+ terminated by '@') or a back reference
 * ([0-9]) or a name with template arguments ('?$' literal name followed by the
 * template argument list). The class name components appear in the reverse
 * order in the mangled name, e.g aaa@bbb@ccc@@ will be demangled to
 * ccc::bbb::aaa
Austin English's avatar
Austin English committed
650
 * For each of these class name components a string will be allocated in the
651
 * array.
652 653 654
 */
static BOOL get_class(struct parsed_symbol* sym)
{
655
    const char* name = NULL;
656 657 658 659 660 661 662 663 664 665

    while (*sym->current != '@')
    {
        switch (*sym->current)
        {
        case '\0': return FALSE;

        case '0': case '1': case '2': case '3':
        case '4': case '5': case '6': case '7':
        case '8': case '9':
666
            name = str_array_get_ref(&sym->names, *sym->current++ - '0');
667 668
            break;
        case '?':
669
            switch (*++sym->current)
670
            {
671
            case '$':
672
                sym->current++;
673 674 675
                if ((name = get_template_name(sym)) &&
                    !str_array_push(sym, name, -1, &sym->names))
                    return FALSE;
676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693
                break;
            case '?':
                {
                    struct array stack = sym->stack;
                    unsigned int start = sym->names.start;
                    unsigned int num = sym->names.num;

                    str_array_init( &sym->stack );
                    if (symbol_demangle( sym )) name = str_printf( sym, "`%s'", sym->result );
                    sym->names.start = start;
                    sym->names.num = num;
                    sym->stack = stack;
                }
                break;
            default:
                if (!(name = get_number( sym ))) return FALSE;
                name = str_printf( sym, "`%s'", name );
                break;
694 695 696
            }
            break;
        default:
697
            name = get_literal_string(sym);
698 699
            break;
        }
700
        if (!name || !str_array_push(sym, name, -1, &sym->stack))
701
            return FALSE;
702 703 704 705 706 707 708
    }
    sym->current++;
    return TRUE;
}

/******************************************************************
 *		get_class_string
709 710
 * From an array collected by get_class in sym->stack, constructs the
 * corresponding (allocated) string
711
 */
712
static char* get_class_string(struct parsed_symbol* sym, int start)
713
{
714 715 716
    int          i;
    unsigned int len, sz;
    char*        ret;
717
    struct array *a = &sym->stack;
718

719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
    for (len = 0, i = start; i < a->num; i++)
    {
        assert(a->elts[i]);
        len += 2 + strlen(a->elts[i]);
    }
    if (!(ret = und_alloc(sym, len - 1))) return NULL;
    for (len = 0, i = a->num - 1; i >= start; i--)
    {
        sz = strlen(a->elts[i]);
        memcpy(ret + len, a->elts[i], sz);
        len += sz;
        if (i > start)
        {
            ret[len++] = ':';
            ret[len++] = ':';
        }
    }
    ret[len] = '\0';
    return ret;
}

740 741 742 743 744 745 746 747 748 749 750 751 752 753 754
/******************************************************************
 *            get_class_name
 * Wrapper around get_class and get_class_string.
 */
static char* get_class_name(struct parsed_symbol* sym)
{
    unsigned    mark = sym->stack.num;
    char*       s = NULL;

    if (get_class(sym))
        s = get_class_string(sym, mark);
    sym->stack.num = mark;
    return s;
}

755 756 757 758 759
/******************************************************************
 *		get_calling_convention
 * Returns a static string corresponding to the calling convention described
 * by char 'ch'. Sets export to TRUE iff the calling convention is exported.
 */
760 761
static BOOL get_calling_convention(char ch, const char** call_conv,
                                   const char** exported, unsigned flags)
762 763 764 765 766 767 768 769 770 771 772 773 774 775 776
{
    *call_conv = *exported = NULL;

    if (!(flags & (UNDNAME_NO_MS_KEYWORDS | UNDNAME_NO_ALLOCATION_LANGUAGE)))
    {
        if (flags & UNDNAME_NO_LEADING_UNDERSCORES)
        {
            if (((ch - 'A') % 2) == 1) *exported = "dll_export ";
            switch (ch)
            {
            case 'A': case 'B': *call_conv = "cdecl"; break;
            case 'C': case 'D': *call_conv = "pascal"; break;
            case 'E': case 'F': *call_conv = "thiscall"; break;
            case 'G': case 'H': *call_conv = "stdcall"; break;
            case 'I': case 'J': *call_conv = "fastcall"; break;
777 778
            case 'K': case 'L': break;
            case 'M': *call_conv = "clrcall"; break;
779 780 781 782 783 784 785 786 787 788 789 790 791
            default: ERR("Unknown calling convention %c\n", ch); return FALSE;
            }
        }
        else
        {
            if (((ch - 'A') % 2) == 1) *exported = "__dll_export ";
            switch (ch)
            {
            case 'A': case 'B': *call_conv = "__cdecl"; break;
            case 'C': case 'D': *call_conv = "__pascal"; break;
            case 'E': case 'F': *call_conv = "__thiscall"; break;
            case 'G': case 'H': *call_conv = "__stdcall"; break;
            case 'I': case 'J': *call_conv = "__fastcall"; break;
792 793
            case 'K': case 'L': break;
            case 'M': *call_conv = "__clrcall"; break;
794 795 796 797 798 799 800 801 802 803 804
            default: ERR("Unknown calling convention %c\n", ch); return FALSE;
            }
        }
    }
    return TRUE;
}

/*******************************************************************
 *         get_simple_type
 * Return a string containing an allocated string for a simple data type
 */
805
static const char* get_simple_type(char c)
806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828
{
    const char* type_string;
    
    switch (c)
    {
    case 'C': type_string = "signed char"; break;
    case 'D': type_string = "char"; break;
    case 'E': type_string = "unsigned char"; break;
    case 'F': type_string = "short"; break;
    case 'G': type_string = "unsigned short"; break;
    case 'H': type_string = "int"; break;
    case 'I': type_string = "unsigned int"; break;
    case 'J': type_string = "long"; break;
    case 'K': type_string = "unsigned long"; break;
    case 'M': type_string = "float"; break;
    case 'N': type_string = "double"; break;
    case 'O': type_string = "long double"; break;
    case 'X': type_string = "void"; break;
    case 'Z': type_string = "..."; break;
    default:  type_string = NULL; break;
    }
    return type_string;
}
829

830
/*******************************************************************
Austin English's avatar
Austin English committed
831
 *         get_extended_type
832 833
 * Return a string containing an allocated string for a simple data type
 */
834
static const char* get_extended_type(char c)
835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850
{
    const char* type_string;
    
    switch (c)
    {
    case 'D': type_string = "__int8"; break;
    case 'E': type_string = "unsigned __int8"; break;
    case 'F': type_string = "__int16"; break;
    case 'G': type_string = "unsigned __int16"; break;
    case 'H': type_string = "__int32"; break;
    case 'I': type_string = "unsigned __int32"; break;
    case 'J': type_string = "__int64"; break;
    case 'K': type_string = "unsigned __int64"; break;
    case 'L': type_string = "__int128"; break;
    case 'M': type_string = "unsigned __int128"; break;
    case 'N': type_string = "bool"; break;
851 852 853
    case 'Q': type_string = "char8_t"; break;
    case 'S': type_string = "char16_t"; break;
    case 'U': type_string = "char32_t"; break;
854 855 856 857 858 859
    case 'W': type_string = "wchar_t"; break;
    default:  type_string = NULL; break;
    }
    return type_string;
}

860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885
struct function_signature
{
    const char*             call_conv;
    const char*             exported;
    struct datatype_t       return_ct;
    const char*             arguments;
};

static BOOL get_function_signature(struct parsed_symbol* sym, struct array* pmt_ref,
                                   struct function_signature* fs)
{
    unsigned mark = sym->stack.num;

    if (!get_calling_convention(*sym->current++,
                                &fs->call_conv, &fs->exported,
                                sym->flags & ~UNDNAME_NO_ALLOCATION_LANGUAGE) ||
        !demangle_datatype(sym, &fs->return_ct, pmt_ref, FALSE))
        return FALSE;

    if (!(fs->arguments = get_args(sym, pmt_ref, TRUE, '(', ')')))
        return FALSE;
    sym->stack.num = mark;

    return TRUE;
}

886 887 888 889 890 891 892 893
/*******************************************************************
 *         demangle_datatype
 *
 * Attempt to demangle a C++ data type, which may be datatype.
 * a datatype type is made up of a number of simple types. e.g:
 * char** = (pointer to (pointer to (char)))
 */
static BOOL demangle_datatype(struct parsed_symbol* sym, struct datatype_t* ct,
894
                              struct array* pmt_ref, enum datatype_flags flags)
895 896 897 898 899 900
{
    char                dt;
    BOOL                add_pmt = TRUE;

    assert(ct);
    ct->left = ct->right = NULL;
901 902
    ct->flags = 0;

903 904 905 906
    switch (dt = *sym->current++)
    {
    case '_':
        /* MS type: __int8,__int16 etc */
907
        ct->left = get_extended_type(*sym->current++);
908 909 910 911 912
        break;
    case 'C': case 'D': case 'E': case 'F': case 'G':
    case 'H': case 'I': case 'J': case 'K': case 'M':
    case 'N': case 'O': case 'X': case 'Z':
        /* Simple data types */
913
        ct->left = get_simple_type(dt);
914 915 916 917 918
        add_pmt = FALSE;
        break;
    case 'T': /* union */
    case 'U': /* struct */
    case 'V': /* class */
919 920
    case 'Y': /* cointerface */
        /* Class/struct/union/cointerface */
921 922 923 924
        {
            const char* struct_name = NULL;
            const char* type_name = NULL;

925 926
            if (!(struct_name = get_class_name(sym)))
                goto done;
927 928 929 930 931 932 933
            if (!(sym->flags & UNDNAME_NO_COMPLEX_TYPE)) 
            {
                switch (dt)
                {
                case 'T': type_name = "union ";  break;
                case 'U': type_name = "struct "; break;
                case 'V': type_name = "class ";  break;
934
                case 'Y': type_name = "cointerface "; break;
935 936 937 938 939 940 941
                }
            }
            ct->left = str_printf(sym, "%s%s", type_name, struct_name);
        }
        break;
    case '?':
        /* not all the time is seems */
942
        if (flags & IN_ARGS)
943 944 945 946 947 948 949
        {
            const char*   ptr;
            if (!(ptr = get_number(sym))) goto done;
            ct->left = str_printf(sym, "`template-parameter-%s'", ptr);
        }
        else
        {
950
            if (!get_qualified_type(ct, sym, pmt_ref, '?', flags)) goto done;
951
        }
952
        break;
953 954
    case 'A': /* reference */
    case 'B': /* volatile reference */
955
        if (!get_qualified_type(ct, sym, pmt_ref, dt, flags)) goto done;
956
        break;
957 958 959
    case 'Q': /* const pointer */
    case 'R': /* volatile pointer */
    case 'S': /* const volatile pointer */
960
        if (!get_qualified_type(ct, sym, pmt_ref, (flags & IN_ARGS) ? dt : 'P', flags)) goto done;
961 962
        break;
    case 'P': /* Pointer */
963
        if (isdigit(*sym->current))
964
	{
965 966 967 968 969
            /* FIXME:
             *   P6 = Function pointer
             *   P8 = Member function pointer
             *   others who knows.. */
            if (*sym->current == '8')
970
            {
971 972
                struct function_signature       fs;
                const char*                     class;
973
                const char*                     function_qualifier;
974 975 976 977 978

                sym->current++;

                if (!(class = get_class_name(sym)))
                    goto done;
979
                if (!get_function_qualifier(sym, &function_qualifier))
980
                    goto done;
981 982
                if (!get_function_signature(sym, pmt_ref, &fs))
                     goto done;
983 984

                ct->left  = str_printf(sym, "%s%s (%s %s::*",
985
                                       fs.return_ct.left, fs.return_ct.right, fs.call_conv, class);
986
                ct->right = str_printf(sym, ")%s%s", fs.arguments, function_qualifier);
987 988 989
            }
            else if (*sym->current == '6')
            {
990
                struct function_signature       fs;
991 992

                sym->current++;
993

994 995
                if (!get_function_signature(sym, pmt_ref, &fs))
                     goto done;
996

997 998
                ct->left  = str_printf(sym, "%s%s (%s*",
                                       fs.return_ct.left, fs.return_ct.right, fs.call_conv);
999
                ct->flags = DT_NO_LEADING_WS;
1000
                ct->right = str_printf(sym, ")%s", fs.arguments);
1001 1002 1003
            }
            else goto done;
	}
1004
	else if (!get_qualified_type(ct, sym, pmt_ref, 'P', flags)) goto done;
1005 1006 1007 1008 1009 1010
        break;
    case 'W':
        if (*sym->current == '4')
        {
            char*               enum_name;
            sym->current++;
1011 1012
            if (!(enum_name = get_class_name(sym)))
                goto done;
1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
            if (sym->flags & UNDNAME_NO_COMPLEX_TYPE)
                ct->left = enum_name;
            else
                ct->left = str_printf(sym, "enum %s", enum_name);
        }
        else goto done;
        break;
    case '0': case '1': case '2': case '3': case '4':
    case '5': case '6': case '7': case '8': case '9':
        /* Referring back to previously parsed type */
1023
        /* left and right are pushed as two separate strings */
1024
        if (!pmt_ref) goto done;
1025 1026
        ct->left = str_array_get_ref(pmt_ref, (dt - '0') * 2);
        ct->right = str_array_get_ref(pmt_ref, (dt - '0') * 2 + 1);
1027 1028 1029 1030
        if (!ct->left) goto done;
        add_pmt = FALSE;
        break;
    case '$':
1031
        switch (*sym->current++)
1032
        {
1033 1034 1035 1036
        case '0':
            if (!(ct->left = get_number(sym))) goto done;
            break;
        case 'D':
1037
            {
1038 1039 1040
                const char*   ptr;
                if (!(ptr = get_number(sym))) goto done;
                ct->left = str_printf(sym, "`template-parameter%s'", ptr);
1041
            }
1042 1043
            break;
        case 'F':
1044
            {
1045 1046 1047 1048 1049
                const char*   p1;
                const char*   p2;
                if (!(p1 = get_number(sym))) goto done;
                if (!(p2 = get_number(sym))) goto done;
                ct->left = str_printf(sym, "{%s,%s}", p1, p2);
1050
            }
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069
            break;
        case 'G':
            {
                const char*   p1;
                const char*   p2;
                const char*   p3;
                if (!(p1 = get_number(sym))) goto done;
                if (!(p2 = get_number(sym))) goto done;
                if (!(p3 = get_number(sym))) goto done;
                ct->left = str_printf(sym, "{%s,%s,%s}", p1, p2, p3);
            }
            break;
        case 'Q':
            {
                const char*   ptr;
                if (!(ptr = get_number(sym))) goto done;
                ct->left = str_printf(sym, "`non-type-template-parameter%s'", ptr);
            }
            break;
1070
        case '$':
1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
            if (*sym->current == 'A')
            {
                sym->current++;
                if (*sym->current == '6')
                {
                    struct function_signature fs;

                    sym->current++;

                    if (!get_function_signature(sym, pmt_ref, &fs))
                        goto done;
                    ct->left = str_printf(sym, "%s%s %s%s",
                                          fs.return_ct.left, fs.return_ct.right, fs.call_conv, fs.arguments);
                }
            }
            else if (*sym->current == 'B')
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100
            {
                unsigned            mark = sym->stack.num;
                struct datatype_t   sub_ct;
                const char*         arr = NULL;
                sym->current++;

                /* multidimensional arrays */
                if (*sym->current == 'Y')
                {
                    const char* n1;
                    int num;

                    sym->current++;
                    if (!(n1 = get_number(sym))) goto done;
1101
                    num = atoi(n1);
1102 1103 1104 1105 1106

                    while (num--)
                        arr = str_printf(sym, "%s[%s]", arr, get_number(sym));
                }

1107
                if (!demangle_datatype(sym, &sub_ct, pmt_ref, 0)) goto done;
1108 1109 1110 1111 1112 1113 1114 1115 1116

                if (arr)
                    ct->left = str_printf(sym, "%s %s", sub_ct.left, arr);
                else
                    ct->left = sub_ct.left;
                ct->right = sub_ct.right;
                sym->stack.num = mark;
            }
            else if (*sym->current == 'C')
1117
            {
1118
                struct datatype_t xdt;
1119 1120

                sym->current++;
1121
                if (!get_qualifier(sym, &xdt, NULL)) goto done;
1122
                if (!demangle_datatype(sym, ct, pmt_ref, flags)) goto done;
1123
                ct->left = str_printf(sym, "%s %s", ct->left, xdt.left);
1124
            }
1125 1126 1127
            else if (*sym->current == 'Q')
            {
                sym->current++;
1128
                if (!get_qualified_type(ct, sym, pmt_ref, '$', flags)) goto done;
1129
            }
1130
            break;
1131 1132 1133 1134 1135 1136
        }
        break;
    default :
        ERR("Unknown type %c\n", dt);
        break;
    }
1137
    if (add_pmt && pmt_ref && (flags & IN_ARGS))
1138 1139
    {
        /* left and right are pushed as two separate strings */
1140 1141 1142
        if (!str_array_push(sym, ct->left ? ct->left : "", -1, pmt_ref) ||
            !str_array_push(sym, ct->right ? ct->right : "", -1, pmt_ref))
            return FALSE;
1143
    }
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157
done:
    
    return ct->left != NULL;
}

/******************************************************************
 *		handle_data
 * Does the final parsing and handling for a variable or a field in
 * a class.
 */
static BOOL handle_data(struct parsed_symbol* sym)
{
    const char*         access = NULL;
    const char*         member_type = NULL;
1158
    struct datatype_t   xdt = {NULL};
1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191
    struct datatype_t   ct;
    char*               name = NULL;
    BOOL                ret = FALSE;

    /* 0 private static
     * 1 protected static
     * 2 public static
     * 3 private non-static
     * 4 protected non-static
     * 5 public non-static
     * 6 ?? static
     * 7 ?? static
     */

    if (!(sym->flags & UNDNAME_NO_ACCESS_SPECIFIERS))
    {
        /* we only print the access for static members */
        switch (*sym->current)
        {
        case '0': access = "private: "; break;
        case '1': access = "protected: "; break;
        case '2': access = "public: "; break;
        } 
    }

    if (!(sym->flags & UNDNAME_NO_MEMBER_TYPE))
    {
        if (*sym->current >= '0' && *sym->current <= '2')
            member_type = "static ";
    }

    name = get_class_string(sym, 0);

1192
    switch (*sym->current++)
1193 1194 1195 1196 1197
    {
    case '0': case '1': case '2':
    case '3': case '4': case '5':
        {
            unsigned mark = sym->stack.num;
1198
            struct array pmt;
1199
            const char* class;
1200 1201 1202

            str_array_init(&pmt);

1203
            if (!demangle_datatype(sym, &ct, &pmt, 0)) goto done;
1204
            if (!get_qualifier(sym, &xdt, &class)) goto done; /* class doesn't seem to be displayed */
1205 1206
            if (xdt.left && xdt.right) xdt.left = str_printf(sym, "%s %s", xdt.left, xdt.right);
            else if (!xdt.left) xdt.left = xdt.right;
1207 1208 1209 1210 1211 1212
            sym->stack.num = mark;
        }
        break;
    case '6' : /* compiler generated static */
    case '7' : /* compiler generated static */
        ct.left = ct.right = NULL;
1213
        if (!get_qualifier(sym, &xdt, NULL)) goto done;
1214 1215 1216 1217
        if (*sym->current != '@')
        {
            char*       cls = NULL;

1218 1219
            if (!(cls = get_class_name(sym)))
                goto done;
1220 1221 1222
            ct.right = str_printf(sym, "{for `%s'}", cls);
        }
        break;
1223 1224
    case '8':
    case '9':
1225
        xdt.left = ct.left = ct.right = NULL;
1226
        break;
1227 1228
    default: goto done;
    }
1229
    if (sym->flags & UNDNAME_NAME_ONLY) ct.left = ct.right = xdt.left = NULL;
1230

1231
    sym->result = str_printf(sym, "%s%s%s%s%s%s%s%s", access,
1232 1233 1234
                             member_type, ct.left,
                             xdt.left && ct.left ? " " : NULL, xdt.left,
                             xdt.left || ct.left ? " " : NULL, name, ct.right);
1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246
    ret = TRUE;
done:
    return ret;
}

/******************************************************************
 *		handle_method
 * Does the final parsing and handling for a function or a method in
 * a class.
 */
static BOOL handle_method(struct parsed_symbol* sym, BOOL cast_op)
{
1247
    char                accmem;
1248
    const char*         access = NULL;
1249
    int                 access_id = -1;
1250 1251 1252
    const char*         member_type = NULL;
    struct datatype_t   ct_ret;
    const char*         call_conv;
1253
    const char*         function_qualifier = NULL;
1254 1255 1256
    const char*         exported;
    const char*         args_str = NULL;
    const char*         name = NULL;
1257
    BOOL                ret = FALSE, has_args = TRUE, has_ret = TRUE;
1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287
    unsigned            mark;
    struct array        array_pmt;

    /* FIXME: why 2 possible letters for each option?
     * 'A' private:
     * 'B' private:
     * 'C' private: static
     * 'D' private: static
     * 'E' private: virtual
     * 'F' private: virtual
     * 'G' private: thunk
     * 'H' private: thunk
     * 'I' protected:
     * 'J' protected:
     * 'K' protected: static
     * 'L' protected: static
     * 'M' protected: virtual
     * 'N' protected: virtual
     * 'O' protected: thunk
     * 'P' protected: thunk
     * 'Q' public:
     * 'R' public:
     * 'S' public: static
     * 'T' public: static
     * 'U' public: virtual
     * 'V' public: virtual
     * 'W' public: thunk
     * 'X' public: thunk
     * 'Y'
     * 'Z'
1288 1289 1290 1291 1292 1293
     * "$0" private: thunk vtordisp
     * "$1" private: thunk vtordisp
     * "$2" protected: thunk vtordisp
     * "$3" protected: thunk vtordisp
     * "$4" public: thunk vtordisp
     * "$5" public: thunk vtordisp
1294
     * "$B" vcall thunk
1295
     * "$R" thunk vtordispex
1296
     */
1297
    accmem = *sym->current++;
1298 1299
    if (accmem == '$')
    {
1300 1301
        if (*sym->current >= '0' && *sym->current <= '5')
            access_id = (*sym->current - '0') / 2;
1302 1303
        else if (*sym->current == 'R')
            access_id = (sym->current[1] - '0') / 2;
1304 1305
        else if (*sym->current != 'B')
            goto done;
1306
    }
1307 1308 1309 1310
    else if (accmem >= 'A' && accmem <= 'Z')
        access_id = (accmem - 'A') / 8;
    else
        goto done;
1311

1312
    switch (access_id)
1313
    {
1314 1315 1316
    case 0: access = "private: "; break;
    case 1: access = "protected: "; break;
    case 2: access = "public: "; break;
1317
    }
1318 1319 1320
    if (accmem == '$' || (accmem - 'A') % 8 == 6 || (accmem - 'A') % 8 == 7)
        access = str_printf(sym, "[thunk]:%s", access ? access : " ");

1321
    if (accmem == '$' && *sym->current != 'B')
1322 1323
        member_type = "virtual ";
    else if (accmem <= 'X')
1324
    {
1325
        switch ((accmem - 'A') % 8)
1326
        {
1327 1328
        case 2: case 3: member_type = "static "; break;
        case 4: case 5: case 6: case 7: member_type = "virtual "; break;
1329 1330 1331
        }
    }

1332 1333 1334 1335 1336
    if (sym->flags & UNDNAME_NO_ACCESS_SPECIFIERS)
        access = NULL;
    if (sym->flags & UNDNAME_NO_MEMBER_TYPE)
        member_type = NULL;

1337 1338
    name = get_class_string(sym, 0);

1339
    if (accmem == '$' && *sym->current == 'B') /* vcall thunk */
1340
    {
1341 1342 1343 1344
        const char *n;

        sym->current++;
        n = get_number(sym);
1345 1346 1347 1348 1349 1350

        if(!n || *sym->current++ != 'A') goto done;
        name = str_printf(sym, "%s{%s,{flat}}' }'", name, n);
        has_args = FALSE;
        has_ret = FALSE;
    }
1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363
    else if (accmem == '$' && *sym->current == 'R') /* vtordispex thunk */
    {
        const char *n1, *n2, *n3, *n4;

        sym->current += 2;
        n1 = get_number(sym);
        n2 = get_number(sym);
        n3 = get_number(sym);
        n4 = get_number(sym);

        if(!n1 || !n2 || !n3 || !n4) goto done;
        name = str_printf(sym, "%s`vtordispex{%s,%s,%s,%s}' ", name, n1, n2, n3, n4);
    }
1364
    else if (accmem == '$') /* vtordisp thunk */
1365
    {
1366 1367 1368 1369 1370
        const char *n1, *n2;

        sym->current++;
        n1 = get_number(sym);
        n2 = get_number(sym);
1371 1372 1373 1374 1375

        if (!n1 || !n2) goto done;
        name = str_printf(sym, "%s`vtordisp{%s,%s}' ", name, n1, n2);
    }
    else if ((accmem - 'A') % 8 == 6 || (accmem - 'A') % 8 == 7) /* a thunk */
1376 1377
        name = str_printf(sym, "%s`adjustor{%s}' ", name, get_number(sym));

1378 1379
    if (has_args && (accmem == '$' ||
                (accmem <= 'X' && (accmem - 'A') % 8 != 2 && (accmem - 'A') % 8 != 3)))
1380
    {
1381
        /* Implicit 'this' pointer */
1382
        if (!get_function_qualifier(sym, &function_qualifier)) goto done;
1383 1384
    }

1385 1386
    if (!get_calling_convention(*sym->current++, &call_conv, &exported,
                                sym->flags))
1387 1388 1389 1390 1391
        goto done;

    str_array_init(&array_pmt);

    /* Return type, or @ if 'void' */
1392
    if (has_ret && *sym->current == '@')
1393 1394 1395 1396 1397
    {
        ct_ret.left = "void";
        ct_ret.right = NULL;
        sym->current++;
    }
1398
    else if (has_ret)
1399
    {
1400
        if (!demangle_datatype(sym, &ct_ret, &array_pmt, cast_op ? WS_AFTER_QUAL_IF : 0))
1401 1402
            goto done;
    }
1403
    if (!has_ret || sym->flags & UNDNAME_NO_FUNCTION_RETURNS)
1404 1405 1406
        ct_ret.left = ct_ret.right = NULL;
    if (cast_op)
    {
1407
        name = str_printf(sym, "%s %s%s", name, ct_ret.left, ct_ret.right);
1408 1409 1410 1411
        ct_ret.left = ct_ret.right = NULL;
    }

    mark = sym->stack.num;
1412
    if (has_args && !(args_str = get_args(sym, &array_pmt, TRUE, '(', ')'))) goto done;
1413 1414
    if (sym->flags & UNDNAME_NAME_ONLY) args_str = function_qualifier = NULL;
    if (sym->flags & UNDNAME_NO_THISTYPE) function_qualifier = NULL;
1415 1416 1417 1418 1419
    sym->stack.num = mark;

    /* Note: '()' after 'Z' means 'throws', but we don't care here
     * Yet!!! FIXME
     */
1420
    sym->result = str_printf(sym, "%s%s%s%s%s%s%s%s%s%s%s",
1421
                             access, member_type, ct_ret.left,
1422 1423
                             (ct_ret.left && !ct_ret.right) ? " " : NULL,
                             call_conv, call_conv ? " " : NULL, exported,
1424
                             name, args_str, function_qualifier, ct_ret.right);
1425 1426 1427 1428 1429 1430
    ret = TRUE;
done:
    return ret;
}

/*******************************************************************
1431
 *         symbol_demangle
1432 1433 1434 1435 1436
 * Demangle a C++ linker symbol
 */
static BOOL symbol_demangle(struct parsed_symbol* sym)
{
    BOOL                ret = FALSE;
1437 1438 1439 1440 1441 1442
    enum {
        PP_NONE,
        PP_CONSTRUCTOR,
        PP_DESTRUCTOR,
        PP_CAST_OPERATOR,
    } post_process = PP_NONE;
1443 1444 1445 1446 1447 1448

    /* FIXME seems wrong as name, as it demangles a simple data type */
    if (sym->flags & UNDNAME_NO_ARGUMENTS)
    {
        struct datatype_t   ct;

1449
        if (demangle_datatype(sym, &ct, NULL, 0))
1450 1451 1452 1453 1454 1455 1456
        {
            sym->result = str_printf(sym, "%s%s", ct.left, ct.right);
            ret = TRUE;
        }
        goto done;
    }

1457 1458
    /* MS mangled names always begin with '?' */
    if (*sym->current != '?') return FALSE;
1459 1460 1461
    sym->current++;

    /* Then function name or operator code */
1462
    if (*sym->current == '?')
1463 1464
    {
        const char* function_name = NULL;
1465
        BOOL in_template = FALSE;
1466

1467
        if (sym->current[1] == '$' && sym->current[2] == '?')
1468
        {
1469
            in_template = TRUE;
1470 1471 1472
            sym->current += 2;
        }

1473 1474 1475
        /* C++ operator code (one character, or two if the first is '_') */
        switch (*++sym->current)
        {
1476 1477
        case '0': function_name = ""; post_process = PP_CONSTRUCTOR; break;
        case '1': function_name = ""; post_process = PP_DESTRUCTOR; break;
1478 1479 1480 1481 1482 1483 1484 1485 1486
        case '2': function_name = "operator new"; break;
        case '3': function_name = "operator delete"; break;
        case '4': function_name = "operator="; break;
        case '5': function_name = "operator>>"; break;
        case '6': function_name = "operator<<"; break;
        case '7': function_name = "operator!"; break;
        case '8': function_name = "operator=="; break;
        case '9': function_name = "operator!="; break;
        case 'A': function_name = "operator[]"; break;
1487
        case 'B': function_name = "operator"; post_process = PP_CAST_OPERATOR; break;
1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526
        case 'C': function_name = "operator->"; break;
        case 'D': function_name = "operator*"; break;
        case 'E': function_name = "operator++"; break;
        case 'F': function_name = "operator--"; break;
        case 'G': function_name = "operator-"; break;
        case 'H': function_name = "operator+"; break;
        case 'I': function_name = "operator&"; break;
        case 'J': function_name = "operator->*"; break;
        case 'K': function_name = "operator/"; break;
        case 'L': function_name = "operator%"; break;
        case 'M': function_name = "operator<"; break;
        case 'N': function_name = "operator<="; break;
        case 'O': function_name = "operator>"; break;
        case 'P': function_name = "operator>="; break;
        case 'Q': function_name = "operator,"; break;
        case 'R': function_name = "operator()"; break;
        case 'S': function_name = "operator~"; break;
        case 'T': function_name = "operator^"; break;
        case 'U': function_name = "operator|"; break;
        case 'V': function_name = "operator&&"; break;
        case 'W': function_name = "operator||"; break;
        case 'X': function_name = "operator*="; break;
        case 'Y': function_name = "operator+="; break;
        case 'Z': function_name = "operator-="; break;
        case '_':
            switch (*++sym->current)
            {
            case '0': function_name = "operator/="; break;
            case '1': function_name = "operator%="; break;
            case '2': function_name = "operator>>="; break;
            case '3': function_name = "operator<<="; break;
            case '4': function_name = "operator&="; break;
            case '5': function_name = "operator|="; break;
            case '6': function_name = "operator^="; break;
            case '7': function_name = "`vftable'"; break;
            case '8': function_name = "`vbtable'"; break;
            case '9': function_name = "`vcall'"; break;
            case 'A': function_name = "`typeof'"; break;
            case 'B': function_name = "`local static guard'"; break;
1527
            case 'C': sym->result = (char*)"`string'"; /* string literal: followed by string encoding (native never undecode it) */
1528 1529 1530
                /* FIXME: should unmangle the whole string for error reporting */
                if (*sym->current && sym->current[strlen(sym->current) - 1] == '@') ret = TRUE;
                goto done;
1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542
            case 'D': function_name = "`vbase destructor'"; break;
            case 'E': function_name = "`vector deleting destructor'"; break;
            case 'F': function_name = "`default constructor closure'"; break;
            case 'G': function_name = "`scalar deleting destructor'"; break;
            case 'H': function_name = "`vector constructor iterator'"; break;
            case 'I': function_name = "`vector destructor iterator'"; break;
            case 'J': function_name = "`vector vbase constructor iterator'"; break;
            case 'K': function_name = "`virtual displacement map'"; break;
            case 'L': function_name = "`eh vector constructor iterator'"; break;
            case 'M': function_name = "`eh vector destructor iterator'"; break;
            case 'N': function_name = "`eh vector vbase constructor iterator'"; break;
            case 'O': function_name = "`copy constructor closure'"; break;
1543 1544 1545 1546 1547 1548 1549 1550 1551
            case 'R':
                sym->flags |= UNDNAME_NO_FUNCTION_RETURNS;
                switch (*++sym->current)
                {
                case '0':
                    {
                        struct datatype_t       ct;

                        sym->current++;
1552
                        if (!demangle_datatype(sym, &ct, NULL, 0))
1553
                            goto done;
1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579
                        function_name = str_printf(sym, "%s%s `RTTI Type Descriptor'",
                                                   ct.left, ct.right);
                        sym->current--;
                    }
                    break;
                case '1':
                    {
                        const char* n1, *n2, *n3, *n4;
                        sym->current++;
                        n1 = get_number(sym);
                        n2 = get_number(sym);
                        n3 = get_number(sym);
                        n4 = get_number(sym);
                        sym->current--;
                        function_name = str_printf(sym, "`RTTI Base Class Descriptor at (%s,%s,%s,%s)'",
                                                   n1, n2, n3, n4);
                    }
                    break;
                case '2': function_name = "`RTTI Base Class Array'"; break;
                case '3': function_name = "`RTTI Class Hierarchy Descriptor'"; break;
                case '4': function_name = "`RTTI Complete Object Locator'"; break;
                default:
                    ERR("Unknown RTTI operator: _R%c\n", *sym->current);
                    break;
                }
                break;
1580 1581 1582 1583 1584 1585
            case 'S': function_name = "`local vftable'"; break;
            case 'T': function_name = "`local vftable constructor closure'"; break;
            case 'U': function_name = "operator new[]"; break;
            case 'V': function_name = "operator delete[]"; break;
            case 'X': function_name = "`placement delete closure'"; break;
            case 'Y': function_name = "`placement delete[] closure'"; break;
1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598
            case '_':
                switch (*++sym->current)
                {
                case 'K':
                    sym->current++;
                    function_name = str_printf(sym, "operator \"\" %s", get_literal_string(sym));
                    --sym->current;
                    break;
                default:
                    FIXME("Unknown operator: __%c\n", *sym->current);
                    return FALSE;
                }
                break;
1599 1600 1601 1602 1603
            default:
                ERR("Unknown operator: _%c\n", *sym->current);
                return FALSE;
            }
            break;
1604 1605 1606 1607 1608
        case '$':
            sym->current++;
            if (!(function_name = get_template_name(sym))) goto done;
            --sym->current;
            break;
1609 1610 1611 1612 1613 1614
        default:
            /* FIXME: Other operators */
            ERR("Unknown operator: %c\n", *sym->current);
            return FALSE;
        }
        sym->current++;
1615 1616 1617 1618 1619 1620 1621 1622 1623 1624
        if (in_template)
        {
            const char *args;
            struct array array_pmt;

            str_array_init(&array_pmt);
            args = get_args(sym, &array_pmt, FALSE, '<', '>');
            if (args) function_name = function_name ? str_printf(sym, "%s%s", function_name, args) : args;
            sym->names.num = 0;
        }
1625 1626
        if (!str_array_push(sym, function_name, -1, &sym->stack))
            return FALSE;
1627
    }
1628 1629 1630 1631 1632
    else if (*sym->current == '$')
    {
        /* Strange construct, it's a name with a template argument list
           and that's all. */
        sym->current++;
1633
        ret = (sym->result = get_template_name(sym)) != NULL;
1634 1635
        goto done;
    }
1636 1637

    /* Either a class name, or '@' if the symbol is not a class member */
1638
    switch (*sym->current)
1639
    {
1640 1641 1642
    case '@': sym->current++; break;
    case '$': break;
    default:
1643 1644
        /* Class the function is associated with, terminated by '@@' */
        if (!get_class(sym)) goto done;
1645
        break;
1646 1647
    }

1648
    switch (post_process)
1649
    {
1650 1651
    case PP_NONE: default: break;
    case PP_CONSTRUCTOR: case PP_DESTRUCTOR:
1652 1653
        /* it's time to set the member name for ctor & dtor */
        if (sym->stack.num <= 1) goto done;
1654 1655
        sym->stack.elts[0] = str_printf(sym, "%s%s%s", post_process == PP_DESTRUCTOR ? "~" : NULL,
                                        sym->stack.elts[1], sym->stack.elts[0]);
1656 1657 1658
        /* ctors and dtors don't have return type */
        sym->flags |= UNDNAME_NO_FUNCTION_RETURNS;
        break;
1659
    case PP_CAST_OPERATOR:
1660 1661 1662 1663 1664
        sym->flags &= ~UNDNAME_NO_FUNCTION_RETURNS;
        break;
    }

    /* Function/Data type and access level */
1665
    if (*sym->current >= '0' && *sym->current <= '9')
1666
        ret = handle_data(sym);
1667
    else if ((*sym->current >= 'A' && *sym->current <= 'Z') || *sym->current == '$')
1668
        ret = handle_method(sym, post_process == PP_CAST_OPERATOR);
1669 1670 1671
    else ret = FALSE;
done:
    if (ret) assert(sym->result);
1672
    else WARN("Failed at %s\n", debugstr_a(sym->current));
1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694

    return ret;
}

/*********************************************************************
 *		__unDNameEx (MSVCRT.@)
 *
 * Demangle a C++ identifier.
 *
 * PARAMS
 *  buffer   [O] If not NULL, the place to put the demangled string
 *  mangled  [I] Mangled name of the function
 *  buflen   [I] Length of buffer
 *  memget   [I] Function to allocate memory with
 *  memfree  [I] Function to free memory with
 *  unknown  [?] Unknown, possibly a call back
 *  flags    [I] Flags determining demangled format
 *
 * RETURNS
 *  Success: A string pointing to the unmangled name, allocated with memget.
 *  Failure: NULL.
 */
1695 1696 1697
char* CDECL __unDNameEx(char* buffer, const char* mangled, int buflen,
                        malloc_func_t memget, free_func_t memfree,
                        void* unknown, unsigned short int flags)
1698 1699
{
    struct parsed_symbol        sym;
1700
    const char*                 result;
1701

1702
    TRACE("(%p,%s,%d,%p,%p,%p,%x)\n",
1703
          buffer, debugstr_a(mangled), buflen, memget, memfree, unknown, flags);
1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718
    
    /* The flags details is not documented by MS. However, it looks exactly
     * like the UNDNAME_ manifest constants from imagehlp.h and dbghelp.h
     * So, we copied those (on top of the file)
     */
    memset(&sym, 0, sizeof(struct parsed_symbol));
    if (flags & UNDNAME_NAME_ONLY)
        flags |= UNDNAME_NO_FUNCTION_RETURNS | UNDNAME_NO_ACCESS_SPECIFIERS |
            UNDNAME_NO_MEMBER_TYPE | UNDNAME_NO_ALLOCATION_LANGUAGE |
            UNDNAME_NO_COMPLEX_TYPE;

    sym.flags         = flags;
    sym.mem_alloc_ptr = memget;
    sym.mem_free_ptr  = memfree;
    sym.current       = mangled;
1719 1720
    str_array_init( &sym.names );
    str_array_init( &sym.stack );
1721

1722 1723
    result = symbol_demangle(&sym) ? sym.result : mangled;
    if (buffer && buflen)
1724
    {
1725
        lstrcpynA( buffer, result, buflen);
1726 1727 1728 1729 1730
    }
    else
    {
        buffer = memget(strlen(result) + 1);
        if (buffer) strcpy(buffer, result);
1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741
    }

    und_free_all(&sym);

    return buffer;
}


/*********************************************************************
 *		__unDName (MSVCRT.@)
 */
1742 1743 1744
char* CDECL __unDName(char* buffer, const char* mangled, int buflen,
                      malloc_func_t memget, free_func_t memfree,
                      unsigned short int flags)
1745 1746 1747
{
    return __unDNameEx(buffer, mangled, buflen, memget, memfree, NULL, flags);
}