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