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