urlmon: Added CUri ClassFactory implementation.
[wine] / dlls / dbghelp / msc.c
1 /*
2  * File msc.c - read VC++ debug information from COFF and eventually
3  * from PDB files.
4  *
5  * Copyright (C) 1996,      Eric Youngdale.
6  * Copyright (C) 1999-2000, Ulrich Weigand.
7  * Copyright (C) 2004-2009, Eric Pouech.
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this library; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22  */
23
24 /*
25  * Note - this handles reading debug information for 32 bit applications
26  * that run under Windows-NT for example.  I doubt that this would work well
27  * for 16 bit applications, but I don't think it really matters since the
28  * file format is different, and we should never get in here in such cases.
29  *
30  * TODO:
31  *      Get 16 bit CV stuff working.
32  *      Add symbol size to internal symbol table.
33  */
34
35 #define NONAMELESSUNION
36
37 #include "config.h"
38 #include "wine/port.h"
39
40 #include <assert.h>
41 #include <stdio.h>
42 #include <stdlib.h>
43
44 #include <string.h>
45 #ifdef HAVE_UNISTD_H
46 # include <unistd.h>
47 #endif
48
49 #include <stdarg.h>
50 #include "windef.h"
51 #include "winbase.h"
52 #include "winternl.h"
53
54 #include "wine/exception.h"
55 #include "wine/debug.h"
56 #include "dbghelp_private.h"
57 #include "wine/mscvpdb.h"
58
59 WINE_DEFAULT_DEBUG_CHANNEL(dbghelp_msc);
60
61 #define MAX_PATHNAME_LEN 1024
62
63 struct pdb_stream_name
64 {
65     const char* name;
66     unsigned    index;
67 };
68
69 struct pdb_file_info
70 {
71     enum pdb_kind               kind;
72     DWORD                       age;
73     HANDLE                      hMap;
74     const char*                 image;
75     struct pdb_stream_name*     stream_dict;
76     unsigned                    fpoext_stream;
77     union
78     {
79         struct
80         {
81             DWORD               timestamp;
82             struct PDB_JG_TOC*  toc;
83         } jg;
84         struct
85         {
86             GUID                guid;
87             struct PDB_DS_TOC*  toc;
88         } ds;
89     } u;
90 };
91
92 /* FIXME: don't make it static */
93 #define CV_MAX_MODULES          32
94 struct pdb_module_info
95 {
96     unsigned                    used_subfiles;
97     struct pdb_file_info        pdb_files[CV_MAX_MODULES];
98 };
99
100 /*========================================================================
101  * Debug file access helper routines
102  */
103
104 static void dump(const void* ptr, unsigned len)
105 {
106     unsigned int i, j;
107     char        msg[128];
108     const char* hexof = "0123456789abcdef";
109     const BYTE* x = ptr;
110
111     for (i = 0; i < len; i += 16)
112     {
113         sprintf(msg, "%08x: ", i);
114         memset(msg + 10, ' ', 3 * 16 + 1 + 16);
115         for (j = 0; j < min(16, len - i); j++)
116         {
117             msg[10 + 3 * j + 0] = hexof[x[i + j] >> 4];
118             msg[10 + 3 * j + 1] = hexof[x[i + j] & 15];
119             msg[10 + 3 * j + 2] = ' ';
120             msg[10 + 3 * 16 + 1 + j] = (x[i + j] >= 0x20 && x[i + j] < 0x7f) ?
121                 x[i + j] : '.';
122         }
123         msg[10 + 3 * 16] = ' ';
124         msg[10 + 3 * 16 + 1 + 16] = '\0';
125         FIXME("%s\n", msg);
126     }
127 }
128
129 /*========================================================================
130  * Process CodeView type information.
131  */
132
133 #define MAX_BUILTIN_TYPES       0x06FF
134 #define FIRST_DEFINABLE_TYPE    0x1000
135
136 static struct symt*     cv_basic_types[MAX_BUILTIN_TYPES];
137
138 struct cv_defined_module
139 {
140     BOOL                allowed;
141     unsigned int        num_defined_types;
142     struct symt**       defined_types;
143 };
144 /* FIXME: don't make it static */
145 #define CV_MAX_MODULES          32
146 static struct cv_defined_module cv_zmodules[CV_MAX_MODULES];
147 static struct cv_defined_module*cv_current_module;
148
149 static void codeview_init_basic_types(struct module* module)
150 {
151     /*
152      * These are the common builtin types that are used by VC++.
153      */
154     cv_basic_types[T_NOTYPE] = NULL;
155     cv_basic_types[T_ABS]    = NULL;
156     cv_basic_types[T_VOID]   = &symt_new_basic(module, btVoid,  "void", 0)->symt;
157     cv_basic_types[T_CHAR]   = &symt_new_basic(module, btChar,  "char", 1)->symt;
158     cv_basic_types[T_SHORT]  = &symt_new_basic(module, btInt,   "short int", 2)->symt;
159     cv_basic_types[T_LONG]   = &symt_new_basic(module, btInt,   "long int", 4)->symt;
160     cv_basic_types[T_QUAD]   = &symt_new_basic(module, btInt,   "long long int", 8)->symt;
161     cv_basic_types[T_UCHAR]  = &symt_new_basic(module, btUInt,  "unsigned char", 1)->symt;
162     cv_basic_types[T_USHORT] = &symt_new_basic(module, btUInt,  "unsigned short", 2)->symt;
163     cv_basic_types[T_ULONG]  = &symt_new_basic(module, btUInt,  "unsigned long", 4)->symt;
164     cv_basic_types[T_UQUAD]  = &symt_new_basic(module, btUInt,  "unsigned long long", 8)->symt;
165     cv_basic_types[T_BOOL08] = &symt_new_basic(module, btBool,  "BOOL08", 1)->symt;
166     cv_basic_types[T_BOOL16] = &symt_new_basic(module, btBool,  "BOOL16", 2)->symt;
167     cv_basic_types[T_BOOL32] = &symt_new_basic(module, btBool,  "BOOL32", 4)->symt;
168     cv_basic_types[T_BOOL64] = &symt_new_basic(module, btBool,  "BOOL64", 8)->symt;
169     cv_basic_types[T_REAL32] = &symt_new_basic(module, btFloat, "float", 4)->symt;
170     cv_basic_types[T_REAL64] = &symt_new_basic(module, btFloat, "double", 8)->symt;
171     cv_basic_types[T_REAL80] = &symt_new_basic(module, btFloat, "long double", 10)->symt;
172     cv_basic_types[T_RCHAR]  = &symt_new_basic(module, btInt,   "signed char", 1)->symt;
173     cv_basic_types[T_WCHAR]  = &symt_new_basic(module, btWChar, "wchar_t", 2)->symt;
174     cv_basic_types[T_INT2]   = &symt_new_basic(module, btInt,   "INT2", 2)->symt;
175     cv_basic_types[T_UINT2]  = &symt_new_basic(module, btUInt,  "UINT2", 2)->symt;
176     cv_basic_types[T_INT4]   = &symt_new_basic(module, btInt,   "INT4", 4)->symt;
177     cv_basic_types[T_UINT4]  = &symt_new_basic(module, btUInt,  "UINT4", 4)->symt;
178     cv_basic_types[T_INT8]   = &symt_new_basic(module, btInt,   "INT8", 8)->symt;
179     cv_basic_types[T_UINT8]  = &symt_new_basic(module, btUInt,  "UINT8", 8)->symt;
180     cv_basic_types[T_HRESULT]= &symt_new_basic(module, btUInt,  "HRESULT", 4)->symt;
181
182     cv_basic_types[T_32PVOID]   = &symt_new_pointer(module, cv_basic_types[T_VOID], 4)->symt;
183     cv_basic_types[T_32PCHAR]   = &symt_new_pointer(module, cv_basic_types[T_CHAR], 4)->symt;
184     cv_basic_types[T_32PSHORT]  = &symt_new_pointer(module, cv_basic_types[T_SHORT], 4)->symt;
185     cv_basic_types[T_32PLONG]   = &symt_new_pointer(module, cv_basic_types[T_LONG], 4)->symt;
186     cv_basic_types[T_32PQUAD]   = &symt_new_pointer(module, cv_basic_types[T_QUAD], 4)->symt;
187     cv_basic_types[T_32PUCHAR]  = &symt_new_pointer(module, cv_basic_types[T_UCHAR], 4)->symt;
188     cv_basic_types[T_32PUSHORT] = &symt_new_pointer(module, cv_basic_types[T_USHORT], 4)->symt;
189     cv_basic_types[T_32PULONG]  = &symt_new_pointer(module, cv_basic_types[T_ULONG], 4)->symt;
190     cv_basic_types[T_32PUQUAD]  = &symt_new_pointer(module, cv_basic_types[T_UQUAD], 4)->symt;
191     cv_basic_types[T_32PBOOL08] = &symt_new_pointer(module, cv_basic_types[T_BOOL08], 4)->symt;
192     cv_basic_types[T_32PBOOL16] = &symt_new_pointer(module, cv_basic_types[T_BOOL16], 4)->symt;
193     cv_basic_types[T_32PBOOL32] = &symt_new_pointer(module, cv_basic_types[T_BOOL32], 4)->symt;
194     cv_basic_types[T_32PBOOL64] = &symt_new_pointer(module, cv_basic_types[T_BOOL64], 4)->symt;
195     cv_basic_types[T_32PREAL32] = &symt_new_pointer(module, cv_basic_types[T_REAL32], 4)->symt;
196     cv_basic_types[T_32PREAL64] = &symt_new_pointer(module, cv_basic_types[T_REAL64], 4)->symt;
197     cv_basic_types[T_32PREAL80] = &symt_new_pointer(module, cv_basic_types[T_REAL80], 4)->symt;
198     cv_basic_types[T_32PRCHAR]  = &symt_new_pointer(module, cv_basic_types[T_RCHAR], 4)->symt;
199     cv_basic_types[T_32PWCHAR]  = &symt_new_pointer(module, cv_basic_types[T_WCHAR], 4)->symt;
200     cv_basic_types[T_32PINT2]   = &symt_new_pointer(module, cv_basic_types[T_INT2], 4)->symt;
201     cv_basic_types[T_32PUINT2]  = &symt_new_pointer(module, cv_basic_types[T_UINT2], 4)->symt;
202     cv_basic_types[T_32PINT4]   = &symt_new_pointer(module, cv_basic_types[T_INT4], 4)->symt;
203     cv_basic_types[T_32PUINT4]  = &symt_new_pointer(module, cv_basic_types[T_UINT4], 4)->symt;
204     cv_basic_types[T_32PINT8]   = &symt_new_pointer(module, cv_basic_types[T_INT8], 4)->symt;
205     cv_basic_types[T_32PUINT8]  = &symt_new_pointer(module, cv_basic_types[T_UINT8], 4)->symt;
206     cv_basic_types[T_32PHRESULT]= &symt_new_pointer(module, cv_basic_types[T_HRESULT], 4)->symt;
207
208     cv_basic_types[T_64PVOID]   = &symt_new_pointer(module, cv_basic_types[T_VOID], 8)->symt;
209     cv_basic_types[T_64PCHAR]   = &symt_new_pointer(module, cv_basic_types[T_CHAR], 8)->symt;
210     cv_basic_types[T_64PSHORT]  = &symt_new_pointer(module, cv_basic_types[T_SHORT], 8)->symt;
211     cv_basic_types[T_64PLONG]   = &symt_new_pointer(module, cv_basic_types[T_LONG], 8)->symt;
212     cv_basic_types[T_64PQUAD]   = &symt_new_pointer(module, cv_basic_types[T_QUAD], 8)->symt;
213     cv_basic_types[T_64PUCHAR]  = &symt_new_pointer(module, cv_basic_types[T_UCHAR], 8)->symt;
214     cv_basic_types[T_64PUSHORT] = &symt_new_pointer(module, cv_basic_types[T_USHORT], 8)->symt;
215     cv_basic_types[T_64PULONG]  = &symt_new_pointer(module, cv_basic_types[T_ULONG], 8)->symt;
216     cv_basic_types[T_64PUQUAD]  = &symt_new_pointer(module, cv_basic_types[T_UQUAD], 8)->symt;
217     cv_basic_types[T_64PBOOL08] = &symt_new_pointer(module, cv_basic_types[T_BOOL08], 8)->symt;
218     cv_basic_types[T_64PBOOL16] = &symt_new_pointer(module, cv_basic_types[T_BOOL16], 8)->symt;
219     cv_basic_types[T_64PBOOL32] = &symt_new_pointer(module, cv_basic_types[T_BOOL32], 8)->symt;
220     cv_basic_types[T_64PBOOL64] = &symt_new_pointer(module, cv_basic_types[T_BOOL64], 8)->symt;
221     cv_basic_types[T_64PREAL32] = &symt_new_pointer(module, cv_basic_types[T_REAL32], 8)->symt;
222     cv_basic_types[T_64PREAL64] = &symt_new_pointer(module, cv_basic_types[T_REAL64], 8)->symt;
223     cv_basic_types[T_64PREAL80] = &symt_new_pointer(module, cv_basic_types[T_REAL80], 8)->symt;
224     cv_basic_types[T_64PRCHAR]  = &symt_new_pointer(module, cv_basic_types[T_RCHAR], 8)->symt;
225     cv_basic_types[T_64PWCHAR]  = &symt_new_pointer(module, cv_basic_types[T_WCHAR], 8)->symt;
226     cv_basic_types[T_64PINT2]   = &symt_new_pointer(module, cv_basic_types[T_INT2], 8)->symt;
227     cv_basic_types[T_64PUINT2]  = &symt_new_pointer(module, cv_basic_types[T_UINT2], 8)->symt;
228     cv_basic_types[T_64PINT4]   = &symt_new_pointer(module, cv_basic_types[T_INT4], 8)->symt;
229     cv_basic_types[T_64PUINT4]  = &symt_new_pointer(module, cv_basic_types[T_UINT4], 8)->symt;
230     cv_basic_types[T_64PINT8]   = &symt_new_pointer(module, cv_basic_types[T_INT8], 8)->symt;
231     cv_basic_types[T_64PUINT8]  = &symt_new_pointer(module, cv_basic_types[T_UINT8], 8)->symt;
232     cv_basic_types[T_64PHRESULT]= &symt_new_pointer(module, cv_basic_types[T_HRESULT], 8)->symt;
233 }
234
235 static int leaf_as_variant(VARIANT* v, const unsigned short int* leaf)
236 {
237     unsigned short int type = *leaf++;
238     int length = 2;
239
240     if (type < LF_NUMERIC)
241     {
242         v->n1.n2.vt = VT_UINT;
243         v->n1.n2.n3.uintVal = type;
244     }
245     else
246     {
247         switch (type)
248         {
249         case LF_CHAR:
250             length += 1;
251             v->n1.n2.vt = VT_I1;
252             v->n1.n2.n3.cVal = *(const char*)leaf;
253             break;
254
255         case LF_SHORT:
256             length += 2;
257             v->n1.n2.vt = VT_I2;
258             v->n1.n2.n3.iVal = *(const short*)leaf;
259             break;
260
261         case LF_USHORT:
262             length += 2;
263             v->n1.n2.vt = VT_UI2;
264             v->n1.n2.n3.uiVal = *leaf;
265             break;
266
267         case LF_LONG:
268             length += 4;
269             v->n1.n2.vt = VT_I4;
270             v->n1.n2.n3.lVal = *(const int*)leaf;
271             break;
272
273         case LF_ULONG:
274             length += 4;
275             v->n1.n2.vt = VT_UI4;
276             v->n1.n2.n3.uiVal = *(const unsigned int*)leaf;
277             break;
278
279         case LF_QUADWORD:
280             length += 8;
281             v->n1.n2.vt = VT_I8;
282             v->n1.n2.n3.llVal = *(const long long int*)leaf;
283             break;
284
285         case LF_UQUADWORD:
286             length += 8;
287             v->n1.n2.vt = VT_UI8;
288             v->n1.n2.n3.ullVal = *(const long long unsigned int*)leaf;
289             break;
290
291         case LF_REAL32:
292             length += 4;
293             v->n1.n2.vt = VT_R4;
294             v->n1.n2.n3.fltVal = *(const float*)leaf;
295             break;
296
297         case LF_REAL48:
298             FIXME("Unsupported numeric leaf type %04x\n", type);
299             length += 6;
300             v->n1.n2.vt = VT_EMPTY;     /* FIXME */
301             break;
302
303         case LF_REAL64:
304             length += 8;
305             v->n1.n2.vt = VT_R8;
306             v->n1.n2.n3.fltVal = *(const double*)leaf;
307             break;
308
309         case LF_REAL80:
310             FIXME("Unsupported numeric leaf type %04x\n", type);
311             length += 10;
312             v->n1.n2.vt = VT_EMPTY;     /* FIXME */
313             break;
314
315         case LF_REAL128:
316             FIXME("Unsupported numeric leaf type %04x\n", type);
317             length += 16;
318             v->n1.n2.vt = VT_EMPTY;     /* FIXME */
319             break;
320
321         case LF_COMPLEX32:
322             FIXME("Unsupported numeric leaf type %04x\n", type);
323             length += 4;
324             v->n1.n2.vt = VT_EMPTY;     /* FIXME */
325             break;
326
327         case LF_COMPLEX64:
328             FIXME("Unsupported numeric leaf type %04x\n", type);
329             length += 8;
330             v->n1.n2.vt = VT_EMPTY;     /* FIXME */
331             break;
332
333         case LF_COMPLEX80:
334             FIXME("Unsupported numeric leaf type %04x\n", type);
335             length += 10;
336             v->n1.n2.vt = VT_EMPTY;     /* FIXME */
337             break;
338
339         case LF_COMPLEX128:
340             FIXME("Unsupported numeric leaf type %04x\n", type);
341             length += 16;
342             v->n1.n2.vt = VT_EMPTY;     /* FIXME */
343             break;
344
345         case LF_VARSTRING:
346             FIXME("Unsupported numeric leaf type %04x\n", type);
347             length += 2 + *leaf;
348             v->n1.n2.vt = VT_EMPTY;     /* FIXME */
349             break;
350
351         default:
352             FIXME("Unknown numeric leaf type %04x\n", type);
353             v->n1.n2.vt = VT_EMPTY;     /* FIXME */
354             break;
355         }
356     }
357
358     return length;
359 }
360
361 static int numeric_leaf(int* value, const unsigned short int* leaf)
362 {
363     unsigned short int type = *leaf++;
364     int length = 2;
365
366     if (type < LF_NUMERIC)
367     {
368         *value = type;
369     }
370     else
371     {
372         switch (type)
373         {
374         case LF_CHAR:
375             length += 1;
376             *value = *(const char*)leaf;
377             break;
378
379         case LF_SHORT:
380             length += 2;
381             *value = *(const short*)leaf;
382             break;
383
384         case LF_USHORT:
385             length += 2;
386             *value = *leaf;
387             break;
388
389         case LF_LONG:
390             length += 4;
391             *value = *(const int*)leaf;
392             break;
393
394         case LF_ULONG:
395             length += 4;
396             *value = *(const unsigned int*)leaf;
397             break;
398
399         case LF_QUADWORD:
400         case LF_UQUADWORD:
401             FIXME("Unsupported numeric leaf type %04x\n", type);
402             length += 8;
403             *value = 0;    /* FIXME */
404             break;
405
406         case LF_REAL32:
407             FIXME("Unsupported numeric leaf type %04x\n", type);
408             length += 4;
409             *value = 0;    /* FIXME */
410             break;
411
412         case LF_REAL48:
413             FIXME("Unsupported numeric leaf type %04x\n", type);
414             length += 6;
415             *value = 0;    /* FIXME */
416             break;
417
418         case LF_REAL64:
419             FIXME("Unsupported numeric leaf type %04x\n", type);
420             length += 8;
421             *value = 0;    /* FIXME */
422             break;
423
424         case LF_REAL80:
425             FIXME("Unsupported numeric leaf type %04x\n", type);
426             length += 10;
427             *value = 0;    /* FIXME */
428             break;
429
430         case LF_REAL128:
431             FIXME("Unsupported numeric leaf type %04x\n", type);
432             length += 16;
433             *value = 0;    /* FIXME */
434             break;
435
436         case LF_COMPLEX32:
437             FIXME("Unsupported numeric leaf type %04x\n", type);
438             length += 4;
439             *value = 0;    /* FIXME */
440             break;
441
442         case LF_COMPLEX64:
443             FIXME("Unsupported numeric leaf type %04x\n", type);
444             length += 8;
445             *value = 0;    /* FIXME */
446             break;
447
448         case LF_COMPLEX80:
449             FIXME("Unsupported numeric leaf type %04x\n", type);
450             length += 10;
451             *value = 0;    /* FIXME */
452             break;
453
454         case LF_COMPLEX128:
455             FIXME("Unsupported numeric leaf type %04x\n", type);
456             length += 16;
457             *value = 0;    /* FIXME */
458             break;
459
460         case LF_VARSTRING:
461             FIXME("Unsupported numeric leaf type %04x\n", type);
462             length += 2 + *leaf;
463             *value = 0;    /* FIXME */
464             break;
465
466         default:
467             FIXME("Unknown numeric leaf type %04x\n", type);
468             *value = 0;
469             break;
470         }
471     }
472
473     return length;
474 }
475
476 /* convert a pascal string (as stored in debug information) into
477  * a C string (null terminated).
478  */
479 static const char* terminate_string(const struct p_string* p_name)
480 {
481     static char symname[256];
482
483     memcpy(symname, p_name->name, p_name->namelen);
484     symname[p_name->namelen] = '\0';
485
486     return (!*symname || strcmp(symname, "__unnamed") == 0) ? NULL : symname;
487 }
488
489 static struct symt*  codeview_get_type(unsigned int typeno, BOOL quiet)
490 {
491     struct symt*        symt = NULL;
492
493     /*
494      * Convert Codeview type numbers into something we can grok internally.
495      * Numbers < FIRST_DEFINABLE_TYPE are all fixed builtin types.
496      * Numbers from FIRST_DEFINABLE_TYPE and up are all user defined (structs, etc).
497      */
498     if (typeno < FIRST_DEFINABLE_TYPE)
499     {
500         if (typeno < MAX_BUILTIN_TYPES)
501             symt = cv_basic_types[typeno];
502     }
503     else
504     {
505         unsigned        mod_index = typeno >> 24;
506         unsigned        mod_typeno = typeno & 0x00FFFFFF;
507         struct cv_defined_module*       mod;
508
509         mod = (mod_index == 0) ? cv_current_module : &cv_zmodules[mod_index];
510
511         if (mod_index >= CV_MAX_MODULES || !mod->allowed) 
512             FIXME("Module of index %d isn't loaded yet (%x)\n", mod_index, typeno);
513         else
514         {
515             if (mod_typeno - FIRST_DEFINABLE_TYPE < mod->num_defined_types)
516                 symt = mod->defined_types[mod_typeno - FIRST_DEFINABLE_TYPE];
517         }
518     }
519     if (!quiet && !symt && typeno) FIXME("Returning NULL symt for type-id %x\n", typeno);
520     return symt;
521 }
522
523 struct codeview_type_parse
524 {
525     struct module*      module;
526     const BYTE*         table;
527     const DWORD*        offset;
528     DWORD               num;
529 };
530
531 static inline const void* codeview_jump_to_type(const struct codeview_type_parse* ctp, DWORD idx)
532 {
533     if (idx < FIRST_DEFINABLE_TYPE) return NULL;
534     idx -= FIRST_DEFINABLE_TYPE;
535     return (idx >= ctp->num) ? NULL : (ctp->table + ctp->offset[idx]); 
536 }
537
538 static int codeview_add_type(unsigned int typeno, struct symt* dt)
539 {
540     if (typeno < FIRST_DEFINABLE_TYPE)
541         FIXME("What the heck\n");
542     if (!cv_current_module)
543     {
544         FIXME("Adding %x to non allowed module\n", typeno);
545         return FALSE;
546     }
547     if ((typeno >> 24) != 0)
548         FIXME("No module index while inserting type-id assumption is wrong %x\n",
549               typeno);
550     if (typeno - FIRST_DEFINABLE_TYPE >= cv_current_module->num_defined_types)
551     {
552         if (cv_current_module->defined_types)
553         {
554             cv_current_module->num_defined_types = max( cv_current_module->num_defined_types * 2,
555                                                         typeno - FIRST_DEFINABLE_TYPE + 1 );
556             cv_current_module->defined_types = HeapReAlloc(GetProcessHeap(),
557                             HEAP_ZERO_MEMORY, cv_current_module->defined_types,
558                             cv_current_module->num_defined_types * sizeof(struct symt*));
559         }
560         else
561         {
562             cv_current_module->num_defined_types = max( 256, typeno - FIRST_DEFINABLE_TYPE + 1 );
563             cv_current_module->defined_types = HeapAlloc(GetProcessHeap(),
564                             HEAP_ZERO_MEMORY,
565                             cv_current_module->num_defined_types * sizeof(struct symt*));
566         }
567         if (cv_current_module->defined_types == NULL) return FALSE;
568     }
569     if (cv_current_module->defined_types[typeno - FIRST_DEFINABLE_TYPE])
570     {
571         if (cv_current_module->defined_types[typeno - FIRST_DEFINABLE_TYPE] != dt)
572             FIXME("Overwriting at %x\n", typeno);
573     }
574     cv_current_module->defined_types[typeno - FIRST_DEFINABLE_TYPE] = dt;
575     return TRUE;
576 }
577
578 static void codeview_clear_type_table(void)
579 {
580     int i;
581
582     for (i = 0; i < CV_MAX_MODULES; i++)
583     {
584         if (cv_zmodules[i].allowed)
585             HeapFree(GetProcessHeap(), 0, cv_zmodules[i].defined_types);
586         cv_zmodules[i].allowed = FALSE;
587         cv_zmodules[i].defined_types = NULL;
588         cv_zmodules[i].num_defined_types = 0;
589     }
590     cv_current_module = NULL;
591 }
592
593 static struct symt* codeview_parse_one_type(struct codeview_type_parse* ctp,
594                                             unsigned curr_type,
595                                             const union codeview_type* type, BOOL details);
596
597 static void* codeview_cast_symt(struct symt* symt, enum SymTagEnum tag)
598 {
599     if (symt->tag != tag)
600     {
601         FIXME("Bad tag. Expected %d, but got %d\n", tag, symt->tag);
602         return NULL;
603     }   
604     return symt;
605 }
606
607 static struct symt* codeview_fetch_type(struct codeview_type_parse* ctp,
608                                         unsigned typeno, BOOL details)
609 {
610     struct symt*                symt;
611     const union codeview_type*  p;
612
613     if (!typeno) return NULL;
614     if ((symt = codeview_get_type(typeno, TRUE))) return symt;
615
616     /* forward declaration */
617     if (!(p = codeview_jump_to_type(ctp, typeno)))
618     {
619         FIXME("Cannot locate type %x\n", typeno);
620         return NULL;
621     }
622     symt = codeview_parse_one_type(ctp, typeno, p, details);
623     if (!symt) FIXME("Couldn't load forward type %x\n", typeno);
624     return symt;
625 }
626
627 static struct symt* codeview_add_type_pointer(struct codeview_type_parse* ctp,
628                                               struct symt* existing,
629                                               unsigned int pointee_type)
630 {
631     struct symt* pointee;
632
633     if (existing)
634     {
635         existing = codeview_cast_symt(existing, SymTagPointerType);
636         return existing;
637     }
638     pointee = codeview_fetch_type(ctp, pointee_type, FALSE);
639     return &symt_new_pointer(ctp->module, pointee, sizeof(void *))->symt;
640 }
641
642 static struct symt* codeview_add_type_array(struct codeview_type_parse* ctp, 
643                                             const char* name,
644                                             unsigned int elemtype,
645                                             unsigned int indextype,
646                                             unsigned int arr_len)
647 {
648     struct symt*        elem = codeview_fetch_type(ctp, elemtype, FALSE);
649     struct symt*        index = codeview_fetch_type(ctp, indextype, FALSE);
650
651     return &symt_new_array(ctp->module, 0, -arr_len, elem, index)->symt;
652 }
653
654 static int codeview_add_type_enum_field_list(struct module* module,
655                                              struct symt_enum* symt,
656                                              const union codeview_reftype* ref_type)
657 {
658     const unsigned char*                ptr = ref_type->fieldlist.list;
659     const unsigned char*                last = (const BYTE*)ref_type + ref_type->generic.len + 2;
660     const union codeview_fieldtype*     type;
661
662     while (ptr < last)
663     {
664         if (*ptr >= 0xf0)       /* LF_PAD... */
665         {
666             ptr += *ptr & 0x0f;
667             continue;
668         }
669
670         type = (const union codeview_fieldtype*)ptr;
671
672         switch (type->generic.id)
673         {
674         case LF_ENUMERATE_V1:
675         {
676             int value, vlen = numeric_leaf(&value, &type->enumerate_v1.value);
677             const struct p_string* p_name = (const struct p_string*)((const unsigned char*)&type->enumerate_v1.value + vlen);
678
679             symt_add_enum_element(module, symt, terminate_string(p_name), value);
680             ptr += 2 + 2 + vlen + (1 + p_name->namelen);
681             break;
682         }
683         case LF_ENUMERATE_V3:
684         {
685             int value, vlen = numeric_leaf(&value, &type->enumerate_v3.value);
686             const char* name = (const char*)&type->enumerate_v3.value + vlen;
687
688             symt_add_enum_element(module, symt, name, value);
689             ptr += 2 + 2 + vlen + (1 + strlen(name));
690             break;
691         }
692
693         default:
694             FIXME("Unsupported type %04x in ENUM field list\n", type->generic.id);
695             return FALSE;
696         }
697     }
698     return TRUE;
699 }
700
701 static void codeview_add_udt_element(struct codeview_type_parse* ctp,
702                                      struct symt_udt* symt, const char* name,
703                                      int value, unsigned type)
704 {
705     struct symt*                subtype;
706     const union codeview_reftype*cv_type;
707
708     if ((cv_type = codeview_jump_to_type(ctp, type)))
709     {
710         switch (cv_type->generic.id)
711         {
712         case LF_BITFIELD_V1:
713             symt_add_udt_element(ctp->module, symt, name,
714                                  codeview_fetch_type(ctp, cv_type->bitfield_v1.type, FALSE),
715                                  (value << 3) + cv_type->bitfield_v1.bitoff,
716                                  cv_type->bitfield_v1.nbits);
717             return;
718         case LF_BITFIELD_V2:
719             symt_add_udt_element(ctp->module, symt, name,
720                                  codeview_fetch_type(ctp, cv_type->bitfield_v2.type, FALSE),
721                                  (value << 3) + cv_type->bitfield_v2.bitoff,
722                                  cv_type->bitfield_v2.nbits);
723             return;
724         }
725     }
726     subtype = codeview_fetch_type(ctp, type, FALSE);
727
728     if (subtype)
729     {
730         DWORD64 elem_size = 0;
731         symt_get_info(ctp->module, subtype, TI_GET_LENGTH, &elem_size);
732         symt_add_udt_element(ctp->module, symt, name, subtype,
733                              value << 3, (DWORD)elem_size << 3);
734     }
735 }
736
737 static int codeview_add_type_struct_field_list(struct codeview_type_parse* ctp,
738                                                struct symt_udt* symt,
739                                                unsigned fieldlistno)
740 {
741     const unsigned char*        ptr;
742     const unsigned char*        last;
743     int                         value, leaf_len;
744     const struct p_string*      p_name;
745     const char*                 c_name;
746     const union codeview_reftype*type_ref;
747     const union codeview_fieldtype* type;
748
749     if (!fieldlistno) return TRUE;
750     type_ref = codeview_jump_to_type(ctp, fieldlistno);
751     ptr = type_ref->fieldlist.list;
752     last = (const BYTE*)type_ref + type_ref->generic.len + 2;
753
754     while (ptr < last)
755     {
756         if (*ptr >= 0xf0)       /* LF_PAD... */
757         {
758             ptr += *ptr & 0x0f;
759             continue;
760         }
761
762         type = (const union codeview_fieldtype*)ptr;
763
764         switch (type->generic.id)
765         {
766         case LF_BCLASS_V1:
767             leaf_len = numeric_leaf(&value, &type->bclass_v1.offset);
768
769             /* FIXME: ignored for now */
770
771             ptr += 2 + 2 + 2 + leaf_len;
772             break;
773
774         case LF_BCLASS_V2:
775             leaf_len = numeric_leaf(&value, &type->bclass_v2.offset);
776
777             /* FIXME: ignored for now */
778
779             ptr += 2 + 2 + 4 + leaf_len;
780             break;
781
782         case LF_VBCLASS_V1:
783         case LF_IVBCLASS_V1:
784             {
785                 const unsigned short int* p_vboff;
786                 int vpoff, vplen;
787                 leaf_len = numeric_leaf(&value, &type->vbclass_v1.vbpoff);
788                 p_vboff = (const unsigned short int*)((const char*)&type->vbclass_v1.vbpoff + leaf_len);
789                 vplen = numeric_leaf(&vpoff, p_vboff);
790
791                 /* FIXME: ignored for now */
792
793                 ptr += 2 + 2 + 2 + 2 + leaf_len + vplen;
794             }
795             break;
796
797         case LF_VBCLASS_V2:
798         case LF_IVBCLASS_V2:
799             {
800                 const unsigned short int* p_vboff;
801                 int vpoff, vplen;
802                 leaf_len = numeric_leaf(&value, &type->vbclass_v2.vbpoff);
803                 p_vboff = (const unsigned short int*)((const char*)&type->vbclass_v2.vbpoff + leaf_len);
804                 vplen = numeric_leaf(&vpoff, p_vboff);
805
806                 /* FIXME: ignored for now */
807
808                 ptr += 2 + 2 + 4 + 4 + leaf_len + vplen;
809             }
810             break;
811
812         case LF_MEMBER_V1:
813             leaf_len = numeric_leaf(&value, &type->member_v1.offset);
814             p_name = (const struct p_string*)((const char*)&type->member_v1.offset + leaf_len);
815
816             codeview_add_udt_element(ctp, symt, terminate_string(p_name), value, 
817                                      type->member_v1.type);
818
819             ptr += 2 + 2 + 2 + leaf_len + (1 + p_name->namelen);
820             break;
821
822         case LF_MEMBER_V2:
823             leaf_len = numeric_leaf(&value, &type->member_v2.offset);
824             p_name = (const struct p_string*)((const unsigned char*)&type->member_v2.offset + leaf_len);
825
826             codeview_add_udt_element(ctp, symt, terminate_string(p_name), value, 
827                                      type->member_v2.type);
828
829             ptr += 2 + 2 + 4 + leaf_len + (1 + p_name->namelen);
830             break;
831
832         case LF_MEMBER_V3:
833             leaf_len = numeric_leaf(&value, &type->member_v3.offset);
834             c_name = (const char*)&type->member_v3.offset + leaf_len;
835
836             codeview_add_udt_element(ctp, symt, c_name, value, type->member_v3.type);
837
838             ptr += 2 + 2 + 4 + leaf_len + (strlen(c_name) + 1);
839             break;
840
841         case LF_STMEMBER_V1:
842             /* FIXME: ignored for now */
843             ptr += 2 + 2 + 2 + (1 + type->stmember_v1.p_name.namelen);
844             break;
845
846         case LF_STMEMBER_V2:
847             /* FIXME: ignored for now */
848             ptr += 2 + 4 + 2 + (1 + type->stmember_v2.p_name.namelen);
849             break;
850
851         case LF_STMEMBER_V3:
852             /* FIXME: ignored for now */
853             ptr += 2 + 4 + 2 + (strlen(type->stmember_v3.name) + 1);
854             break;
855
856         case LF_METHOD_V1:
857             /* FIXME: ignored for now */
858             ptr += 2 + 2 + 2 + (1 + type->method_v1.p_name.namelen);
859             break;
860
861         case LF_METHOD_V2:
862             /* FIXME: ignored for now */
863             ptr += 2 + 2 + 4 + (1 + type->method_v2.p_name.namelen);
864             break;
865
866         case LF_METHOD_V3:
867             /* FIXME: ignored for now */
868             ptr += 2 + 2 + 4 + (strlen(type->method_v3.name) + 1);
869             break;
870
871         case LF_NESTTYPE_V1:
872             /* FIXME: ignored for now */
873             ptr += 2 + 2 + (1 + type->nesttype_v1.p_name.namelen);
874             break;
875
876         case LF_NESTTYPE_V2:
877             /* FIXME: ignored for now */
878             ptr += 2 + 2 + 4 + (1 + type->nesttype_v2.p_name.namelen);
879             break;
880
881         case LF_NESTTYPE_V3:
882             /* FIXME: ignored for now */
883             ptr += 2 + 2 + 4 + (strlen(type->nesttype_v3.name) + 1);
884             break;
885
886         case LF_VFUNCTAB_V1:
887             /* FIXME: ignored for now */
888             ptr += 2 + 2;
889             break;
890
891         case LF_VFUNCTAB_V2:
892             /* FIXME: ignored for now */
893             ptr += 2 + 2 + 4;
894             break;
895
896         case LF_ONEMETHOD_V1:
897             /* FIXME: ignored for now */
898             switch ((type->onemethod_v1.attribute >> 2) & 7)
899             {
900             case 4: case 6: /* (pure) introducing virtual method */
901                 ptr += 2 + 2 + 2 + 4 + (1 + type->onemethod_virt_v1.p_name.namelen);
902                 break;
903
904             default:
905                 ptr += 2 + 2 + 2 + (1 + type->onemethod_v1.p_name.namelen);
906                 break;
907             }
908             break;
909
910         case LF_ONEMETHOD_V2:
911             /* FIXME: ignored for now */
912             switch ((type->onemethod_v2.attribute >> 2) & 7)
913             {
914             case 4: case 6: /* (pure) introducing virtual method */
915                 ptr += 2 + 2 + 4 + 4 + (1 + type->onemethod_virt_v2.p_name.namelen);
916                 break;
917
918             default:
919                 ptr += 2 + 2 + 4 + (1 + type->onemethod_v2.p_name.namelen);
920                 break;
921             }
922             break;
923
924         case LF_ONEMETHOD_V3:
925             /* FIXME: ignored for now */
926             switch ((type->onemethod_v3.attribute >> 2) & 7)
927             {
928             case 4: case 6: /* (pure) introducing virtual method */
929                 ptr += 2 + 2 + 4 + 4 + (strlen(type->onemethod_virt_v3.name) + 1);
930                 break;
931
932             default:
933                 ptr += 2 + 2 + 4 + (strlen(type->onemethod_v3.name) + 1);
934                 break;
935             }
936             break;
937
938         default:
939             FIXME("Unsupported type %04x in STRUCT field list\n", type->generic.id);
940             return FALSE;
941         }
942     }
943
944     return TRUE;
945 }
946
947 static struct symt* codeview_add_type_enum(struct codeview_type_parse* ctp,
948                                            struct symt* existing,
949                                            const char* name,
950                                            unsigned fieldlistno,
951                                            unsigned basetype)
952 {
953     struct symt_enum*   symt;
954
955     if (existing)
956     {
957         if (!(symt = codeview_cast_symt(existing, SymTagEnum))) return NULL;
958         /* should also check that all fields are the same */
959     }
960     else
961     {
962         symt = symt_new_enum(ctp->module, name,
963                              codeview_fetch_type(ctp, basetype, FALSE));
964         if (fieldlistno)
965         {
966             const union codeview_reftype* fieldlist;
967             fieldlist = codeview_jump_to_type(ctp, fieldlistno);
968             codeview_add_type_enum_field_list(ctp->module, symt, fieldlist);
969         }
970     }
971     return &symt->symt;
972 }
973
974 static struct symt* codeview_add_type_struct(struct codeview_type_parse* ctp,
975                                              struct symt* existing,
976                                              const char* name, int structlen,
977                                              enum UdtKind kind, unsigned property)
978 {
979     struct symt_udt*    symt;
980
981     /* if we don't have an existing type, try to find one with same name
982      * FIXME: what to do when several types in different CUs have same name ?
983      */
984     if (!existing)
985     {
986         void*                       ptr;
987         struct symt_ht*             type;
988         struct hash_table_iter      hti;
989
990         hash_table_iter_init(&ctp->module->ht_types, &hti, name);
991         while ((ptr = hash_table_iter_up(&hti)))
992         {
993             type = GET_ENTRY(ptr, struct symt_ht, hash_elt);
994
995             if (type->symt.tag == SymTagUDT &&
996                 type->hash_elt.name && !strcmp(type->hash_elt.name, name))
997             {
998                 existing = &type->symt;
999                 break;
1000             }
1001         }
1002     }
1003     if (existing)
1004     {
1005         if (!(symt = codeview_cast_symt(existing, SymTagUDT))) return NULL;
1006         /* should also check that all fields are the same */
1007         if (!(property & 0x80)) /* 0x80 = forward declaration */
1008         {
1009             if (!symt->size) /* likely prior forward declaration, set UDT size */
1010                 symt_set_udt_size(ctp->module, symt, structlen);
1011             else /* different UDT with same name, create a new type */
1012                 existing = NULL;
1013         }
1014     }
1015     if (!existing) symt = symt_new_udt(ctp->module, name, structlen, kind);
1016
1017     return &symt->symt;
1018 }
1019
1020 static struct symt* codeview_new_func_signature(struct codeview_type_parse* ctp, 
1021                                                 struct symt* existing,
1022                                                 enum CV_call_e call_conv)
1023 {
1024     struct symt_function_signature*     sym;
1025
1026     if (existing)
1027     {
1028         sym = codeview_cast_symt(existing, SymTagFunctionType);
1029         if (!sym) return NULL;
1030     }
1031     else
1032     {
1033         sym = symt_new_function_signature(ctp->module, NULL, call_conv);
1034     }
1035     return &sym->symt;
1036 }
1037
1038 static void codeview_add_func_signature_args(struct codeview_type_parse* ctp,
1039                                              struct symt_function_signature* sym,
1040                                              unsigned ret_type,
1041                                              unsigned args_list)
1042 {
1043     const union codeview_reftype*       reftype;
1044
1045     sym->rettype = codeview_fetch_type(ctp, ret_type, FALSE);
1046     if (args_list && (reftype = codeview_jump_to_type(ctp, args_list)))
1047     {
1048         unsigned int i;
1049         switch (reftype->generic.id)
1050         {
1051         case LF_ARGLIST_V1:
1052             for (i = 0; i < reftype->arglist_v1.num; i++)
1053                 symt_add_function_signature_parameter(ctp->module, sym,
1054                                                       codeview_fetch_type(ctp, reftype->arglist_v1.args[i], FALSE));
1055             break;
1056         case LF_ARGLIST_V2:
1057             for (i = 0; i < reftype->arglist_v2.num; i++)
1058                 symt_add_function_signature_parameter(ctp->module, sym,
1059                                                       codeview_fetch_type(ctp, reftype->arglist_v2.args[i], FALSE));
1060             break;
1061         default:
1062             FIXME("Unexpected leaf %x for signature's pmt\n", reftype->generic.id);
1063         }
1064     }
1065 }
1066
1067 static struct symt* codeview_parse_one_type(struct codeview_type_parse* ctp,
1068                                             unsigned curr_type,
1069                                             const union codeview_type* type, BOOL details)
1070 {
1071     struct symt*                symt;
1072     int                         value, leaf_len;
1073     const struct p_string*      p_name;
1074     const char*                 c_name;
1075     struct symt*                existing;
1076
1077     existing = codeview_get_type(curr_type, TRUE);
1078
1079     switch (type->generic.id)
1080     {
1081     case LF_MODIFIER_V1:
1082         /* FIXME: we don't handle modifiers,
1083          * but read previous type on the curr_type
1084          */
1085         WARN("Modifier on %x: %s%s%s%s\n",
1086              type->modifier_v1.type,
1087              type->modifier_v1.attribute & 0x01 ? "const " : "",
1088              type->modifier_v1.attribute & 0x02 ? "volatile " : "",
1089              type->modifier_v1.attribute & 0x04 ? "unaligned " : "",
1090              type->modifier_v1.attribute & ~0x07 ? "unknown " : "");
1091         symt = codeview_fetch_type(ctp, type->modifier_v1.type, details);
1092         break;
1093     case LF_MODIFIER_V2:
1094         /* FIXME: we don't handle modifiers, but readd previous type on the curr_type */
1095         WARN("Modifier on %x: %s%s%s%s\n",
1096              type->modifier_v2.type,
1097              type->modifier_v2.attribute & 0x01 ? "const " : "",
1098              type->modifier_v2.attribute & 0x02 ? "volatile " : "",
1099              type->modifier_v2.attribute & 0x04 ? "unaligned " : "",
1100              type->modifier_v2.attribute & ~0x07 ? "unknown " : "");
1101         symt = codeview_fetch_type(ctp, type->modifier_v2.type, details);
1102         break;
1103
1104     case LF_POINTER_V1:
1105         symt = codeview_add_type_pointer(ctp, existing, type->pointer_v1.datatype);
1106         break;
1107     case LF_POINTER_V2:
1108         symt = codeview_add_type_pointer(ctp, existing, type->pointer_v2.datatype);
1109         break;
1110
1111     case LF_ARRAY_V1:
1112         if (existing) symt = codeview_cast_symt(existing, SymTagArrayType);
1113         else
1114         {
1115             leaf_len = numeric_leaf(&value, &type->array_v1.arrlen);
1116             p_name = (const struct p_string*)((const unsigned char*)&type->array_v1.arrlen + leaf_len);
1117             symt = codeview_add_type_array(ctp, terminate_string(p_name),
1118                                            type->array_v1.elemtype,
1119                                            type->array_v1.idxtype, value);
1120         }
1121         break;
1122     case LF_ARRAY_V2:
1123         if (existing) symt = codeview_cast_symt(existing, SymTagArrayType);
1124         else
1125         {
1126             leaf_len = numeric_leaf(&value, &type->array_v2.arrlen);
1127             p_name = (const struct p_string*)((const unsigned char*)&type->array_v2.arrlen + leaf_len);
1128
1129             symt = codeview_add_type_array(ctp, terminate_string(p_name),
1130                                            type->array_v2.elemtype,
1131                                            type->array_v2.idxtype, value);
1132         }
1133         break;
1134     case LF_ARRAY_V3:
1135         if (existing) symt = codeview_cast_symt(existing, SymTagArrayType);
1136         else
1137         {
1138             leaf_len = numeric_leaf(&value, &type->array_v3.arrlen);
1139             c_name = (const char*)&type->array_v3.arrlen + leaf_len;
1140
1141             symt = codeview_add_type_array(ctp, c_name,
1142                                            type->array_v3.elemtype,
1143                                            type->array_v3.idxtype, value);
1144         }
1145         break;
1146
1147     case LF_STRUCTURE_V1:
1148     case LF_CLASS_V1:
1149         leaf_len = numeric_leaf(&value, &type->struct_v1.structlen);
1150         p_name = (const struct p_string*)((const unsigned char*)&type->struct_v1.structlen + leaf_len);
1151         symt = codeview_add_type_struct(ctp, existing, terminate_string(p_name), value,
1152                                         type->generic.id == LF_CLASS_V1 ? UdtClass : UdtStruct,
1153                                         type->struct_v1.property);
1154         if (details)
1155         {
1156             codeview_add_type(curr_type, symt);
1157             if (!(type->struct_v1.property & 0x80)) /* 0x80 = forward declaration */
1158                 codeview_add_type_struct_field_list(ctp, (struct symt_udt*)symt,
1159                                                     type->struct_v1.fieldlist);
1160         }
1161         break;
1162
1163     case LF_STRUCTURE_V2:
1164     case LF_CLASS_V2:
1165         leaf_len = numeric_leaf(&value, &type->struct_v2.structlen);
1166         p_name = (const struct p_string*)((const unsigned char*)&type->struct_v2.structlen + leaf_len);
1167         symt = codeview_add_type_struct(ctp, existing, terminate_string(p_name), value,
1168                                         type->generic.id == LF_CLASS_V2 ? UdtClass : UdtStruct,
1169                                         type->struct_v2.property);
1170         if (details)
1171         {
1172             codeview_add_type(curr_type, symt);
1173             if (!(type->struct_v2.property & 0x80)) /* 0x80 = forward declaration */
1174                 codeview_add_type_struct_field_list(ctp, (struct symt_udt*)symt,
1175                                                     type->struct_v2.fieldlist);
1176         }
1177         break;
1178
1179     case LF_STRUCTURE_V3:
1180     case LF_CLASS_V3:
1181         leaf_len = numeric_leaf(&value, &type->struct_v3.structlen);
1182         c_name = (const char*)&type->struct_v3.structlen + leaf_len;
1183         symt = codeview_add_type_struct(ctp, existing, c_name, value,
1184                                         type->generic.id == LF_CLASS_V3 ? UdtClass : UdtStruct,
1185                                         type->struct_v3.property);
1186         if (details)
1187         {
1188             codeview_add_type(curr_type, symt);
1189             if (!(type->struct_v3.property & 0x80)) /* 0x80 = forward declaration */
1190                 codeview_add_type_struct_field_list(ctp, (struct symt_udt*)symt,
1191                                                     type->struct_v3.fieldlist);
1192         }
1193         break;
1194
1195     case LF_UNION_V1:
1196         leaf_len = numeric_leaf(&value, &type->union_v1.un_len);
1197         p_name = (const struct p_string*)((const unsigned char*)&type->union_v1.un_len + leaf_len);
1198         symt = codeview_add_type_struct(ctp, existing, terminate_string(p_name),
1199                                         value, UdtUnion, type->union_v1.property);
1200         if (details)
1201         {
1202             codeview_add_type(curr_type, symt);
1203             codeview_add_type_struct_field_list(ctp, (struct symt_udt*)symt,
1204                                                 type->union_v1.fieldlist);
1205         }
1206         break;
1207
1208     case LF_UNION_V2:
1209         leaf_len = numeric_leaf(&value, &type->union_v2.un_len);
1210         p_name = (const struct p_string*)((const unsigned char*)&type->union_v2.un_len + leaf_len);
1211         symt = codeview_add_type_struct(ctp, existing, terminate_string(p_name),
1212                                         value, UdtUnion, type->union_v2.property);
1213         if (details)
1214         {
1215             codeview_add_type(curr_type, symt);
1216             codeview_add_type_struct_field_list(ctp, (struct symt_udt*)symt,
1217                                                 type->union_v2.fieldlist);
1218         }
1219         break;
1220
1221     case LF_UNION_V3:
1222         leaf_len = numeric_leaf(&value, &type->union_v3.un_len);
1223         c_name = (const char*)&type->union_v3.un_len + leaf_len;
1224         symt = codeview_add_type_struct(ctp, existing, c_name,
1225                                         value, UdtUnion, type->union_v3.property);
1226         if (details)
1227         {
1228             codeview_add_type(curr_type, symt);
1229             codeview_add_type_struct_field_list(ctp, (struct symt_udt*)symt,
1230                                                 type->union_v3.fieldlist);
1231         }
1232         break;
1233
1234     case LF_ENUM_V1:
1235         symt = codeview_add_type_enum(ctp, existing,
1236                                       terminate_string(&type->enumeration_v1.p_name),
1237                                       type->enumeration_v1.fieldlist,
1238                                       type->enumeration_v1.type);
1239         break;
1240
1241     case LF_ENUM_V2:
1242         symt = codeview_add_type_enum(ctp, existing,
1243                                       terminate_string(&type->enumeration_v2.p_name),
1244                                       type->enumeration_v2.fieldlist,
1245                                       type->enumeration_v2.type);
1246         break;
1247
1248     case LF_ENUM_V3:
1249         symt = codeview_add_type_enum(ctp, existing, type->enumeration_v3.name,
1250                                       type->enumeration_v3.fieldlist,
1251                                       type->enumeration_v3.type);
1252         break;
1253
1254     case LF_PROCEDURE_V1:
1255         symt = codeview_new_func_signature(ctp, existing, type->procedure_v1.call);
1256         if (details)
1257         {
1258             codeview_add_type(curr_type, symt);
1259             codeview_add_func_signature_args(ctp,
1260                                              (struct symt_function_signature*)symt,
1261                                              type->procedure_v1.rvtype,
1262                                              type->procedure_v1.arglist);
1263         }
1264         break;
1265     case LF_PROCEDURE_V2:
1266         symt = codeview_new_func_signature(ctp, existing,type->procedure_v2.call);
1267         if (details)
1268         {
1269             codeview_add_type(curr_type, symt);
1270             codeview_add_func_signature_args(ctp,
1271                                              (struct symt_function_signature*)symt,
1272                                              type->procedure_v2.rvtype,
1273                                              type->procedure_v2.arglist);
1274         }
1275         break;
1276
1277     case LF_MFUNCTION_V1:
1278         /* FIXME: for C++, this is plain wrong, but as we don't use arg types
1279          * nor class information, this would just do for now
1280          */
1281         symt = codeview_new_func_signature(ctp, existing, type->mfunction_v1.call);
1282         if (details)
1283         {
1284             codeview_add_type(curr_type, symt);
1285             codeview_add_func_signature_args(ctp,
1286                                              (struct symt_function_signature*)symt,
1287                                              type->mfunction_v1.rvtype,
1288                                              type->mfunction_v1.arglist);
1289         }
1290         break;
1291     case LF_MFUNCTION_V2:
1292         /* FIXME: for C++, this is plain wrong, but as we don't use arg types
1293          * nor class information, this would just do for now
1294          */
1295         symt = codeview_new_func_signature(ctp, existing, type->mfunction_v2.call);
1296         if (details)
1297         {
1298             codeview_add_type(curr_type, symt);
1299             codeview_add_func_signature_args(ctp,
1300                                              (struct symt_function_signature*)symt,
1301                                              type->mfunction_v2.rvtype,
1302                                              type->mfunction_v2.arglist);
1303         }
1304         break;
1305
1306     case LF_VTSHAPE_V1:
1307         /* this is an ugly hack... FIXME when we have C++ support */
1308         if (!(symt = existing))
1309         {
1310             char    buf[128];
1311             snprintf(buf, sizeof(buf), "__internal_vt_shape_%x\n", curr_type);
1312             symt = &symt_new_udt(ctp->module, buf, 0, UdtStruct)->symt;
1313         }
1314         break;
1315     default:
1316         FIXME("Unsupported type-id leaf %x\n", type->generic.id);
1317         dump(type, 2 + type->generic.len);
1318         return FALSE;
1319     }
1320     return codeview_add_type(curr_type, symt) ? symt : NULL;
1321 }
1322
1323 static int codeview_parse_type_table(struct codeview_type_parse* ctp)
1324 {
1325     unsigned int                curr_type = FIRST_DEFINABLE_TYPE;
1326     const union codeview_type*  type;
1327
1328     for (curr_type = FIRST_DEFINABLE_TYPE; curr_type < FIRST_DEFINABLE_TYPE + ctp->num; curr_type++)
1329     {
1330         type = codeview_jump_to_type(ctp, curr_type);
1331
1332         /* type records we're interested in are the ones referenced by symbols
1333          * The known ranges are (X mark the ones we want):
1334          *   X  0000-0016       for V1 types
1335          *      0200-020c       for V1 types referenced by other types
1336          *      0400-040f       for V1 types (complex lists & sets)
1337          *   X  1000-100f       for V2 types
1338          *      1200-120c       for V2 types referenced by other types
1339          *      1400-140f       for V1 types (complex lists & sets)
1340          *   X  1500-150d       for V3 types
1341          *      8000-8010       for numeric leafes
1342          */
1343         if (!(type->generic.id & 0x8600) || (type->generic.id & 0x0100))
1344             codeview_parse_one_type(ctp, curr_type, type, TRUE);
1345     }
1346
1347     return TRUE;
1348 }
1349
1350 /*========================================================================
1351  * Process CodeView line number information.
1352  */
1353 static unsigned long codeview_get_address(const struct msc_debug_info* msc_dbg,
1354                                           unsigned seg, unsigned offset);
1355
1356 static void codeview_snarf_linetab(const struct msc_debug_info* msc_dbg, const BYTE* linetab,
1357                                    int size, BOOL pascal_str)
1358 {
1359     const BYTE*                 ptr = linetab;
1360     int                         nfile, nseg;
1361     int                         i, j, k;
1362     const unsigned int*         filetab;
1363     const unsigned int*         lt_ptr;
1364     const unsigned short*       linenos;
1365     const struct startend*      start;
1366     unsigned                    source;
1367     unsigned long               addr, func_addr0;
1368     struct symt_function*       func;
1369     const struct codeview_linetab_block* ltb;
1370
1371     nfile = *(const short*)linetab;
1372     filetab = (const unsigned int*)(linetab + 2 * sizeof(short));
1373
1374     for (i = 0; i < nfile; i++)
1375     {
1376         ptr = linetab + filetab[i];
1377         nseg = *(const short*)ptr;
1378         lt_ptr = (const unsigned int*)(ptr + 2 * sizeof(short));
1379         start = (const struct startend*)(lt_ptr + nseg);
1380
1381         /*
1382          * Now snarf the filename for all of the segments for this file.
1383          */
1384         if (pascal_str)
1385             source = source_new(msc_dbg->module, NULL, terminate_string((const struct p_string*)(start + nseg)));
1386         else
1387             source = source_new(msc_dbg->module, NULL, (const char*)(start + nseg));
1388
1389         for (j = 0; j < nseg; j++)
1390         {
1391             ltb = (const struct codeview_linetab_block*)(linetab + *lt_ptr++);
1392             linenos = (const unsigned short*)&ltb->offsets[ltb->num_lines];
1393             func_addr0 = codeview_get_address(msc_dbg, ltb->seg, start[j].start);
1394             if (!func_addr0) continue;
1395             for (func = NULL, k = 0; k < ltb->num_lines; k++)
1396             {
1397                 /* now locate function (if any) */
1398                 addr = func_addr0 + ltb->offsets[k] - start[j].start;
1399                 /* unfortunately, we can have several functions in the same block, if there's no
1400                  * gap between them... find the new function if needed
1401                  */
1402                 if (!func || addr >= func->address + func->size)
1403                 {
1404                     func = (struct symt_function*)symt_find_nearest(msc_dbg->module, addr);
1405                     /* FIXME: at least labels support line numbers */
1406                     if (!func || func->symt.tag != SymTagFunction)
1407                     {
1408                         WARN("--not a func at %04x:%08x %lx tag=%d\n",
1409                              ltb->seg, ltb->offsets[k], addr, func ? func->symt.tag : -1);
1410                         func = NULL;
1411                         break;
1412                     }
1413                 }
1414                 symt_add_func_line(msc_dbg->module, func, source,
1415                                    linenos[k], addr - func->address);
1416             }
1417         }
1418     }
1419 }
1420
1421 static void codeview_snarf_linetab2(const struct msc_debug_info* msc_dbg, const BYTE* linetab, DWORD size,
1422                                     const char* strimage, DWORD strsize)
1423 {
1424     unsigned    i;
1425     DWORD_PTR       addr;
1426     const struct codeview_linetab2*     lt2;
1427     const struct codeview_linetab2*     lt2_files = NULL;
1428     const struct codeview_lt2blk_lines* lines_blk;
1429     const struct codeview_linetab2_file*fd;
1430     unsigned    source;
1431     struct symt_function* func;
1432
1433     /* locate LT2_FILES_BLOCK (if any) */
1434     lt2 = (const struct codeview_linetab2*)linetab;
1435     while ((const BYTE*)(lt2 + 1) < linetab + size)
1436     {
1437         if (lt2->header == LT2_FILES_BLOCK)
1438         {
1439             lt2_files = lt2;
1440             break;
1441         }
1442         lt2 = codeview_linetab2_next_block(lt2);
1443     }
1444     if (!lt2_files)
1445     {
1446         TRACE("No LT2_FILES_BLOCK found\n");
1447         return;
1448     }
1449
1450     lt2 = (const struct codeview_linetab2*)linetab;
1451     while ((const BYTE*)(lt2 + 1) < linetab + size)
1452     {
1453         /* FIXME: should also check that whole lines_blk fits in linetab + size */
1454         switch (lt2->header)
1455         {
1456         case LT2_LINES_BLOCK:
1457             /* Skip blocks that are too small - Intel C Compiler generates these. */
1458             if (lt2->size_of_block < sizeof (struct codeview_lt2blk_lines)) break;
1459             lines_blk = (const struct codeview_lt2blk_lines*)lt2;
1460             /* FIXME: should check that file_offset is within the LT2_FILES_BLOCK we've seen */
1461             addr = codeview_get_address(msc_dbg, lines_blk->seg, lines_blk->start);
1462             TRACE("block from %04x:%08x #%x (%x lines)\n",
1463                   lines_blk->seg, lines_blk->start, lines_blk->size, lines_blk->nlines);
1464             fd = (const struct codeview_linetab2_file*)((const char*)lt2_files + 8 + lines_blk->file_offset);
1465             /* FIXME: should check that string is within strimage + strsize */
1466             source = source_new(msc_dbg->module, NULL, strimage + fd->offset);
1467             func = (struct symt_function*)symt_find_nearest(msc_dbg->module, addr);
1468             /* FIXME: at least labels support line numbers */
1469             if (!func || func->symt.tag != SymTagFunction)
1470             {
1471                 WARN("--not a func at %04x:%08x %lx tag=%d\n",
1472                      lines_blk->seg, lines_blk->start, addr, func ? func->symt.tag : -1);
1473                 break;
1474             }
1475             for (i = 0; i < lines_blk->nlines; i++)
1476             {
1477                 symt_add_func_line(msc_dbg->module, func, source,
1478                                    lines_blk->l[i].lineno ^ 0x80000000,
1479                                    lines_blk->l[i].offset);
1480             }
1481             break;
1482         case LT2_FILES_BLOCK: /* skip */
1483             break;
1484         default:
1485             TRACE("Block end %x\n", lt2->header);
1486             lt2 = (const struct codeview_linetab2*)((const char*)linetab + size);
1487             continue;
1488         }
1489         lt2 = codeview_linetab2_next_block(lt2);
1490     }
1491 }
1492
1493 /*========================================================================
1494  * Process CodeView symbol information.
1495  */
1496
1497 static unsigned int codeview_map_offset(const struct msc_debug_info* msc_dbg,
1498                                         unsigned int offset)
1499 {
1500     int                 nomap = msc_dbg->nomap;
1501     const OMAP_DATA*    omapp = msc_dbg->omapp;
1502     int                 i;
1503
1504     if (!nomap || !omapp) return offset;
1505
1506     /* FIXME: use binary search */
1507     for (i = 0; i < nomap - 1; i++)
1508         if (omapp[i].from <= offset && omapp[i+1].from > offset)
1509             return !omapp[i].to ? 0 : omapp[i].to + (offset - omapp[i].from);
1510
1511     return 0;
1512 }
1513
1514 static unsigned long codeview_get_address(const struct msc_debug_info* msc_dbg,
1515                                           unsigned seg, unsigned offset)
1516 {
1517     int                         nsect = msc_dbg->nsect;
1518     const IMAGE_SECTION_HEADER* sectp = msc_dbg->sectp;
1519
1520     if (!seg || seg > nsect) return 0;
1521     return msc_dbg->module->module.BaseOfImage +
1522         codeview_map_offset(msc_dbg, sectp[seg-1].VirtualAddress + offset);
1523 }
1524
1525 static inline void codeview_add_variable(const struct msc_debug_info* msc_dbg,
1526                                          struct symt_compiland* compiland,
1527                                          const char* name,
1528                                          unsigned segment, unsigned offset,
1529                                          unsigned symtype, BOOL is_local, BOOL in_tls, BOOL force)
1530 {
1531     if (name && *name)
1532     {
1533         struct location loc;
1534
1535         loc.kind = in_tls ? loc_tlsrel : loc_absolute;
1536         loc.reg = 0;
1537         loc.offset = in_tls ? offset : codeview_get_address(msc_dbg, segment, offset);
1538         if (force || in_tls || !symt_find_nearest(msc_dbg->module, loc.offset))
1539         {
1540             symt_new_global_variable(msc_dbg->module, compiland,
1541                                      name, is_local, loc, 0,
1542                                      codeview_get_type(symtype, FALSE));
1543         }
1544     }
1545 }
1546
1547 static int codeview_snarf(const struct msc_debug_info* msc_dbg, const BYTE* root, 
1548                           int offset, int size, BOOL do_globals)
1549 {
1550     struct symt_function*               curr_func = NULL;
1551     int                                 i, length;
1552     struct symt_block*                  block = NULL;
1553     struct symt*                        symt;
1554     const char*                         name;
1555     struct symt_compiland*              compiland = NULL;
1556     struct location                     loc;
1557
1558     /*
1559      * Loop over the different types of records and whenever we
1560      * find something we are interested in, record it and move on.
1561      */
1562     for (i = offset; i < size; i += length)
1563     {
1564         const union codeview_symbol* sym = (const union codeview_symbol*)(root + i);
1565         length = sym->generic.len + 2;
1566         if (i + length > size) break;
1567         if (!sym->generic.id || length < 4) break;
1568         if (length & 3) FIXME("unpadded len %u\n", length);
1569
1570         switch (sym->generic.id)
1571         {
1572         /*
1573          * Global and local data symbols.  We don't associate these
1574          * with any given source file.
1575          */
1576         case S_GDATA_V1:
1577         case S_LDATA_V1:
1578             if (do_globals)
1579                 codeview_add_variable(msc_dbg, compiland, terminate_string(&sym->data_v1.p_name),
1580                                       sym->data_v1.segment, sym->data_v1.offset, sym->data_v1.symtype,
1581                                       sym->generic.id == S_LDATA_V1, FALSE, TRUE);
1582             break;
1583         case S_GDATA_V2:
1584         case S_LDATA_V2:
1585             if (do_globals)
1586                 codeview_add_variable(msc_dbg, compiland, terminate_string(&sym->data_v2.p_name),
1587                                       sym->data_v2.segment, sym->data_v2.offset, sym->data_v2.symtype,
1588                                       sym->generic.id == S_LDATA_V2, FALSE, TRUE);
1589             break;
1590         case S_GDATA_V3:
1591         case S_LDATA_V3:
1592             if (do_globals)
1593                 codeview_add_variable(msc_dbg, compiland, sym->data_v3.name,
1594                                       sym->data_v3.segment, sym->data_v3.offset, sym->data_v3.symtype,
1595                                       sym->generic.id == S_LDATA_V3, FALSE, TRUE);
1596             break;
1597
1598         /* variables with thread storage */
1599         case S_GTHREAD_V1:
1600         case S_LTHREAD_V1:
1601             if (do_globals)
1602                 codeview_add_variable(msc_dbg, compiland, terminate_string(&sym->thread_v1.p_name),
1603                                       sym->thread_v1.segment, sym->thread_v1.offset, sym->thread_v1.symtype,
1604                                       sym->generic.id == S_LTHREAD_V1, TRUE, TRUE);
1605             break;
1606         case S_GTHREAD_V2:
1607         case S_LTHREAD_V2:
1608             if (do_globals)
1609                 codeview_add_variable(msc_dbg, compiland, terminate_string(&sym->thread_v2.p_name),
1610                                       sym->thread_v2.segment, sym->thread_v2.offset, sym->thread_v2.symtype,
1611                                       sym->generic.id == S_LTHREAD_V2, TRUE, TRUE);
1612             break;
1613         case S_GTHREAD_V3:
1614         case S_LTHREAD_V3:
1615             if (do_globals)
1616                 codeview_add_variable(msc_dbg, compiland, sym->thread_v3.name,
1617                                       sym->thread_v3.segment, sym->thread_v3.offset, sym->thread_v3.symtype,
1618                                       sym->generic.id == S_LTHREAD_V3, TRUE, TRUE);
1619             break;
1620
1621         /* Public symbols */
1622         case S_PUB_V1:
1623         case S_PUB_V2:
1624         case S_PUB_V3:
1625         case S_PUB_FUNC1_V3:
1626         case S_PUB_FUNC2_V3:
1627             /* will be handled later on in codeview_snarf_public */
1628             break;
1629
1630         /*
1631          * Sort of like a global function, but it just points
1632          * to a thunk, which is a stupid name for what amounts to
1633          * a PLT slot in the normal jargon that everyone else uses.
1634          */
1635         case S_THUNK_V1:
1636             symt_new_thunk(msc_dbg->module, compiland,
1637                            terminate_string(&sym->thunk_v1.p_name), sym->thunk_v1.thtype,
1638                            codeview_get_address(msc_dbg, sym->thunk_v1.segment, sym->thunk_v1.offset),
1639                            sym->thunk_v1.thunk_len);
1640             break;
1641         case S_THUNK_V3:
1642             symt_new_thunk(msc_dbg->module, compiland,
1643                            sym->thunk_v3.name, sym->thunk_v3.thtype,
1644                            codeview_get_address(msc_dbg, sym->thunk_v3.segment, sym->thunk_v3.offset),
1645                            sym->thunk_v3.thunk_len);
1646             break;
1647
1648         /*
1649          * Global and static functions.
1650          */
1651         case S_GPROC_V1:
1652         case S_LPROC_V1:
1653             if (curr_func) FIXME("nested function\n");
1654             curr_func = symt_new_function(msc_dbg->module, compiland,
1655                                           terminate_string(&sym->proc_v1.p_name),
1656                                           codeview_get_address(msc_dbg, sym->proc_v1.segment, sym->proc_v1.offset),
1657                                           sym->proc_v1.proc_len,
1658                                           codeview_get_type(sym->proc_v1.proctype, FALSE));
1659             loc.kind = loc_absolute;
1660             loc.offset = sym->proc_v1.debug_start;
1661             symt_add_function_point(msc_dbg->module, curr_func, SymTagFuncDebugStart, &loc, NULL);
1662             loc.offset = sym->proc_v1.debug_end;
1663             symt_add_function_point(msc_dbg->module, curr_func, SymTagFuncDebugEnd, &loc, NULL);
1664             break;
1665         case S_GPROC_V2:
1666         case S_LPROC_V2:
1667             if (curr_func) FIXME("nested function\n");
1668             curr_func = symt_new_function(msc_dbg->module, compiland,
1669                                           terminate_string(&sym->proc_v2.p_name),
1670                                           codeview_get_address(msc_dbg, sym->proc_v2.segment, sym->proc_v2.offset),
1671                                           sym->proc_v2.proc_len,
1672                                           codeview_get_type(sym->proc_v2.proctype, FALSE));
1673             loc.kind = loc_absolute;
1674             loc.offset = sym->proc_v2.debug_start;
1675             symt_add_function_point(msc_dbg->module, curr_func, SymTagFuncDebugStart, &loc, NULL);
1676             loc.offset = sym->proc_v2.debug_end;
1677             symt_add_function_point(msc_dbg->module, curr_func, SymTagFuncDebugEnd, &loc, NULL);
1678             break;
1679         case S_GPROC_V3:
1680         case S_LPROC_V3:
1681             if (curr_func) FIXME("nested function\n");
1682             curr_func = symt_new_function(msc_dbg->module, compiland,
1683                                           sym->proc_v3.name,
1684                                           codeview_get_address(msc_dbg, sym->proc_v3.segment, sym->proc_v3.offset),
1685                                           sym->proc_v3.proc_len,
1686                                           codeview_get_type(sym->proc_v3.proctype, FALSE));
1687             loc.kind = loc_absolute;
1688             loc.offset = sym->proc_v3.debug_start;
1689             symt_add_function_point(msc_dbg->module, curr_func, SymTagFuncDebugStart, &loc, NULL);
1690             loc.offset = sym->proc_v3.debug_end;
1691             symt_add_function_point(msc_dbg->module, curr_func, SymTagFuncDebugEnd, &loc, NULL);
1692             break;
1693         /*
1694          * Function parameters and stack variables.
1695          */
1696         case S_BPREL_V1:
1697             loc.kind = loc_regrel;
1698             /* Yes, it's i386 dependent, but that's the symbol purpose. S_REGREL is used on other CPUs */
1699             loc.reg = CV_REG_EBP;
1700             loc.offset = sym->stack_v1.offset;
1701             symt_add_func_local(msc_dbg->module, curr_func, 
1702                                 sym->stack_v1.offset > 0 ? DataIsParam : DataIsLocal, 
1703                                 &loc, block,
1704                                 codeview_get_type(sym->stack_v1.symtype, FALSE),
1705                                 terminate_string(&sym->stack_v1.p_name));
1706             break;
1707         case S_BPREL_V2:
1708             loc.kind = loc_regrel;
1709             /* Yes, it's i386 dependent, but that's the symbol purpose. S_REGREL is used on other CPUs */
1710             loc.reg = CV_REG_EBP;
1711             loc.offset = sym->stack_v2.offset;
1712             symt_add_func_local(msc_dbg->module, curr_func, 
1713                                 sym->stack_v2.offset > 0 ? DataIsParam : DataIsLocal, 
1714                                 &loc, block,
1715                                 codeview_get_type(sym->stack_v2.symtype, FALSE),
1716                                 terminate_string(&sym->stack_v2.p_name));
1717             break;
1718         case S_BPREL_V3:
1719             loc.kind = loc_regrel;
1720             /* Yes, it's i386 dependent, but that's the symbol purpose. S_REGREL is used on other CPUs */
1721             loc.reg = CV_REG_EBP;
1722             loc.offset = sym->stack_v3.offset;
1723             symt_add_func_local(msc_dbg->module, curr_func, 
1724                                 sym->stack_v3.offset > 0 ? DataIsParam : DataIsLocal, 
1725                                 &loc, block,
1726                                 codeview_get_type(sym->stack_v3.symtype, FALSE),
1727                                 sym->stack_v3.name);
1728             break;
1729         case S_REGREL_V3:
1730             loc.kind = loc_regrel;
1731             loc.reg = sym->regrel_v3.reg;
1732             loc.offset = sym->regrel_v3.offset;
1733             symt_add_func_local(msc_dbg->module, curr_func,
1734                                 /* FIXME this is wrong !!! */
1735                                 sym->regrel_v3.offset > 0 ? DataIsParam : DataIsLocal,
1736                                 &loc, block,
1737                                 codeview_get_type(sym->regrel_v3.symtype, FALSE),
1738                                 sym->regrel_v3.name);
1739             break;
1740
1741         case S_REGISTER_V1:
1742             loc.kind = loc_register;
1743             loc.reg = sym->register_v1.reg;
1744             loc.offset = 0;
1745             symt_add_func_local(msc_dbg->module, curr_func, 
1746                                 DataIsLocal, &loc,
1747                                 block, codeview_get_type(sym->register_v1.type, FALSE),
1748                                 terminate_string(&sym->register_v1.p_name));
1749             break;
1750         case S_REGISTER_V2:
1751             loc.kind = loc_register;
1752             loc.reg = sym->register_v2.reg;
1753             loc.offset = 0;
1754             symt_add_func_local(msc_dbg->module, curr_func, 
1755                                 DataIsLocal, &loc,
1756                                 block, codeview_get_type(sym->register_v2.type, FALSE),
1757                                 terminate_string(&sym->register_v2.p_name));
1758             break;
1759         case S_REGISTER_V3:
1760             loc.kind = loc_register;
1761             loc.reg = sym->register_v3.reg;
1762             loc.offset = 0;
1763             symt_add_func_local(msc_dbg->module, curr_func,
1764                                 DataIsLocal, &loc,
1765                                 block, codeview_get_type(sym->register_v3.type, FALSE),
1766                                 sym->register_v3.name);
1767             break;
1768
1769         case S_BLOCK_V1:
1770             block = symt_open_func_block(msc_dbg->module, curr_func, block, 
1771                                          codeview_get_address(msc_dbg, sym->block_v1.segment, sym->block_v1.offset),
1772                                          sym->block_v1.length);
1773             break;
1774         case S_BLOCK_V3:
1775             block = symt_open_func_block(msc_dbg->module, curr_func, block, 
1776                                          codeview_get_address(msc_dbg, sym->block_v3.segment, sym->block_v3.offset),
1777                                          sym->block_v3.length);
1778             break;
1779
1780         case S_END_V1:
1781             if (block)
1782             {
1783                 block = symt_close_func_block(msc_dbg->module, curr_func, block, 0);
1784             }
1785             else if (curr_func)
1786             {
1787                 symt_normalize_function(msc_dbg->module, curr_func);
1788                 curr_func = NULL;
1789             }
1790             break;
1791
1792         case S_COMPILAND_V1:
1793             TRACE("S-Compiland-V1 %x %s\n",
1794                   sym->compiland_v1.unknown, terminate_string(&sym->compiland_v1.p_name));
1795             break;
1796
1797         case S_COMPILAND_V2:
1798             TRACE("S-Compiland-V2 %s\n", terminate_string(&sym->compiland_v2.p_name));
1799             if (TRACE_ON(dbghelp_msc))
1800             {
1801                 const char* ptr1 = sym->compiland_v2.p_name.name + sym->compiland_v2.p_name.namelen;
1802                 const char* ptr2;
1803                 while (*ptr1)
1804                 {
1805                     ptr2 = ptr1 + strlen(ptr1) + 1;
1806                     TRACE("\t%s => %s\n", ptr1, debugstr_a(ptr2));
1807                     ptr1 = ptr2 + strlen(ptr2) + 1;
1808                 }
1809             }
1810             break;
1811         case S_COMPILAND_V3:
1812             TRACE("S-Compiland-V3 %s\n", sym->compiland_v3.name);
1813             if (TRACE_ON(dbghelp_msc))
1814             {
1815                 const char* ptr1 = sym->compiland_v3.name + strlen(sym->compiland_v3.name);
1816                 const char* ptr2;
1817                 while (*ptr1)
1818                 {
1819                     ptr2 = ptr1 + strlen(ptr1) + 1;
1820                     TRACE("\t%s => %s\n", ptr1, debugstr_a(ptr2));
1821                     ptr1 = ptr2 + strlen(ptr2) + 1;
1822                 }
1823             }
1824             break;
1825
1826         case S_OBJNAME_V1:
1827             TRACE("S-ObjName %s\n", terminate_string(&sym->objname_v1.p_name));
1828             compiland = symt_new_compiland(msc_dbg->module, 0 /* FIXME */,
1829                                            source_new(msc_dbg->module, NULL,
1830                                                       terminate_string(&sym->objname_v1.p_name)));
1831             break;
1832
1833         case S_LABEL_V1:
1834             if (curr_func)
1835             {
1836                 loc.kind = loc_absolute;
1837                 loc.offset = codeview_get_address(msc_dbg, sym->label_v1.segment, sym->label_v1.offset) - curr_func->address;
1838                 symt_add_function_point(msc_dbg->module, curr_func, SymTagLabel, &loc,
1839                                         terminate_string(&sym->label_v1.p_name));
1840             }
1841             else symt_new_label(msc_dbg->module, compiland,
1842                                 terminate_string(&sym->label_v1.p_name),
1843                                 codeview_get_address(msc_dbg, sym->label_v1.segment, sym->label_v1.offset));
1844             break;
1845         case S_LABEL_V3:
1846             if (curr_func)
1847             {
1848                 loc.kind = loc_absolute;
1849                 loc.offset = codeview_get_address(msc_dbg, sym->label_v3.segment, sym->label_v3.offset) - curr_func->address;
1850                 symt_add_function_point(msc_dbg->module, curr_func, SymTagLabel, 
1851                                         &loc, sym->label_v3.name);
1852             }
1853             else symt_new_label(msc_dbg->module, compiland, sym->label_v3.name,
1854                                 codeview_get_address(msc_dbg, sym->label_v3.segment, sym->label_v3.offset));
1855             break;
1856
1857         case S_CONSTANT_V1:
1858             {
1859                 int                     vlen;
1860                 const struct p_string*  name;
1861                 struct symt*            se;
1862                 VARIANT                 v;
1863
1864                 vlen = leaf_as_variant(&v, &sym->constant_v1.cvalue);
1865                 name = (const struct p_string*)((const char*)&sym->constant_v1.cvalue + vlen);
1866                 se = codeview_get_type(sym->constant_v1.type, FALSE);
1867
1868                 TRACE("S-Constant-V1 %u %s %x\n",
1869                       v.n1.n2.n3.intVal, terminate_string(name), sym->constant_v1.type);
1870                 symt_new_constant(msc_dbg->module, compiland, terminate_string(name),
1871                                   se, &v);
1872             }
1873             break;
1874         case S_CONSTANT_V2:
1875             {
1876                 int                     vlen;
1877                 const struct p_string*  name;
1878                 struct symt*            se;
1879                 VARIANT                 v;
1880
1881                 vlen = leaf_as_variant(&v, &sym->constant_v2.cvalue);
1882                 name = (const struct p_string*)((const char*)&sym->constant_v2.cvalue + vlen);
1883                 se = codeview_get_type(sym->constant_v2.type, FALSE);
1884
1885                 TRACE("S-Constant-V2 %u %s %x\n",
1886                       v.n1.n2.n3.intVal, terminate_string(name), sym->constant_v2.type);
1887                 symt_new_constant(msc_dbg->module, compiland, terminate_string(name),
1888                                   se, &v);
1889             }
1890             break;
1891         case S_CONSTANT_V3:
1892             {
1893                 int                     vlen;
1894                 const char*             name;
1895                 struct symt*            se;
1896                 VARIANT                 v;
1897
1898                 vlen = leaf_as_variant(&v, &sym->constant_v3.cvalue);
1899                 name = (const char*)&sym->constant_v3.cvalue + vlen;
1900                 se = codeview_get_type(sym->constant_v3.type, FALSE);
1901
1902                 TRACE("S-Constant-V3 %u %s %x\n",
1903                       v.n1.n2.n3.intVal, name, sym->constant_v3.type);
1904                 /* FIXME: we should add this as a constant value */
1905                 symt_new_constant(msc_dbg->module, compiland, name, se, &v);
1906             }
1907             break;
1908
1909         case S_UDT_V1:
1910             if (sym->udt_v1.type)
1911             {
1912                 if ((symt = codeview_get_type(sym->udt_v1.type, FALSE)))
1913                     symt_new_typedef(msc_dbg->module, symt, 
1914                                      terminate_string(&sym->udt_v1.p_name));
1915                 else
1916                     FIXME("S-Udt %s: couldn't find type 0x%x\n", 
1917                           terminate_string(&sym->udt_v1.p_name), sym->udt_v1.type);
1918             }
1919             break;
1920         case S_UDT_V2:
1921             if (sym->udt_v2.type)
1922             {
1923                 if ((symt = codeview_get_type(sym->udt_v2.type, FALSE)))
1924                     symt_new_typedef(msc_dbg->module, symt, 
1925                                      terminate_string(&sym->udt_v2.p_name));
1926                 else
1927                     FIXME("S-Udt %s: couldn't find type 0x%x\n", 
1928                           terminate_string(&sym->udt_v2.p_name), sym->udt_v2.type);
1929             }
1930             break;
1931         case S_UDT_V3:
1932             if (sym->udt_v3.type)
1933             {
1934                 if ((symt = codeview_get_type(sym->udt_v3.type, FALSE)))
1935                     symt_new_typedef(msc_dbg->module, symt, sym->udt_v3.name);
1936                 else
1937                     FIXME("S-Udt %s: couldn't find type 0x%x\n", 
1938                           sym->udt_v3.name, sym->udt_v3.type);
1939             }
1940             break;
1941
1942          /*
1943          * These are special, in that they are always followed by an
1944          * additional length-prefixed string which is *not* included
1945          * into the symbol length count.  We need to skip it.
1946          */
1947         case S_PROCREF_V1:
1948         case S_DATAREF_V1:
1949         case S_LPROCREF_V1:
1950             name = (const char*)sym + length;
1951             length += (*name + 1 + 3) & ~3;
1952             break;
1953
1954         case S_MSTOOL_V3: /* just to silence a few warnings */
1955         case S_MSTOOLINFO_V3:
1956         case S_MSTOOLENV_V3:
1957             break;
1958
1959         case S_SSEARCH_V1:
1960             TRACE("Start search: seg=0x%x at offset 0x%08x\n",
1961                   sym->ssearch_v1.segment, sym->ssearch_v1.offset);
1962             break;
1963
1964         case S_ALIGN_V1:
1965             TRACE("S-Align V1\n");
1966             break;
1967
1968         /* the symbols we can safely ignore for now */
1969         case 0x112c:
1970         case S_FRAMEINFO_V2:
1971         case S_SECUCOOKIE_V3:
1972         case S_SECTINFO_V3:
1973         case S_SUBSECTINFO_V3:
1974         case S_ENTRYPOINT_V3:
1975         case 0x1139:
1976             TRACE("Unsupported symbol id %x\n", sym->generic.id);
1977             break;
1978
1979         default:
1980             FIXME("Unsupported symbol id %x\n", sym->generic.id);
1981             dump(sym, 2 + sym->generic.len);
1982             break;
1983         }
1984     }
1985
1986     if (curr_func) symt_normalize_function(msc_dbg->module, curr_func);
1987
1988     return TRUE;
1989 }
1990
1991 static int codeview_snarf_public(const struct msc_debug_info* msc_dbg, const BYTE* root,
1992                                  int offset, int size)
1993
1994 {
1995     int                                 i, length;
1996     struct symt_compiland*              compiland = NULL;
1997
1998     /*
1999      * Loop over the different types of records and whenever we
2000      * find something we are interested in, record it and move on.
2001      */
2002     for (i = offset; i < size; i += length)
2003     {
2004         const union codeview_symbol* sym = (const union codeview_symbol*)(root + i);
2005         length = sym->generic.len + 2;
2006         if (i + length > size) break;
2007         if (!sym->generic.id || length < 4) break;
2008         if (length & 3) FIXME("unpadded len %u\n", length);
2009
2010         switch (sym->generic.id)
2011         {
2012         case S_PUB_V1: /* FIXME is this really a 'data_v1' structure ?? */
2013             if (!(dbghelp_options & SYMOPT_NO_PUBLICS))
2014             {
2015                 symt_new_public(msc_dbg->module, compiland,
2016                                 terminate_string(&sym->data_v1.p_name),
2017                                 codeview_get_address(msc_dbg, sym->data_v1.segment, sym->data_v1.offset), 1);
2018             }
2019             break;
2020         case S_PUB_V2: /* FIXME is this really a 'data_v2' structure ?? */
2021             if (!(dbghelp_options & SYMOPT_NO_PUBLICS))
2022             {
2023                 symt_new_public(msc_dbg->module, compiland,
2024                                 terminate_string(&sym->data_v2.p_name),
2025                                 codeview_get_address(msc_dbg, sym->data_v2.segment, sym->data_v2.offset), 1);
2026             }
2027             break;
2028
2029         case S_PUB_V3:
2030             if (!(dbghelp_options & SYMOPT_NO_PUBLICS))
2031             {
2032                 symt_new_public(msc_dbg->module, compiland,
2033                                 sym->data_v3.name,
2034                                 codeview_get_address(msc_dbg, sym->data_v3.segment, sym->data_v3.offset), 1);
2035             }
2036             break;
2037         case S_PUB_FUNC1_V3:
2038         case S_PUB_FUNC2_V3: /* using a data_v3 isn't what we'd expect */
2039 #if 0
2040             /* FIXME: this is plain wrong (from a simple test) */
2041             if (!(dbghelp_options & SYMOPT_NO_PUBLICS))
2042             {
2043                 symt_new_public(msc_dbg->module, compiland,
2044                                 sym->data_v3.name,
2045                                 codeview_get_address(msc_dbg, sym->data_v3.segment, sym->data_v3.offset), 1);
2046             }
2047 #endif
2048             break;
2049         /*
2050          * Global and local data symbols.  We don't associate these
2051          * with any given source file.
2052          */
2053         case S_GDATA_V1:
2054         case S_LDATA_V1:
2055             codeview_add_variable(msc_dbg, compiland, terminate_string(&sym->data_v1.p_name),
2056                                   sym->data_v1.segment, sym->data_v1.offset, sym->data_v1.symtype,
2057                                   sym->generic.id == S_LDATA_V1, FALSE, FALSE);
2058             break;
2059         case S_GDATA_V2:
2060         case S_LDATA_V2:
2061             codeview_add_variable(msc_dbg, compiland, terminate_string(&sym->data_v2.p_name),
2062                                   sym->data_v2.segment, sym->data_v2.offset, sym->data_v2.symtype,
2063                                   sym->generic.id == S_LDATA_V2, FALSE, FALSE);
2064             break;
2065         case S_GDATA_V3:
2066         case S_LDATA_V3:
2067             codeview_add_variable(msc_dbg, compiland, sym->data_v3.name,
2068                                   sym->data_v3.segment, sym->data_v3.offset, sym->data_v3.symtype,
2069                                   sym->generic.id == S_LDATA_V3, FALSE, FALSE);
2070             break;
2071
2072         /* variables with thread storage */
2073         case S_GTHREAD_V1:
2074         case S_LTHREAD_V1:
2075             codeview_add_variable(msc_dbg, compiland, terminate_string(&sym->thread_v1.p_name),
2076                                   sym->thread_v1.segment, sym->thread_v1.offset, sym->thread_v1.symtype,
2077                                   sym->generic.id == S_LTHREAD_V1, TRUE, FALSE);
2078             break;
2079         case S_GTHREAD_V2:
2080         case S_LTHREAD_V2:
2081             codeview_add_variable(msc_dbg, compiland, terminate_string(&sym->thread_v2.p_name),
2082                                   sym->thread_v2.segment, sym->thread_v2.offset, sym->thread_v2.symtype,
2083                                   sym->generic.id == S_LTHREAD_V2, TRUE, FALSE);
2084             break;
2085         case S_GTHREAD_V3:
2086         case S_LTHREAD_V3:
2087             codeview_add_variable(msc_dbg, compiland, sym->thread_v3.name,
2088                                   sym->thread_v3.segment, sym->thread_v3.offset, sym->thread_v3.symtype,
2089                                   sym->generic.id == S_LTHREAD_V3, TRUE, FALSE);
2090             break;
2091
2092         /*
2093          * These are special, in that they are always followed by an
2094          * additional length-prefixed string which is *not* included
2095          * into the symbol length count.  We need to skip it.
2096          */
2097         case S_PROCREF_V1:
2098         case S_DATAREF_V1:
2099         case S_LPROCREF_V1:
2100             length += (((const char*)sym)[length] + 1 + 3) & ~3;
2101             break;
2102         }
2103         msc_dbg->module->sortlist_valid = TRUE;
2104     }
2105     msc_dbg->module->sortlist_valid = FALSE;
2106     return TRUE;
2107 }
2108
2109 /*========================================================================
2110  * Process PDB file.
2111  */
2112
2113 static void* pdb_jg_read(const struct PDB_JG_HEADER* pdb, const WORD* block_list,
2114                          int size)
2115 {
2116     int                         i, num_blocks;
2117     BYTE*                       buffer;
2118
2119     if (!size) return NULL;
2120
2121     num_blocks = (size + pdb->block_size - 1) / pdb->block_size;
2122     buffer = HeapAlloc(GetProcessHeap(), 0, num_blocks * pdb->block_size);
2123
2124     for (i = 0; i < num_blocks; i++)
2125         memcpy(buffer + i * pdb->block_size,
2126                (const char*)pdb + block_list[i] * pdb->block_size, pdb->block_size);
2127
2128     return buffer;
2129 }
2130
2131 static void* pdb_ds_read(const struct PDB_DS_HEADER* pdb, const DWORD* block_list,
2132                          int size)
2133 {
2134     int                         i, num_blocks;
2135     BYTE*                       buffer;
2136
2137     if (!size) return NULL;
2138
2139     num_blocks = (size + pdb->block_size - 1) / pdb->block_size;
2140     buffer = HeapAlloc(GetProcessHeap(), 0, num_blocks * pdb->block_size);
2141
2142     for (i = 0; i < num_blocks; i++)
2143         memcpy(buffer + i * pdb->block_size,
2144                (const char*)pdb + block_list[i] * pdb->block_size, pdb->block_size);
2145
2146     return buffer;
2147 }
2148
2149 static void* pdb_read_jg_file(const struct PDB_JG_HEADER* pdb,
2150                               const struct PDB_JG_TOC* toc, DWORD file_nr)
2151 {
2152     const WORD*                 block_list;
2153     DWORD                       i;
2154
2155     if (!toc || file_nr >= toc->num_files) return NULL;
2156
2157     block_list = (const WORD*) &toc->file[toc->num_files];
2158     for (i = 0; i < file_nr; i++)
2159         block_list += (toc->file[i].size + pdb->block_size - 1) / pdb->block_size;
2160
2161     return pdb_jg_read(pdb, block_list, toc->file[file_nr].size);
2162 }
2163
2164 static void* pdb_read_ds_file(const struct PDB_DS_HEADER* pdb,
2165                               const struct PDB_DS_TOC* toc, DWORD file_nr)
2166 {
2167     const DWORD*                block_list;
2168     DWORD                       i;
2169
2170     if (!toc || file_nr >= toc->num_files) return NULL;
2171     if (toc->file_size[file_nr] == 0 || toc->file_size[file_nr] == 0xFFFFFFFF) return NULL;
2172
2173     block_list = &toc->file_size[toc->num_files];
2174     for (i = 0; i < file_nr; i++)
2175         block_list += (toc->file_size[i] + pdb->block_size - 1) / pdb->block_size;
2176
2177     return pdb_ds_read(pdb, block_list, toc->file_size[file_nr]);
2178 }
2179
2180 static void* pdb_read_file(const struct pdb_file_info* pdb_file,
2181                            DWORD file_nr)
2182 {
2183     switch (pdb_file->kind)
2184     {
2185     case PDB_JG:
2186         return pdb_read_jg_file((const struct PDB_JG_HEADER*)pdb_file->image,
2187                                 pdb_file->u.jg.toc, file_nr);
2188     case PDB_DS:
2189         return pdb_read_ds_file((const struct PDB_DS_HEADER*)pdb_file->image,
2190                                 pdb_file->u.ds.toc, file_nr);
2191     }
2192     return NULL;
2193 }
2194
2195 static unsigned pdb_get_file_size(const struct pdb_file_info* pdb_file, DWORD file_nr)
2196 {
2197     switch (pdb_file->kind)
2198     {
2199     case PDB_JG: return pdb_file->u.jg.toc->file[file_nr].size;
2200     case PDB_DS: return pdb_file->u.ds.toc->file_size[file_nr];
2201     }
2202     return 0;
2203 }
2204
2205 static void pdb_free(void* buffer)
2206 {
2207     HeapFree(GetProcessHeap(), 0, buffer);
2208 }
2209
2210 static void pdb_free_file(struct pdb_file_info* pdb_file)
2211 {
2212     switch (pdb_file->kind)
2213     {
2214     case PDB_JG:
2215         pdb_free(pdb_file->u.jg.toc);
2216         pdb_file->u.jg.toc = NULL;
2217         break;
2218     case PDB_DS:
2219         pdb_free(pdb_file->u.ds.toc);
2220         pdb_file->u.ds.toc = NULL;
2221         break;
2222     }
2223     HeapFree(GetProcessHeap(), 0, pdb_file->stream_dict);
2224 }
2225
2226 static BOOL pdb_load_stream_name_table(struct pdb_file_info* pdb_file, const char* str, unsigned cb)
2227 {
2228     DWORD*      pdw;
2229     DWORD*      ok_bits;
2230     DWORD       count, numok;
2231     unsigned    i, j;
2232     char*       cpstr;
2233
2234     pdw = (DWORD*)(str + cb);
2235     numok = *pdw++;
2236     count = *pdw++;
2237
2238     pdb_file->stream_dict = HeapAlloc(GetProcessHeap(), 0, (numok + 1) * sizeof(struct pdb_stream_name) + cb);
2239     if (!pdb_file->stream_dict) return FALSE;
2240     cpstr = (char*)(pdb_file->stream_dict + numok + 1);
2241     memcpy(cpstr, str, cb);
2242
2243     /* bitfield: first dword is len (in dword), then data */
2244     ok_bits = pdw;
2245     pdw += *ok_bits++ + 1;
2246     if (*pdw++ != 0)
2247     {
2248         FIXME("unexpected value\n");
2249         return -1;
2250     }
2251
2252     for (i = j = 0; i < count; i++)
2253     {
2254         if (ok_bits[i / 32] & (1 << (i % 32)))
2255         {
2256             if (j >= numok) break;
2257             pdb_file->stream_dict[j].name = &cpstr[*pdw++];
2258             pdb_file->stream_dict[j].index = *pdw++;
2259             j++;
2260         }
2261     }
2262     /* add sentinel */
2263     pdb_file->stream_dict[numok].name = NULL;
2264     pdb_file->fpoext_stream = -1;
2265     return j == numok && i == count;
2266 }
2267
2268 static unsigned pdb_get_stream_by_name(const struct pdb_file_info* pdb_file, const char* name)
2269 {
2270     struct pdb_stream_name*     psn;
2271
2272     for (psn = pdb_file->stream_dict; psn && psn->name; psn++)
2273     {
2274         if (!strcmp(psn->name, name)) return psn->index;
2275     }
2276     return -1;
2277 }
2278
2279 static void* pdb_read_strings(const struct pdb_file_info* pdb_file)
2280 {
2281     unsigned idx;
2282     void *ret;
2283
2284     idx = pdb_get_stream_by_name(pdb_file, "/names");
2285     if (idx != -1)
2286     {
2287         ret = pdb_read_file( pdb_file, idx );
2288         if (ret && *(const DWORD *)ret == 0xeffeeffe) return ret;
2289         pdb_free( ret );
2290     }
2291     WARN("string table not found\n");
2292     return NULL;
2293 }
2294
2295 static void pdb_module_remove(struct process* pcsn, struct module_format* modfmt)
2296 {
2297     unsigned    i;
2298
2299     for (i = 0; i < modfmt->u.pdb_info->used_subfiles; i++)
2300     {
2301         pdb_free_file(&modfmt->u.pdb_info->pdb_files[i]);
2302         if (modfmt->u.pdb_info->pdb_files[i].image)
2303             UnmapViewOfFile(modfmt->u.pdb_info->pdb_files[i].image);
2304         if (modfmt->u.pdb_info->pdb_files[i].hMap)
2305             CloseHandle(modfmt->u.pdb_info->pdb_files[i].hMap);
2306     }
2307     HeapFree(GetProcessHeap(), 0, modfmt);
2308 }
2309
2310 static void pdb_convert_types_header(PDB_TYPES* types, const BYTE* image)
2311 {
2312     memset(types, 0, sizeof(PDB_TYPES));
2313     if (!image) return;
2314
2315     if (*(const DWORD*)image < 19960000)   /* FIXME: correct version? */
2316     {
2317         /* Old version of the types record header */
2318         const PDB_TYPES_OLD*    old = (const PDB_TYPES_OLD*)image;
2319         types->version     = old->version;
2320         types->type_offset = sizeof(PDB_TYPES_OLD);
2321         types->type_size   = old->type_size;
2322         types->first_index = old->first_index;
2323         types->last_index  = old->last_index;
2324         types->file        = old->file;
2325     }
2326     else
2327     {
2328         /* New version of the types record header */
2329         *types = *(const PDB_TYPES*)image;
2330     }
2331 }
2332
2333 static void pdb_convert_symbols_header(PDB_SYMBOLS* symbols,
2334                                        int* header_size, const BYTE* image)
2335 {
2336     memset(symbols, 0, sizeof(PDB_SYMBOLS));
2337     if (!image) return;
2338
2339     if (*(const DWORD*)image != 0xffffffff)
2340     {
2341         /* Old version of the symbols record header */
2342         const PDB_SYMBOLS_OLD*  old = (const PDB_SYMBOLS_OLD*)image;
2343         symbols->version         = 0;
2344         symbols->module_size     = old->module_size;
2345         symbols->offset_size     = old->offset_size;
2346         symbols->hash_size       = old->hash_size;
2347         symbols->srcmodule_size  = old->srcmodule_size;
2348         symbols->pdbimport_size  = 0;
2349         symbols->hash1_file      = old->hash1_file;
2350         symbols->hash2_file      = old->hash2_file;
2351         symbols->gsym_file       = old->gsym_file;
2352
2353         *header_size = sizeof(PDB_SYMBOLS_OLD);
2354     }
2355     else
2356     {
2357         /* New version of the symbols record header */
2358         *symbols = *(const PDB_SYMBOLS*)image;
2359         *header_size = sizeof(PDB_SYMBOLS);
2360     }
2361 }
2362
2363 static void pdb_convert_symbol_file(const PDB_SYMBOLS* symbols, 
2364                                     PDB_SYMBOL_FILE_EX* sfile, 
2365                                     unsigned* size, const void* image)
2366
2367 {
2368     if (symbols->version < 19970000)
2369     {
2370         const PDB_SYMBOL_FILE *sym_file = image;
2371         memset(sfile, 0, sizeof(*sfile));
2372         sfile->file        = sym_file->file;
2373         sfile->range.index = sym_file->range.index;
2374         sfile->symbol_size = sym_file->symbol_size;
2375         sfile->lineno_size = sym_file->lineno_size;
2376         *size = sizeof(PDB_SYMBOL_FILE) - 1;
2377     }
2378     else
2379     {
2380         memcpy(sfile, image, sizeof(PDB_SYMBOL_FILE_EX));
2381         *size = sizeof(PDB_SYMBOL_FILE_EX) - 1;
2382     }
2383 }
2384
2385 static HANDLE map_pdb_file(const struct process* pcs,
2386                            const struct pdb_lookup* lookup,
2387                            struct module* module)
2388 {
2389     HANDLE      hFile, hMap = NULL;
2390     char        dbg_file_path[MAX_PATH];
2391     BOOL        ret = FALSE;
2392
2393     switch (lookup->kind)
2394     {
2395     case PDB_JG:
2396         ret = path_find_symbol_file(pcs, lookup->filename, NULL, lookup->timestamp,
2397                                     lookup->age, dbg_file_path, &module->module.PdbUnmatched);
2398         break;
2399     case PDB_DS:
2400         ret = path_find_symbol_file(pcs, lookup->filename, &lookup->guid, 0,
2401                                     lookup->age, dbg_file_path, &module->module.PdbUnmatched);
2402         break;
2403     }
2404     if (!ret)
2405     {
2406         WARN("\tCouldn't find %s\n", lookup->filename);
2407         return NULL;
2408     }
2409     if ((hFile = CreateFileA(dbg_file_path, GENERIC_READ, FILE_SHARE_READ, NULL,
2410                              OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)) != INVALID_HANDLE_VALUE)
2411     {
2412         hMap = CreateFileMappingW(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
2413         CloseHandle(hFile);
2414     }
2415     return hMap;
2416 }
2417
2418 static void pdb_process_types(const struct msc_debug_info* msc_dbg,
2419                               const struct pdb_file_info* pdb_file)
2420 {
2421     BYTE*       types_image = NULL;
2422
2423     types_image = pdb_read_file(pdb_file, 2);
2424     if (types_image)
2425     {
2426         PDB_TYPES               types;
2427         struct codeview_type_parse      ctp;
2428         DWORD                   total;
2429         const BYTE*             ptr;
2430         DWORD*                  offset;
2431
2432         pdb_convert_types_header(&types, types_image);
2433
2434         /* Check for unknown versions */
2435         switch (types.version)
2436         {
2437         case 19950410:      /* VC 4.0 */
2438         case 19951122:
2439         case 19961031:      /* VC 5.0 / 6.0 */
2440         case 19990903:      /* VC 7.0 */
2441         case 20040203:      /* VC 8.0 */
2442             break;
2443         default:
2444             ERR("-Unknown type info version %d\n", types.version);
2445         }
2446
2447         ctp.module = msc_dbg->module;
2448         /* reconstruct the types offset...
2449          * FIXME: maybe it's present in the newest PDB_TYPES structures
2450          */
2451         total = types.last_index - types.first_index + 1;
2452         offset = HeapAlloc(GetProcessHeap(), 0, sizeof(DWORD) * total);
2453         ctp.table = ptr = types_image + types.type_offset;
2454         ctp.num = 0;
2455         while (ptr < ctp.table + types.type_size && ctp.num < total)
2456         {
2457             offset[ctp.num++] = ptr - ctp.table;
2458             ptr += ((const union codeview_type*)ptr)->generic.len + 2;
2459         }
2460         ctp.offset = offset;
2461
2462         /* Read type table */
2463         codeview_parse_type_table(&ctp);
2464         HeapFree(GetProcessHeap(), 0, offset);
2465         pdb_free(types_image);
2466     }
2467 }
2468
2469 static const char       PDB_JG_IDENT[] = "Microsoft C/C++ program database 2.00\r\n\032JG\0";
2470 static const char       PDB_DS_IDENT[] = "Microsoft C/C++ MSF 7.00\r\n\032DS\0";
2471
2472 /******************************************************************
2473  *              pdb_init
2474  *
2475  * Tries to load a pdb file
2476  * 'matched' is filled with the number of correct matches for this file:
2477  *      - age counts for one
2478  *      - timestamp or guid depending on kind counts for one
2479  * a wrong kind of file returns FALSE (FIXME ?)
2480  */
2481 static BOOL pdb_init(const struct pdb_lookup* pdb_lookup, struct pdb_file_info* pdb_file,
2482                      const char* image, unsigned* matched)
2483 {
2484     BOOL        ret = TRUE;
2485
2486     /* check the file header, and if ok, load the TOC */
2487     TRACE("PDB(%s): %.40s\n", pdb_lookup->filename, debugstr_an(image, 40));
2488
2489     *matched = 0;
2490     if (!memcmp(image, PDB_JG_IDENT, sizeof(PDB_JG_IDENT)))
2491     {
2492         const struct PDB_JG_HEADER* pdb = (const struct PDB_JG_HEADER*)image;
2493         struct PDB_JG_ROOT*         root;
2494
2495         pdb_file->u.jg.toc = pdb_jg_read(pdb, pdb->toc_block, pdb->toc.size);
2496         root = pdb_read_jg_file(pdb, pdb_file->u.jg.toc, 1);
2497         if (!root)
2498         {
2499             ERR("-Unable to get root from .PDB in %s\n", pdb_lookup->filename);
2500             return FALSE;
2501         }
2502         switch (root->Version)
2503         {
2504         case 19950623:      /* VC 4.0 */
2505         case 19950814:
2506         case 19960307:      /* VC 5.0 */
2507         case 19970604:      /* VC 6.0 */
2508             break;
2509         default:
2510             ERR("-Unknown root block version %d\n", root->Version);
2511         }
2512         if (pdb_lookup->kind != PDB_JG)
2513         {
2514             WARN("Found %s, but wrong PDB kind\n", pdb_lookup->filename);
2515             return FALSE;
2516         }
2517         pdb_file->kind = PDB_JG;
2518         pdb_file->u.jg.timestamp = root->TimeDateStamp;
2519         pdb_file->age = root->Age;
2520         if (root->TimeDateStamp == pdb_lookup->timestamp) (*matched)++;
2521         else WARN("Found %s, but wrong signature: %08x %08x\n",
2522                   pdb_lookup->filename, root->TimeDateStamp, pdb_lookup->timestamp);
2523         if (root->Age == pdb_lookup->age) (*matched)++;
2524         else WARN("Found %s, but wrong age: %08x %08x\n",
2525                   pdb_lookup->filename, root->Age, pdb_lookup->age);
2526         TRACE("found JG for %s: age=%x timestamp=%x\n",
2527               pdb_lookup->filename, root->Age, root->TimeDateStamp);
2528         pdb_load_stream_name_table(pdb_file, &root->names[0], root->cbNames);
2529
2530         pdb_free(root);
2531     }
2532     else if (!memcmp(image, PDB_DS_IDENT, sizeof(PDB_DS_IDENT)))
2533     {
2534         const struct PDB_DS_HEADER* pdb = (const struct PDB_DS_HEADER*)image;
2535         struct PDB_DS_ROOT*         root;
2536
2537         pdb_file->u.ds.toc =
2538             pdb_ds_read(pdb, 
2539                         (const DWORD*)((const char*)pdb + pdb->toc_page * pdb->block_size), 
2540                         pdb->toc_size);
2541         root = pdb_read_ds_file(pdb, pdb_file->u.ds.toc, 1);
2542         if (!root)
2543         {
2544             ERR("-Unable to get root from .PDB in %s\n", pdb_lookup->filename);
2545             return FALSE;
2546         }
2547         switch (root->Version)
2548         {
2549         case 20000404:
2550             break;
2551         default:
2552             ERR("-Unknown root block version %d\n", root->Version);
2553         }
2554         pdb_file->kind = PDB_DS;
2555         pdb_file->u.ds.guid = root->guid;
2556         pdb_file->age = root->Age;
2557         if (!memcmp(&root->guid, &pdb_lookup->guid, sizeof(GUID))) (*matched)++;
2558         else WARN("Found %s, but wrong GUID: %s %s\n",
2559                   pdb_lookup->filename, debugstr_guid(&root->guid),
2560                      debugstr_guid(&pdb_lookup->guid));
2561         if (root->Age == pdb_lookup->age) (*matched)++;
2562         else WARN("Found %s, but wrong age: %08x %08x\n",
2563                   pdb_lookup->filename, root->Age, pdb_lookup->age);
2564         TRACE("found DS for %s: age=%x guid=%s\n",
2565               pdb_lookup->filename, root->Age, debugstr_guid(&root->guid));
2566         pdb_load_stream_name_table(pdb_file, &root->names[0], root->cbNames);
2567
2568         pdb_free(root);
2569     }
2570
2571     if (0) /* some tool to dump the internal files from a PDB file */
2572     {
2573         int     i, num_files;
2574         
2575         switch (pdb_file->kind)
2576         {
2577         case PDB_JG: num_files = pdb_file->u.jg.toc->num_files; break;
2578         case PDB_DS: num_files = pdb_file->u.ds.toc->num_files; break;
2579         }
2580
2581         for (i = 1; i < num_files; i++)
2582         {
2583             unsigned char* x = pdb_read_file(pdb_file, i);
2584             FIXME("********************** [%u]: size=%08x\n",
2585                   i, pdb_get_file_size(pdb_file, i));
2586             dump(x, pdb_get_file_size(pdb_file, i));
2587             pdb_free(x);
2588         }
2589     }
2590     return ret;
2591 }
2592
2593 static BOOL pdb_process_internal(const struct process* pcs, 
2594                                  const struct msc_debug_info* msc_dbg,
2595                                  const struct pdb_lookup* pdb_lookup,
2596                                  struct pdb_module_info* pdb_module_info,
2597                                  unsigned module_index);
2598
2599 static void pdb_process_symbol_imports(const struct process* pcs, 
2600                                        const struct msc_debug_info* msc_dbg,
2601                                        const PDB_SYMBOLS* symbols,
2602                                        const void* symbols_image,
2603                                        const char* image,
2604                                        const struct pdb_lookup* pdb_lookup,
2605                                        struct pdb_module_info* pdb_module_info,
2606                                        unsigned module_index)
2607 {
2608     if (module_index == -1 && symbols && symbols->pdbimport_size)
2609     {
2610         const PDB_SYMBOL_IMPORT*imp;
2611         const void*             first;
2612         const void*             last;
2613         const char*             ptr;
2614         int                     i = 0;
2615         struct pdb_file_info    sf0 = pdb_module_info->pdb_files[0];
2616
2617         imp = (const PDB_SYMBOL_IMPORT*)((const char*)symbols_image + sizeof(PDB_SYMBOLS) + 
2618                                          symbols->module_size + symbols->offset_size + 
2619                                          symbols->hash_size + symbols->srcmodule_size);
2620         first = imp;
2621         last = (const char*)imp + symbols->pdbimport_size;
2622         while (imp < (const PDB_SYMBOL_IMPORT*)last)
2623         {
2624             ptr = (const char*)imp + sizeof(*imp) + strlen(imp->filename);
2625             if (i >= CV_MAX_MODULES) FIXME("Out of bounds !!!\n");
2626             if (!strcasecmp(pdb_lookup->filename, imp->filename))
2627             {
2628                 if (module_index != -1) FIXME("Twice the entry\n");
2629                 else module_index = i;
2630                 pdb_module_info->pdb_files[i] = sf0;
2631             }
2632             else
2633             {
2634                 struct pdb_lookup       imp_pdb_lookup;
2635
2636                 /* FIXME: this is an import of a JG PDB file
2637                  * how's a DS PDB handled ?
2638                  */
2639                 imp_pdb_lookup.filename = imp->filename;
2640                 imp_pdb_lookup.kind = PDB_JG;
2641                 imp_pdb_lookup.timestamp = imp->TimeDateStamp;
2642                 imp_pdb_lookup.age = imp->Age;
2643                 TRACE("got for %s: age=%u ts=%x\n",
2644                       imp->filename, imp->Age, imp->TimeDateStamp);
2645                 pdb_process_internal(pcs, msc_dbg, &imp_pdb_lookup, pdb_module_info, i);
2646             }
2647             i++;
2648             imp = (const PDB_SYMBOL_IMPORT*)((const char*)first + ((ptr - (const char*)first + strlen(ptr) + 1 + 3) & ~3));
2649         }
2650         pdb_module_info->used_subfiles = i;
2651     }
2652     if (module_index == -1)
2653     {
2654         module_index = 0;
2655         pdb_module_info->used_subfiles = 1;
2656     }
2657     cv_current_module = &cv_zmodules[module_index];
2658     if (cv_current_module->allowed) FIXME("Already allowed ??\n");
2659     cv_current_module->allowed = TRUE;
2660 }
2661
2662 static BOOL pdb_process_internal(const struct process* pcs, 
2663                                  const struct msc_debug_info* msc_dbg,
2664                                  const struct pdb_lookup* pdb_lookup,
2665                                  struct pdb_module_info* pdb_module_info,
2666                                  unsigned module_index)
2667 {
2668     HANDLE      hMap = NULL;
2669     char*       image = NULL;
2670     BYTE*       symbols_image = NULL;
2671     char*       files_image = NULL;
2672     DWORD       files_size = 0;
2673     unsigned    matched;
2674     struct pdb_file_info* pdb_file;
2675
2676     TRACE("Processing PDB file %s\n", pdb_lookup->filename);
2677
2678     pdb_file = &pdb_module_info->pdb_files[module_index == -1 ? 0 : module_index];
2679     /* Open and map() .PDB file */
2680     if ((hMap = map_pdb_file(pcs, pdb_lookup, msc_dbg->module)) == NULL ||
2681         ((image = MapViewOfFile(hMap, FILE_MAP_READ, 0, 0, 0)) == NULL))
2682     {
2683         WARN("Unable to open .PDB file: %s\n", pdb_lookup->filename);
2684         CloseHandle(hMap);
2685         return FALSE;
2686     }
2687     if (!pdb_init(pdb_lookup, pdb_file, image, &matched) || matched != 2)
2688     {
2689         CloseHandle(hMap);
2690         UnmapViewOfFile(image);
2691         return FALSE;
2692     }
2693
2694     pdb_file->hMap = hMap;
2695     pdb_file->image = image;
2696     symbols_image = pdb_read_file(pdb_file, 3);
2697     if (symbols_image)
2698     {
2699         PDB_SYMBOLS symbols;
2700         BYTE*       globalimage;
2701         BYTE*       modimage;
2702         BYTE*       file;
2703         int         header_size = 0;
2704         PDB_STREAM_INDEXES* psi;
2705
2706         pdb_convert_symbols_header(&symbols, &header_size, symbols_image);
2707         switch (symbols.version)
2708         {
2709         case 0:            /* VC 4.0 */
2710         case 19960307:     /* VC 5.0 */
2711         case 19970606:     /* VC 6.0 */
2712         case 19990903:
2713             break;
2714         default:
2715             ERR("-Unknown symbol info version %d %08x\n",
2716                 symbols.version, symbols.version);
2717         }
2718
2719         switch (symbols.stream_index_size)
2720         {
2721         case 0:
2722         case sizeof(PDB_STREAM_INDEXES_OLD):
2723             /* no fpo ext stream in this case */
2724             break;
2725         case sizeof(PDB_STREAM_INDEXES):
2726             psi = (PDB_STREAM_INDEXES*)((const char*)symbols_image + sizeof(PDB_SYMBOLS) +
2727                                         symbols.module_size + symbols.offset_size +
2728                                         symbols.hash_size + symbols.srcmodule_size +
2729                                         symbols.pdbimport_size + symbols.unknown2_size);
2730             pdb_file->fpoext_stream = psi->FPO_EXT;
2731             break;
2732         default:
2733             FIXME("Unknown PDB_STREAM_INDEXES size (%d)\n", symbols.stream_index_size);
2734             break;
2735         }
2736         files_image = pdb_read_strings(pdb_file);
2737         if (files_image) files_size = *(const DWORD*)(files_image + 8);
2738
2739         pdb_process_symbol_imports(pcs, msc_dbg, &symbols, symbols_image, image,
2740                                    pdb_lookup, pdb_module_info, module_index);
2741         pdb_process_types(msc_dbg, pdb_file);
2742
2743         /* Read global symbol table */
2744         globalimage = pdb_read_file(pdb_file, symbols.gsym_file);
2745         if (globalimage)
2746         {
2747             codeview_snarf(msc_dbg, globalimage, 0,
2748                            pdb_get_file_size(pdb_file, symbols.gsym_file), FALSE);
2749         }
2750
2751         /* Read per-module symbols' tables */
2752         file = symbols_image + header_size;
2753         while (file - symbols_image < header_size + symbols.module_size)
2754         {
2755             PDB_SYMBOL_FILE_EX          sfile;
2756             const char*                 file_name;
2757             unsigned                    size;
2758
2759             HeapValidate(GetProcessHeap(), 0, NULL);
2760             pdb_convert_symbol_file(&symbols, &sfile, &size, file);
2761
2762             modimage = pdb_read_file(pdb_file, sfile.file);
2763             if (modimage)
2764             {
2765                 if (sfile.symbol_size)
2766                     codeview_snarf(msc_dbg, modimage, sizeof(DWORD),
2767                                    sfile.symbol_size, TRUE);
2768
2769                 if (sfile.lineno_size)
2770                     codeview_snarf_linetab(msc_dbg,
2771                                            modimage + sfile.symbol_size,
2772                                            sfile.lineno_size,
2773                                            pdb_file->kind == PDB_JG);
2774                 if (files_image)
2775                     codeview_snarf_linetab2(msc_dbg, modimage + sfile.symbol_size + sfile.lineno_size,
2776                                    pdb_get_file_size(pdb_file, sfile.file) - sfile.symbol_size - sfile.lineno_size,
2777                                    files_image + 12, files_size);
2778
2779                 pdb_free(modimage);
2780             }
2781             file_name = (const char*)file + size;
2782             file_name += strlen(file_name) + 1;
2783             file = (BYTE*)((DWORD_PTR)(file_name + strlen(file_name) + 1 + 3) & ~3);
2784         }
2785         /* finish the remaining public and global information */
2786         if (globalimage)
2787         {
2788             codeview_snarf_public(msc_dbg, globalimage, 0,
2789                                   pdb_get_file_size(pdb_file, symbols.gsym_file));
2790             pdb_free(globalimage);
2791         }
2792     }
2793     else
2794         pdb_process_symbol_imports(pcs, msc_dbg, NULL, NULL, image,
2795                                    pdb_lookup, pdb_module_info, module_index);
2796
2797     pdb_free(symbols_image);
2798     pdb_free(files_image);
2799
2800     return TRUE;
2801 }
2802
2803 static BOOL pdb_process_file(const struct process* pcs, 
2804                              const struct msc_debug_info* msc_dbg,
2805                              struct pdb_lookup* pdb_lookup)
2806 {
2807     BOOL                        ret;
2808     struct module_format*       modfmt;
2809     struct pdb_module_info*     pdb_module_info;
2810
2811     modfmt = HeapAlloc(GetProcessHeap(), 0,
2812                        sizeof(struct module_format) + sizeof(struct pdb_module_info));
2813     if (!modfmt) return FALSE;
2814
2815     pdb_module_info = (void*)(modfmt + 1);
2816     msc_dbg->module->format_info[DFI_PDB] = modfmt;
2817     modfmt->module      = msc_dbg->module;
2818     modfmt->remove      = pdb_module_remove;
2819     modfmt->loc_compute = NULL;
2820     modfmt->u.pdb_info  = pdb_module_info;
2821
2822     memset(cv_zmodules, 0, sizeof(cv_zmodules));
2823     codeview_init_basic_types(msc_dbg->module);
2824     ret = pdb_process_internal(pcs, msc_dbg, pdb_lookup,
2825                                msc_dbg->module->format_info[DFI_PDB]->u.pdb_info, -1);
2826     codeview_clear_type_table();
2827     if (ret)
2828     {
2829         struct pdb_module_info*     pdb_info = msc_dbg->module->format_info[DFI_PDB]->u.pdb_info;
2830         msc_dbg->module->module.SymType = SymCv;
2831         if (pdb_info->pdb_files[0].kind == PDB_JG)
2832             msc_dbg->module->module.PdbSig = pdb_info->pdb_files[0].u.jg.timestamp;
2833         else
2834             msc_dbg->module->module.PdbSig70 = pdb_info->pdb_files[0].u.ds.guid;
2835         msc_dbg->module->module.PdbAge = pdb_info->pdb_files[0].age;
2836         MultiByteToWideChar(CP_ACP, 0, pdb_lookup->filename, -1,
2837                             msc_dbg->module->module.LoadedPdbName,
2838                             sizeof(msc_dbg->module->module.LoadedPdbName) / sizeof(WCHAR));
2839         /* FIXME: we could have a finer grain here */
2840         msc_dbg->module->module.LineNumbers = TRUE;
2841         msc_dbg->module->module.GlobalSymbols = TRUE;
2842         msc_dbg->module->module.TypeInfo = TRUE;
2843         msc_dbg->module->module.SourceIndexed = TRUE;
2844         msc_dbg->module->module.Publics = TRUE;
2845     }
2846     else
2847     {
2848         msc_dbg->module->format_info[DFI_PDB] = NULL;
2849         HeapFree(GetProcessHeap(), 0, modfmt);
2850     }
2851     return ret;
2852 }
2853
2854 BOOL pdb_fetch_file_info(const struct pdb_lookup* pdb_lookup, unsigned* matched)
2855 {
2856     HANDLE              hFile, hMap = NULL;
2857     char*               image = NULL;
2858     BOOL                ret;
2859     struct pdb_file_info pdb_file;
2860
2861     if ((hFile = CreateFileA(pdb_lookup->filename, GENERIC_READ, FILE_SHARE_READ, NULL,
2862                              OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE ||
2863         ((hMap = CreateFileMappingW(hFile, NULL, PAGE_READONLY, 0, 0, NULL)) == NULL) ||
2864         ((image = MapViewOfFile(hMap, FILE_MAP_READ, 0, 0, 0)) == NULL))
2865     {
2866         WARN("Unable to open .PDB file: %s\n", pdb_lookup->filename);
2867         ret = FALSE;
2868     }
2869     else
2870     {
2871         ret = pdb_init(pdb_lookup, &pdb_file, image, matched);
2872         pdb_free_file(&pdb_file);
2873     }
2874
2875     if (image) UnmapViewOfFile(image);
2876     if (hMap) CloseHandle(hMap);
2877     if (hFile != INVALID_HANDLE_VALUE) CloseHandle(hFile);
2878
2879     return ret;
2880 }
2881
2882 /*========================================================================
2883  * FPO unwinding code
2884  */
2885
2886 /* Stack unwinding is based on postfixed operations.
2887  * Let's define our Postfix EValuator
2888  */
2889 #define PEV_MAX_LEN      32
2890 struct pevaluator
2891 {
2892     struct cpu_stack_walk*  csw;
2893     struct pool             pool;
2894     struct vector           stack;
2895     unsigned                stk_index;
2896     struct hash_table       values;
2897     char                    error[64];
2898 };
2899
2900 struct zvalue
2901 {
2902     DWORD_PTR                   value;
2903     struct hash_table_elt       elt;
2904 };
2905
2906 #define PEV_ERROR(pev, msg)       snprintf((pev)->error, sizeof((pev)->error), "%s", (msg)),FALSE
2907 #define PEV_ERROR1(pev, msg, pmt) snprintf((pev)->error, sizeof((pev)->error), (msg), (pmt)),FALSE
2908
2909 #if 0
2910 static void pev_dump_stack(struct pevaluator* pev)
2911 {
2912     unsigned i;
2913     FIXME("stack #%d\n", pev->stk_index);
2914     for (i = 0; i < pev->stk_index; i++)
2915     {
2916         FIXME("\t%d) %s\n", i, *(char**)vector_at(&pev->stack, i));
2917     }
2918 }
2919 #endif
2920
2921 /* get the value out of an operand (variable or literal) */
2922 static BOOL  pev_get_val(struct pevaluator* pev, const char* str, DWORD_PTR* val)
2923 {
2924     char*                       n;
2925     struct hash_table_iter      hti;
2926     void*                       ptr;
2927
2928     switch (str[0])
2929     {
2930     case '$':
2931     case '.':
2932         hash_table_iter_init(&pev->values, &hti, str);
2933         while ((ptr = hash_table_iter_up(&hti)))
2934         {
2935             if (!strcmp(GET_ENTRY(ptr, struct zvalue, elt)->elt.name, str))
2936             {
2937                 *val = GET_ENTRY(ptr, struct zvalue, elt)->value;
2938                 return TRUE;
2939             }
2940         }
2941         return PEV_ERROR1(pev, "get_zvalue: no value found (%s)", str);
2942     default:
2943         *val = strtol(str, &n, 10);
2944         if (n == str || *n != '\0')
2945             return PEV_ERROR1(pev, "get_val: not a literal (%s)", str);
2946         return TRUE;
2947     }
2948 }
2949
2950 /* push an operand onto the stack */
2951 static BOOL  pev_push(struct pevaluator* pev, const char* elt)
2952 {
2953     char**      at;
2954     if (pev->stk_index < vector_length(&pev->stack))
2955         at = vector_at(&pev->stack, pev->stk_index);
2956     else
2957         at = vector_add(&pev->stack, &pev->pool);
2958     if (!at) return PEV_ERROR(pev, "push: out of memory");
2959     *at = pool_strdup(&pev->pool, elt);
2960     pev->stk_index++;
2961     return TRUE;
2962 }
2963
2964 /* pop an operand from the stack */
2965 static BOOL  pev_pop(struct pevaluator* pev, char* elt)
2966 {
2967     char**      at = vector_at(&pev->stack, --pev->stk_index);
2968     if (!at) return PEV_ERROR(pev, "pop: stack empty");
2969     strcpy(elt, *at);
2970     return TRUE;
2971 }
2972
2973 /* pop an operand from the stack, and gets its value */
2974 static BOOL  pev_pop_val(struct pevaluator* pev, DWORD_PTR* val)
2975 {
2976     char        p[PEV_MAX_LEN];
2977
2978     return pev_pop(pev, p) && pev_get_val(pev, p, val);
2979 }
2980
2981 /* set var 'name' a new value (creates the var if it doesn't exist) */
2982 static BOOL  pev_set_value(struct pevaluator* pev, const char* name, DWORD_PTR val)
2983 {
2984     struct hash_table_iter      hti;
2985     void*                       ptr;
2986
2987     hash_table_iter_init(&pev->values, &hti, name);
2988     while ((ptr = hash_table_iter_up(&hti)))
2989     {
2990         if (!strcmp(GET_ENTRY(ptr, struct zvalue, elt)->elt.name, name))
2991         {
2992             GET_ENTRY(ptr, struct zvalue, elt)->value = val;
2993             break;
2994         }
2995     }
2996     if (!ptr)
2997     {
2998         struct zvalue* zv = pool_alloc(&pev->pool, sizeof(*zv));
2999         if (!zv) return PEV_ERROR(pev, "set_value: out of memory");
3000         zv->value = val;
3001
3002         zv->elt.name = pool_strdup(&pev->pool, name);
3003         hash_table_add(&pev->values, &zv->elt);
3004     }
3005     return TRUE;
3006 }
3007
3008 /* execute a binary operand from the two top most values on the stack.
3009  * puts result on top of the stack */
3010 static BOOL  pev_binop(struct pevaluator* pev, char op)
3011 {
3012     char        res[PEV_MAX_LEN];
3013     DWORD_PTR   v1, v2, c;
3014
3015     if (!pev_pop_val(pev, &v1) || !pev_pop_val(pev, &v2)) return FALSE;
3016     switch (op)
3017     {
3018     case '+': c = v1 + v2; break;
3019     case '-': c = v1 - v2; break;
3020     case '*': c = v1 * v2; break;
3021     case '/': c = v1 / v2; break;
3022     case '%': c = v1 % v2; break;
3023     default: return PEV_ERROR1(pev, "binop: unknown op (%c)", op);
3024     }
3025     snprintf(res, sizeof(res), "%ld", c);
3026     pev_push(pev, res);
3027     return TRUE;
3028 }
3029
3030 /* pops top most operand, dereference it, on pushes the result on top of the stack */
3031 static BOOL  pev_deref(struct pevaluator* pev)
3032 {
3033     char        res[PEV_MAX_LEN];
3034     DWORD_PTR   v1, v2;
3035
3036     if (!pev_pop_val(pev, &v1)) return FALSE;
3037     if (!sw_read_mem(pev->csw, v1, &v2, sizeof(v2)))
3038         return PEV_ERROR1(pev, "deref: cannot read mem at %lx\n", v1);
3039     snprintf(res, sizeof(res), "%ld", v2);
3040     pev_push(pev, res);
3041     return TRUE;
3042 }
3043
3044 /* assign value to variable (from two top most operands) */
3045 static BOOL  pev_assign(struct pevaluator* pev)
3046 {
3047     char                p2[PEV_MAX_LEN];
3048     DWORD_PTR           v1;
3049
3050     if (!pev_pop_val(pev, &v1) || !pev_pop(pev, p2)) return FALSE;
3051     if (p2[0] != '$') return PEV_ERROR1(pev, "assign: %s isn't a variable", p2);
3052     pev_set_value(pev, p2, v1);
3053
3054     return TRUE;
3055 }
3056
3057 /* initializes the postfix evaluator */
3058 static void  pev_init(struct pevaluator* pev, struct cpu_stack_walk* csw,
3059                       PDB_FPO_DATA* fpoext, struct pdb_cmd_pair* cpair)
3060 {
3061     pev->csw = csw;
3062     pool_init(&pev->pool, 512);
3063     vector_init(&pev->stack, sizeof(char*), 8);
3064     pev->stk_index = 0;
3065     hash_table_init(&pev->pool, &pev->values, 8);
3066     pev->error[0] = '\0';
3067     for (; cpair->name; cpair++)
3068         pev_set_value(pev, cpair->name, *cpair->pvalue);
3069     pev_set_value(pev, ".raSearchStart", fpoext->start);
3070     pev_set_value(pev, ".cbLocals",      fpoext->locals_size);
3071     pev_set_value(pev, ".cbParams",      fpoext->params_size);
3072     pev_set_value(pev, ".cbSavedRegs",   fpoext->savedregs_size);
3073 }
3074
3075 static BOOL  pev_free(struct pevaluator* pev, struct pdb_cmd_pair* cpair)
3076 {
3077     DWORD_PTR   val;
3078
3079     if (cpair) for (; cpair->name; cpair++)
3080     {
3081         if (pev_get_val(pev, cpair->name, &val))
3082             *cpair->pvalue = val;
3083     }
3084     pool_destroy(&pev->pool);
3085     return TRUE;
3086 }
3087
3088 static BOOL  pdb_parse_cmd_string(struct cpu_stack_walk* csw, PDB_FPO_DATA* fpoext,
3089                                   const char* cmd, struct pdb_cmd_pair* cpair)
3090 {
3091     char                token[PEV_MAX_LEN];
3092     char*               ptok = token;
3093     const char*         ptr;
3094     BOOL                over = FALSE;
3095     struct pevaluator   pev;
3096
3097     pev_init(&pev, csw, fpoext, cpair);
3098     for (ptr = cmd; !over; ptr++)
3099     {
3100         if (*ptr == ' ' || (over = *ptr == '\0'))
3101         {
3102             *ptok = '\0';
3103
3104             if (!strcmp(token, "+") || !strcmp(token, "-") || !strcmp(token, "*") ||
3105                 !strcmp(token, "/") || !strcmp(token, "%"))
3106             {
3107                 if (!pev_binop(&pev, token[0])) goto done;
3108             }
3109             else if (!strcmp(token, "^"))
3110             {
3111                 if (!pev_deref(&pev)) goto done;
3112             }
3113             else if (!strcmp(token, "="))
3114             {
3115                 if (!pev_assign(&pev)) goto done;
3116             }
3117             else
3118             {
3119                 if (!pev_push(&pev, token)) goto done;
3120             }
3121             ptok = token;
3122         }
3123         else
3124         {
3125             if (ptok - token >= PEV_MAX_LEN - 1)
3126             {
3127                 PEV_ERROR1(&pev, "parse: token too long (%s)", ptr - (ptok - token));
3128                 goto done;
3129             }
3130             *ptok++ = *ptr;
3131         }
3132     }
3133     pev_free(&pev, cpair);
3134     return TRUE;
3135 done:
3136     FIXME("Couldn't evaluate %s => %s\n", wine_dbgstr_a(cmd), pev.error);
3137     pev_free(&pev, NULL);
3138     return FALSE;
3139 }
3140
3141 BOOL         pdb_virtual_unwind(struct cpu_stack_walk* csw, DWORD_PTR ip,
3142                                 CONTEXT* context, struct pdb_cmd_pair* cpair)
3143 {
3144     struct module_pair          pair;
3145     struct pdb_module_info*     pdb_info;
3146     PDB_FPO_DATA*               fpoext;
3147     unsigned                    i, size, strsize;
3148     char*                       strbase;
3149     BOOL                        ret = TRUE;
3150
3151     if (!(pair.pcs = process_find_by_handle(csw->hProcess)) ||
3152         !(pair.requested = module_find_by_addr(pair.pcs, ip, DMT_UNKNOWN)) ||
3153         !module_get_debug(&pair))
3154         return FALSE;
3155     if (!pair.effective->format_info[DFI_PDB]) return FALSE;
3156     pdb_info = pair.effective->format_info[DFI_PDB]->u.pdb_info;
3157     TRACE("searching %lx => %lx\n", ip, ip - (DWORD_PTR)pair.effective->module.BaseOfImage);
3158     ip -= (DWORD_PTR)pair.effective->module.BaseOfImage;
3159
3160     strbase = pdb_read_strings(&pdb_info->pdb_files[0]);
3161     if (!strbase) return FALSE;
3162     strsize = *(const DWORD*)(strbase + 8);
3163     fpoext = pdb_read_file(&pdb_info->pdb_files[0], pdb_info->pdb_files[0].fpoext_stream);
3164     size = pdb_get_file_size(&pdb_info->pdb_files[0], pdb_info->pdb_files[0].fpoext_stream);
3165     if (fpoext && (size % sizeof(*fpoext)) == 0)
3166     {
3167         size /= sizeof(*fpoext);
3168         for (i = 0; i < size; i++)
3169         {
3170             if (fpoext[i].start <= ip && ip < fpoext[i].start + fpoext[i].func_size)
3171             {
3172                 TRACE("\t%08x %08x %8x %8x %4x %4x %4x %08x %s\n",
3173                       fpoext[i].start, fpoext[i].func_size, fpoext[i].locals_size,
3174                       fpoext[i].params_size, fpoext[i].maxstack_size, fpoext[i].prolog_size,
3175                       fpoext[i].savedregs_size, fpoext[i].flags,
3176                       fpoext[i].str_offset < strsize ?
3177                           wine_dbgstr_a(strbase + 12 + fpoext[i].str_offset) : "<out of bounds>");
3178                 if (fpoext[i].str_offset < strsize)
3179                     ret = pdb_parse_cmd_string(csw, &fpoext[i], strbase + 12 + fpoext[i].str_offset, cpair);
3180                 else
3181                     ret = FALSE;
3182                 break;
3183             }
3184         }
3185     }
3186     else ret = FALSE;
3187     pdb_free(fpoext);
3188     pdb_free(strbase);
3189
3190     return ret;
3191 }
3192
3193 /*========================================================================
3194  * Process CodeView debug information.
3195  */
3196
3197 #define MAKESIG(a,b,c,d)        ((a) | ((b) << 8) | ((c) << 16) | ((d) << 24))
3198 #define CODEVIEW_NB09_SIG       MAKESIG('N','B','0','9')
3199 #define CODEVIEW_NB10_SIG       MAKESIG('N','B','1','0')
3200 #define CODEVIEW_NB11_SIG       MAKESIG('N','B','1','1')
3201 #define CODEVIEW_RSDS_SIG       MAKESIG('R','S','D','S')
3202
3203 static BOOL codeview_process_info(const struct process* pcs, 
3204                                   const struct msc_debug_info* msc_dbg)
3205 {
3206     const DWORD*                signature = (const DWORD*)msc_dbg->root;
3207     BOOL                        ret = FALSE;
3208     struct pdb_lookup           pdb_lookup;
3209
3210     TRACE("Processing signature %.4s\n", (const char*)signature);
3211
3212     switch (*signature)
3213     {
3214     case CODEVIEW_NB09_SIG:
3215     case CODEVIEW_NB11_SIG:
3216     {
3217         const OMFSignature*     cv = (const OMFSignature*)msc_dbg->root;
3218         const OMFDirHeader*     hdr = (const OMFDirHeader*)(msc_dbg->root + cv->filepos);
3219         const OMFDirEntry*      ent;
3220         const OMFDirEntry*      prev;
3221         const OMFDirEntry*      next;
3222         unsigned int                    i;
3223
3224         codeview_init_basic_types(msc_dbg->module);
3225
3226         for (i = 0; i < hdr->cDir; i++)
3227         {
3228             ent = (const OMFDirEntry*)((const BYTE*)hdr + hdr->cbDirHeader + i * hdr->cbDirEntry);
3229             if (ent->SubSection == sstGlobalTypes)
3230             {
3231                 const OMFGlobalTypes*           types;
3232                 struct codeview_type_parse      ctp;
3233
3234                 types = (const OMFGlobalTypes*)(msc_dbg->root + ent->lfo);
3235                 ctp.module = msc_dbg->module;
3236                 ctp.offset = (const DWORD*)(types + 1);
3237                 ctp.num    = types->cTypes;
3238                 ctp.table  = (const BYTE*)(ctp.offset + types->cTypes);
3239
3240                 cv_current_module = &cv_zmodules[0];
3241                 if (cv_current_module->allowed) FIXME("Already allowed ??\n");
3242                 cv_current_module->allowed = TRUE;
3243
3244                 codeview_parse_type_table(&ctp);
3245                 break;
3246             }
3247         }
3248
3249         ent = (const OMFDirEntry*)((const BYTE*)hdr + hdr->cbDirHeader);
3250         for (i = 0; i < hdr->cDir; i++, ent = next)
3251         {
3252             next = (i == hdr->cDir-1) ? NULL :
3253                    (const OMFDirEntry*)((const BYTE*)ent + hdr->cbDirEntry);
3254             prev = (i == 0) ? NULL :
3255                    (const OMFDirEntry*)((const BYTE*)ent - hdr->cbDirEntry);
3256
3257             if (ent->SubSection == sstAlignSym)
3258             {
3259                 codeview_snarf(msc_dbg, msc_dbg->root + ent->lfo, sizeof(DWORD),
3260                                ent->cb, TRUE);
3261
3262                 /*
3263                  * Check the next and previous entry.  If either is a
3264                  * sstSrcModule, it contains the line number info for
3265                  * this file.
3266                  *
3267                  * FIXME: This is not a general solution!
3268                  */
3269                 if (next && next->iMod == ent->iMod && next->SubSection == sstSrcModule)
3270                     codeview_snarf_linetab(msc_dbg, msc_dbg->root + next->lfo,
3271                                            next->cb, TRUE);
3272
3273                 if (prev && prev->iMod == ent->iMod && prev->SubSection == sstSrcModule)
3274                     codeview_snarf_linetab(msc_dbg, msc_dbg->root + prev->lfo,
3275                                            prev->cb, TRUE);
3276
3277             }
3278         }
3279
3280         msc_dbg->module->module.SymType = SymCv;
3281         /* FIXME: we could have a finer grain here */
3282         msc_dbg->module->module.LineNumbers = TRUE;
3283         msc_dbg->module->module.GlobalSymbols = TRUE;
3284         msc_dbg->module->module.TypeInfo = TRUE;
3285         msc_dbg->module->module.SourceIndexed = TRUE;
3286         msc_dbg->module->module.Publics = TRUE;
3287         codeview_clear_type_table();
3288         ret = TRUE;
3289         break;
3290     }
3291
3292     case CODEVIEW_NB10_SIG:
3293     {
3294         const CODEVIEW_PDB_DATA* pdb = (const CODEVIEW_PDB_DATA*)msc_dbg->root;
3295         pdb_lookup.filename = pdb->name;
3296         pdb_lookup.kind = PDB_JG;
3297         pdb_lookup.timestamp = pdb->timestamp;
3298         pdb_lookup.age = pdb->age;
3299         ret = pdb_process_file(pcs, msc_dbg, &pdb_lookup);
3300         break;
3301     }
3302     case CODEVIEW_RSDS_SIG:
3303     {
3304         const OMFSignatureRSDS* rsds = (const OMFSignatureRSDS*)msc_dbg->root;
3305
3306         TRACE("Got RSDS type of PDB file: guid=%s age=%08x name=%s\n",
3307               wine_dbgstr_guid(&rsds->guid), rsds->age, rsds->name);
3308         pdb_lookup.filename = rsds->name;
3309         pdb_lookup.kind = PDB_DS;
3310         pdb_lookup.guid = rsds->guid;
3311         pdb_lookup.age = rsds->age;
3312         ret = pdb_process_file(pcs, msc_dbg, &pdb_lookup);
3313         break;
3314     }
3315     default:
3316         ERR("Unknown CODEVIEW signature %08x in module %s\n",
3317             *signature, debugstr_w(msc_dbg->module->module.ModuleName));
3318         break;
3319     }
3320     if (ret)
3321     {
3322         msc_dbg->module->module.CVSig = *signature;
3323         memcpy(msc_dbg->module->module.CVData, msc_dbg->root,
3324                sizeof(msc_dbg->module->module.CVData));
3325     }
3326     return ret;
3327 }
3328
3329 /*========================================================================
3330  * Process debug directory.
3331  */
3332 BOOL pe_load_debug_directory(const struct process* pcs, struct module* module, 
3333                              const BYTE* mapping,
3334                              const IMAGE_SECTION_HEADER* sectp, DWORD nsect,
3335                              const IMAGE_DEBUG_DIRECTORY* dbg, int nDbg)
3336 {
3337     BOOL                        ret;
3338     int                         i;
3339     struct msc_debug_info       msc_dbg;
3340
3341     msc_dbg.module = module;
3342     msc_dbg.nsect  = nsect;
3343     msc_dbg.sectp  = sectp;
3344     msc_dbg.nomap  = 0;
3345     msc_dbg.omapp  = NULL;
3346
3347     __TRY
3348     {
3349         ret = FALSE;
3350
3351         /* First, watch out for OMAP data */
3352         for (i = 0; i < nDbg; i++)
3353         {
3354             if (dbg[i].Type == IMAGE_DEBUG_TYPE_OMAP_FROM_SRC)
3355             {
3356                 msc_dbg.nomap = dbg[i].SizeOfData / sizeof(OMAP_DATA);
3357                 msc_dbg.omapp = (const OMAP_DATA*)(mapping + dbg[i].PointerToRawData);
3358                 break;
3359             }
3360         }
3361   
3362         /* Now, try to parse CodeView debug info */
3363         for (i = 0; i < nDbg; i++)
3364         {
3365             if (dbg[i].Type == IMAGE_DEBUG_TYPE_CODEVIEW)
3366             {
3367                 msc_dbg.root = mapping + dbg[i].PointerToRawData;
3368                 if ((ret = codeview_process_info(pcs, &msc_dbg))) goto done;
3369             }
3370         }
3371     
3372         /* If not found, try to parse COFF debug info */
3373         for (i = 0; i < nDbg; i++)
3374         {
3375             if (dbg[i].Type == IMAGE_DEBUG_TYPE_COFF)
3376             {
3377                 msc_dbg.root = mapping + dbg[i].PointerToRawData;
3378                 if ((ret = coff_process_info(&msc_dbg))) goto done;
3379             }
3380         }
3381     done:
3382          /* FIXME: this should be supported... this is the debug information for
3383           * functions compiled without a frame pointer (FPO = frame pointer omission)
3384           * the associated data helps finding out the relevant information
3385           */
3386         for (i = 0; i < nDbg; i++)
3387             if (dbg[i].Type == IMAGE_DEBUG_TYPE_FPO)
3388                 FIXME("This guy has FPO information\n");
3389 #if 0
3390
3391 #define FRAME_FPO   0
3392 #define FRAME_TRAP  1
3393 #define FRAME_TSS   2
3394
3395 typedef struct _FPO_DATA 
3396 {
3397         DWORD       ulOffStart;            /* offset 1st byte of function code */
3398         DWORD       cbProcSize;            /* # bytes in function */
3399         DWORD       cdwLocals;             /* # bytes in locals/4 */
3400         WORD        cdwParams;             /* # bytes in params/4 */
3401
3402         WORD        cbProlog : 8;          /* # bytes in prolog */
3403         WORD        cbRegs   : 3;          /* # regs saved */
3404         WORD        fHasSEH  : 1;          /* TRUE if SEH in func */
3405         WORD        fUseBP   : 1;          /* TRUE if EBP has been allocated */
3406         WORD        reserved : 1;          /* reserved for future use */
3407         WORD        cbFrame  : 2;          /* frame type */
3408 } FPO_DATA;
3409 #endif
3410
3411     }
3412     __EXCEPT_PAGE_FAULT
3413     {
3414         ERR("Got a page fault while loading symbols\n");
3415         ret = FALSE;
3416     }
3417     __ENDTRY
3418     return ret;
3419 }