msvcrt: Test that some functions depends on locale codepage, not the one set by _setmbcp.
[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, size_t 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 const char* get_modified_type(struct parsed_symbol* sym, char modif)
370 {
371     const char* modifier;
372     const char* ret = NULL;
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 NULL;
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, NULL, FALSE))
394             return NULL;
395         ret = str_printf(sym, "%s%s%s%s%s", 
396                          sub_ct.left, sub_ct.left && modifier ? " " : NULL, 
397                          modifier, sub_ct.right, str_modif);
398         sym->stack.num = mark;
399     }
400     return ret;
401 }
402
403 /******************************************************************
404  *             get_literal_string
405  * Gets the literal name from the current position in the mangled
406  * symbol to the first '@' character. It pushes the parsed name to
407  * the symbol names stack and returns a pointer to it or NULL in
408  * case of an error.
409  */
410 static char* get_literal_string(struct parsed_symbol* sym)
411 {
412     const char *ptr = sym->current;
413
414     do {
415         if (!((*sym->current >= 'A' && *sym->current <= 'Z') ||
416               (*sym->current >= 'a' && *sym->current <= 'z') ||
417               (*sym->current >= '0' && *sym->current <= '9') ||
418               *sym->current == '_' || *sym->current == '$')) {
419             TRACE("Failed at '%c' in %s\n", *sym->current, ptr);
420             return NULL;
421         }
422     } while (*++sym->current != '@');
423     sym->current++;
424     str_array_push(sym, ptr, sym->current - 1 - ptr, &sym->names);
425
426     return str_array_get_ref(&sym->names, sym->names.num - sym->names.start - 1);
427 }
428
429 /******************************************************************
430  *              get_template_name
431  * Parses a name with a template argument list and returns it as
432  * a string.
433  * In a template argument list the back reference to the names
434  * table is separately created. '0' points to the class component
435  * name with the template arguments.  We use the same stack array
436  * to hold the names but save/restore the stack state before/after
437  * parsing the template argument list.
438  */
439 static char* get_template_name(struct parsed_symbol* sym)
440 {
441     char *name, *args;
442     unsigned num_mark = sym->names.num;
443     unsigned start_mark = sym->names.start;
444     unsigned stack_mark = sym->stack.num;
445     struct array array_pmt;
446
447     sym->names.start = sym->names.num;
448     if (!(name = get_literal_string(sym)))
449         return FALSE;
450     str_array_init(&array_pmt);
451     args = get_args(sym, &array_pmt, FALSE, '<', '>');
452     if (args != NULL)
453         name = str_printf(sym, "%s%s", name, args);
454     sym->names.num = num_mark;
455     sym->names.start = start_mark;
456     sym->stack.num = stack_mark;
457     return name;
458 }
459
460 /******************************************************************
461  *              get_class
462  * Parses class as a list of parent-classes, terminated by '@' and stores the
463  * result in 'a' array. Each parent-classes, as well as the inner element
464  * (either field/method name or class name), are represented in the mangled
465  * name by a literal name ([a-zA-Z0-9_]+ terminated by '@') or a back reference
466  * ([0-9]) or a name with template arguments ('?$' literal name followed by the
467  * template argument list). The class name components appear in the reverse
468  * order in the mangled name, e.g aaa@bbb@ccc@@ will be demangled to
469  * ccc::bbb::aaa
470  * For each of this class name componets a string will be allocated in the
471  * array.
472  */
473 static BOOL get_class(struct parsed_symbol* sym)
474 {
475     const char* name = NULL;
476
477     while (*sym->current != '@')
478     {
479         switch (*sym->current)
480         {
481         case '\0': return FALSE;
482
483         case '0': case '1': case '2': case '3':
484         case '4': case '5': case '6': case '7':
485         case '8': case '9':
486             name = str_array_get_ref(&sym->names, *sym->current++ - '0');
487             break;
488         case '?':
489             if (*++sym->current == '$') 
490             {
491                 sym->current++;
492                 name = get_template_name(sym);
493                 str_array_push(sym, name, -1, &sym->names);
494             }
495             break;
496         default:
497             name = get_literal_string(sym);
498             break;
499         }
500         if (!name)
501             return FALSE;
502         str_array_push(sym, name, -1, &sym->stack);
503     }
504     sym->current++;
505     return TRUE;
506 }
507
508 /******************************************************************
509  *              get_class_string
510  * From an array collected by get_class in sym->stack, constructs the
511  * corresponding (allocated) string
512  */
513 static char* get_class_string(struct parsed_symbol* sym, int start)
514 {
515     int         i;
516     size_t      len, sz;
517     char*       ret;
518     struct array *a = &sym->stack;
519
520     for (len = 0, i = start; i < a->num; i++)
521     {
522         assert(a->elts[i]);
523         len += 2 + strlen(a->elts[i]);
524     }
525     if (!(ret = und_alloc(sym, len - 1))) return NULL;
526     for (len = 0, i = a->num - 1; i >= start; i--)
527     {
528         sz = strlen(a->elts[i]);
529         memcpy(ret + len, a->elts[i], sz);
530         len += sz;
531         if (i > start)
532         {
533             ret[len++] = ':';
534             ret[len++] = ':';
535         }
536     }
537     ret[len] = '\0';
538     return ret;
539 }
540
541 /******************************************************************
542  *            get_class_name
543  * Wrapper around get_class and get_class_string.
544  */
545 static char* get_class_name(struct parsed_symbol* sym)
546 {
547     unsigned    mark = sym->stack.num;
548     char*       s = NULL;
549
550     if (get_class(sym))
551         s = get_class_string(sym, mark);
552     sym->stack.num = mark;
553     return s;
554 }
555
556 /******************************************************************
557  *              get_calling_convention
558  * Returns a static string corresponding to the calling convention described
559  * by char 'ch'. Sets export to TRUE iff the calling convention is exported.
560  */
561 static BOOL get_calling_convention(char ch, const char** call_conv,
562                                    const char** exported, unsigned flags)
563 {
564     *call_conv = *exported = NULL;
565
566     if (!(flags & (UNDNAME_NO_MS_KEYWORDS | UNDNAME_NO_ALLOCATION_LANGUAGE)))
567     {
568         if (flags & UNDNAME_NO_LEADING_UNDERSCORES)
569         {
570             if (((ch - 'A') % 2) == 1) *exported = "dll_export ";
571             switch (ch)
572             {
573             case 'A': case 'B': *call_conv = "cdecl"; break;
574             case 'C': case 'D': *call_conv = "pascal"; break;
575             case 'E': case 'F': *call_conv = "thiscall"; break;
576             case 'G': case 'H': *call_conv = "stdcall"; break;
577             case 'I': case 'J': *call_conv = "fastcall"; break;
578             case 'K': break;
579             default: ERR("Unknown calling convention %c\n", ch); return FALSE;
580             }
581         }
582         else
583         {
584             if (((ch - 'A') % 2) == 1) *exported = "__dll_export ";
585             switch (ch)
586             {
587             case 'A': case 'B': *call_conv = "__cdecl"; break;
588             case 'C': case 'D': *call_conv = "__pascal"; break;
589             case 'E': case 'F': *call_conv = "__thiscall"; break;
590             case 'G': case 'H': *call_conv = "__stdcall"; break;
591             case 'I': case 'J': *call_conv = "__fastcall"; break;
592             case 'K': break;
593             default: ERR("Unknown calling convention %c\n", ch); return FALSE;
594             }
595         }
596     }
597     return TRUE;
598 }
599
600 /*******************************************************************
601  *         get_simple_type
602  * Return a string containing an allocated string for a simple data type
603  */
604 static const char* get_simple_type(char c)
605 {
606     const char* type_string;
607     
608     switch (c)
609     {
610     case 'C': type_string = "signed char"; break;
611     case 'D': type_string = "char"; break;
612     case 'E': type_string = "unsigned char"; break;
613     case 'F': type_string = "short"; break;
614     case 'G': type_string = "unsigned short"; break;
615     case 'H': type_string = "int"; break;
616     case 'I': type_string = "unsigned int"; break;
617     case 'J': type_string = "long"; break;
618     case 'K': type_string = "unsigned long"; break;
619     case 'M': type_string = "float"; break;
620     case 'N': type_string = "double"; break;
621     case 'O': type_string = "long double"; break;
622     case 'X': type_string = "void"; break;
623     case 'Z': type_string = "..."; break;
624     default:  type_string = NULL; break;
625     }
626     return type_string;
627 }
628
629 /*******************************************************************
630  *         get_extented_type
631  * Return a string containing an allocated string for a simple data type
632  */
633 static const char* get_extended_type(char c)
634 {
635     const char* type_string;
636     
637     switch (c)
638     {
639     case 'D': type_string = "__int8"; break;
640     case 'E': type_string = "unsigned __int8"; break;
641     case 'F': type_string = "__int16"; break;
642     case 'G': type_string = "unsigned __int16"; break;
643     case 'H': type_string = "__int32"; break;
644     case 'I': type_string = "unsigned __int32"; break;
645     case 'J': type_string = "__int64"; break;
646     case 'K': type_string = "unsigned __int64"; break;
647     case 'L': type_string = "__int128"; break;
648     case 'M': type_string = "unsigned __int128"; break;
649     case 'N': type_string = "bool"; break;
650     case 'W': type_string = "wchar_t"; break;
651     default:  type_string = NULL; break;
652     }
653     return type_string;
654 }
655
656 /*******************************************************************
657  *         demangle_datatype
658  *
659  * Attempt to demangle a C++ data type, which may be datatype.
660  * a datatype type is made up of a number of simple types. e.g:
661  * char** = (pointer to (pointer to (char)))
662  */
663 static BOOL demangle_datatype(struct parsed_symbol* sym, struct datatype_t* ct,
664                               struct array* pmt_ref, BOOL in_args)
665 {
666     char                dt;
667     BOOL                add_pmt = TRUE;
668     int                 num_args=0;
669
670     assert(ct);
671     ct->left = ct->right = NULL;
672     
673     switch (dt = *sym->current++)
674     {
675     case '_':
676         /* MS type: __int8,__int16 etc */
677         ct->left = get_extended_type(*sym->current++);
678         break;
679     case 'C': case 'D': case 'E': case 'F': case 'G':
680     case 'H': case 'I': case 'J': case 'K': case 'M':
681     case 'N': case 'O': case 'X': case 'Z':
682         /* Simple data types */
683         ct->left = get_simple_type(dt);
684         add_pmt = FALSE;
685         break;
686     case 'T': /* union */
687     case 'U': /* struct */
688     case 'V': /* class */
689         /* Class/struct/union */
690         {
691             const char* struct_name = NULL;
692             const char* type_name = NULL;
693
694             if (!(struct_name = get_class_name(sym)))
695                 goto done;
696             if (!(sym->flags & UNDNAME_NO_COMPLEX_TYPE)) 
697             {
698                 switch (dt)
699                 {
700                 case 'T': type_name = "union ";  break;
701                 case 'U': type_name = "struct "; break;
702                 case 'V': type_name = "class ";  break;
703                 }
704             }
705             ct->left = str_printf(sym, "%s%s", type_name, struct_name);
706         }
707         break;
708     case '?':
709         /* not all the time is seems */
710         if (!(ct->left = get_modified_type(sym, '?'))) goto done;
711         break;
712     case 'A': /* reference */
713     case 'B': /* volatile reference */
714         if (!(ct->left = get_modified_type(sym, dt))) goto done;
715         break;
716     case 'Q': /* const pointer */
717     case 'R': /* volatile pointer */
718     case 'S': /* const volatile pointer */
719         if (!(ct->left = get_modified_type(sym, in_args ? dt : 'P'))) goto done;
720         break;
721     case 'P': /* Pointer */
722         if (isdigit(*sym->current))
723         {
724             /* FIXME: P6 = Function pointer, others who knows.. */
725             if (*sym->current++ == '6')
726             {
727                 char*                   args = NULL;
728                 const char*             call_conv;
729                 const char*             exported;
730                 struct datatype_t       sub_ct;
731                 unsigned                mark = sym->stack.num;
732
733                 if (!get_calling_convention(*sym->current++,
734                                             &call_conv, &exported, 
735                                             sym->flags & ~UNDNAME_NO_ALLOCATION_LANGUAGE) ||
736                     !demangle_datatype(sym, &sub_ct, pmt_ref, FALSE))
737                     goto done;
738
739                 args = get_args(sym, pmt_ref, TRUE, '(', ')');
740                 if (!args) goto done;
741                 sym->stack.num = mark;
742
743                 ct->left  = str_printf(sym, "%s%s (%s*", 
744                                        sub_ct.left, sub_ct.right, call_conv);
745                 ct->right = str_printf(sym, ")%s", args);
746             }
747             else goto done;
748         }
749         else if (!(ct->left = get_modified_type(sym, 'P'))) goto done;
750         break;
751     case 'W':
752         if (*sym->current == '4')
753         {
754             char*               enum_name;
755             sym->current++;
756             if (!(enum_name = get_class_name(sym)))
757                 goto done;
758             if (sym->flags & UNDNAME_NO_COMPLEX_TYPE)
759                 ct->left = enum_name;
760             else
761                 ct->left = str_printf(sym, "enum %s", enum_name);
762         }
763         else goto done;
764         break;
765     case '0': case '1': case '2': case '3': case '4':
766     case '5': case '6': case '7': case '8': case '9':
767         /* Referring back to previously parsed type */
768         ct->left = str_array_get_ref(pmt_ref, dt - '0');
769         if (!ct->left) goto done;
770         add_pmt = FALSE;
771         break;
772     case '$':
773         if (sym->current[0] != '0') goto done;
774         if (sym->current[1] >= '0' && sym->current[1] <= '9')
775         {
776             char*       ptr;
777             ptr = und_alloc(sym, 2);
778             ptr[0] = sym->current[1] + 1;
779             ptr[1] = 0;
780             ct->left = ptr;
781             sym->current += 2;
782         }
783         else if (sym->current[1] >= 'A' && sym->current[1] <= 'P')
784         {
785             while (sym->current[1] >= 'A' && sym->current[1] <= 'P')
786             {
787                 num_args *= 16;
788                 num_args += sym->current[1] - 'A';
789                 sym->current += 1;
790             }
791             if(sym->current[1] == '@')
792             {
793                 char *ptr;
794                 ptr = und_alloc(sym, 17);
795                 sprintf(ptr,"%d",num_args);
796                 ct->left = ptr;
797                 sym->current += 1;
798             }
799         }
800         else goto done;
801         break;
802     default :
803         ERR("Unknown type %c\n", dt);
804         break;
805     }
806     if (add_pmt && pmt_ref && in_args)
807         str_array_push(sym, str_printf(sym, "%s%s", ct->left, ct->right), 
808                        -1, pmt_ref);
809 done:
810     
811     return ct->left != NULL;
812 }
813
814 /******************************************************************
815  *              handle_data
816  * Does the final parsing and handling for a variable or a field in
817  * a class.
818  */
819 static BOOL handle_data(struct parsed_symbol* sym)
820 {
821     const char*         access = NULL;
822     const char*         member_type = NULL;
823     const char*         modifier = NULL;
824     struct datatype_t   ct;
825     char*               name = NULL;
826     BOOL                ret = FALSE;
827     char                dt;
828
829     /* 0 private static
830      * 1 protected static
831      * 2 public static
832      * 3 private non-static
833      * 4 protected non-static
834      * 5 public non-static
835      * 6 ?? static
836      * 7 ?? static
837      */
838
839     if (!(sym->flags & UNDNAME_NO_ACCESS_SPECIFIERS))
840     {
841         /* we only print the access for static members */
842         switch (*sym->current)
843         {
844         case '0': access = "private: "; break;
845         case '1': access = "protected: "; break;
846         case '2': access = "public: "; break;
847         } 
848     }
849
850     if (!(sym->flags & UNDNAME_NO_MEMBER_TYPE))
851     {
852         if (*sym->current >= '0' && *sym->current <= '2')
853             member_type = "static ";
854     }
855
856     name = get_class_string(sym, 0);
857
858     switch (dt = *sym->current++)
859     {
860     case '0': case '1': case '2':
861     case '3': case '4': case '5':
862         {
863             unsigned mark = sym->stack.num;
864             struct array pmt;
865
866             str_array_init(&pmt);
867
868             if (!demangle_datatype(sym, &ct, &pmt, FALSE)) goto done;
869             if (!get_modifier(*sym->current++, &modifier)) goto done;
870             sym->stack.num = mark;
871         }
872         break;
873     case '6' : /* compiler generated static */
874     case '7' : /* compiler generated static */
875         ct.left = ct.right = NULL;
876         if (!get_modifier(*sym->current++, &modifier)) goto done;
877         if (*sym->current != '@')
878         {
879             char*       cls = NULL;
880
881             if (!(cls = get_class_name(sym)))
882                 goto done;
883             ct.right = str_printf(sym, "{for `%s'}", cls);
884         }
885         break;
886     default: goto done;
887     }
888     if (sym->flags & UNDNAME_NAME_ONLY) ct.left = ct.right = modifier = NULL;
889     sym->result = str_printf(sym, "%s%s%s%s%s%s%s%s", access,
890                              member_type, ct.left, 
891                              modifier && ct.left ? " " : NULL, modifier, 
892                              modifier || ct.left ? " " : NULL, name, ct.right);
893     ret = TRUE;
894 done:
895     return ret;
896 }
897
898 /******************************************************************
899  *              handle_method
900  * Does the final parsing and handling for a function or a method in
901  * a class.
902  */
903 static BOOL handle_method(struct parsed_symbol* sym, BOOL cast_op)
904 {
905     const char*         access = NULL;
906     const char*         member_type = NULL;
907     struct datatype_t   ct_ret;
908     const char*         call_conv;
909     const char*         modifier = NULL;
910     const char*         exported;
911     const char*         args_str = NULL;
912     const char*         name = NULL;
913     BOOL                ret = FALSE;
914     unsigned            mark;
915     struct array        array_pmt;
916
917     /* FIXME: why 2 possible letters for each option?
918      * 'A' private:
919      * 'B' private:
920      * 'C' private: static
921      * 'D' private: static
922      * 'E' private: virtual
923      * 'F' private: virtual
924      * 'G' private: thunk
925      * 'H' private: thunk
926      * 'I' protected:
927      * 'J' protected:
928      * 'K' protected: static
929      * 'L' protected: static
930      * 'M' protected: virtual
931      * 'N' protected: virtual
932      * 'O' protected: thunk
933      * 'P' protected: thunk
934      * 'Q' public:
935      * 'R' public:
936      * 'S' public: static
937      * 'T' public: static
938      * 'U' public: virtual
939      * 'V' public: virtual
940      * 'W' public: thunk
941      * 'X' public: thunk
942      * 'Y'
943      * 'Z'
944      */
945
946     if (!(sym->flags & UNDNAME_NO_ACCESS_SPECIFIERS))
947     {
948         switch ((*sym->current - 'A') / 8)
949         {
950         case 0: access = "private: "; break;
951         case 1: access = "protected: "; break;
952         case 2: access = "public: "; break;
953         }
954     }
955     if (!(sym->flags & UNDNAME_NO_MEMBER_TYPE))
956     {
957         if (*sym->current >= 'A' && *sym->current <= 'X')
958         {
959             switch ((*sym->current - 'A') % 8)
960             {
961             case 2: case 3: member_type = "static "; break;
962             case 4: case 5: member_type = "virtual "; break;
963             case 6: case 7: member_type = "thunk "; break;
964             }
965         }
966     }
967
968     if (*sym->current >= 'A' && *sym->current <= 'X')
969     {
970         if (!((*sym->current - 'A') & 2))
971         {
972             /* Implicit 'this' pointer */
973             /* If there is an implicit this pointer, const modifier follows */
974             if (!get_modifier(*++sym->current, &modifier)) goto done;
975         }
976     }
977     else if (*sym->current < 'A' || *sym->current > 'Z') goto done;
978     sym->current++;
979
980     name = get_class_string(sym, 0);
981   
982     if (!get_calling_convention(*sym->current++, &call_conv, &exported,
983                                 sym->flags))
984         goto done;
985
986     str_array_init(&array_pmt);
987
988     /* Return type, or @ if 'void' */
989     if (*sym->current == '@')
990     {
991         ct_ret.left = "void";
992         ct_ret.right = NULL;
993         sym->current++;
994     }
995     else
996     {
997         if (!demangle_datatype(sym, &ct_ret, &array_pmt, FALSE))
998             goto done;
999     }
1000     if (sym->flags & UNDNAME_NO_FUNCTION_RETURNS)
1001         ct_ret.left = ct_ret.right = NULL;
1002     if (cast_op)
1003     {
1004         name = str_printf(sym, "%s%s%s", name, ct_ret.left, ct_ret.right);
1005         ct_ret.left = ct_ret.right = NULL;
1006     }
1007
1008     mark = sym->stack.num;
1009     if (!(args_str = get_args(sym, &array_pmt, TRUE, '(', ')'))) goto done;
1010     if (sym->flags & UNDNAME_NAME_ONLY) args_str = modifier = NULL;
1011     sym->stack.num = mark;
1012
1013     /* Note: '()' after 'Z' means 'throws', but we don't care here
1014      * Yet!!! FIXME
1015      */
1016     sym->result = str_printf(sym, "%s%s%s%s%s%s%s%s%s%s%s%s",
1017                              access, member_type, ct_ret.left, 
1018                              (ct_ret.left && !ct_ret.right) ? " " : NULL,
1019                              call_conv, call_conv ? " " : NULL, exported,
1020                              name, args_str, modifier, 
1021                              modifier ? " " : NULL, ct_ret.right);
1022     ret = TRUE;
1023 done:
1024     return ret;
1025 }
1026
1027 /*******************************************************************
1028  *         symbol_demangle
1029  * Demangle a C++ linker symbol
1030  */
1031 static BOOL symbol_demangle(struct parsed_symbol* sym)
1032 {
1033     BOOL                ret = FALSE;
1034     unsigned            do_after = 0;
1035     static CHAR         dashed_null[] = "--null--";
1036
1037     /* FIXME seems wrong as name, as it demangles a simple data type */
1038     if (sym->flags & UNDNAME_NO_ARGUMENTS)
1039     {
1040         struct datatype_t   ct;
1041
1042         if (demangle_datatype(sym, &ct, NULL, FALSE))
1043         {
1044             sym->result = str_printf(sym, "%s%s", ct.left, ct.right);
1045             ret = TRUE;
1046         }
1047         goto done;
1048     }
1049
1050     /* MS mangled names always begin with '?' */
1051     if (*sym->current != '?') return FALSE;
1052     str_array_init(&sym->names);
1053     str_array_init(&sym->stack);
1054     sym->current++;
1055
1056     /* Then function name or operator code */
1057     if (*sym->current == '?' && sym->current[1] != '$')
1058     {
1059         const char* function_name = NULL;
1060
1061         /* C++ operator code (one character, or two if the first is '_') */
1062         switch (*++sym->current)
1063         {
1064         case '0': do_after = 1; break;
1065         case '1': do_after = 2; break;
1066         case '2': function_name = "operator new"; break;
1067         case '3': function_name = "operator delete"; break;
1068         case '4': function_name = "operator="; break;
1069         case '5': function_name = "operator>>"; break;
1070         case '6': function_name = "operator<<"; break;
1071         case '7': function_name = "operator!"; break;
1072         case '8': function_name = "operator=="; break;
1073         case '9': function_name = "operator!="; break;
1074         case 'A': function_name = "operator[]"; break;
1075         case 'B': function_name = "operator "; do_after = 3; break;
1076         case 'C': function_name = "operator->"; break;
1077         case 'D': function_name = "operator*"; break;
1078         case 'E': function_name = "operator++"; break;
1079         case 'F': function_name = "operator--"; break;
1080         case 'G': function_name = "operator-"; break;
1081         case 'H': function_name = "operator+"; break;
1082         case 'I': function_name = "operator&"; break;
1083         case 'J': function_name = "operator->*"; break;
1084         case 'K': function_name = "operator/"; break;
1085         case 'L': function_name = "operator%"; break;
1086         case 'M': function_name = "operator<"; break;
1087         case 'N': function_name = "operator<="; break;
1088         case 'O': function_name = "operator>"; break;
1089         case 'P': function_name = "operator>="; break;
1090         case 'Q': function_name = "operator,"; break;
1091         case 'R': function_name = "operator()"; break;
1092         case 'S': function_name = "operator~"; break;
1093         case 'T': function_name = "operator^"; break;
1094         case 'U': function_name = "operator|"; break;
1095         case 'V': function_name = "operator&&"; break;
1096         case 'W': function_name = "operator||"; break;
1097         case 'X': function_name = "operator*="; break;
1098         case 'Y': function_name = "operator+="; break;
1099         case 'Z': function_name = "operator-="; break;
1100         case '_':
1101             switch (*++sym->current)
1102             {
1103             case '0': function_name = "operator/="; break;
1104             case '1': function_name = "operator%="; break;
1105             case '2': function_name = "operator>>="; break;
1106             case '3': function_name = "operator<<="; break;
1107             case '4': function_name = "operator&="; break;
1108             case '5': function_name = "operator|="; break;
1109             case '6': function_name = "operator^="; break;
1110             case '7': function_name = "`vftable'"; break;
1111             case '8': function_name = "`vbtable'"; break;
1112             case '9': function_name = "`vcall'"; break;
1113             case 'A': function_name = "`typeof'"; break;
1114             case 'B': function_name = "`local static guard'"; break;
1115             case 'C': function_name = "`string'"; do_after = 4; break;
1116             case 'D': function_name = "`vbase destructor'"; break;
1117             case 'E': function_name = "`vector deleting destructor'"; break;
1118             case 'F': function_name = "`default constructor closure'"; break;
1119             case 'G': function_name = "`scalar deleting destructor'"; break;
1120             case 'H': function_name = "`vector constructor iterator'"; break;
1121             case 'I': function_name = "`vector destructor iterator'"; break;
1122             case 'J': function_name = "`vector vbase constructor iterator'"; break;
1123             case 'K': function_name = "`virtual displacement map'"; break;
1124             case 'L': function_name = "`eh vector constructor iterator'"; break;
1125             case 'M': function_name = "`eh vector destructor iterator'"; break;
1126             case 'N': function_name = "`eh vector vbase constructor iterator'"; break;
1127             case 'O': function_name = "`copy constructor closure'"; break;
1128             case 'S': function_name = "`local vftable'"; break;
1129             case 'T': function_name = "`local vftable constructor closure'"; break;
1130             case 'U': function_name = "operator new[]"; break;
1131             case 'V': function_name = "operator delete[]"; break;
1132             case 'X': function_name = "`placement delete closure'"; break;
1133             case 'Y': function_name = "`placement delete[] closure'"; break;
1134             default:
1135                 ERR("Unknown operator: _%c\n", *sym->current);
1136                 return FALSE;
1137             }
1138             break;
1139         default:
1140             /* FIXME: Other operators */
1141             ERR("Unknown operator: %c\n", *sym->current);
1142             return FALSE;
1143         }
1144         sym->current++;
1145         switch (do_after)
1146         {
1147         case 1: case 2:
1148             sym->stack.num = sym->stack.max = 1;
1149             sym->stack.elts[0] = dashed_null;
1150             break;
1151         case 4:
1152             sym->result = (char*)function_name;
1153             ret = TRUE;
1154             goto done;
1155         default:
1156             str_array_push(sym, function_name, -1, &sym->stack);
1157             break;
1158         }
1159         sym->stack.start = 1;
1160     }
1161     else if (*sym->current == '$')
1162     {
1163         /* Strange construct, it's a name with a template argument list
1164            and that's all. */
1165         sym->current++;
1166         sym->result = get_template_name(sym);
1167         ret = TRUE;
1168         goto done;
1169     }
1170
1171     /* Either a class name, or '@' if the symbol is not a class member */
1172     if (*sym->current != '@')
1173     {
1174         /* Class the function is associated with, terminated by '@@' */
1175         if (!get_class(sym)) goto done;
1176     }
1177     else sym->current++;
1178
1179     switch (do_after)
1180     {
1181     case 0: default: break;
1182     case 1: case 2:
1183         /* it's time to set the member name for ctor & dtor */
1184         if (sym->stack.num <= 1) goto done;
1185         if (do_after == 1)
1186             sym->stack.elts[0] = sym->stack.elts[1];
1187         else
1188             sym->stack.elts[0] = str_printf(sym, "~%s", sym->stack.elts[1]);
1189         /* ctors and dtors don't have return type */
1190         sym->flags |= UNDNAME_NO_FUNCTION_RETURNS;
1191         break;
1192     case 3:
1193         sym->flags &= ~UNDNAME_NO_FUNCTION_RETURNS;
1194         break;
1195     }
1196
1197     /* Function/Data type and access level */
1198     if (*sym->current >= '0' && *sym->current <= '7')
1199         ret = handle_data(sym);
1200     else if (*sym->current >= 'A' && *sym->current <= 'Z')
1201         ret = handle_method(sym, do_after == 3);
1202     else ret = FALSE;
1203 done:
1204     if (ret) assert(sym->result);
1205     else WARN("Failed at %s\n", sym->current);
1206
1207     return ret;
1208 }
1209
1210 /*********************************************************************
1211  *              __unDNameEx (MSVCRT.@)
1212  *
1213  * Demangle a C++ identifier.
1214  *
1215  * PARAMS
1216  *  buffer   [O] If not NULL, the place to put the demangled string
1217  *  mangled  [I] Mangled name of the function
1218  *  buflen   [I] Length of buffer
1219  *  memget   [I] Function to allocate memory with
1220  *  memfree  [I] Function to free memory with
1221  *  unknown  [?] Unknown, possibly a call back
1222  *  flags    [I] Flags determining demangled format
1223  *
1224  * RETURNS
1225  *  Success: A string pointing to the unmangled name, allocated with memget.
1226  *  Failure: NULL.
1227  */
1228 char* CDECL __unDNameEx(char* buffer, const char* mangled, int buflen,
1229                         malloc_func_t memget, free_func_t memfree,
1230                         void* unknown, unsigned short int flags)
1231 {
1232     struct parsed_symbol        sym;
1233     const char*                 result;
1234
1235     TRACE("(%p,%s,%d,%p,%p,%p,%x)\n",
1236           buffer, mangled, buflen, memget, memfree, unknown, flags);
1237     
1238     /* The flags details is not documented by MS. However, it looks exactly
1239      * like the UNDNAME_ manifest constants from imagehlp.h and dbghelp.h
1240      * So, we copied those (on top of the file)
1241      */
1242     memset(&sym, 0, sizeof(struct parsed_symbol));
1243     if (flags & UNDNAME_NAME_ONLY)
1244         flags |= UNDNAME_NO_FUNCTION_RETURNS | UNDNAME_NO_ACCESS_SPECIFIERS |
1245             UNDNAME_NO_MEMBER_TYPE | UNDNAME_NO_ALLOCATION_LANGUAGE |
1246             UNDNAME_NO_COMPLEX_TYPE;
1247
1248     sym.flags         = flags;
1249     sym.mem_alloc_ptr = memget;
1250     sym.mem_free_ptr  = memfree;
1251     sym.current       = mangled;
1252
1253     result = symbol_demangle(&sym) ? sym.result : mangled;
1254     if (buffer && buflen)
1255     {
1256         lstrcpynA( buffer, result, buflen);
1257     }
1258     else
1259     {
1260         buffer = memget(strlen(result) + 1);
1261         if (buffer) strcpy(buffer, result);
1262     }
1263
1264     und_free_all(&sym);
1265
1266     return buffer;
1267 }
1268
1269
1270 /*********************************************************************
1271  *              __unDName (MSVCRT.@)
1272  */
1273 char* CDECL __unDName(char* buffer, const char* mangled, int buflen,
1274                       malloc_func_t memget, free_func_t memfree,
1275                       unsigned short int flags)
1276 {
1277     return __unDNameEx(buffer, mangled, buflen, memget, memfree, NULL, flags);
1278 }