dsound: DPRINTF -> TRACE.
[wine] / dlls / msvcrt / undname.c
1 /*
2  *  Demangle VC++ symbols into C function prototypes
3  *
4  *  Copyright 2000 Jon Griffiths
5  *            2004 Eric Pouech
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20  */
21
22 #include "config.h"
23 #include "wine/port.h"
24
25 #include <assert.h>
26 #include <stdio.h>
27 #include "msvcrt.h"
28
29 #include "wine/debug.h"
30
31 WINE_DEFAULT_DEBUG_CHANNEL(msvcrt);
32
33 /* TODO:
34  * - document a bit (grammar + functions)
35  * - back-port this new code into tools/winedump/msmangle.c
36  */
37
38 #define UNDNAME_COMPLETE                 (0x0000)
39 #define UNDNAME_NO_LEADING_UNDERSCORES   (0x0001) /* Don't show __ in calling convention */
40 #define UNDNAME_NO_MS_KEYWORDS           (0x0002) /* Don't show calling convention at all */
41 #define UNDNAME_NO_FUNCTION_RETURNS      (0x0004) /* Don't show function/method return value */
42 #define UNDNAME_NO_ALLOCATION_MODEL      (0x0008)
43 #define UNDNAME_NO_ALLOCATION_LANGUAGE   (0x0010)
44 #define UNDNAME_NO_MS_THISTYPE           (0x0020)
45 #define UNDNAME_NO_CV_THISTYPE           (0x0040)
46 #define UNDNAME_NO_THISTYPE              (0x0060)
47 #define UNDNAME_NO_ACCESS_SPECIFIERS     (0x0080) /* Don't show access specifier (public/protected/private) */
48 #define UNDNAME_NO_THROW_SIGNATURES      (0x0100)
49 #define UNDNAME_NO_MEMBER_TYPE           (0x0200) /* Don't show static/virtual specifier */
50 #define UNDNAME_NO_RETURN_UDT_MODEL      (0x0400)
51 #define UNDNAME_32_BIT_DECODE            (0x0800)
52 #define UNDNAME_NAME_ONLY                (0x1000) /* Only report the variable/method name */
53 #define UNDNAME_NO_ARGUMENTS             (0x2000) /* Don't show method arguments */
54 #define UNDNAME_NO_SPECIAL_SYMS          (0x4000)
55 #define UNDNAME_NO_COMPLEX_TYPE          (0x8000)
56
57 /* How data types modifiers are stored:
58  * M (in the following definitions) is defined for 
59  * 'A', 'B', 'C' and 'D' as follows
60  *      {<A>}:  ""
61  *      {<B>}:  "const "
62  *      {<C>}:  "volatile "
63  *      {<D>}:  "const volatile "
64  *
65  *      in arguments:
66  *              P<M>x   {<M>}x*
67  *              Q<M>x   {<M>}x* const
68  *              A<M>x   {<M>}x&
69  *      in data fields:
70  *              same as for arguments and also the following
71  *              ?<M>x   {<M>}x
72  *              
73  */
74
75 #define MAX_ARRAY_ELTS  32
76 struct array
77 {
78     unsigned            start;          /* first valid reference in array */
79     unsigned            num;            /* total number of used elts */
80     unsigned            max;
81     char*               elts[MAX_ARRAY_ELTS];
82 };
83
84 /* Structure holding a parsed symbol */
85 struct parsed_symbol
86 {
87     unsigned            flags;          /* the UNDNAME_ flags used for demangling */
88     malloc_func_t       mem_alloc_ptr;  /* internal allocator */
89     free_func_t         mem_free_ptr;   /* internal deallocator */
90
91     const char*         current;        /* pointer in input (mangled) string */
92     char*               result;         /* demangled string */
93
94     struct array        names;          /* array of names for back reference */
95     struct array        stack;          /* stack of parsed strings */
96
97     void*               alloc_list;     /* linked list of allocated blocks */
98     unsigned            avail_in_first; /* number of available bytes in head block */
99 };
100
101 /* Type for parsing mangled types */
102 struct datatype_t
103 {
104     const char*         left;
105     const char*         right;
106 };
107
108 /******************************************************************
109  *              und_alloc
110  *
111  * Internal allocator. Uses a simple linked list of large blocks
112  * where we use a poor-man allocator. It's fast, and since all
113  * allocation is pool, memory management is easy (esp. freeing).
114  */
115 static void*    und_alloc(struct parsed_symbol* sym, size_t len)
116 {
117     void*       ptr;
118
119 #define BLOCK_SIZE      1024
120 #define AVAIL_SIZE      (1024 - sizeof(void*))
121
122     if (len > AVAIL_SIZE)
123     {
124         /* allocate a specific block */
125         ptr = sym->mem_alloc_ptr(sizeof(void*) + len);
126         if (!ptr) return NULL;
127         *(void**)ptr = sym->alloc_list;
128         sym->alloc_list = ptr;
129         sym->avail_in_first = 0;
130         ptr = (char*)sym->alloc_list + sizeof(void*);
131     }
132     else 
133     {
134         if (len > sym->avail_in_first)
135         {
136             /* add a new block */
137             ptr = sym->mem_alloc_ptr(BLOCK_SIZE);
138             if (!ptr) return NULL;
139             *(void**)ptr = sym->alloc_list;
140             sym->alloc_list = ptr;
141             sym->avail_in_first = AVAIL_SIZE;
142         }
143         /* grab memory from head block */
144         ptr = (char*)sym->alloc_list + BLOCK_SIZE - sym->avail_in_first;
145         sym->avail_in_first -= len;
146     }
147     return ptr;
148 #undef BLOCK_SIZE
149 #undef AVAIL_SIZE
150 }
151
152 /******************************************************************
153  *              und_free
154  * Frees all the blocks in the list of large blocks allocated by
155  * und_alloc.
156  */
157 static void und_free_all(struct parsed_symbol* sym)
158 {
159     void*       next;
160
161     while (sym->alloc_list)
162     {
163         next = *(void**)sym->alloc_list;
164         if(sym->mem_free_ptr) sym->mem_free_ptr(sym->alloc_list);
165         sym->alloc_list = next;
166     }
167     sym->avail_in_first = 0;
168 }
169
170 /******************************************************************
171  *              str_array_init
172  * Initialises an array of strings
173  */
174 static void str_array_init(struct array* a)
175 {
176     a->start = a->num = a->max = 0;
177 }
178
179 /******************************************************************
180  *              str_array_push
181  * Adding a new string to an array
182  */
183 static void str_array_push(struct parsed_symbol* sym, const char* ptr, int len,
184                            struct array* a)
185 {
186     assert(ptr);
187     assert(a);
188     assert(a->num < MAX_ARRAY_ELTS);
189     if (len == -1) len = strlen(ptr);
190     a->elts[a->num] = und_alloc(sym, len + 1);
191     assert(a->elts[a->num]);
192     memcpy(a->elts[a->num], ptr, len);
193     a->elts[a->num][len] = '\0'; 
194     if (++a->num >= a->max) a->max = a->num;
195     {
196         int i;
197         char c;
198
199         for (i = a->max - 1; i >= 0; i--)
200         {
201             c = '>';
202             if (i < a->start) c = '-';
203             else if (i >= a->num) c = '}';
204             TRACE("%p\t%d%c %s\n", a, i, c, a->elts[i]);
205         }
206     }
207 }
208
209 /******************************************************************
210  *              str_array_get_ref
211  * Extracts a reference from an existing array (doing proper type
212  * checking)
213  */
214 static char* str_array_get_ref(struct array* cref, unsigned idx)
215 {
216     assert(cref);
217     if (cref->start + idx >= cref->max)
218     {
219         WARN("Out of bounds: %p %d + %d >= %d\n", 
220               cref, cref->start, idx, cref->max);
221         return NULL;
222     }
223     TRACE("Returning %p[%d] => %s\n", 
224           cref, idx, cref->elts[cref->start + idx]);
225     return cref->elts[cref->start + idx];
226 }
227
228 /******************************************************************
229  *              str_printf
230  * Helper for printf type of command (only %s and %c are implemented) 
231  * while dynamically allocating the buffer
232  */
233 static char* str_printf(struct parsed_symbol* sym, const char* format, ...)
234 {
235     va_list     args;
236     size_t      len = 1, i, sz;
237     char*       tmp;
238     char*       p;
239     char*       t;
240
241     va_start(args, format);
242     for (i = 0; format[i]; i++)
243     {
244         if (format[i] == '%')
245         {
246             switch (format[++i])
247             {
248             case 's': t = va_arg(args, char*); if (t) len += strlen(t); break;
249             case 'c': (void)va_arg(args, int); len++; break;
250             default: i--; /* fall thru */
251             case '%': len++; break;
252             }
253         }
254         else len++;
255     }
256     va_end(args);
257     if (!(tmp = und_alloc(sym, len))) return NULL;
258     va_start(args, format);
259     for (p = tmp, i = 0; format[i]; i++)
260     {
261         if (format[i] == '%')
262         {
263             switch (format[++i])
264             {
265             case 's':
266                 t = va_arg(args, char*);
267                 if (t)
268                 {
269                     sz = strlen(t);
270                     memcpy(p, t, sz);
271                     p += sz;
272                 }
273                 break;
274             case 'c':
275                 *p++ = (char)va_arg(args, int);
276                 break;
277             default: i--; /* fall thru */
278             case '%': *p++ = '%'; break;
279             }
280         }
281         else *p++ = format[i];
282     }
283     va_end(args);
284     *p = '\0';
285     return tmp;
286 }
287
288 /* forward declaration */
289 static BOOL demangle_datatype(struct parsed_symbol* sym, struct datatype_t* ct,
290                               struct array* pmt, BOOL in_args);
291
292 /******************************************************************
293  *              get_args
294  * Parses a list of function/method arguments, creates a string corresponding
295  * to the arguments' list.
296  */
297 static char* get_args(struct parsed_symbol* sym, struct array* pmt_ref, BOOL z_term, 
298                       char open_char, char close_char)
299
300 {
301     struct datatype_t   ct;
302     struct array        arg_collect;
303     char*               args_str = NULL;
304     int                 i;
305
306     str_array_init(&arg_collect);
307
308     /* Now come the function arguments */
309     while (*sym->current)
310     {
311         /* Decode each data type and append it to the argument list */
312         if (*sym->current == '@')
313         {
314             sym->current++;
315             break;
316         }
317         if (!demangle_datatype(sym, &ct, pmt_ref, TRUE))
318             return NULL;
319         /* 'void' terminates an argument list */
320         if (!strcmp(ct.left, "void"))
321         {
322             if (!z_term && *sym->current == '@') sym->current++;
323             break;
324         }
325         str_array_push(sym, str_printf(sym, "%s%s", ct.left, ct.right), -1, 
326                        &arg_collect);
327         if (!strcmp(ct.left, "...")) break;
328     }
329     /* Functions are always terminated by 'Z'. If we made it this far and
330      * don't find it, we have incorrectly identified a data type.
331      */
332     if (z_term && *sym->current++ != 'Z') return NULL;
333
334     if (arg_collect.num == 0 || 
335         (arg_collect.num == 1 && !strcmp(arg_collect.elts[0], "void")))        
336         return str_printf(sym, "%cvoid%c", open_char, close_char);
337     for (i = 1; i < arg_collect.num; i++)
338     {
339         args_str = str_printf(sym, "%s,%s", args_str, arg_collect.elts[i]);
340     }
341
342     if (close_char == '>' && args_str && args_str[strlen(args_str) - 1] == '>')
343         args_str = str_printf(sym, "%c%s%s %c", 
344                               open_char, arg_collect.elts[0], args_str, close_char);
345     else
346         args_str = str_printf(sym, "%c%s%s%c", 
347                               open_char, arg_collect.elts[0], args_str, close_char);
348     
349     return args_str;
350 }
351
352 /******************************************************************
353  *              get_modifier
354  * Parses the type modifier. Always returns a static string
355  */
356 static BOOL get_modifier(char ch, const char** ret)
357 {
358     switch (ch)
359     {
360     case 'A': *ret = NULL; break;
361     case 'B': *ret = "const"; break;
362     case 'C': *ret = "volatile"; break;
363     case 'D': *ret = "const volatile"; break;
364     default: return FALSE;
365     }
366     return TRUE;
367 }
368
369 static BOOL get_modified_type(struct datatype_t *ct, struct parsed_symbol* sym,
370                               struct array *pmt_ref, char modif)
371 {
372     const char* modifier;
373     const char* str_modif;
374
375     switch (modif)
376     {
377     case 'A': str_modif = " &"; break;
378     case 'B': str_modif = " & volatile"; break;
379     case 'P': str_modif = " *"; break;
380     case 'Q': str_modif = " * const"; break;
381     case 'R': str_modif = " * volatile"; break;
382     case 'S': str_modif = " * const volatile"; break;
383     case '?': str_modif = ""; break;
384     default: return FALSE;
385     }
386
387     if (get_modifier(*sym->current++, &modifier))
388     {
389         unsigned            mark = sym->stack.num;
390         struct datatype_t   sub_ct;
391
392         /* Recurse to get the referred-to type */
393         if (!demangle_datatype(sym, &sub_ct, pmt_ref, FALSE))
394             return FALSE;
395         if (modifier)
396             ct->left = str_printf(sym, "%s %s%s", sub_ct.left, modifier, str_modif );
397         else
398         {
399             /* don't insert a space between duplicate '*' */
400             if (str_modif[0] && str_modif[1] == '*' && sub_ct.left[strlen(sub_ct.left)-1] == '*')
401                 str_modif++;
402             ct->left = str_printf(sym, "%s%s", sub_ct.left, str_modif );
403         }
404         ct->right = sub_ct.right;
405         sym->stack.num = mark;
406     }
407     return TRUE;
408 }
409
410 /******************************************************************
411  *             get_literal_string
412  * Gets the literal name from the current position in the mangled
413  * symbol to the first '@' character. It pushes the parsed name to
414  * the symbol names stack and returns a pointer to it or NULL in
415  * case of an error.
416  */
417 static char* get_literal_string(struct parsed_symbol* sym)
418 {
419     const char *ptr = sym->current;
420
421     do {
422         if (!((*sym->current >= 'A' && *sym->current <= 'Z') ||
423               (*sym->current >= 'a' && *sym->current <= 'z') ||
424               (*sym->current >= '0' && *sym->current <= '9') ||
425               *sym->current == '_' || *sym->current == '$')) {
426             TRACE("Failed at '%c' in %s\n", *sym->current, ptr);
427             return NULL;
428         }
429     } while (*++sym->current != '@');
430     sym->current++;
431     str_array_push(sym, ptr, sym->current - 1 - ptr, &sym->names);
432
433     return str_array_get_ref(&sym->names, sym->names.num - sym->names.start - 1);
434 }
435
436 /******************************************************************
437  *              get_template_name
438  * Parses a name with a template argument list and returns it as
439  * a string.
440  * In a template argument list the back reference to the names
441  * table is separately created. '0' points to the class component
442  * name with the template arguments.  We use the same stack array
443  * to hold the names but save/restore the stack state before/after
444  * parsing the template argument list.
445  */
446 static char* get_template_name(struct parsed_symbol* sym)
447 {
448     char *name, *args;
449     unsigned num_mark = sym->names.num;
450     unsigned start_mark = sym->names.start;
451     unsigned stack_mark = sym->stack.num;
452     struct array array_pmt;
453
454     sym->names.start = sym->names.num;
455     if (!(name = get_literal_string(sym)))
456         return FALSE;
457     str_array_init(&array_pmt);
458     args = get_args(sym, &array_pmt, FALSE, '<', '>');
459     if (args != NULL)
460         name = str_printf(sym, "%s%s", name, args);
461     sym->names.num = num_mark;
462     sym->names.start = start_mark;
463     sym->stack.num = stack_mark;
464     return name;
465 }
466
467 /******************************************************************
468  *              get_class
469  * Parses class as a list of parent-classes, terminated by '@' and stores the
470  * result in 'a' array. Each parent-classes, as well as the inner element
471  * (either field/method name or class name), are represented in the mangled
472  * name by a literal name ([a-zA-Z0-9_]+ terminated by '@') or a back reference
473  * ([0-9]) or a name with template arguments ('?$' literal name followed by the
474  * template argument list). The class name components appear in the reverse
475  * order in the mangled name, e.g aaa@bbb@ccc@@ will be demangled to
476  * ccc::bbb::aaa
477  * For each of this class name componets a string will be allocated in the
478  * array.
479  */
480 static BOOL get_class(struct parsed_symbol* sym)
481 {
482     const char* name = NULL;
483
484     while (*sym->current != '@')
485     {
486         switch (*sym->current)
487         {
488         case '\0': return FALSE;
489
490         case '0': case '1': case '2': case '3':
491         case '4': case '5': case '6': case '7':
492         case '8': case '9':
493             name = str_array_get_ref(&sym->names, *sym->current++ - '0');
494             break;
495         case '?':
496             if (*++sym->current == '$') 
497             {
498                 sym->current++;
499                 name = get_template_name(sym);
500                 str_array_push(sym, name, -1, &sym->names);
501             }
502             break;
503         default:
504             name = get_literal_string(sym);
505             break;
506         }
507         if (!name)
508             return FALSE;
509         str_array_push(sym, name, -1, &sym->stack);
510     }
511     sym->current++;
512     return TRUE;
513 }
514
515 /******************************************************************
516  *              get_class_string
517  * From an array collected by get_class in sym->stack, constructs the
518  * corresponding (allocated) string
519  */
520 static char* get_class_string(struct parsed_symbol* sym, int start)
521 {
522     int         i;
523     size_t      len, sz;
524     char*       ret;
525     struct array *a = &sym->stack;
526
527     for (len = 0, i = start; i < a->num; i++)
528     {
529         assert(a->elts[i]);
530         len += 2 + strlen(a->elts[i]);
531     }
532     if (!(ret = und_alloc(sym, len - 1))) return NULL;
533     for (len = 0, i = a->num - 1; i >= start; i--)
534     {
535         sz = strlen(a->elts[i]);
536         memcpy(ret + len, a->elts[i], sz);
537         len += sz;
538         if (i > start)
539         {
540             ret[len++] = ':';
541             ret[len++] = ':';
542         }
543     }
544     ret[len] = '\0';
545     return ret;
546 }
547
548 /******************************************************************
549  *            get_class_name
550  * Wrapper around get_class and get_class_string.
551  */
552 static char* get_class_name(struct parsed_symbol* sym)
553 {
554     unsigned    mark = sym->stack.num;
555     char*       s = NULL;
556
557     if (get_class(sym))
558         s = get_class_string(sym, mark);
559     sym->stack.num = mark;
560     return s;
561 }
562
563 /******************************************************************
564  *              get_calling_convention
565  * Returns a static string corresponding to the calling convention described
566  * by char 'ch'. Sets export to TRUE iff the calling convention is exported.
567  */
568 static BOOL get_calling_convention(char ch, const char** call_conv,
569                                    const char** exported, unsigned flags)
570 {
571     *call_conv = *exported = NULL;
572
573     if (!(flags & (UNDNAME_NO_MS_KEYWORDS | UNDNAME_NO_ALLOCATION_LANGUAGE)))
574     {
575         if (flags & UNDNAME_NO_LEADING_UNDERSCORES)
576         {
577             if (((ch - 'A') % 2) == 1) *exported = "dll_export ";
578             switch (ch)
579             {
580             case 'A': case 'B': *call_conv = "cdecl"; break;
581             case 'C': case 'D': *call_conv = "pascal"; break;
582             case 'E': case 'F': *call_conv = "thiscall"; break;
583             case 'G': case 'H': *call_conv = "stdcall"; break;
584             case 'I': case 'J': *call_conv = "fastcall"; break;
585             case 'K': break;
586             default: ERR("Unknown calling convention %c\n", ch); return FALSE;
587             }
588         }
589         else
590         {
591             if (((ch - 'A') % 2) == 1) *exported = "__dll_export ";
592             switch (ch)
593             {
594             case 'A': case 'B': *call_conv = "__cdecl"; break;
595             case 'C': case 'D': *call_conv = "__pascal"; break;
596             case 'E': case 'F': *call_conv = "__thiscall"; break;
597             case 'G': case 'H': *call_conv = "__stdcall"; break;
598             case 'I': case 'J': *call_conv = "__fastcall"; break;
599             case 'K': break;
600             default: ERR("Unknown calling convention %c\n", ch); return FALSE;
601             }
602         }
603     }
604     return TRUE;
605 }
606
607 /*******************************************************************
608  *         get_simple_type
609  * Return a string containing an allocated string for a simple data type
610  */
611 static const char* get_simple_type(char c)
612 {
613     const char* type_string;
614     
615     switch (c)
616     {
617     case 'C': type_string = "signed char"; break;
618     case 'D': type_string = "char"; break;
619     case 'E': type_string = "unsigned char"; break;
620     case 'F': type_string = "short"; break;
621     case 'G': type_string = "unsigned short"; break;
622     case 'H': type_string = "int"; break;
623     case 'I': type_string = "unsigned int"; break;
624     case 'J': type_string = "long"; break;
625     case 'K': type_string = "unsigned long"; break;
626     case 'M': type_string = "float"; break;
627     case 'N': type_string = "double"; break;
628     case 'O': type_string = "long double"; break;
629     case 'X': type_string = "void"; break;
630     case 'Z': type_string = "..."; break;
631     default:  type_string = NULL; break;
632     }
633     return type_string;
634 }
635
636 /*******************************************************************
637  *         get_extented_type
638  * Return a string containing an allocated string for a simple data type
639  */
640 static const char* get_extended_type(char c)
641 {
642     const char* type_string;
643     
644     switch (c)
645     {
646     case 'D': type_string = "__int8"; break;
647     case 'E': type_string = "unsigned __int8"; break;
648     case 'F': type_string = "__int16"; break;
649     case 'G': type_string = "unsigned __int16"; break;
650     case 'H': type_string = "__int32"; break;
651     case 'I': type_string = "unsigned __int32"; break;
652     case 'J': type_string = "__int64"; break;
653     case 'K': type_string = "unsigned __int64"; break;
654     case 'L': type_string = "__int128"; break;
655     case 'M': type_string = "unsigned __int128"; break;
656     case 'N': type_string = "bool"; break;
657     case 'W': type_string = "wchar_t"; break;
658     default:  type_string = NULL; break;
659     }
660     return type_string;
661 }
662
663 /*******************************************************************
664  *         demangle_datatype
665  *
666  * Attempt to demangle a C++ data type, which may be datatype.
667  * a datatype type is made up of a number of simple types. e.g:
668  * char** = (pointer to (pointer to (char)))
669  */
670 static BOOL demangle_datatype(struct parsed_symbol* sym, struct datatype_t* ct,
671                               struct array* pmt_ref, BOOL in_args)
672 {
673     char                dt;
674     BOOL                add_pmt = TRUE;
675     int                 num_args=0;
676
677     assert(ct);
678     ct->left = ct->right = NULL;
679     
680     switch (dt = *sym->current++)
681     {
682     case '_':
683         /* MS type: __int8,__int16 etc */
684         ct->left = get_extended_type(*sym->current++);
685         break;
686     case 'C': case 'D': case 'E': case 'F': case 'G':
687     case 'H': case 'I': case 'J': case 'K': case 'M':
688     case 'N': case 'O': case 'X': case 'Z':
689         /* Simple data types */
690         ct->left = get_simple_type(dt);
691         add_pmt = FALSE;
692         break;
693     case 'T': /* union */
694     case 'U': /* struct */
695     case 'V': /* class */
696         /* Class/struct/union */
697         {
698             const char* struct_name = NULL;
699             const char* type_name = NULL;
700
701             if (!(struct_name = get_class_name(sym)))
702                 goto done;
703             if (!(sym->flags & UNDNAME_NO_COMPLEX_TYPE)) 
704             {
705                 switch (dt)
706                 {
707                 case 'T': type_name = "union ";  break;
708                 case 'U': type_name = "struct "; break;
709                 case 'V': type_name = "class ";  break;
710                 }
711             }
712             ct->left = str_printf(sym, "%s%s", type_name, struct_name);
713         }
714         break;
715     case '?':
716         /* not all the time is seems */
717         if (!get_modified_type(ct, sym, pmt_ref, '?')) goto done;
718         break;
719     case 'A': /* reference */
720     case 'B': /* volatile reference */
721         if (!get_modified_type(ct, sym, pmt_ref, dt)) goto done;
722         break;
723     case 'Q': /* const pointer */
724     case 'R': /* volatile pointer */
725     case 'S': /* const volatile pointer */
726         if (!get_modified_type(ct, sym, pmt_ref, in_args ? dt : 'P')) goto done;
727         break;
728     case 'P': /* Pointer */
729         if (isdigit(*sym->current))
730         {
731             /* FIXME: P6 = Function pointer, others who knows.. */
732             if (*sym->current++ == '6')
733             {
734                 char*                   args = NULL;
735                 const char*             call_conv;
736                 const char*             exported;
737                 struct datatype_t       sub_ct;
738                 unsigned                mark = sym->stack.num;
739
740                 if (!get_calling_convention(*sym->current++,
741                                             &call_conv, &exported, 
742                                             sym->flags & ~UNDNAME_NO_ALLOCATION_LANGUAGE) ||
743                     !demangle_datatype(sym, &sub_ct, pmt_ref, FALSE))
744                     goto done;
745
746                 args = get_args(sym, pmt_ref, TRUE, '(', ')');
747                 if (!args) goto done;
748                 sym->stack.num = mark;
749
750                 ct->left  = str_printf(sym, "%s%s (%s*", 
751                                        sub_ct.left, sub_ct.right, call_conv);
752                 ct->right = str_printf(sym, ")%s", args);
753             }
754             else goto done;
755         }
756         else if (!get_modified_type(ct, sym, pmt_ref, 'P')) goto done;
757         break;
758     case 'W':
759         if (*sym->current == '4')
760         {
761             char*               enum_name;
762             sym->current++;
763             if (!(enum_name = get_class_name(sym)))
764                 goto done;
765             if (sym->flags & UNDNAME_NO_COMPLEX_TYPE)
766                 ct->left = enum_name;
767             else
768                 ct->left = str_printf(sym, "enum %s", enum_name);
769         }
770         else goto done;
771         break;
772     case '0': case '1': case '2': case '3': case '4':
773     case '5': case '6': case '7': case '8': case '9':
774         /* Referring back to previously parsed type */
775         /* left and right are pushed as two separate strings */
776         ct->left = str_array_get_ref(pmt_ref, (dt - '0') * 2);
777         ct->right = str_array_get_ref(pmt_ref, (dt - '0') * 2 + 1);
778         if (!ct->left) goto done;
779         add_pmt = FALSE;
780         break;
781     case '$':
782         if (sym->current[0] != '0') goto done;
783         if (sym->current[1] >= '0' && sym->current[1] <= '9')
784         {
785             char*       ptr;
786             ptr = und_alloc(sym, 2);
787             ptr[0] = sym->current[1] + 1;
788             ptr[1] = 0;
789             ct->left = ptr;
790             sym->current += 2;
791         }
792         else if (sym->current[1] >= 'A' && sym->current[1] <= 'P')
793         {
794             while (sym->current[1] >= 'A' && sym->current[1] <= 'P')
795             {
796                 num_args *= 16;
797                 num_args += sym->current[1] - 'A';
798                 sym->current += 1;
799             }
800             if(sym->current[1] == '@')
801             {
802                 char *ptr;
803                 ptr = und_alloc(sym, 17);
804                 sprintf(ptr,"%d",num_args);
805                 ct->left = ptr;
806                 sym->current += 1;
807             }
808         }
809         else goto done;
810         break;
811     default :
812         ERR("Unknown type %c\n", dt);
813         break;
814     }
815     if (add_pmt && pmt_ref && in_args)
816     {
817         /* left and right are pushed as two separate strings */
818         str_array_push(sym, ct->left ? ct->left : "", -1, pmt_ref);
819         str_array_push(sym, ct->right ? ct->right : "", -1, pmt_ref);
820     }
821 done:
822     
823     return ct->left != NULL;
824 }
825
826 /******************************************************************
827  *              handle_data
828  * Does the final parsing and handling for a variable or a field in
829  * a class.
830  */
831 static BOOL handle_data(struct parsed_symbol* sym)
832 {
833     const char*         access = NULL;
834     const char*         member_type = NULL;
835     const char*         modifier = NULL;
836     struct datatype_t   ct;
837     char*               name = NULL;
838     BOOL                ret = FALSE;
839     char                dt;
840
841     /* 0 private static
842      * 1 protected static
843      * 2 public static
844      * 3 private non-static
845      * 4 protected non-static
846      * 5 public non-static
847      * 6 ?? static
848      * 7 ?? static
849      */
850
851     if (!(sym->flags & UNDNAME_NO_ACCESS_SPECIFIERS))
852     {
853         /* we only print the access for static members */
854         switch (*sym->current)
855         {
856         case '0': access = "private: "; break;
857         case '1': access = "protected: "; break;
858         case '2': access = "public: "; break;
859         } 
860     }
861
862     if (!(sym->flags & UNDNAME_NO_MEMBER_TYPE))
863     {
864         if (*sym->current >= '0' && *sym->current <= '2')
865             member_type = "static ";
866     }
867
868     name = get_class_string(sym, 0);
869
870     switch (dt = *sym->current++)
871     {
872     case '0': case '1': case '2':
873     case '3': case '4': case '5':
874         {
875             unsigned mark = sym->stack.num;
876             struct array pmt;
877
878             str_array_init(&pmt);
879
880             if (!demangle_datatype(sym, &ct, &pmt, FALSE)) goto done;
881             if (!get_modifier(*sym->current++, &modifier)) goto done;
882             sym->stack.num = mark;
883         }
884         break;
885     case '6' : /* compiler generated static */
886     case '7' : /* compiler generated static */
887         ct.left = ct.right = NULL;
888         if (!get_modifier(*sym->current++, &modifier)) goto done;
889         if (*sym->current != '@')
890         {
891             char*       cls = NULL;
892
893             if (!(cls = get_class_name(sym)))
894                 goto done;
895             ct.right = str_printf(sym, "{for `%s'}", cls);
896         }
897         break;
898     default: goto done;
899     }
900     if (sym->flags & UNDNAME_NAME_ONLY) ct.left = ct.right = modifier = NULL;
901     sym->result = str_printf(sym, "%s%s%s%s%s%s%s%s", access,
902                              member_type, ct.left, 
903                              modifier && ct.left ? " " : NULL, modifier, 
904                              modifier || ct.left ? " " : NULL, name, ct.right);
905     ret = TRUE;
906 done:
907     return ret;
908 }
909
910 /******************************************************************
911  *              handle_method
912  * Does the final parsing and handling for a function or a method in
913  * a class.
914  */
915 static BOOL handle_method(struct parsed_symbol* sym, BOOL cast_op)
916 {
917     const char*         access = NULL;
918     const char*         member_type = NULL;
919     struct datatype_t   ct_ret;
920     const char*         call_conv;
921     const char*         modifier = NULL;
922     const char*         exported;
923     const char*         args_str = NULL;
924     const char*         name = NULL;
925     BOOL                ret = FALSE;
926     unsigned            mark;
927     struct array        array_pmt;
928
929     /* FIXME: why 2 possible letters for each option?
930      * 'A' private:
931      * 'B' private:
932      * 'C' private: static
933      * 'D' private: static
934      * 'E' private: virtual
935      * 'F' private: virtual
936      * 'G' private: thunk
937      * 'H' private: thunk
938      * 'I' protected:
939      * 'J' protected:
940      * 'K' protected: static
941      * 'L' protected: static
942      * 'M' protected: virtual
943      * 'N' protected: virtual
944      * 'O' protected: thunk
945      * 'P' protected: thunk
946      * 'Q' public:
947      * 'R' public:
948      * 'S' public: static
949      * 'T' public: static
950      * 'U' public: virtual
951      * 'V' public: virtual
952      * 'W' public: thunk
953      * 'X' public: thunk
954      * 'Y'
955      * 'Z'
956      */
957
958     if (!(sym->flags & UNDNAME_NO_ACCESS_SPECIFIERS))
959     {
960         switch ((*sym->current - 'A') / 8)
961         {
962         case 0: access = "private: "; break;
963         case 1: access = "protected: "; break;
964         case 2: access = "public: "; break;
965         }
966     }
967     if (!(sym->flags & UNDNAME_NO_MEMBER_TYPE))
968     {
969         if (*sym->current >= 'A' && *sym->current <= 'X')
970         {
971             switch ((*sym->current - 'A') % 8)
972             {
973             case 2: case 3: member_type = "static "; break;
974             case 4: case 5: member_type = "virtual "; break;
975             case 6: case 7: member_type = "thunk "; break;
976             }
977         }
978     }
979
980     if (*sym->current >= 'A' && *sym->current <= 'X')
981     {
982         if (!((*sym->current - 'A') & 2))
983         {
984             /* Implicit 'this' pointer */
985             /* If there is an implicit this pointer, const modifier follows */
986             if (!get_modifier(*++sym->current, &modifier)) goto done;
987         }
988     }
989     else if (*sym->current < 'A' || *sym->current > 'Z') goto done;
990     sym->current++;
991
992     name = get_class_string(sym, 0);
993   
994     if (!get_calling_convention(*sym->current++, &call_conv, &exported,
995                                 sym->flags))
996         goto done;
997
998     str_array_init(&array_pmt);
999
1000     /* Return type, or @ if 'void' */
1001     if (*sym->current == '@')
1002     {
1003         ct_ret.left = "void";
1004         ct_ret.right = NULL;
1005         sym->current++;
1006     }
1007     else
1008     {
1009         if (!demangle_datatype(sym, &ct_ret, &array_pmt, FALSE))
1010             goto done;
1011     }
1012     if (sym->flags & UNDNAME_NO_FUNCTION_RETURNS)
1013         ct_ret.left = ct_ret.right = NULL;
1014     if (cast_op)
1015     {
1016         name = str_printf(sym, "%s%s%s", name, ct_ret.left, ct_ret.right);
1017         ct_ret.left = ct_ret.right = NULL;
1018     }
1019
1020     mark = sym->stack.num;
1021     if (!(args_str = get_args(sym, &array_pmt, TRUE, '(', ')'))) goto done;
1022     if (sym->flags & UNDNAME_NAME_ONLY) args_str = modifier = NULL;
1023     sym->stack.num = mark;
1024
1025     /* Note: '()' after 'Z' means 'throws', but we don't care here
1026      * Yet!!! FIXME
1027      */
1028     sym->result = str_printf(sym, "%s%s%s%s%s%s%s%s%s%s%s%s",
1029                              access, member_type, ct_ret.left, 
1030                              (ct_ret.left && !ct_ret.right) ? " " : NULL,
1031                              call_conv, call_conv ? " " : NULL, exported,
1032                              name, args_str, modifier, 
1033                              modifier ? " " : NULL, ct_ret.right);
1034     ret = TRUE;
1035 done:
1036     return ret;
1037 }
1038
1039 /*******************************************************************
1040  *         symbol_demangle
1041  * Demangle a C++ linker symbol
1042  */
1043 static BOOL symbol_demangle(struct parsed_symbol* sym)
1044 {
1045     BOOL                ret = FALSE;
1046     unsigned            do_after = 0;
1047     static CHAR         dashed_null[] = "--null--";
1048
1049     /* FIXME seems wrong as name, as it demangles a simple data type */
1050     if (sym->flags & UNDNAME_NO_ARGUMENTS)
1051     {
1052         struct datatype_t   ct;
1053
1054         if (demangle_datatype(sym, &ct, NULL, FALSE))
1055         {
1056             sym->result = str_printf(sym, "%s%s", ct.left, ct.right);
1057             ret = TRUE;
1058         }
1059         goto done;
1060     }
1061
1062     /* MS mangled names always begin with '?' */
1063     if (*sym->current != '?') return FALSE;
1064     str_array_init(&sym->names);
1065     str_array_init(&sym->stack);
1066     sym->current++;
1067
1068     /* Then function name or operator code */
1069     if (*sym->current == '?' && sym->current[1] != '$')
1070     {
1071         const char* function_name = NULL;
1072
1073         /* C++ operator code (one character, or two if the first is '_') */
1074         switch (*++sym->current)
1075         {
1076         case '0': do_after = 1; break;
1077         case '1': do_after = 2; break;
1078         case '2': function_name = "operator new"; break;
1079         case '3': function_name = "operator delete"; break;
1080         case '4': function_name = "operator="; break;
1081         case '5': function_name = "operator>>"; break;
1082         case '6': function_name = "operator<<"; break;
1083         case '7': function_name = "operator!"; break;
1084         case '8': function_name = "operator=="; break;
1085         case '9': function_name = "operator!="; break;
1086         case 'A': function_name = "operator[]"; break;
1087         case 'B': function_name = "operator "; do_after = 3; break;
1088         case 'C': function_name = "operator->"; break;
1089         case 'D': function_name = "operator*"; break;
1090         case 'E': function_name = "operator++"; break;
1091         case 'F': function_name = "operator--"; break;
1092         case 'G': function_name = "operator-"; break;
1093         case 'H': function_name = "operator+"; break;
1094         case 'I': function_name = "operator&"; break;
1095         case 'J': function_name = "operator->*"; break;
1096         case 'K': function_name = "operator/"; break;
1097         case 'L': function_name = "operator%"; break;
1098         case 'M': function_name = "operator<"; break;
1099         case 'N': function_name = "operator<="; break;
1100         case 'O': function_name = "operator>"; break;
1101         case 'P': function_name = "operator>="; break;
1102         case 'Q': function_name = "operator,"; break;
1103         case 'R': function_name = "operator()"; break;
1104         case 'S': function_name = "operator~"; break;
1105         case 'T': function_name = "operator^"; break;
1106         case 'U': function_name = "operator|"; break;
1107         case 'V': function_name = "operator&&"; break;
1108         case 'W': function_name = "operator||"; break;
1109         case 'X': function_name = "operator*="; break;
1110         case 'Y': function_name = "operator+="; break;
1111         case 'Z': function_name = "operator-="; break;
1112         case '_':
1113             switch (*++sym->current)
1114             {
1115             case '0': function_name = "operator/="; break;
1116             case '1': function_name = "operator%="; break;
1117             case '2': function_name = "operator>>="; break;
1118             case '3': function_name = "operator<<="; break;
1119             case '4': function_name = "operator&="; break;
1120             case '5': function_name = "operator|="; break;
1121             case '6': function_name = "operator^="; break;
1122             case '7': function_name = "`vftable'"; break;
1123             case '8': function_name = "`vbtable'"; break;
1124             case '9': function_name = "`vcall'"; break;
1125             case 'A': function_name = "`typeof'"; break;
1126             case 'B': function_name = "`local static guard'"; break;
1127             case 'C': function_name = "`string'"; do_after = 4; break;
1128             case 'D': function_name = "`vbase destructor'"; break;
1129             case 'E': function_name = "`vector deleting destructor'"; break;
1130             case 'F': function_name = "`default constructor closure'"; break;
1131             case 'G': function_name = "`scalar deleting destructor'"; break;
1132             case 'H': function_name = "`vector constructor iterator'"; break;
1133             case 'I': function_name = "`vector destructor iterator'"; break;
1134             case 'J': function_name = "`vector vbase constructor iterator'"; break;
1135             case 'K': function_name = "`virtual displacement map'"; break;
1136             case 'L': function_name = "`eh vector constructor iterator'"; break;
1137             case 'M': function_name = "`eh vector destructor iterator'"; break;
1138             case 'N': function_name = "`eh vector vbase constructor iterator'"; break;
1139             case 'O': function_name = "`copy constructor closure'"; break;
1140             case 'S': function_name = "`local vftable'"; break;
1141             case 'T': function_name = "`local vftable constructor closure'"; break;
1142             case 'U': function_name = "operator new[]"; break;
1143             case 'V': function_name = "operator delete[]"; break;
1144             case 'X': function_name = "`placement delete closure'"; break;
1145             case 'Y': function_name = "`placement delete[] closure'"; break;
1146             default:
1147                 ERR("Unknown operator: _%c\n", *sym->current);
1148                 return FALSE;
1149             }
1150             break;
1151         default:
1152             /* FIXME: Other operators */
1153             ERR("Unknown operator: %c\n", *sym->current);
1154             return FALSE;
1155         }
1156         sym->current++;
1157         switch (do_after)
1158         {
1159         case 1: case 2:
1160             sym->stack.num = sym->stack.max = 1;
1161             sym->stack.elts[0] = dashed_null;
1162             break;
1163         case 4:
1164             sym->result = (char*)function_name;
1165             ret = TRUE;
1166             goto done;
1167         default:
1168             str_array_push(sym, function_name, -1, &sym->stack);
1169             break;
1170         }
1171         sym->stack.start = 1;
1172     }
1173     else if (*sym->current == '$')
1174     {
1175         /* Strange construct, it's a name with a template argument list
1176            and that's all. */
1177         sym->current++;
1178         sym->result = get_template_name(sym);
1179         ret = TRUE;
1180         goto done;
1181     }
1182
1183     /* Either a class name, or '@' if the symbol is not a class member */
1184     if (*sym->current != '@')
1185     {
1186         /* Class the function is associated with, terminated by '@@' */
1187         if (!get_class(sym)) goto done;
1188     }
1189     else sym->current++;
1190
1191     switch (do_after)
1192     {
1193     case 0: default: break;
1194     case 1: case 2:
1195         /* it's time to set the member name for ctor & dtor */
1196         if (sym->stack.num <= 1) goto done;
1197         if (do_after == 1)
1198             sym->stack.elts[0] = sym->stack.elts[1];
1199         else
1200             sym->stack.elts[0] = str_printf(sym, "~%s", sym->stack.elts[1]);
1201         /* ctors and dtors don't have return type */
1202         sym->flags |= UNDNAME_NO_FUNCTION_RETURNS;
1203         break;
1204     case 3:
1205         sym->flags &= ~UNDNAME_NO_FUNCTION_RETURNS;
1206         break;
1207     }
1208
1209     /* Function/Data type and access level */
1210     if (*sym->current >= '0' && *sym->current <= '7')
1211         ret = handle_data(sym);
1212     else if (*sym->current >= 'A' && *sym->current <= 'Z')
1213         ret = handle_method(sym, do_after == 3);
1214     else ret = FALSE;
1215 done:
1216     if (ret) assert(sym->result);
1217     else WARN("Failed at %s\n", sym->current);
1218
1219     return ret;
1220 }
1221
1222 /*********************************************************************
1223  *              __unDNameEx (MSVCRT.@)
1224  *
1225  * Demangle a C++ identifier.
1226  *
1227  * PARAMS
1228  *  buffer   [O] If not NULL, the place to put the demangled string
1229  *  mangled  [I] Mangled name of the function
1230  *  buflen   [I] Length of buffer
1231  *  memget   [I] Function to allocate memory with
1232  *  memfree  [I] Function to free memory with
1233  *  unknown  [?] Unknown, possibly a call back
1234  *  flags    [I] Flags determining demangled format
1235  *
1236  * RETURNS
1237  *  Success: A string pointing to the unmangled name, allocated with memget.
1238  *  Failure: NULL.
1239  */
1240 char* CDECL __unDNameEx(char* buffer, const char* mangled, int buflen,
1241                         malloc_func_t memget, free_func_t memfree,
1242                         void* unknown, unsigned short int flags)
1243 {
1244     struct parsed_symbol        sym;
1245     const char*                 result;
1246
1247     TRACE("(%p,%s,%d,%p,%p,%p,%x)\n",
1248           buffer, mangled, buflen, memget, memfree, unknown, flags);
1249     
1250     /* The flags details is not documented by MS. However, it looks exactly
1251      * like the UNDNAME_ manifest constants from imagehlp.h and dbghelp.h
1252      * So, we copied those (on top of the file)
1253      */
1254     memset(&sym, 0, sizeof(struct parsed_symbol));
1255     if (flags & UNDNAME_NAME_ONLY)
1256         flags |= UNDNAME_NO_FUNCTION_RETURNS | UNDNAME_NO_ACCESS_SPECIFIERS |
1257             UNDNAME_NO_MEMBER_TYPE | UNDNAME_NO_ALLOCATION_LANGUAGE |
1258             UNDNAME_NO_COMPLEX_TYPE;
1259
1260     sym.flags         = flags;
1261     sym.mem_alloc_ptr = memget;
1262     sym.mem_free_ptr  = memfree;
1263     sym.current       = mangled;
1264
1265     result = symbol_demangle(&sym) ? sym.result : mangled;
1266     if (buffer && buflen)
1267     {
1268         lstrcpynA( buffer, result, buflen);
1269     }
1270     else
1271     {
1272         buffer = memget(strlen(result) + 1);
1273         if (buffer) strcpy(buffer, result);
1274     }
1275
1276     und_free_all(&sym);
1277
1278     return buffer;
1279 }
1280
1281
1282 /*********************************************************************
1283  *              __unDName (MSVCRT.@)
1284  */
1285 char* CDECL __unDName(char* buffer, const char* mangled, int buflen,
1286                       malloc_func_t memget, free_func_t memfree,
1287                       unsigned short int flags)
1288 {
1289     return __unDNameEx(buffer, mangled, buflen, memget, memfree, NULL, flags);
1290 }