POSIX threads emulation, tricks glibc into being threadsafe.
[wine] / debugger / 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, Ulrich Weigand.
7  *
8  * Note - this handles reading debug information for 32 bit applications
9  * that run under Windows-NT for example.  I doubt that this would work well
10  * for 16 bit applications, but I don't think it really matters since the
11  * file format is different, and we should never get in here in such cases.
12  *
13  * TODO:
14  *      Get 16 bit CV stuff working.
15  *      Add symbol size to internal symbol table.
16  */
17
18 #include "config.h"
19 #include <stdlib.h>
20
21 #include <string.h>
22 #include <unistd.h>
23 #ifndef PATH_MAX
24 #define PATH_MAX _MAX_PATH
25 #endif
26 #include "debugger.h"
27 #include "neexe.h"
28 #include "peexe.h"
29 #include "file.h"
30
31 typedef struct {
32    IMAGE_DEBUG_DIRECTORY        dbgdir;
33    u_long                       sect_ofs;
34    int                          nsect;
35    char*                        dbg_info;
36    int                          dbg_size;
37 } MSC_DBG_INFO;
38
39 #define MSC_INFO(module)        ((MSC_DBG_INFO*)((module)->extra_info))
40
41 static int DEBUG_ProcessMSCDebugInfo(DBG_MODULE* module);
42
43 /*
44  * dbg_filename must be at least MAX_PATHNAME_LEN bytes in size
45  */
46 static void DEBUG_LocateDebugInfoFile(const char *filename, char *dbg_filename)
47 {
48     char          *str1 = DBG_alloc(MAX_PATHNAME_LEN);
49     char          *str2 = DBG_alloc(MAX_PATHNAME_LEN*10);
50     const char    *file;
51     char          *name_part;
52     
53     file = strrchr(filename, '\\');
54     if( file == NULL ) file = filename; else file++;
55
56     if ((GetEnvironmentVariable("_NT_SYMBOL_PATH", str1, MAX_PATHNAME_LEN) &&
57          (SearchPath(str1, file, NULL, MAX_PATHNAME_LEN*10, str2, &name_part))) ||
58         (GetEnvironmentVariable("_NT_ALT_SYMBOL_PATH", str1, MAX_PATHNAME_LEN) &&
59          (SearchPath(str1, file, NULL, MAX_PATHNAME_LEN*10, str2, &name_part))) ||
60         (SearchPath(NULL, file, NULL, MAX_PATHNAME_LEN*10, str2, &name_part)))
61         lstrcpyn(dbg_filename, str2, MAX_PATHNAME_LEN);
62     else
63         lstrcpyn(dbg_filename, filename, MAX_PATHNAME_LEN);
64     DBG_free(str1);
65     DBG_free(str2);
66 }
67
68 /***********************************************************************
69  *           DEBUG_MapDebugInfoFile
70  */
71 static void*    DEBUG_MapDebugInfoFile(const char* name, DWORD offset, DWORD size,
72                                        HANDLE* hFile, HANDLE* hMap)
73 {
74     OFSTRUCT    ofs;
75     DWORD       g_offset;       /* offset aligned on map granuality */
76     DWORD       g_size;         /* size to map, with offset aligned */
77     char*       ret;
78
79     *hMap = 0;
80
81     if (name != NULL) {
82        char     filename[MAX_PATHNAME_LEN];
83
84        DEBUG_LocateDebugInfoFile(name, filename);
85        if ((*hFile = OpenFile(filename, &ofs, OF_READ)) == HFILE_ERROR)
86           return NULL;
87     }
88
89     if (!size) {
90        DWORD file_size = GetFileSize(*hFile, NULL);
91        if (file_size == (DWORD)-1) return NULL;
92        size = file_size - offset;
93     }
94
95     g_offset = offset & ~0xFFFF; /* FIXME: is granularity portable ? */
96     g_size = offset + size - g_offset;
97
98     if ((*hMap = CreateFileMapping(*hFile, NULL, PAGE_READONLY, 0, 0, NULL)) == 0)
99        return NULL;
100     
101     if ((ret = MapViewOfFile(*hMap, FILE_MAP_READ, 0, g_offset, g_size)) != NULL)
102        ret += offset - g_offset;
103     return ret;
104 }
105
106 /***********************************************************************
107  *           DEBUG_UnmapDebugInfoFile
108  */
109 static void     DEBUG_UnmapDebugInfoFile(HANDLE hFile, HANDLE hMap, void* addr)
110 {
111    if (addr) UnmapViewOfFile(addr);
112    if (hMap) CloseHandle(hMap);
113    if (hFile) CloseHandle(hFile);
114 }
115
116 union any_size
117 {
118   char           * c;
119   short          * s;
120   int            * i;
121   unsigned int   * ui;
122 };
123
124 /*
125  * This is a convenience structure used to map portions of the
126  * line number table.
127  */
128 struct startend
129 {
130   unsigned int    start;
131   unsigned int    end;
132 };
133
134 /*
135  * This is how we reference the various record types.
136  */
137 union codeview_symbol
138 {
139   struct
140   {
141     short int   len;
142     short int   id;
143   } generic;
144
145   struct
146   {
147         short int       len;
148         short int       id;
149         unsigned int    offset;
150         unsigned short  seg;
151         unsigned short  symtype;
152         unsigned char   namelen;
153         unsigned char   name[1];
154   } data;
155
156   struct
157   {
158         short int       len;
159         short int       id;
160         unsigned int    symtype;
161         unsigned int    offset;
162         unsigned short  seg;
163         unsigned char   namelen;
164         unsigned char   name[1];
165   } data32;
166
167   struct
168   {
169         short int       len;
170         short int       id;
171         unsigned int    pparent;
172         unsigned int    pend;
173         unsigned int    next;
174         unsigned int    offset;
175         unsigned short  segment;
176         unsigned short  thunk_len;
177         unsigned char   thtype;
178         unsigned char   namelen;
179         unsigned char   name[1];
180   } thunk;
181
182   struct
183   {
184         short int       len;
185         short int       id;
186         unsigned int    pparent;
187         unsigned int    pend;
188         unsigned int    next;
189         unsigned int    proc_len;
190         unsigned int    debug_start;
191         unsigned int    debug_end;
192         unsigned int    offset;
193         unsigned short  segment;
194         unsigned short  proctype;
195         unsigned char   flags;
196         unsigned char   namelen;
197         unsigned char   name[1];
198   } proc;
199
200   struct
201   {
202         short int       len;
203         short int       id;
204         unsigned int    pparent;
205         unsigned int    pend;
206         unsigned int    next;
207         unsigned int    proc_len;
208         unsigned int    debug_start;
209         unsigned int    debug_end;
210         unsigned int    proctype;
211         unsigned int    offset;
212         unsigned short  segment;
213         unsigned char   flags;
214         unsigned char   namelen;
215         unsigned char   name[1];
216   } proc32;
217
218   struct
219   {
220         short int       len;    /* Total length of this entry */
221         short int       id;             /* Always S_BPREL32 */
222         unsigned int    offset; /* Stack offset relative to BP */
223         unsigned short  symtype;
224         unsigned char   namelen;
225         unsigned char   name[1];
226   } stack;
227
228   struct
229   {
230         short int       len;    /* Total length of this entry */
231         short int       id;             /* Always S_BPREL32 */
232         unsigned int    offset; /* Stack offset relative to BP */
233         unsigned int    symtype;
234         unsigned char   namelen;
235         unsigned char   name[1];
236   } stack32;
237
238 };
239
240 union codeview_type
241 {
242   struct
243   {
244     short int   len;
245     short int   id;
246   } generic;
247
248   struct
249   {
250     short int           len;
251     short int           id;
252     short int           attribute;
253     short int           datatype;
254     unsigned char       variant[1];
255   } pointer;
256
257   struct
258   {
259     short int           len;
260     short int           id;
261     unsigned int        datatype;
262     unsigned int        attribute;
263     unsigned char       variant[1];
264   } pointer32;
265
266   struct
267   {
268     short int           len;
269     short int           id;
270     unsigned char       nbits;
271     unsigned char       bitoff;
272     unsigned short      type;
273   } bitfield;
274
275   struct
276   {
277     short int           len;
278     short int           id;
279     unsigned int        type;
280     unsigned char       nbits;
281     unsigned char       bitoff;
282   } bitfield32;
283
284   struct
285   {
286     short int           len;
287     short int           id;
288     short int           elemtype;
289     short int           idxtype;
290     unsigned char       arrlen;
291     unsigned char       namelen;
292     unsigned char       name[1];
293   } array;
294
295   struct
296   {
297     short int           len;
298     short int           id;
299     unsigned int        elemtype;
300     unsigned int        idxtype;
301     unsigned char       arrlen;
302     unsigned char       namelen;
303     unsigned char       name[1];
304   } array32;
305
306   struct
307   {
308     short int           len;
309     short int           id;
310     short int           n_element;
311     short int           fieldlist;
312     short int           property;
313     short int           derived;
314     short int           vshape;
315     unsigned short      structlen;
316     unsigned char       namelen;
317     unsigned char       name[1];
318   } structure;
319
320   struct
321   {
322     short int           len;
323     short int           id;
324     short int           n_element;
325     short int           property;
326     unsigned int        fieldlist;
327     unsigned int        derived;
328     unsigned int        vshape;
329     unsigned short      structlen;
330     unsigned char       namelen;
331     unsigned char       name[1];
332   } structure32;
333
334   struct
335   {
336     short int           len;
337     short int           id;
338     short int           count;
339     short int           field;
340     short int           property;
341     unsigned short      un_len;
342     unsigned char       namelen;
343     unsigned char       name[1];
344   } t_union;
345
346   struct
347   {
348     short int           len;
349     short int           id;
350     short int           count;
351     short int           property;
352     unsigned int        field;
353     unsigned short      un_len;
354     unsigned char       namelen;
355     unsigned char       name[1];
356   } t_union32;
357
358   struct
359   {
360     short int           len;
361     short int           id;
362     short int           count;
363     short int           type;
364     short int           field;
365     short int           property;
366     unsigned char       namelen;
367     unsigned char       name[1];
368   } enumeration;
369
370   struct
371   {
372     short int           len;
373     short int           id;
374     short int           count;
375     short int           property;
376     unsigned int        type;
377     unsigned int        field;
378     unsigned char       namelen;
379     unsigned char       name[1];
380   } enumeration32;
381
382   struct
383   {
384     short int           id;
385     short int           attribute;
386     unsigned short int  value;
387     unsigned char       namelen;
388     unsigned char       name[1];
389   } enumerate;
390
391   struct
392   {
393     short int           id;
394     short int           type;
395     short int           attribute;
396     unsigned short int  offset;
397     unsigned char       namelen;
398     unsigned char       name[1];
399   } member;
400
401   struct
402   {
403     short int           id;
404     short int           attribute;
405     unsigned int        type;
406     unsigned short int  offset;
407     unsigned char       namelen;
408     unsigned char       name[1];
409   } member32;
410 };
411
412 #define S_COMPILE       0x0001
413 #define S_REGISTER      0x0002
414 #define S_CONSTANT      0x0003
415 #define S_UDT           0x0004
416 #define S_SSEARCH       0x0005
417 #define S_END           0x0006
418 #define S_SKIP          0x0007
419 #define S_CVRESERVE     0x0008
420 #define S_OBJNAME       0x0009
421 #define S_ENDARG        0x000a
422 #define S_COBOLUDT      0x000b
423 #define S_MANYREG       0x000c
424 #define S_RETURN        0x000d
425 #define S_ENTRYTHIS     0x000e
426
427 #define S_BPREL         0x0200
428 #define S_LDATA         0x0201
429 #define S_GDATA         0x0202
430 #define S_PUB           0x0203
431 #define S_LPROC         0x0204
432 #define S_GPROC         0x0205
433 #define S_THUNK         0x0206
434 #define S_BLOCK         0x0207
435 #define S_WITH          0x0208
436 #define S_LABEL         0x0209
437 #define S_CEXMODEL      0x020a
438 #define S_VFTPATH       0x020b
439 #define S_REGREL        0x020c
440 #define S_LTHREAD       0x020d
441 #define S_GTHREAD       0x020e
442
443 #define S_PROCREF       0x0400
444 #define S_DATAREF       0x0401
445 #define S_ALIGN         0x0402
446 #define S_LPROCREF      0x0403
447
448 #define S_REGISTER_32   0x1001 /* Variants with new 32-bit type indices */
449 #define S_CONSTANT_32   0x1002
450 #define S_UDT_32        0x1003
451 #define S_COBOLUDT_32   0x1004
452 #define S_MANYREG_32    0x1005
453
454 #define S_BPREL_32      0x1006
455 #define S_LDATA_32      0x1007
456 #define S_GDATA_32      0x1008
457 #define S_PUB_32        0x1009
458 #define S_LPROC_32      0x100a
459 #define S_GPROC_32      0x100b
460 #define S_VFTTABLE_32   0x100c
461 #define S_REGREL_32     0x100d
462 #define S_LTHREAD_32    0x100e
463 #define S_GTHREAD_32    0x100f
464
465
466 /*
467  * This covers the basic datatypes that VC++ seems to be using these days.
468  * 32 bit mode only.  There are additional numbers for the pointers in 16
469  * bit mode.  There are many other types listed in the documents, but these
470  * are apparently not used by the compiler, or represent pointer types
471  * that are not used.
472  */
473 #define T_NOTYPE        0x0000  /* Notype */
474 #define T_ABS           0x0001  /* Abs */
475 #define T_VOID          0x0003  /* Void */
476 #define T_CHAR          0x0010  /* signed char */
477 #define T_SHORT         0x0011  /* short */
478 #define T_LONG          0x0012  /* long */
479 #define T_QUAD          0x0013  /* long long */
480 #define T_UCHAR         0x0020  /* unsigned  char */
481 #define T_USHORT        0x0021  /* unsigned short */
482 #define T_ULONG         0x0022  /* unsigned long */
483 #define T_UQUAD         0x0023  /* unsigned long long */
484 #define T_REAL32        0x0040  /* float */
485 #define T_REAL64        0x0041  /* double */
486 #define T_RCHAR         0x0070  /* real char */
487 #define T_WCHAR         0x0071  /* wide char */
488 #define T_INT4          0x0074  /* int */
489 #define T_UINT4         0x0075  /* unsigned int */
490
491 #define T_32PVOID       0x0403  /* 32 bit near pointer to void */
492 #define T_32PCHAR       0x0410  /* 16:32 near pointer to signed char */
493 #define T_32PSHORT      0x0411  /* 16:32 near pointer to short */
494 #define T_32PLONG       0x0412  /* 16:32 near pointer to int */
495 #define T_32PQUAD       0x0413  /* 16:32 near pointer to long long */
496 #define T_32PUCHAR      0x0420  /* 16:32 near pointer to unsigned char */
497 #define T_32PUSHORT     0x0421  /* 16:32 near pointer to unsigned short */
498 #define T_32PULONG      0x0422  /* 16:32 near pointer to unsigned int */
499 #define T_32PUQUAD      0x0423  /* 16:32 near pointer to long long */
500 #define T_32PREAL32     0x0440  /* 16:32 near pointer to float */
501 #define T_32PREAL64     0x0441  /* 16:32 near pointer to float */
502 #define T_32PRCHAR      0x0470  /* 16:32 near pointer to real char */
503 #define T_32PWCHAR      0x0471  /* 16:32 near pointer to real char */
504 #define T_32PINT4       0x0474  /* 16:32 near pointer to int */
505 #define T_32PUINT4      0x0475  /* 16:32 near pointer to unsigned int */
506
507 #define LF_MODIFIER     0x0001
508 #define LF_POINTER      0x0002
509 #define LF_ARRAY        0x0003
510 #define LF_CLASS        0x0004
511 #define LF_STRUCTURE    0x0005
512 #define LF_UNION        0x0006
513 #define LF_ENUM         0x0007
514 #define LF_PROCEDURE    0x0008
515 #define LF_MFUNCTION    0x0009
516 #define LF_VTSHAPE      0x000a
517 #define LF_COBOL0       0x000b
518 #define LF_COBOL1       0x000c
519 #define LF_BARRAY       0x000d
520 #define LF_LABEL        0x000e
521 #define LF_NULL         0x000f
522 #define LF_NOTTRAN      0x0010
523 #define LF_DIMARRAY     0x0011
524 #define LF_VFTPATH      0x0012
525 #define LF_PRECOMP      0x0013
526 #define LF_ENDPRECOMP   0x0014
527 #define LF_OEM          0x0015
528 #define LF_TYPESERVER   0x0016
529
530 #define LF_MODIFIER_32  0x1001     /* variants with new 32-bit type indices */
531 #define LF_POINTER_32   0x1002
532 #define LF_ARRAY_32     0x1003
533 #define LF_CLASS_32     0x1004
534 #define LF_STRUCTURE_32 0x1005
535 #define LF_UNION_32     0x1006
536 #define LF_ENUM_32      0x1007
537 #define LF_PROCEDURE_32 0x1008
538 #define LF_MFUNCTION_32 0x1009
539 #define LF_COBOL0_32    0x100a
540 #define LF_BARRAY_32    0x100b
541 #define LF_DIMARRAY_32  0x100c
542 #define LF_VFTPATH_32   0x100d
543 #define LF_PRECOMP_32   0x100e
544 #define LF_OEM_32       0x100f
545
546 #define LF_SKIP         0x0200
547 #define LF_ARGLIST      0x0201
548 #define LF_DEFARG       0x0202
549 #define LF_LIST         0x0203
550 #define LF_FIELDLIST    0x0204
551 #define LF_DERIVED      0x0205
552 #define LF_BITFIELD     0x0206
553 #define LF_METHODLIST   0x0207
554 #define LF_DIMCONU      0x0208
555 #define LF_DIMCONLU     0x0209
556 #define LF_DIMVARU      0x020a
557 #define LF_DIMVARLU     0x020b
558 #define LF_REFSYM       0x020c
559
560 #define LF_SKIP_32      0x1200    /* variants with new 32-bit type indices */
561 #define LF_ARGLIST_32   0x1201
562 #define LF_DEFARG_32    0x1202
563 #define LF_FIELDLIST_32 0x1203
564 #define LF_DERIVED_32   0x1204
565 #define LF_BITFIELD_32  0x1205
566 #define LF_METHODLIST_32 0x1206
567 #define LF_DIMCONU_32   0x1207
568 #define LF_DIMCONLU_32  0x1208
569 #define LF_DIMVARU_32   0x1209
570 #define LF_DIMVARLU_32  0x120a
571
572 #define LF_BCLASS       0x0400
573 #define LF_VBCLASS      0x0401
574 #define LF_IVBCLASS     0x0402
575 #define LF_ENUMERATE    0x0403
576 #define LF_FRIENDFCN    0x0404
577 #define LF_INDEX        0x0405
578 #define LF_MEMBER       0x0406
579 #define LF_STMEMBER     0x0407
580 #define LF_METHOD       0x0408
581 #define LF_NESTTYPE     0x0409
582 #define LF_VFUNCTAB     0x040a
583 #define LF_FRIENDCLS    0x040b
584 #define LF_ONEMETHOD    0x040c
585 #define LF_VFUNCOFF     0x040d
586 #define LF_NESTTYPEEX   0x040e
587 #define LF_MEMBERMODIFY 0x040f
588
589 #define LF_BCLASS_32    0x1400    /* variants with new 32-bit type indices */
590 #define LF_VBCLASS_32   0x1401
591 #define LF_IVBCLASS_32  0x1402
592 #define LF_FRIENDFCN_32 0x1403
593 #define LF_INDEX_32     0x1404
594 #define LF_MEMBER_32    0x1405
595 #define LF_STMEMBER_32  0x1406
596 #define LF_METHOD_32    0x1407
597 #define LF_NESTTYPE_32  0x1408
598 #define LF_VFUNCTAB_32  0x1409
599 #define LF_FRIENDCLS_32 0x140a
600 #define LF_ONEMETHOD_32 0x140b
601 #define LF_VFUNCOFF_32  0x140c
602 #define LF_NESTTYPEEX_32 0x140d
603
604
605
606
607 #define MAX_BUILTIN_TYPES       0x480
608 static struct datatype * cv_basic_types[MAX_BUILTIN_TYPES];
609 static int num_cv_defined_types = 0;
610 static struct datatype **cv_defined_types = NULL;
611
612 /*
613  * For the type CODEVIEW debug directory entries, the debug directory
614  * points to a structure like this.  The cv_name field is the name
615  * of an external .PDB file.
616  */
617 struct CodeViewDebug
618 {
619         char                cv_nbtype[8];
620         unsigned int        cv_timestamp;
621         char                cv_unknown[4];
622         char                cv_name[1];
623 };
624
625 struct MiscDebug {
626     unsigned int       DataType;
627     unsigned int       Length;
628     char               Unicode;
629     char               Reserved[3];
630     char               Data[1];
631 };
632
633 /*
634  * This is the header that the COFF variety of debug header points to.
635  */
636 struct CoffDebug {
637     unsigned int   N_Sym;
638     unsigned int   SymbolOffset;
639     unsigned int   N_Linenum;
640     unsigned int   LinenumberOffset;
641     unsigned int   Unused[4];
642 };
643
644 struct CoffLinenum {
645         unsigned int            VirtualAddr;
646         unsigned short int      Linenum;
647 };
648
649 struct CoffFiles {
650         unsigned int    startaddr;
651         unsigned int    endaddr;
652         char          * filename;
653         int             linetab_offset;
654         int             linecnt;
655         struct name_hash **entries;
656         int                    neps;
657         int              neps_alloc;
658 };
659
660
661 struct CoffSymbol {
662     union {
663         char    ShortName[8];
664         struct {
665             unsigned int   NotLong;
666             unsigned int   StrTaboff;
667         } Name;
668     } N;
669     unsigned int   Value;
670     short          SectionNumber;
671     short          Type;
672     char           StorageClass;
673     unsigned char  NumberOfAuxSymbols;
674 };
675
676 struct CoffAuxSection{
677   unsigned int   Length;
678   unsigned short NumberOfRelocations;
679   unsigned short NumberOfLinenumbers;
680   unsigned int   CheckSum;
681   short          Number;
682   char           Selection;
683 } Section;
684
685 /*
686  * These two structures are used in the directory within a .DBG file
687  * to locate the individual important bits that we might want to see.
688  */
689 struct CV4_DirHead {
690   short unsigned int       dhsize;
691   short unsigned int       desize;
692   unsigned int             ndir;
693   unsigned int             next_offset;
694   unsigned int             flags;
695 };
696
697 struct CV4_DirEnt {
698   short unsigned int       subsect_number;
699   short unsigned int       module_number;
700   unsigned int             offset;
701   unsigned int             size;
702 };
703
704 /*
705  * These are the values of interest that the subsect_number field takes.
706  */
707 #define sstAlignSym             0x125
708 #define sstSrcModule            0x127
709
710 struct codeview_linetab_hdr
711 {
712   unsigned int             nline;
713   unsigned int             segno;
714   unsigned int             start;
715   unsigned int             end;
716   char                   * sourcefile;
717   unsigned short         * linetab;
718   unsigned int           * offtab;
719 };
720
721
722 /*
723  * A simple macro that tells us whether a given COFF symbol is a
724  * function or not.
725  */
726 #define N_TMASK                             0x0030
727 #define IMAGE_SYM_DTYPE_FUNCTION            2
728 #define N_BTSHFT                            4
729 #define ISFCN(x) (((x) & N_TMASK) == (IMAGE_SYM_DTYPE_FUNCTION << N_BTSHFT))
730
731
732 /*
733  * This is what we are looking for in the COFF symbols.
734  */
735 #define IMAGE_SYM_CLASS_EXTERNAL            0x2
736 #define IMAGE_SYM_CLASS_STATIC              0x3
737 #define IMAGE_SYM_CLASS_FILE                0x67
738
739 static 
740 struct datatype * DEBUG_GetCVType(unsigned int typeno)
741 {
742   struct datatype * dt = NULL;
743
744   /*
745    * Convert Codeview type numbers into something we can grok internally.
746    * Numbers < 0x1000 are all fixed builtin types.  Numbers from 0x1000 and
747    * up are all user defined (structs, etc).
748    */
749   if( typeno < 0x1000 )
750     {
751       if( typeno < MAX_BUILTIN_TYPES )
752         {
753           dt = cv_basic_types[typeno];
754         }
755     }
756   else
757     {
758       if( typeno - 0x1000 < num_cv_defined_types )
759         {
760           dt = cv_defined_types[typeno - 0x1000];
761         } 
762     }
763
764   return dt;
765 }
766
767 static int
768 DEBUG_ParseTypeTable(char * table, int len)
769 {
770   int                             arr_max;
771   int                             curr_type;
772   enum debug_type                 fieldtype;
773   int                             elem_size;
774   union any_size                  ptr;
775   union any_size                  ptr2;
776   struct datatype               * subtype;
777   char                            symname[256];
778   union codeview_type           * type;
779   union codeview_type           * type2;
780   struct datatype               * typeptr;
781
782   curr_type = 0x1000;
783
784   ptr.c = table;
785   while( ptr.c - table < len )
786     {
787       type = (union codeview_type *) ptr.c;
788
789       if( curr_type - 0x1000 >= num_cv_defined_types )
790         {
791           num_cv_defined_types += 0x100;
792           cv_defined_types = (struct datatype **) DBG_realloc(cv_defined_types,
793                   num_cv_defined_types * sizeof(struct datatype *));
794           memset(cv_defined_types + num_cv_defined_types - 0x100,
795                  0,
796                  0x100 * sizeof(struct datatype *));
797           if( cv_defined_types == NULL )
798             {
799               return FALSE;
800             }
801         }
802
803       switch(type->generic.id)
804         {
805         case LF_POINTER:
806           cv_defined_types[curr_type - 0x1000] = 
807             DEBUG_FindOrMakePointerType(DEBUG_GetCVType(type->pointer.datatype));
808           break;
809         case LF_POINTER_32:
810           cv_defined_types[curr_type - 0x1000] = 
811             DEBUG_FindOrMakePointerType(DEBUG_GetCVType(type->pointer32.datatype));
812           break;
813         case LF_ARRAY:
814           if( type->array.arrlen >= 0x8000 )
815             {
816               /*
817                * This is a numeric leaf, I am too lazy to handle this right
818                * now.
819                */
820               DEBUG_Printf(DBG_CHN_MESG, "Ignoring large numberic leaf.\n");
821               break;
822             }
823           if( type->array.namelen != 0 )
824             {
825               memset(symname, 0, sizeof(symname));
826               memcpy(symname, type->array.name, type->array.namelen);
827               typeptr = DEBUG_NewDataType(DT_ARRAY, symname);
828             }
829           else
830             {
831               typeptr = DEBUG_NewDataType(DT_ARRAY, NULL);
832             }
833           cv_defined_types[curr_type - 0x1000] = typeptr;
834
835           subtype = DEBUG_GetCVType(type->array.elemtype);
836           if(    (subtype == NULL)
837               || (elem_size = DEBUG_GetObjectSize(subtype)) == 0 )
838             {
839               arr_max = 0;
840             }
841           else
842             {
843               arr_max = type->array.arrlen / DEBUG_GetObjectSize(subtype);
844             }
845
846           DEBUG_SetArrayParams(typeptr, 0, arr_max, subtype);
847           break;
848         case LF_ARRAY_32:
849           if( type->array32.arrlen >= 0x8000 )
850             {
851               /*
852                * This is a numeric leaf, I am too lazy to handle this right
853                * now.
854                */
855               DEBUG_Printf(DBG_CHN_MESG, "Ignoring large numberic leaf.\n");
856               break;
857             }
858           if( type->array32.namelen != 0 )
859             {
860               memset(symname, 0, sizeof(symname));
861               memcpy(symname, type->array32.name, type->array32.namelen);
862               typeptr = DEBUG_NewDataType(DT_ARRAY, symname);
863             }
864           else
865             {
866               typeptr = DEBUG_NewDataType(DT_ARRAY, NULL);
867             }
868           cv_defined_types[curr_type - 0x1000] = typeptr;
869
870           subtype = DEBUG_GetCVType(type->array32.elemtype);
871           if(    (subtype == NULL)
872               || (elem_size = DEBUG_GetObjectSize(subtype)) == 0 )
873             {
874               arr_max = 0;
875             }
876           else
877             {
878               arr_max = type->array32.arrlen / DEBUG_GetObjectSize(subtype);
879             }
880
881           DEBUG_SetArrayParams(typeptr, 0, arr_max, subtype);
882           break;
883         case LF_FIELDLIST:
884           /*
885            * This is where the basic list of fields is defined for
886            * structures and classes.
887            *
888            * First, we need to look ahead and see whether we are building
889            * a fieldlist for an enum or a struct.
890            */
891           ptr2.i = ptr.i + 1;
892           type2 = (union codeview_type *) ptr2.c;
893           if( type2->member.id == LF_MEMBER )
894             {
895               typeptr = DEBUG_NewDataType(DT_STRUCT, NULL);
896               fieldtype = DT_STRUCT;
897             }
898           else if( type2->member.id == LF_ENUMERATE )
899             {
900               typeptr = DEBUG_NewDataType(DT_ENUM, NULL);
901               fieldtype = DT_ENUM;
902             }
903           else
904             {
905               break;
906             }
907
908           cv_defined_types[curr_type - 0x1000] = typeptr;
909           while( ptr2.c < (ptr.c + ((type->generic.len + 3) & ~3)) )
910             {
911               type2 = (union codeview_type *) ptr2.c;
912               if( type2->member.id == LF_MEMBER && fieldtype == DT_STRUCT )
913                 {
914                   memset(symname, 0, sizeof(symname));
915                   memcpy(symname, type2->member.name, type2->member.namelen);
916                   
917                   subtype = DEBUG_GetCVType(type2->member.type);
918                   elem_size = 0;
919                   if( subtype != NULL )
920                     {
921                       elem_size = DEBUG_GetObjectSize(subtype);
922                     }
923                   
924                   if( type2->member.offset >= 0x8000 )
925                     {
926                       /*
927                        * This is a numeric leaf, I am too lazy to handle this right
928                        * now.
929                        */
930                       DEBUG_Printf(DBG_CHN_MESG, "Ignoring large numberic leaf.\n");
931                     }
932                   else
933                     {
934                       DEBUG_AddStructElement(typeptr, symname, subtype, 
935                                              type2->member.offset << 3,
936                                              elem_size << 3);
937                     }
938                 }
939               else if( type2->member.id == LF_ENUMERATE && fieldtype == DT_ENUM )
940                 {
941                   memset(symname, 0, sizeof(symname));
942                   memcpy(symname, type2->enumerate.name, type2->enumerate.namelen);
943                   
944                   if( type2->enumerate.value >= 0x8000 )
945                     {
946                       /*
947                        * This is a numeric leaf, I am too lazy to handle this right
948                        * now.
949                        */
950                       DEBUG_Printf(DBG_CHN_MESG, "Ignoring large numberic leaf.\n");
951                     }
952                   else
953                     {
954                       DEBUG_AddStructElement(typeptr, symname, NULL, 
955                                              type2->enumerate.value, 0);
956                     }
957                 }
958               else
959                 {
960                   /*
961                    * Something else I have never seen before.  Either wrong type of
962                    * object in the fieldlist, or some other problem which I wouldn't
963                    * really know how to handle until it came up.
964                    */
965                   DEBUG_Printf(DBG_CHN_MESG, "Unexpected entry in fieldlist\n");
966                   break;
967                 }
968
969
970               ptr2.c += ((type2->member.namelen + 9 + 3) & ~3);
971             }
972           break;
973         case LF_FIELDLIST_32:
974           /*
975            * This is where the basic list of fields is defined for
976            * structures and classes.
977            *
978            * First, we need to look ahead and see whether we are building
979            * a fieldlist for an enum or a struct.
980            */
981           ptr2.i = ptr.i + 1;
982           type2 = (union codeview_type *) ptr2.c;
983           if( type2->member32.id == LF_MEMBER_32 )
984             {
985               typeptr = DEBUG_NewDataType(DT_STRUCT, NULL);
986               fieldtype = DT_STRUCT;
987             }
988           else if( type2->member32.id == LF_ENUMERATE )
989             {
990               typeptr = DEBUG_NewDataType(DT_ENUM, NULL);
991               fieldtype = DT_ENUM;
992             }
993           else
994             {
995               break;
996             }
997
998           cv_defined_types[curr_type - 0x1000] = typeptr;
999           while( ptr2.c < (ptr.c + ((type->generic.len + 3) & ~3)) )
1000             {
1001               type2 = (union codeview_type *) ptr2.c;
1002               if( type2->member.id == LF_MEMBER_32 && fieldtype == DT_STRUCT )
1003                 {
1004                   memset(symname, 0, sizeof(symname));
1005                   memcpy(symname, type2->member32.name, type2->member32.namelen);
1006                   
1007                   subtype = DEBUG_GetCVType(type2->member32.type);
1008                   elem_size = 0;
1009                   if( subtype != NULL )
1010                     {
1011                       elem_size = DEBUG_GetObjectSize(subtype);
1012                     }
1013                   
1014                   if( type2->member32.offset >= 0x8000 )
1015                     {
1016                       /*
1017                        * This is a numeric leaf, I am too lazy to handle this right
1018                        * now.
1019                        */
1020                       DEBUG_Printf(DBG_CHN_MESG, "Ignoring large numberic leaf.\n");
1021                     }
1022                   else
1023                     {
1024                       DEBUG_AddStructElement(typeptr, symname, subtype, 
1025                                              type2->member32.offset << 3,
1026                                              elem_size << 3);
1027                     }
1028                 }
1029               else if( type2->member32.id == LF_ENUMERATE && fieldtype == DT_ENUM )
1030                 {
1031                   memset(symname, 0, sizeof(symname));
1032                   memcpy(symname, type2->enumerate.name, type2->enumerate.namelen);
1033                   
1034                   if( type2->enumerate.value >= 0x8000 )
1035                     {
1036                       /*
1037                        * This is a numeric leaf, I am too lazy to handle this right
1038                        * now.
1039                        */
1040                       DEBUG_Printf(DBG_CHN_MESG, "Ignoring large numberic leaf.\n");
1041                     }
1042                   else
1043                     {
1044                       DEBUG_AddStructElement(typeptr, symname, NULL, 
1045                                              type2->enumerate.value, 0);
1046                     }
1047                 }
1048               else
1049                 {
1050                   /*
1051                    * Something else I have never seen before.  Either wrong type of
1052                    * object in the fieldlist, or some other problem which I wouldn't
1053                    * really know how to handle until it came up.
1054                    */
1055                   DEBUG_Printf(DBG_CHN_MESG, "Unexpected entry in fieldlist\n");
1056                   break;
1057                 }
1058
1059
1060               ptr2.c += ((type2->member32.namelen + 9 + 3) & ~3);
1061             }
1062           break;
1063         case LF_STRUCTURE:
1064         case LF_CLASS:
1065           if( type->structure.structlen >= 0x8000 )
1066             {
1067               /*
1068                * This is a numeric leaf, I am too lazy to handle this right
1069                * now.
1070                */
1071               DEBUG_Printf(DBG_CHN_MESG, "Ignoring large numberic leaf.\n");
1072               break;
1073             }
1074           memset(symname, 0, sizeof(symname));
1075           memcpy(symname, type->structure.name, type->structure.namelen);
1076           if( strcmp(symname, "__unnamed") == 0 )
1077             {
1078               typeptr = DEBUG_NewDataType(DT_STRUCT, NULL);
1079             }
1080           else
1081             {
1082               typeptr = DEBUG_NewDataType(DT_STRUCT, symname);
1083             }
1084           cv_defined_types[curr_type - 0x1000] = typeptr;
1085
1086           /*
1087            * Now copy the relevant bits from the fieldlist that we specified.
1088            */
1089           subtype = DEBUG_GetCVType(type->structure.fieldlist);
1090
1091           if( subtype != NULL )
1092             {
1093               DEBUG_SetStructSize(typeptr, type->structure.structlen);
1094               DEBUG_CopyFieldlist(typeptr, subtype);
1095             }
1096           break;
1097         case LF_STRUCTURE_32:
1098         case LF_CLASS_32:
1099           if( type->structure32.structlen >= 0x8000 )
1100             {
1101               /*
1102                * This is a numeric leaf, I am too lazy to handle this right
1103                * now.
1104                */
1105               DEBUG_Printf(DBG_CHN_MESG, "Ignoring large numberic leaf.\n");
1106               break;
1107             }
1108           memset(symname, 0, sizeof(symname));
1109           memcpy(symname, type->structure32.name, type->structure32.namelen);
1110           if( strcmp(symname, "__unnamed") == 0 )
1111             {
1112               typeptr = DEBUG_NewDataType(DT_STRUCT, NULL);
1113             }
1114           else
1115             {
1116               typeptr = DEBUG_NewDataType(DT_STRUCT, symname);
1117             }
1118           cv_defined_types[curr_type - 0x1000] = typeptr;
1119
1120           /*
1121            * Now copy the relevant bits from the fieldlist that we specified.
1122            */
1123           subtype = DEBUG_GetCVType(type->structure32.fieldlist);
1124
1125           if( subtype != NULL )
1126             {
1127               DEBUG_SetStructSize(typeptr, type->structure32.structlen);
1128               DEBUG_CopyFieldlist(typeptr, subtype);
1129             }
1130           break;
1131         case LF_UNION:
1132           if( type->t_union.un_len >= 0x8000 )
1133             {
1134               /*
1135                * This is a numeric leaf, I am too lazy to handle this right
1136                * now.
1137                */
1138               DEBUG_Printf(DBG_CHN_MESG, "Ignoring large numberic leaf.\n");
1139               break;
1140             }
1141           memset(symname, 0, sizeof(symname));
1142           memcpy(symname, type->t_union.name, type->t_union.namelen);
1143
1144           if( strcmp(symname, "__unnamed") == 0 )
1145             {
1146               typeptr = DEBUG_NewDataType(DT_STRUCT, NULL);
1147             }
1148           else
1149             {
1150               typeptr = DEBUG_NewDataType(DT_STRUCT, symname);
1151             }
1152
1153           cv_defined_types[curr_type - 0x1000] = typeptr;
1154
1155           /*
1156            * Now copy the relevant bits from the fieldlist that we specified.
1157            */
1158           subtype = DEBUG_GetCVType(type->t_union.field);
1159
1160           if( subtype != NULL )
1161             {
1162               DEBUG_SetStructSize(typeptr, type->t_union.un_len);
1163               DEBUG_CopyFieldlist(typeptr, subtype);
1164             }
1165           break;
1166         case LF_UNION_32:
1167           if( type->t_union32.un_len >= 0x8000 )
1168             {
1169               /*
1170                * This is a numeric leaf, I am too lazy to handle this right
1171                * now.
1172                */
1173               DEBUG_Printf(DBG_CHN_MESG, "Ignoring large numberic leaf.\n");
1174               break;
1175             }
1176           memset(symname, 0, sizeof(symname));
1177           memcpy(symname, type->t_union32.name, type->t_union32.namelen);
1178
1179           if( strcmp(symname, "__unnamed") == 0 )
1180             {
1181               typeptr = DEBUG_NewDataType(DT_STRUCT, NULL);
1182             }
1183           else
1184             {
1185               typeptr = DEBUG_NewDataType(DT_STRUCT, symname);
1186             }
1187
1188           cv_defined_types[curr_type - 0x1000] = typeptr;
1189
1190           /*
1191            * Now copy the relevant bits from the fieldlist that we specified.
1192            */
1193           subtype = DEBUG_GetCVType(type->t_union32.field);
1194
1195           if( subtype != NULL )
1196             {
1197               DEBUG_SetStructSize(typeptr, type->t_union32.un_len);
1198               DEBUG_CopyFieldlist(typeptr, subtype);
1199             }
1200           break;
1201         case LF_BITFIELD:
1202           typeptr = DEBUG_NewDataType(DT_BITFIELD, NULL);
1203           cv_defined_types[curr_type - 0x1000] = typeptr;
1204           DEBUG_SetBitfieldParams(typeptr, type->bitfield.bitoff,
1205                                   type->bitfield.nbits, 
1206                                   DEBUG_GetCVType(type->bitfield.type));
1207           break;
1208         case LF_BITFIELD_32:
1209           typeptr = DEBUG_NewDataType(DT_BITFIELD, NULL);
1210           cv_defined_types[curr_type - 0x1000] = typeptr;
1211           DEBUG_SetBitfieldParams(typeptr, type->bitfield32.bitoff,
1212                                   type->bitfield32.nbits, 
1213                                   DEBUG_GetCVType(type->bitfield32.type));
1214           break;
1215         case LF_ENUM:
1216           memset(symname, 0, sizeof(symname));
1217           memcpy(symname, type->enumeration.name, type->enumeration.namelen);
1218           typeptr = DEBUG_NewDataType(DT_ENUM, symname);
1219           cv_defined_types[curr_type - 0x1000] = typeptr;
1220
1221           /*
1222            * Now copy the relevant bits from the fieldlist that we specified.
1223            */
1224           subtype = DEBUG_GetCVType(type->enumeration.field);
1225
1226           if( subtype != NULL )
1227             {
1228               DEBUG_CopyFieldlist(typeptr, subtype);
1229             }
1230           break;
1231         case LF_ENUM_32:
1232           memset(symname, 0, sizeof(symname));
1233           memcpy(symname, type->enumeration32.name, type->enumeration32.namelen);
1234           typeptr = DEBUG_NewDataType(DT_ENUM, symname);
1235           cv_defined_types[curr_type - 0x1000] = typeptr;
1236
1237           /*
1238            * Now copy the relevant bits from the fieldlist that we specified.
1239            */
1240           subtype = DEBUG_GetCVType(type->enumeration32.field);
1241
1242           if( subtype != NULL )
1243             {
1244               DEBUG_CopyFieldlist(typeptr, subtype);
1245             }
1246           break;
1247         default:
1248           break;
1249         }
1250       curr_type++;
1251       ptr.c += (type->generic.len + 3) & ~3;
1252     }
1253
1254   return TRUE;
1255 }
1256
1257 void
1258 DEBUG_InitCVDataTypes(void)
1259 {
1260   /*
1261    * These are the common builtin types that are used by VC++.
1262    */
1263   cv_basic_types[T_NOTYPE] = NULL;
1264   cv_basic_types[T_ABS] = NULL;
1265   cv_basic_types[T_VOID] = DEBUG_NewDataType(DT_BASIC, "void");
1266   cv_basic_types[T_CHAR] = DEBUG_NewDataType(DT_BASIC, "char");
1267   cv_basic_types[T_SHORT] = DEBUG_NewDataType(DT_BASIC, "short int");
1268   cv_basic_types[T_LONG] = DEBUG_NewDataType(DT_BASIC, "long int");
1269   cv_basic_types[T_QUAD] = DEBUG_NewDataType(DT_BASIC, "long long int");
1270   cv_basic_types[T_UCHAR] = DEBUG_NewDataType(DT_BASIC, "unsigned char");
1271   cv_basic_types[T_USHORT] = DEBUG_NewDataType(DT_BASIC, "short unsigned int");
1272   cv_basic_types[T_ULONG] = DEBUG_NewDataType(DT_BASIC, "long unsigned int");
1273   cv_basic_types[T_UQUAD] = DEBUG_NewDataType(DT_BASIC, "long long unsigned int");
1274   cv_basic_types[T_REAL32] = DEBUG_NewDataType(DT_BASIC, "float");
1275   cv_basic_types[T_REAL64] = DEBUG_NewDataType(DT_BASIC, "double");
1276   cv_basic_types[T_RCHAR] = DEBUG_NewDataType(DT_BASIC, "char");
1277   cv_basic_types[T_WCHAR] = DEBUG_NewDataType(DT_BASIC, "short");
1278   cv_basic_types[T_INT4] = DEBUG_NewDataType(DT_BASIC, "int");
1279   cv_basic_types[T_UINT4] = DEBUG_NewDataType(DT_BASIC, "unsigned int");
1280
1281   cv_basic_types[T_32PVOID] = DEBUG_FindOrMakePointerType(cv_basic_types[T_VOID]);
1282   cv_basic_types[T_32PCHAR] = DEBUG_FindOrMakePointerType(cv_basic_types[T_CHAR]);
1283   cv_basic_types[T_32PSHORT] = DEBUG_FindOrMakePointerType(cv_basic_types[T_SHORT]);
1284   cv_basic_types[T_32PLONG] = DEBUG_FindOrMakePointerType(cv_basic_types[T_LONG]);
1285   cv_basic_types[T_32PQUAD] = DEBUG_FindOrMakePointerType(cv_basic_types[T_QUAD]);
1286   cv_basic_types[T_32PUCHAR] = DEBUG_FindOrMakePointerType(cv_basic_types[T_UCHAR]);
1287   cv_basic_types[T_32PUSHORT] = DEBUG_FindOrMakePointerType(cv_basic_types[T_USHORT]);
1288   cv_basic_types[T_32PULONG] = DEBUG_FindOrMakePointerType(cv_basic_types[T_ULONG]);
1289   cv_basic_types[T_32PUQUAD] = DEBUG_FindOrMakePointerType(cv_basic_types[T_UQUAD]);
1290   cv_basic_types[T_32PREAL32] = DEBUG_FindOrMakePointerType(cv_basic_types[T_REAL32]);
1291   cv_basic_types[T_32PREAL64] = DEBUG_FindOrMakePointerType(cv_basic_types[T_REAL64]);
1292   cv_basic_types[T_32PRCHAR] = DEBUG_FindOrMakePointerType(cv_basic_types[T_RCHAR]);
1293   cv_basic_types[T_32PWCHAR] = DEBUG_FindOrMakePointerType(cv_basic_types[T_WCHAR]);
1294   cv_basic_types[T_32PINT4] = DEBUG_FindOrMakePointerType(cv_basic_types[T_INT4]);
1295   cv_basic_types[T_32PUINT4] = DEBUG_FindOrMakePointerType(cv_basic_types[T_UINT4]);
1296 }
1297
1298 /*
1299  * In this function, we keep track of deferred debugging information
1300  * that we may need later if we were to need to use the internal debugger.
1301  * We don't fully process it here for performance reasons.
1302  */
1303 int
1304 DEBUG_RegisterMSCDebugInfo(DBG_MODULE* module, HANDLE hFile, void* _nth, unsigned long nth_ofs)
1305 {
1306   int                     has_codeview = FALSE;
1307   int                     rtn = FALSE;
1308   IMAGE_DEBUG_DIRECTORY   dbg;
1309   u_long                  v_addr, size, orig_size;
1310   PIMAGE_NT_HEADERS       nth = (PIMAGE_NT_HEADERS)_nth;
1311
1312   orig_size = nth->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].Size;
1313   if (orig_size) {
1314     v_addr = nth->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress;
1315     for(size = orig_size; size >= sizeof(dbg); size -= sizeof(dbg))
1316     {
1317       if (!DEBUG_READ_MEM_VERBOSE((void*)((char *) module->load_addr + v_addr), &dbg, sizeof(dbg))) continue;
1318
1319       switch(dbg.Type)
1320         {
1321         case IMAGE_DEBUG_TYPE_CODEVIEW:
1322         case IMAGE_DEBUG_TYPE_MISC:
1323           has_codeview = TRUE;
1324           break;
1325         }
1326       v_addr += sizeof(dbg);
1327     }
1328
1329     v_addr = nth->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress;
1330     for(size = orig_size; size >= sizeof(dbg); size -= sizeof(dbg))
1331     {
1332       if (!DEBUG_READ_MEM_VERBOSE((void*)((char *)module->load_addr + v_addr), &dbg, sizeof(dbg))) continue;
1333
1334       switch(dbg.Type)
1335         {
1336         case IMAGE_DEBUG_TYPE_COFF:
1337           /*
1338            * If we have both codeview and COFF debug info, ignore the
1339            * coff debug info as it would just confuse us, and it is 
1340            * less complete.
1341            *
1342            * FIXME - this is broken - if we cannot find the PDB file, then
1343            * we end up with no debugging info at all.  In this case, we
1344            * should use the COFF info as a backup.
1345            */
1346           if( has_codeview )
1347             {
1348               break;
1349             }
1350         case IMAGE_DEBUG_TYPE_CODEVIEW:
1351         case IMAGE_DEBUG_TYPE_MISC:
1352           /*
1353            * This is usually an indirection to a .DBG file.
1354            * This is similar to (but a slightly older format) from the
1355            * PDB file.
1356            *
1357            * First check to see if the image was 'stripped'.  If so, it
1358            * means that this entry points to a .DBG file.  Otherwise,
1359            * it just points to itself, and we can ignore this.
1360            */
1361
1362           if(   (dbg.Type != IMAGE_DEBUG_TYPE_MISC) ||
1363                 (nth->FileHeader.Characteristics & IMAGE_FILE_DEBUG_STRIPPED) != 0 )
1364             {
1365                 /*
1366                  * Read the important bits.  What we do after this depends
1367                  * upon the type, but this is always enough so we are able
1368                  * to proceed if we know what we need to do next.
1369                  */                  
1370                 /* basically, the PE loader maps all sections (data, resources...), but doesn't map
1371                  * the DataDirectory array's content. One its entry contains the *beloved*
1372                  * debug information. (Note the DataDirectory is mapped, not its content)
1373                  */
1374                 HANDLE  hMap;
1375                 char*   dbg_info;
1376
1377                 DEBUG_Printf(DBG_CHN_TRACE, "PE debugging info at %ld<%ld>\n", dbg.PointerToRawData, dbg.SizeOfData);
1378                 dbg_info = DEBUG_MapDebugInfoFile(NULL, dbg.PointerToRawData, dbg.SizeOfData,
1379                                                   &hFile, &hMap);
1380
1381                 if (dbg_info != NULL && 
1382                     (module->extra_info = DBG_alloc(sizeof(MSC_DBG_INFO))) != NULL) {
1383                    MSC_INFO(module)->dbg_info = dbg_info;
1384                    MSC_INFO(module)->dbg_size = dbg.SizeOfData;
1385                    MSC_INFO(module)->dbgdir = dbg;
1386                    MSC_INFO(module)->sect_ofs = nth_ofs + OFFSET_OF(IMAGE_NT_HEADERS, OptionalHeader) +
1387                       nth->FileHeader.SizeOfOptionalHeader;
1388                    MSC_INFO(module)->nsect = nth->FileHeader.NumberOfSections;
1389                    DEBUG_ProcessMSCDebugInfo(module);
1390                    DBG_free(MSC_INFO(module));
1391                    MSC_INFO(module) = NULL;
1392                 }
1393                 DEBUG_UnmapDebugInfoFile(0, hMap, dbg_info);
1394             }
1395           break;
1396 #if 0
1397         default:
1398 #endif
1399         }
1400       v_addr += sizeof(dbg);
1401     }
1402     DEBUG_CurrProcess->next_index++;
1403   }
1404
1405   return rtn;
1406 }
1407
1408 /* look for stabs information in PE header (it's how mingw compiler provides its
1409  * debugging information), and also wine PE <-> ELF linking thru .wsolnk sections
1410  */
1411 int DEBUG_RegisterStabsDebugInfo(DBG_MODULE* module, HANDLE hFile, void* _nth, 
1412                                  unsigned long nth_ofs)
1413 {
1414     IMAGE_SECTION_HEADER        pe_seg;
1415     unsigned long               pe_seg_ofs;
1416     int                         i, stabsize = 0, stabstrsize = 0, xcnlnksize = 0;
1417     unsigned int                stabs = 0, stabstr = 0, xcnlnk = 0;
1418     PIMAGE_NT_HEADERS           nth = (PIMAGE_NT_HEADERS)_nth;
1419
1420     pe_seg_ofs = nth_ofs + OFFSET_OF(IMAGE_NT_HEADERS, OptionalHeader) +
1421         nth->FileHeader.SizeOfOptionalHeader;
1422
1423     for (i = 0; i < nth->FileHeader.NumberOfSections; i++, pe_seg_ofs += sizeof(pe_seg)) {
1424       if (!DEBUG_READ_MEM_VERBOSE((void*)((char *)module->load_addr + pe_seg_ofs), 
1425                                   &pe_seg, sizeof(pe_seg)))
1426           continue;
1427
1428       if (!strcasecmp(pe_seg.Name, ".stab")) {
1429         stabs = pe_seg.VirtualAddress;
1430         stabsize = pe_seg.SizeOfRawData;
1431       } else if (!strncasecmp(pe_seg.Name, ".stabstr", 8)) {
1432         stabstr = pe_seg.VirtualAddress;
1433         stabstrsize = pe_seg.SizeOfRawData;
1434       } else if (!strncasecmp(pe_seg.Name, ".xcnlnk", 7)) {
1435         xcnlnk = pe_seg.VirtualAddress;
1436         xcnlnksize = pe_seg.SizeOfRawData;
1437       }
1438     }
1439
1440     if (stabstrsize && stabsize) {
1441        char*    s1 = DBG_alloc(stabsize+stabstrsize);
1442
1443        if (s1) {
1444           if (DEBUG_READ_MEM_VERBOSE((char*)module->load_addr + stabs, s1, stabsize) &&
1445               DEBUG_READ_MEM_VERBOSE((char*)module->load_addr + stabstr, 
1446                                      s1 + stabsize, stabstrsize)) {
1447              DEBUG_ParseStabs(s1, 0, 0, stabsize, stabsize, stabstrsize);
1448           } else {
1449              DEBUG_Printf(DBG_CHN_MESG, "couldn't read data block\n");
1450           }
1451           DBG_free(s1);
1452        } else {
1453           DEBUG_Printf(DBG_CHN_MESG, "couldn't alloc %d bytes\n", 
1454                        stabsize + stabstrsize);
1455        }
1456     }
1457     if (xcnlnksize) {
1458        DWORD    addr;
1459        char     bufstr[256];
1460
1461        if (DEBUG_READ_MEM_VERBOSE((char*)module->load_addr + xcnlnk, &addr, 
1462                                   sizeof(addr)) &&
1463            DEBUG_READ_MEM_VERBOSE((char*)addr, bufstr, sizeof(bufstr))) {
1464           bufstr[sizeof(bufstr) - 1] = 0;
1465           DEBUG_Printf(DBG_CHN_TRACE, "Got xcnlnk: argv0 '%s'\n", bufstr);
1466           DEBUG_ReadExecutableDbgInfo(bufstr);
1467        }
1468     }
1469     return TRUE;
1470 }
1471
1472 /*
1473  * Process COFF debugging information embedded in a Win32 application.
1474  *
1475  */
1476 static
1477 int
1478 DEBUG_ProcessCoff(DBG_MODULE* module)
1479 {
1480   struct CoffAuxSection * aux;
1481   struct CoffDebug   * coff;
1482   struct CoffFiles   * coff_files = NULL;
1483   struct CoffLinenum * coff_linetab;
1484   char               * coff_strtab;
1485   struct CoffSymbol  * coff_sym;
1486   struct CoffSymbol  * coff_symbol;
1487   struct CoffFiles   * curr_file = NULL;
1488   int                  i;
1489   int                  j;
1490   int                  k;
1491   struct CoffLinenum * linepnt;
1492   int                  linetab_indx;
1493   char                 namebuff[9];
1494   char               * nampnt;
1495   int                  naux;
1496   DBG_VALUE            new_value;
1497   int                  nfiles = 0;
1498   int                  nfiles_alloc = 0;
1499   struct CoffFiles     orig_file;
1500   int                  rtn = FALSE;
1501   char               * this_file = NULL;
1502
1503   coff = (struct CoffDebug *) MSC_INFO(module)->dbg_info;
1504
1505   coff_symbol = (struct CoffSymbol *) ((unsigned int) coff + coff->SymbolOffset);
1506   coff_linetab = (struct CoffLinenum *) ((unsigned int) coff + coff->LinenumberOffset);
1507   coff_strtab = (char *) ((unsigned int) coff_symbol + 18*coff->N_Sym);
1508
1509   linetab_indx = 0;
1510
1511   new_value.cookie = DV_TARGET;
1512   new_value.type = NULL;
1513
1514   for(i=0; i < coff->N_Sym; i++ )
1515     {
1516       /*
1517        * We do this because some compilers (i.e. gcc) incorrectly
1518        * pad the structure up to a 4 byte boundary.  The structure
1519        * is really only 18 bytes long, so we have to manually make sure
1520        * we get it right.
1521        *
1522        * FIXME - there must be a way to have autoconf figure out the
1523        * correct compiler option for this.  If it is always gcc, that
1524        * makes life simpler, but I don't want to force this.
1525        */
1526       coff_sym = (struct CoffSymbol *) ((unsigned int) coff_symbol + 18*i);
1527       naux = coff_sym->NumberOfAuxSymbols;
1528
1529       if( coff_sym->StorageClass == IMAGE_SYM_CLASS_FILE )
1530         {
1531           if( nfiles + 1 >= nfiles_alloc )
1532             {
1533               nfiles_alloc += 10;
1534               coff_files = (struct CoffFiles *) DBG_realloc(coff_files,
1535                         nfiles_alloc * sizeof(struct CoffFiles));
1536             }
1537           curr_file = coff_files + nfiles;
1538           nfiles++;
1539           curr_file->startaddr = 0xffffffff;
1540           curr_file->endaddr   = 0;
1541           curr_file->filename =  ((char *) coff_sym) + 18;
1542           curr_file->linetab_offset = -1;
1543           curr_file->linecnt = 0;
1544           curr_file->entries = NULL;
1545           curr_file->neps = curr_file->neps_alloc = 0;
1546           DEBUG_Printf(DBG_CHN_TRACE,"New file %s\n", curr_file->filename);
1547           i += naux;
1548           continue;
1549         }
1550
1551       /*
1552        * This guy marks the size and location of the text section
1553        * for the current file.  We need to keep track of this so
1554        * we can figure out what file the different global functions
1555        * go with.
1556        */
1557       if(    (coff_sym->StorageClass == IMAGE_SYM_CLASS_STATIC)
1558           && (naux != 0)
1559           && (coff_sym->Type == 0)
1560           && (coff_sym->SectionNumber == 1) )
1561         {
1562           aux = (struct CoffAuxSection *) ((unsigned int) coff_sym + 18);
1563
1564           if( curr_file->linetab_offset != -1 )
1565             {
1566 #if 0
1567               DEBUG_Printf(DBG_CHN_TRACE, "Duplicating sect from %s: %x %x %x %d %d\n",
1568                            curr_file->filename,
1569                            aux->Length,
1570                            aux->NumberOfRelocations,
1571                            aux->NumberOfLinenumbers,
1572                            aux->Number,
1573                            aux->Selection);
1574               DEBUG_Printf(DBG_CHN_TRACE, "More sect %d %x %d %d %d\n", 
1575                            coff_sym->SectionNumber,
1576                            coff_sym->Value,
1577                            coff_sym->Type,
1578                            coff_sym->StorageClass,
1579                            coff_sym->NumberOfAuxSymbols);
1580 #endif
1581
1582               /*
1583                * Save this so we can copy bits from it.
1584                */
1585               orig_file = *curr_file;
1586
1587               /*
1588                * Duplicate the file entry.  We have no way to describe
1589                * multiple text sections in our current way of handling things.
1590                */
1591               if( nfiles + 1 >= nfiles_alloc )
1592                 {
1593                   nfiles_alloc += 10;
1594                   coff_files = (struct CoffFiles *) DBG_realloc(coff_files,
1595                                                                 nfiles_alloc * sizeof(struct CoffFiles));
1596                 }
1597               curr_file = coff_files + nfiles;
1598               nfiles++;
1599               curr_file->startaddr = 0xffffffff;
1600               curr_file->endaddr   = 0;
1601               curr_file->filename = orig_file.filename;
1602               curr_file->linetab_offset = -1;
1603               curr_file->linecnt = 0;
1604               curr_file->entries = NULL;
1605               curr_file->neps = curr_file->neps_alloc = 0;
1606             }
1607 #if 0
1608           else
1609             {
1610               DEBUG_Printf(DBG_CHN_TRACE, "New text sect from %s: %x %x %x %d %d\n",
1611                            curr_file->filename,
1612                            aux->Length,
1613                            aux->NumberOfRelocations,
1614                            aux->NumberOfLinenumbers,
1615                            aux->Number,
1616                            aux->Selection);
1617             }
1618 #endif
1619
1620           if( curr_file->startaddr > coff_sym->Value )
1621             {
1622               curr_file->startaddr = coff_sym->Value;
1623             }
1624           
1625           if( curr_file->startaddr > coff_sym->Value )
1626             {
1627               curr_file->startaddr = coff_sym->Value;
1628             }
1629           
1630           if( curr_file->endaddr < coff_sym->Value + aux->Length )
1631             {
1632               curr_file->endaddr = coff_sym->Value + aux->Length;
1633             }
1634           
1635           curr_file->linetab_offset = linetab_indx;
1636           curr_file->linecnt = aux->NumberOfLinenumbers;
1637           linetab_indx += aux->NumberOfLinenumbers;
1638           i += naux;
1639           continue;
1640         }
1641
1642       if(    (coff_sym->StorageClass == IMAGE_SYM_CLASS_STATIC)
1643           && (naux == 0)
1644           && (coff_sym->SectionNumber == 1) )
1645         {
1646           /*
1647            * This is a normal static function when naux == 0.
1648            * Just register it.  The current file is the correct
1649            * one in this instance.
1650            */
1651           if( coff_sym->N.Name.NotLong )
1652             {
1653               memcpy(namebuff, coff_sym->N.ShortName, 8);
1654               namebuff[8] = '\0';
1655               nampnt = &namebuff[0];
1656             }
1657           else
1658             {
1659               nampnt = coff_strtab + coff_sym->N.Name.StrTaboff;
1660             }
1661
1662           if( nampnt[0] == '_' )
1663             {
1664               nampnt++;
1665             }
1666
1667           new_value.addr.seg = 0;
1668           new_value.addr.off = (int) ((char *)module->load_addr + coff_sym->Value);
1669
1670           if( curr_file->neps + 1 >= curr_file->neps_alloc )
1671             {
1672               curr_file->neps_alloc += 10;
1673               curr_file->entries = (struct name_hash **) 
1674                 DBG_realloc(curr_file->entries, 
1675                          curr_file->neps_alloc * sizeof(struct name_hash *));
1676             }
1677 #if 0
1678           DEBUG_Printf(DBG_CHN_TRACE,"\tAdding static symbol %s\n", nampnt);
1679 #endif
1680           curr_file->entries[curr_file->neps++] =
1681              DEBUG_AddSymbol( nampnt, &new_value, this_file, SYM_WIN32 );
1682           i += naux;
1683           continue;
1684         }
1685
1686       if(    (coff_sym->StorageClass == IMAGE_SYM_CLASS_EXTERNAL)
1687           && ISFCN(coff_sym->Type)
1688           && (coff_sym->SectionNumber > 0) )
1689         {
1690           if( coff_sym->N.Name.NotLong )
1691             {
1692               memcpy(namebuff, coff_sym->N.ShortName, 8);
1693               namebuff[8] = '\0';
1694               nampnt = &namebuff[0];
1695             }
1696           else
1697             {
1698               nampnt = coff_strtab + coff_sym->N.Name.StrTaboff;
1699             }
1700
1701
1702           if( nampnt[0] == '_' )
1703             {
1704               nampnt++;
1705             }
1706
1707           new_value.addr.seg = 0;
1708           new_value.addr.off = (int) ((char *)module->load_addr + coff_sym->Value);
1709
1710 #if 0
1711           DEBUG_Printf(DBG_CHN_TRACE, "%d: %x %s\n", i, new_value.addr.off, nampnt);
1712
1713           DEBUG_Printf(DBG_CHN_TRACE,"\tAdding global symbol %s\n", nampnt);
1714 #endif
1715
1716           /*
1717            * Now we need to figure out which file this guy belongs to.
1718            */
1719           this_file = NULL;
1720           for(j=0; j < nfiles; j++)
1721             {
1722               if( coff_files[j].startaddr <= coff_sym->Value
1723                   && coff_files[j].endaddr > coff_sym->Value )
1724                 {
1725                   this_file = coff_files[j].filename;
1726                   break;
1727                 }
1728             }
1729           if( coff_files[j].neps + 1 >= coff_files[j].neps_alloc )
1730             {
1731               coff_files[j].neps_alloc += 10;
1732               coff_files[j].entries = (struct name_hash **) 
1733                 DBG_realloc(coff_files[j].entries, 
1734                          coff_files[j].neps_alloc * sizeof(struct name_hash *));
1735             }
1736           coff_files[j].entries[coff_files[j].neps++] =
1737             DEBUG_AddSymbol( nampnt, &new_value, this_file, SYM_WIN32 );
1738           i += naux;
1739           continue;
1740         }
1741
1742       if(    (coff_sym->StorageClass == IMAGE_SYM_CLASS_EXTERNAL)
1743           && (coff_sym->SectionNumber > 0) )
1744         {
1745           /*
1746            * Similar to above, but for the case of data symbols.
1747            * These aren't treated as entrypoints.
1748            */
1749           if( coff_sym->N.Name.NotLong )
1750             {
1751               memcpy(namebuff, coff_sym->N.ShortName, 8);
1752               namebuff[8] = '\0';
1753               nampnt = &namebuff[0];
1754             }
1755           else
1756             {
1757               nampnt = coff_strtab + coff_sym->N.Name.StrTaboff;
1758             }
1759
1760
1761           if( nampnt[0] == '_' )
1762             {
1763               nampnt++;
1764             }
1765
1766           new_value.addr.seg = 0;
1767           new_value.addr.off = (int) ((char *)module->load_addr + coff_sym->Value);
1768
1769 #if 0
1770           DEBUG_Printf(DBG_CHN_TRACE, "%d: %x %s\n", i, new_value.addr.off, nampnt);
1771
1772           DEBUG_Printf(DBG_CHN_TRACE,"\tAdding global data symbol %s\n", nampnt);
1773 #endif
1774
1775           /*
1776            * Now we need to figure out which file this guy belongs to.
1777            */
1778           DEBUG_AddSymbol( nampnt, &new_value, NULL, SYM_WIN32 );
1779           i += naux;
1780           continue;
1781         }
1782           
1783       if(    (coff_sym->StorageClass == IMAGE_SYM_CLASS_STATIC)
1784           && (naux == 0) )
1785         {
1786           /*
1787            * Ignore these.  They don't have anything to do with
1788            * reality.
1789            */
1790           i += naux;
1791           continue;
1792         }
1793
1794 #if 0
1795       DEBUG_Printf(DBG_CHN_TRACE,"Skipping unknown entry %d %d %d\n", coff_sym->StorageClass, 
1796                    coff_sym->SectionNumber, naux);
1797 #endif
1798
1799       /*
1800        * For now, skip past the aux entries.
1801        */
1802       i += naux;
1803       
1804     }
1805     
1806   /*
1807    * OK, we now should have a list of files, and we should have a list
1808    * of entrypoints.  We need to sort the entrypoints so that we are
1809    * able to tie the line numbers with the given functions within the
1810    * file.
1811    */
1812   if( coff_files != NULL )
1813     {
1814       for(j=0; j < nfiles; j++)
1815         {
1816           if( coff_files[j].entries != NULL )
1817             {
1818               qsort(coff_files[j].entries, coff_files[j].neps,
1819                     sizeof(struct name_hash *), DEBUG_cmp_sym);
1820             }
1821         }
1822
1823       /*
1824        * Now pick apart the line number tables, and attach the entries
1825        * to the given functions.
1826        */
1827       for(j=0; j < nfiles; j++)
1828         {
1829           i = 0;
1830           if( coff_files[j].neps != 0 )
1831             for(k=0; k < coff_files[j].linecnt; k++)
1832             {
1833               /*
1834                * Another monstrosity caused by the fact that we are using
1835                * a 6 byte structure, and gcc wants to pad structures to 4 byte
1836                * boundaries.  Otherwise we could just index into an array.
1837                */
1838               linepnt = (struct CoffLinenum *) 
1839                 ((unsigned int) coff_linetab + 
1840                  6*(coff_files[j].linetab_offset + k));
1841               /*
1842                * If we have spilled onto the next entrypoint, then
1843                * bump the counter..
1844                */
1845               while(TRUE)
1846                 {
1847                   if (i+1 >= coff_files[j].neps) break;
1848                   DEBUG_GetSymbolAddr(coff_files[j].entries[i+1], &new_value.addr);
1849                   if( (((unsigned int)module->load_addr +
1850                         linepnt->VirtualAddr) >= new_value.addr.off) )
1851                   {
1852                       i++;
1853                   } else break;
1854                 }
1855
1856               /*
1857                * Add the line number.  This is always relative to the
1858                * start of the function, so we need to subtract that offset
1859                * first.
1860                */
1861               DEBUG_GetSymbolAddr(coff_files[j].entries[i], &new_value.addr);
1862               DEBUG_AddLineNumber(coff_files[j].entries[i], 
1863                                   linepnt->Linenum,
1864                                   (unsigned int) module->load_addr 
1865                                   + linepnt->VirtualAddr 
1866                                   - new_value.addr.off);
1867             }
1868         }
1869     }
1870
1871   rtn = TRUE;
1872
1873   if( coff_files != NULL )
1874     {
1875       for(j=0; j < nfiles; j++)
1876         {
1877           if( coff_files[j].entries != NULL )
1878             {
1879               DBG_free(coff_files[j].entries);
1880             }
1881         }
1882       DBG_free(coff_files);
1883     }
1884
1885   return (rtn);
1886
1887 }
1888
1889 /*
1890  * Process a codeview line number table.  Digestify the thing so that
1891  * we can easily reference the thing when we process the rest of
1892  * the information.
1893  */
1894 static struct codeview_linetab_hdr *
1895 DEBUG_SnarfLinetab(char                      * linetab,
1896                    int                         size)
1897 {
1898   int                             file_segcount;
1899   char                            filename[PATH_MAX];
1900   unsigned int                  * filetab;
1901   char                          * fn;
1902   int                             i;
1903   int                             k;
1904   struct codeview_linetab_hdr   * lt_hdr;
1905   unsigned int                  * lt_ptr;
1906   int                             nfile;
1907   int                             nseg;
1908   union any_size                  pnt;
1909   union any_size                  pnt2;
1910   struct startend               * start;
1911   int                             this_seg;
1912
1913   /*
1914    * Now get the important bits.
1915    */
1916   pnt.c = linetab;
1917   nfile = *pnt.s++;
1918   nseg = *pnt.s++;
1919
1920   filetab = (unsigned int *) pnt.c;
1921
1922   /*
1923    * Now count up the number of segments in the file.
1924    */
1925   nseg = 0;
1926   for(i=0; i<nfile; i++)
1927     {
1928       pnt2.c = linetab + filetab[i];
1929       nseg += *pnt2.s;
1930     }
1931
1932   /*
1933    * Next allocate the header we will be returning.
1934    * There is one header for each segment, so that we can reach in
1935    * and pull bits as required.
1936    */
1937   lt_hdr = (struct codeview_linetab_hdr *) 
1938     DBG_alloc((nseg + 1) * sizeof(*lt_hdr));
1939   if( lt_hdr == NULL )
1940     {
1941       goto leave;
1942     }
1943
1944   memset(lt_hdr, 0, sizeof(*lt_hdr) * (nseg+1));
1945
1946   /*
1947    * Now fill the header we will be returning, one for each segment.
1948    * Note that this will basically just contain pointers into the existing
1949    * line table, and we do not actually copy any additional information
1950    * or allocate any additional memory.
1951    */
1952
1953   this_seg = 0;
1954   for(i=0; i<nfile; i++)
1955     {
1956       /*
1957        * Get the pointer into the segment information.
1958        */
1959       pnt2.c = linetab + filetab[i];
1960       file_segcount = *pnt2.s;
1961
1962       pnt2.ui++;
1963       lt_ptr = (unsigned int *) pnt2.c;
1964       start = (struct startend *) (lt_ptr + file_segcount);
1965
1966       /*
1967        * Now snarf the filename for all of the segments for this file.
1968        */
1969       fn = (unsigned char *) (start + file_segcount);
1970       memset(filename, 0, sizeof(filename));
1971       memcpy(filename, fn + 1, *fn);
1972       fn = DBG_strdup(filename);
1973
1974       for(k = 0; k < file_segcount; k++, this_seg++)
1975         {
1976           pnt2.c = linetab + lt_ptr[k];
1977           lt_hdr[this_seg].start      = start[k].start;
1978           lt_hdr[this_seg].end        = start[k].end;
1979           lt_hdr[this_seg].sourcefile = fn;
1980           lt_hdr[this_seg].segno      = *pnt2.s++;
1981           lt_hdr[this_seg].nline      = *pnt2.s++;
1982           lt_hdr[this_seg].offtab     =  pnt2.ui;
1983           lt_hdr[this_seg].linetab    = (unsigned short *) 
1984             (pnt2.ui + lt_hdr[this_seg].nline);
1985         }
1986     }
1987
1988 leave:
1989
1990   return lt_hdr;
1991
1992 }
1993
1994 static int
1995 DEBUG_SnarfCodeView(      DBG_MODULE                  * module,
1996                           char                        * cv_data,
1997                           int                           size,
1998                           struct codeview_linetab_hdr * linetab)
1999 {
2000   struct name_hash      * curr_func = NULL;
2001   struct wine_locals    * curr_sym = NULL;
2002   int                     i;
2003   int                     j;
2004   int                     len;
2005   DBG_VALUE               new_value;
2006   int                     nsect;
2007   union any_size          ptr;
2008   IMAGE_SECTION_HEADER  * sectp;
2009   union codeview_symbol * sym;
2010   char                    symname[PATH_MAX];
2011   struct name_hash      * thunk_sym = NULL;
2012
2013   ptr.c = cv_data;
2014   nsect = MSC_INFO(module)->nsect;
2015   sectp = DBG_alloc(sizeof(*sectp) * nsect);
2016   if (!sectp || 
2017       !DEBUG_READ_MEM_VERBOSE((char *)module->load_addr + MSC_INFO(module)->sect_ofs, 
2018                               sectp, sizeof(*sectp) * nsect))
2019      return FALSE;
2020
2021   /*
2022    * Loop over the different types of records and whenever we
2023    * find something we are interested in, record it and move on.
2024    */
2025   while( ptr.c - cv_data < size )
2026     {
2027       sym = (union codeview_symbol *) ptr.c;
2028
2029       if( sym->generic.len - sizeof(int) == (ptr.c - cv_data) )
2030         {
2031           /*
2032            * This happens when we have indirect symbols that VC++ 4.2
2033            * sometimes uses when there isn't a line number table.
2034            * We ignore it - we will process and enter all of the
2035            * symbols in the global symbol table anyways, so there
2036            * isn't much point in keeping track of all of this crap.
2037            */
2038           break;
2039         }
2040
2041       memset(symname, 0, sizeof(symname));
2042       switch(sym->generic.id)
2043         {
2044         case S_GDATA:
2045         case S_LDATA:
2046         case S_PUB:
2047           /*
2048            * First, a couple of sanity checks.
2049            */
2050           if( sym->data.namelen == 0 )
2051             {
2052               break;
2053             }
2054
2055           if( sym->data.seg == 0 || sym->data.seg > nsect )
2056             {
2057               break;
2058             }
2059
2060           /*
2061            * Global and local data symbols.  We don't associate these
2062            * with any given source file.
2063            */
2064
2065           memcpy(symname, sym->data.name, sym->data.namelen);
2066           new_value.addr.seg = 0;
2067           new_value.type = DEBUG_GetCVType(sym->data.symtype);
2068           new_value.addr.off = (unsigned int) module->load_addr + 
2069              sectp[sym->data.seg - 1].VirtualAddress + 
2070              sym->data.offset;
2071           new_value.cookie = DV_TARGET;
2072           DEBUG_AddSymbol( symname, &new_value, NULL, SYM_WIN32 | SYM_DATA );
2073           break;
2074         case S_GDATA_32:
2075         case S_LDATA_32:
2076         case S_PUB_32:
2077           /*
2078            * First, a couple of sanity checks.
2079            */
2080           if( sym->data32.namelen == 0 )
2081             {
2082               break;
2083             }
2084
2085           if( sym->data32.seg == 0 || sym->data32.seg > nsect )
2086             {
2087               break;
2088             }
2089
2090           /*
2091            * Global and local data symbols.  We don't associate these
2092            * with any given source file.
2093            */
2094
2095           memcpy(symname, sym->data32.name, sym->data32.namelen);
2096           new_value.addr.seg = 0;
2097           new_value.type = DEBUG_GetCVType(sym->data32.symtype);
2098           new_value.addr.off = (unsigned int) module->load_addr + 
2099              sectp[sym->data32.seg - 1].VirtualAddress + 
2100              sym->data32.offset;
2101           new_value.cookie = DV_TARGET;
2102           DEBUG_AddSymbol( symname, &new_value, NULL, SYM_WIN32 | SYM_DATA );
2103           break;
2104         case S_THUNK:
2105           /*
2106            * Sort of like a global function, but it just points
2107            * to a thunk, which is a stupid name for what amounts to
2108            * a PLT slot in the normal jargon that everyone else uses.
2109            */
2110           memcpy(symname, sym->thunk.name, sym->thunk.namelen);
2111           new_value.addr.seg = 0;
2112           new_value.type = NULL;
2113           new_value.addr.off = (unsigned int) module->load_addr + 
2114              sectp[sym->thunk.segment - 1].VirtualAddress + 
2115              sym->thunk.offset;
2116           new_value.cookie = DV_TARGET;
2117           thunk_sym = DEBUG_AddSymbol( symname, &new_value, NULL, 
2118                                        SYM_WIN32 | SYM_FUNC);
2119           DEBUG_SetSymbolSize(thunk_sym, sym->thunk.thunk_len);
2120           break;
2121         case S_GPROC:
2122         case S_LPROC:
2123           /*
2124            * Global and static functions.
2125            */
2126           memcpy(symname, sym->proc.name, sym->proc.namelen);
2127           new_value.addr.seg = 0;
2128           new_value.type = DEBUG_GetCVType(sym->proc.proctype);
2129           new_value.addr.off = (unsigned int) module->load_addr + 
2130              sectp[sym->proc.segment - 1].VirtualAddress + 
2131              sym->proc.offset;
2132           new_value.cookie = DV_TARGET;
2133           /*
2134            * See if we can find a segment that this goes with.  If so,
2135            * it means that we also may have line number information
2136            * for this function.
2137            */
2138           for(i=0; linetab && linetab[i].linetab != NULL; i++)
2139             {
2140               if(     ((unsigned int) module->load_addr 
2141                        + sectp[linetab[i].segno - 1].VirtualAddress 
2142                        + linetab[i].start <= new_value.addr.off)
2143                   &&  ((unsigned int) module->load_addr 
2144                        + sectp[linetab[i].segno - 1].VirtualAddress 
2145                        + linetab[i].end > new_value.addr.off) )
2146                 {
2147                   break;
2148                 }
2149             }
2150
2151           DEBUG_Normalize(curr_func);
2152           if( !linetab || linetab[i].linetab == NULL )
2153             {
2154               curr_func = DEBUG_AddSymbol( symname, &new_value, NULL,
2155                                            SYM_WIN32 | SYM_FUNC);
2156             }
2157           else
2158             {
2159               /*
2160                * First, create the entry.  Then dig through the linetab
2161                * and add whatever line numbers are appropriate for this
2162                * function.
2163                */
2164               curr_func = DEBUG_AddSymbol( symname, &new_value, 
2165                                            linetab[i].sourcefile,
2166                                            SYM_WIN32 | SYM_FUNC);
2167               for(j=0; j < linetab[i].nline; j++)
2168                 {
2169                   if( linetab[i].offtab[j] >= sym->proc.offset 
2170                       && linetab[i].offtab[j] < sym->proc.offset 
2171                       + sym->proc.proc_len )
2172                     {
2173                       DEBUG_AddLineNumber(curr_func, linetab[i].linetab[j],
2174                                           linetab[i].offtab[j] - sym->proc.offset);
2175                     }
2176                 }
2177
2178             }
2179
2180           /*
2181            * Add information about where we should set breakpoints
2182            * in this function.
2183            */
2184           DEBUG_SetSymbolBPOff(curr_func, sym->proc.debug_start);
2185           DEBUG_SetSymbolSize(curr_func, sym->proc.proc_len);
2186           break;
2187         case S_GPROC_32:
2188         case S_LPROC_32:
2189           /*
2190            * Global and static functions.
2191            */
2192           memcpy(symname, sym->proc32.name, sym->proc32.namelen);
2193           new_value.addr.seg = 0;
2194           new_value.type = DEBUG_GetCVType(sym->proc32.proctype);
2195           new_value.addr.off = (unsigned int) module->load_addr + 
2196             sectp[sym->proc32.segment - 1].VirtualAddress + 
2197             sym->proc32.offset;
2198           new_value.cookie = DV_TARGET;
2199           /*
2200            * See if we can find a segment that this goes with.  If so,
2201            * it means that we also may have line number information
2202            * for this function.
2203            */
2204           for(i=0; linetab && linetab[i].linetab != NULL; i++)
2205             {
2206               if(     ((unsigned int) module->load_addr 
2207                        + sectp[linetab[i].segno - 1].VirtualAddress 
2208                        + linetab[i].start <= new_value.addr.off)
2209                   &&  ((unsigned int) module->load_addr 
2210                        + sectp[linetab[i].segno - 1].VirtualAddress 
2211                        + linetab[i].end > new_value.addr.off) )
2212                 {
2213                   break;
2214                 }
2215             }
2216
2217           DEBUG_Normalize(curr_func);
2218           if( !linetab || linetab[i].linetab == NULL )
2219             {
2220               curr_func = DEBUG_AddSymbol( symname, &new_value, NULL,
2221                                            SYM_WIN32 | SYM_FUNC);
2222             }
2223           else
2224             {
2225               /*
2226                * First, create the entry.  Then dig through the linetab
2227                * and add whatever line numbers are appropriate for this
2228                * function.
2229                */
2230               curr_func = DEBUG_AddSymbol( symname, &new_value, 
2231                                            linetab[i].sourcefile,
2232                                            SYM_WIN32 | SYM_FUNC);
2233               for(j=0; j < linetab[i].nline; j++)
2234                 {
2235                   if( linetab[i].offtab[j] >= sym->proc32.offset 
2236                       && linetab[i].offtab[j] < sym->proc32.offset 
2237                       + sym->proc32.proc_len )
2238                     {
2239                       DEBUG_AddLineNumber(curr_func, linetab[i].linetab[j],
2240                                           linetab[i].offtab[j] - sym->proc32.offset);
2241                     }
2242                 }
2243
2244             }
2245
2246           /*
2247            * Add information about where we should set breakpoints
2248            * in this function.
2249            */
2250           DEBUG_SetSymbolBPOff(curr_func, sym->proc32.debug_start);
2251           DEBUG_SetSymbolSize(curr_func, sym->proc32.proc_len);
2252           break;
2253         case S_BPREL:
2254           /*
2255            * Function parameters and stack variables.
2256            */
2257           memcpy(symname, sym->stack.name, sym->stack.namelen);
2258           curr_sym = DEBUG_AddLocal(curr_func, 
2259                          0, 
2260                          sym->stack.offset, 
2261                          0, 
2262                          0, 
2263                          symname);
2264           DEBUG_SetLocalSymbolType(curr_sym, DEBUG_GetCVType(sym->stack.symtype));
2265           
2266           break;
2267         case S_BPREL_32:
2268           /*
2269            * Function parameters and stack variables.
2270            */
2271           memcpy(symname, sym->stack32.name, sym->stack32.namelen);
2272           curr_sym = DEBUG_AddLocal(curr_func, 
2273                          0, 
2274                          sym->stack32.offset, 
2275                          0, 
2276                          0, 
2277                          symname);
2278           DEBUG_SetLocalSymbolType(curr_sym, DEBUG_GetCVType(sym->stack32.symtype));
2279           
2280           break;
2281         default:
2282           break;
2283         }
2284
2285       /*
2286        * Adjust pointer to point to next entry, rounding up to a word
2287        * boundary.  MS preserving alignment?  Stranger things have
2288        * happened.
2289        */
2290       if( sym->generic.id == S_PROCREF
2291           || sym->generic.id == S_DATAREF
2292           || sym->generic.id == S_LPROCREF )
2293         {
2294           len = (sym->generic.len + 3) & ~3;
2295           len += ptr.c[16] + 1;
2296           ptr.c += (len + 3) & ~3;
2297         }
2298       else
2299         {
2300           ptr.c += (sym->generic.len + 3) & ~3;
2301         }
2302     }
2303
2304   if( linetab != NULL )
2305     {
2306       DBG_free(linetab);
2307     }
2308
2309   DBG_free(sectp);
2310   return TRUE;
2311 }
2312
2313
2314 /*
2315  * Process PDB file which contains debug information.
2316  */
2317
2318 #pragma pack(1)
2319 typedef struct _PDB_FILE
2320 {
2321     DWORD size;
2322     DWORD unknown;
2323
2324 } PDB_FILE, *PPDB_FILE;
2325
2326 typedef struct _PDB_HEADER
2327 {
2328     CHAR     ident[40];
2329     DWORD    signature;
2330     DWORD    blocksize;
2331     WORD     freelist;
2332     WORD     total_alloc;
2333     PDB_FILE toc;
2334     WORD     toc_block[ 1 ];
2335
2336 } PDB_HEADER, *PPDB_HEADER;
2337
2338 typedef struct _PDB_TOC
2339 {
2340     DWORD    nFiles;
2341     PDB_FILE file[ 1 ];
2342
2343 } PDB_TOC, *PPDB_TOC;
2344
2345 typedef struct _PDB_ROOT
2346 {
2347     DWORD  version;
2348     DWORD  TimeDateStamp;
2349     DWORD  unknown;
2350     DWORD  cbNames;
2351     CHAR   names[ 1 ];
2352
2353 } PDB_ROOT, *PPDB_ROOT;
2354
2355 typedef struct _PDB_TYPES_OLD
2356 {
2357     DWORD  version;
2358     WORD   first_index;
2359     WORD   last_index;
2360     DWORD  type_size;
2361     WORD   file;
2362     WORD   pad;
2363
2364 } PDB_TYPES_OLD, *PPDB_TYPES_OLD;
2365
2366 typedef struct _PDB_TYPES
2367 {
2368     DWORD  version;
2369     DWORD  type_offset;
2370     DWORD  first_index;
2371     DWORD  last_index;
2372     DWORD  type_size;
2373     WORD   file;
2374     WORD   pad;
2375     DWORD  hash_size;
2376     DWORD  hash_base;
2377     DWORD  hash_offset;
2378     DWORD  hash_len;
2379     DWORD  search_offset;
2380     DWORD  search_len;
2381     DWORD  unknown_offset;
2382     DWORD  unknown_len;
2383
2384 } PDB_TYPES, *PPDB_TYPES;
2385
2386 typedef struct _PDB_SYMBOL_RANGE
2387 {
2388     WORD   segment;
2389     WORD   pad1;
2390     DWORD  offset;
2391     DWORD  size;
2392     DWORD  characteristics;
2393     WORD   index;
2394     WORD   pad2;
2395
2396 } PDB_SYMBOL_RANGE, *PPDB_SYMBOL_RANGE;
2397
2398 typedef struct _PDB_SYMBOL_RANGE_EX
2399 {
2400     WORD   segment;
2401     WORD   pad1;
2402     DWORD  offset;
2403     DWORD  size;
2404     DWORD  characteristics;
2405     WORD   index;
2406     WORD   pad2;
2407     DWORD  timestamp;
2408     DWORD  unknown;
2409
2410 } PDB_SYMBOL_RANGE_EX, *PPDB_SYMBOL_RANGE_EX;
2411
2412 typedef struct _PDB_SYMBOL_FILE
2413 {
2414     DWORD  unknown1;
2415     PDB_SYMBOL_RANGE range;
2416     WORD   flag;
2417     WORD   file;
2418     DWORD  symbol_size;
2419     DWORD  lineno_size;
2420     DWORD  unknown2;
2421     DWORD  nSrcFiles;
2422     DWORD  attribute;
2423     CHAR   filename[ 1 ];
2424
2425 } PDB_SYMBOL_FILE, *PPDB_SYMBOL_FILE;
2426
2427 typedef struct _PDB_SYMBOL_FILE_EX
2428 {
2429     DWORD  unknown1;
2430     PDB_SYMBOL_RANGE_EX range;
2431     WORD   flag;
2432     WORD   file;
2433     DWORD  symbol_size;
2434     DWORD  lineno_size;
2435     DWORD  unknown2;
2436     DWORD  nSrcFiles;
2437     DWORD  attribute;
2438     DWORD  reserved[ 2 ];
2439     CHAR   filename[ 1 ];
2440
2441 } PDB_SYMBOL_FILE_EX, *PPDB_SYMBOL_FILE_EX;
2442
2443 typedef struct _PDB_SYMBOL_SOURCE
2444 {
2445     WORD   nModules;
2446     WORD   nSrcFiles;
2447     WORD   table[ 1 ];
2448
2449 } PDB_SYMBOL_SOURCE, *PPDB_SYMBOL_SOURCE;
2450
2451 typedef struct _PDB_SYMBOL_IMPORT
2452 {
2453     DWORD  unknown1;
2454     DWORD  unknown2;
2455     DWORD  TimeDateStamp;
2456     DWORD  nRequests;
2457     CHAR   filename[ 1 ];
2458
2459 } PDB_SYMBOL_IMPORT, *PPDB_SYMBOL_IMPORT;
2460
2461 typedef struct _PDB_SYMBOLS_OLD
2462 {
2463     WORD   hash1_file;
2464     WORD   hash2_file;
2465     WORD   gsym_file;
2466     WORD   pad;
2467     DWORD  module_size;
2468     DWORD  offset_size;
2469     DWORD  hash_size;
2470     DWORD  srcmodule_size;
2471
2472 } PDB_SYMBOLS_OLD, *PPDB_SYMBOLS_OLD;
2473
2474 typedef struct _PDB_SYMBOLS
2475 {
2476     DWORD  signature;
2477     DWORD  version;
2478     DWORD  extended_format;
2479     DWORD  hash1_file;
2480     DWORD  hash2_file;
2481     DWORD  gsym_file;
2482     DWORD  module_size;
2483     DWORD  offset_size;
2484     DWORD  hash_size;
2485     DWORD  srcmodule_size;
2486     DWORD  pdbimport_size;
2487     DWORD  resvd[ 5 ];
2488
2489 } PDB_SYMBOLS, *PPDB_SYMBOLS;
2490 #pragma pack()
2491
2492
2493 static void *pdb_read( LPBYTE image, WORD *block_list, int size )
2494 {
2495     PPDB_HEADER pdb = (PPDB_HEADER)image;
2496     int i, nBlocks;
2497     LPBYTE buffer;
2498
2499     if ( !size ) return NULL;
2500
2501     nBlocks = (size + pdb->blocksize-1) / pdb->blocksize;
2502     buffer = DBG_alloc( nBlocks * pdb->blocksize );
2503
2504     for ( i = 0; i < nBlocks; i++ )
2505         memcpy( buffer + i*pdb->blocksize,
2506                 image + block_list[i]*pdb->blocksize, pdb->blocksize );
2507
2508     return buffer;
2509 }
2510
2511 static void *pdb_read_file( LPBYTE image, PPDB_TOC toc, int fileNr )
2512 {
2513     PPDB_HEADER pdb = (PPDB_HEADER)image;
2514     WORD *block_list;
2515     int i;
2516
2517     if ( !toc || fileNr >= toc->nFiles )
2518         return NULL;
2519
2520     block_list = (WORD *) &toc->file[ toc->nFiles ];
2521     for ( i = 0; i < fileNr; i++ )
2522         block_list += (toc->file[i].size + pdb->blocksize-1) / pdb->blocksize;
2523
2524     return pdb_read( image, block_list, toc->file[fileNr].size );
2525 }
2526
2527 static void pdb_free( void *buffer )
2528 {
2529     DBG_free( buffer );
2530 }
2531
2532 static void pdb_convert_types_header( PDB_TYPES *types, char *image )
2533 {
2534     memset( types, 0, sizeof(PDB_TYPES) );
2535     if ( !image ) return;
2536
2537     if ( *(DWORD *)image < 19960000 )   /* FIXME: correct version? */
2538     {
2539         /* Old version of the types record header */
2540         PDB_TYPES_OLD *old = (PDB_TYPES_OLD *)image;
2541         types->version     = old->version;
2542         types->type_offset = sizeof(PDB_TYPES_OLD);
2543         types->type_size   = old->type_size;
2544         types->first_index = old->first_index;
2545         types->last_index  = old->last_index;
2546         types->file        = old->file;
2547     }
2548     else
2549     {
2550         /* New version of the types record header */
2551         *types = *(PDB_TYPES *)image;
2552     }
2553 }
2554
2555 static void pdb_convert_symbols_header( PDB_SYMBOLS *symbols, 
2556                                         int *header_size, char *image )
2557 {
2558     memset( symbols, 0, sizeof(PDB_SYMBOLS) );
2559     if ( !image ) return;
2560
2561     if ( *(DWORD *)image != 0xffffffff )
2562     {
2563         /* Old version of the symbols record header */
2564         PDB_SYMBOLS_OLD *old     = (PDB_SYMBOLS_OLD *)image;
2565         symbols->version         = 0;
2566         symbols->extended_format = 0;
2567         symbols->module_size     = old->module_size;
2568         symbols->offset_size     = old->offset_size;
2569         symbols->hash_size       = old->hash_size;
2570         symbols->srcmodule_size  = old->srcmodule_size;
2571         symbols->pdbimport_size  = 0;
2572         symbols->hash1_file      = old->hash1_file;
2573         symbols->hash2_file      = old->hash2_file;
2574         symbols->gsym_file       = old->gsym_file;
2575
2576         *header_size = sizeof(PDB_SYMBOLS_OLD);
2577     }
2578     else
2579     {
2580         /* New version of the symbols record header */
2581         *symbols = *(PDB_SYMBOLS *)image;
2582
2583         *header_size = sizeof(PDB_SYMBOLS);
2584     }
2585 }
2586
2587 static int DEBUG_ProcessPDBFile( DBG_MODULE* module, const char *full_filename )
2588 {
2589     HANDLE hFile, hMap;
2590     char *image = NULL;
2591     PDB_HEADER *pdb = NULL;
2592     PDB_TOC *toc = NULL;
2593     PDB_ROOT *root = NULL;
2594     char *types_image = NULL;
2595     char *symbols_image = NULL;
2596     PDB_TYPES types;
2597     PDB_SYMBOLS symbols;
2598     int header_size = 0;
2599     char *modimage, *file;
2600
2601
2602     /*
2603      * Open and map() .PDB file
2604      */
2605     if ((image = DEBUG_MapDebugInfoFile(full_filename, 0, 0, &hFile, &hMap)) == NULL) {
2606        DEBUG_Printf( DBG_CHN_ERR, "-Unable to peruse .PDB file %s\n", full_filename );
2607        goto leave;
2608     }
2609
2610     /*
2611      * Read in TOC and well-known files
2612      */
2613
2614     pdb = (PPDB_HEADER)image;
2615     toc = pdb_read( image, pdb->toc_block, pdb->toc.size );
2616     root = pdb_read_file( image, toc, 1 );
2617     types_image = pdb_read_file( image, toc, 2 );
2618     symbols_image = pdb_read_file( image, toc, 3 );
2619
2620     pdb_convert_types_header( &types, types_image );
2621     pdb_convert_symbols_header( &symbols, &header_size, symbols_image );
2622
2623     /*
2624      * Check for unknown versions
2625      */
2626
2627     switch ( root->version )
2628     {
2629         case 19950623:      /* VC 4.0 */
2630         case 19950814:
2631         case 19960307:      /* VC 5.0 */
2632         case 19970604:      /* VC 6.0 */
2633             break;
2634         default:
2635             DEBUG_Printf( DBG_CHN_ERR, "-Unknown root block version %ld\n", root->version );
2636     }
2637
2638     switch ( types.version )
2639     {
2640         case 19950410:      /* VC 4.0 */
2641         case 19951122:
2642         case 19961031:      /* VC 5.0 / 6.0 */
2643             break;
2644         default:
2645             DEBUG_Printf( DBG_CHN_ERR, "-Unknown type info version %ld\n", types.version );
2646     }
2647
2648     switch ( symbols.version )
2649     {
2650         case 0:            /* VC 4.0 */
2651         case 19960307:     /* VC 5.0 */
2652         case 19970606:     /* VC 6.0 */
2653             break;
2654         default:
2655             DEBUG_Printf( DBG_CHN_ERR, "-Unknown symbol info version %ld\n", symbols.version );
2656     }
2657
2658
2659     /* 
2660      * Check .PDB time stamp
2661      */
2662
2663     if (      root->TimeDateStamp 
2664          != ((struct CodeViewDebug *)MSC_INFO(module)->dbg_info)->cv_timestamp ) 
2665     {
2666         DEBUG_Printf(DBG_CHN_ERR, "-Wrong time stamp of .PDB file %s\n", full_filename);
2667         goto leave;
2668     }
2669
2670     /* 
2671      * Read type table
2672      */
2673
2674     DEBUG_ParseTypeTable( types_image + types.type_offset, types.type_size );
2675     
2676     /*
2677      * Read type-server .PDB imports
2678      */
2679
2680     if ( symbols.pdbimport_size )
2681     {   
2682         /* FIXME */
2683         DEBUG_Printf(DBG_CHN_ERR, "-Type server .PDB imports ignored!\n" );
2684     }
2685
2686     /* 
2687      * Read global symbol table
2688      */
2689
2690     modimage = pdb_read_file( image, toc, symbols.gsym_file );
2691     if ( modimage )
2692     {
2693         DEBUG_SnarfCodeView( module, modimage, 
2694                              toc->file[symbols.gsym_file].size, NULL );
2695         pdb_free( modimage );
2696     }
2697
2698     /*
2699      * Read per-module symbol / linenumber tables
2700      */
2701
2702     file = symbols_image + header_size;
2703     while ( file - symbols_image < header_size + symbols.module_size )
2704     {
2705         int file_nr, file_index, symbol_size, lineno_size;
2706         char *file_name;
2707
2708         if ( !symbols.extended_format )
2709         {
2710             PDB_SYMBOL_FILE *sym_file = (PDB_SYMBOL_FILE *) file;
2711             file_nr     = sym_file->file;
2712             file_name   = sym_file->filename;
2713             file_index  = sym_file->range.index;
2714             symbol_size = sym_file->symbol_size;
2715             lineno_size = sym_file->lineno_size;
2716         }
2717         else
2718         {
2719             PDB_SYMBOL_FILE_EX *sym_file = (PDB_SYMBOL_FILE_EX *) file;
2720             file_nr     = sym_file->file;
2721             file_name   = sym_file->filename;
2722             file_index  = sym_file->range.index;
2723             symbol_size = sym_file->symbol_size;
2724             lineno_size = sym_file->lineno_size;
2725         }
2726
2727         modimage = pdb_read_file( image, toc, file_nr );
2728         if ( modimage )
2729         {
2730             struct codeview_linetab_hdr *linetab = NULL;
2731
2732             if ( lineno_size )
2733                 linetab = DEBUG_SnarfLinetab( modimage + symbol_size, lineno_size );
2734
2735             if ( symbol_size )
2736                 DEBUG_SnarfCodeView( module, modimage + sizeof(DWORD),
2737                                      symbol_size - sizeof(DWORD), linetab );
2738
2739             pdb_free( modimage );
2740         }
2741
2742         file_name += strlen(file_name) + 1;
2743         file = (char *)( (DWORD)(file_name + strlen(file_name) + 1 + 3) & ~3 );
2744     }
2745     
2746
2747  leave:    
2748
2749     /*
2750      * Cleanup
2751      */
2752
2753     if ( symbols_image ) pdb_free( symbols_image );
2754     if ( types_image ) pdb_free( types_image );
2755     if ( root ) pdb_free( root );
2756     if ( toc ) pdb_free( toc );
2757
2758     DEBUG_UnmapDebugInfoFile(hFile, hMap, image);
2759
2760     return TRUE;
2761 }
2762
2763
2764 /*
2765  * Process DBG file which contains debug information.
2766  */
2767 static
2768 int
2769 DEBUG_ProcessDBGFile(DBG_MODULE* module, const char* filename)
2770 {
2771   HANDLE                        hFile, hMap;
2772   char                        * addr;
2773   char                        * codeview;
2774   struct CV4_DirHead          * codeview_dir;
2775   struct CV4_DirEnt           * codeview_dent;
2776   PIMAGE_DEBUG_DIRECTORY        dbghdr;
2777   DBG_MODULE                    module2;
2778   int                           i;
2779   int                           j;
2780   struct codeview_linetab_hdr * linetab;
2781   int                           nsect;
2782   PIMAGE_SEPARATE_DEBUG_HEADER pdbg = NULL;
2783   IMAGE_SECTION_HEADER        * sectp;
2784
2785   if ((addr = DEBUG_MapDebugInfoFile(filename, 0, 0, &hFile, &hMap)) == NULL) {
2786      DEBUG_Printf(DBG_CHN_ERR, "-Unable to peruse .DBG file %s\n", filename);
2787      goto leave;
2788   }
2789
2790   pdbg = (PIMAGE_SEPARATE_DEBUG_HEADER) addr;
2791
2792   if( pdbg->TimeDateStamp != MSC_INFO(module)->dbgdir.TimeDateStamp )
2793     {
2794       DEBUG_Printf(DBG_CHN_ERR, "Warning - %s has incorrect internal timestamp\n",
2795               filename);
2796 /*      goto leave; */
2797 /*
2798    Well, sometimes this happens to DBG files which ARE REALLY the right .DBG
2799    files but nonetheless this check fails. Anyway, WINDBG (debugger for
2800    Windows by Microsoft) loads debug symbols which have incorrect timestamps.
2801 */
2802    }
2803
2804   DEBUG_Printf(DBG_CHN_MESG, "Processing symbols from %s...\n", filename);
2805
2806   dbghdr = (PIMAGE_DEBUG_DIRECTORY) (  addr + sizeof(*pdbg) 
2807                  + pdbg->NumberOfSections * sizeof(IMAGE_SECTION_HEADER) 
2808                  + pdbg->ExportedNamesSize);
2809
2810   sectp = (PIMAGE_SECTION_HEADER) ((char *) pdbg + sizeof(*pdbg));
2811   nsect = pdbg->NumberOfSections;
2812
2813   for( i=0; i < pdbg->DebugDirectorySize / sizeof(*pdbg); i++, dbghdr++ )
2814     {
2815       switch(dbghdr->Type)
2816                 {
2817                 case IMAGE_DEBUG_TYPE_COFF:
2818                   /*
2819                    * Dummy up a deferred debug header to handle the
2820                    * COFF stuff embedded within the DBG file.
2821                    */
2822                   memset((char *) &module2, 0, sizeof(module2));
2823                   MSC_INFO(&module2)->dbg_info = (addr + dbghdr->PointerToRawData);
2824                   MSC_INFO(&module2)->dbg_size = dbghdr->SizeOfData;
2825                   module2.load_addr = module->load_addr;
2826
2827                   DEBUG_ProcessCoff(&module2);
2828                   break;
2829                 case IMAGE_DEBUG_TYPE_CODEVIEW:
2830                   /*
2831                    * This is the older format by which codeview stuff is 
2832                    * stored, known as the 'NB09' format.  Newer executables
2833                    * and dlls created by VC++ use PDB files instead, which
2834                    * have lots of internal similarities, but the overall
2835                    * format and structure is quite different.
2836                    */
2837                   codeview = (addr + dbghdr->PointerToRawData);
2838
2839                   /*
2840                    * The first thing in the codeview section should be
2841                    * an 'NB09' identifier.  As a sanity check, make sure
2842                    * it is there.
2843                    */
2844                   if( *((unsigned int*) codeview) != 0x3930424e )
2845                     {
2846                       break;
2847                     }
2848                   
2849                   /*
2850                    * Next we need to find the directory.  This is easy too.
2851                    */
2852                   codeview_dir = (struct CV4_DirHead *) 
2853                     (codeview + ((unsigned int*) codeview)[1]);
2854
2855                   /*
2856                    * Some more sanity checks.  Make sure that everything
2857                    * is as we expect it.
2858                    */
2859                   if( codeview_dir->next_offset != 0 
2860                       || codeview_dir->dhsize != sizeof(*codeview_dir)
2861                       || codeview_dir->desize != sizeof(*codeview_dent) )
2862                     {
2863                       break;
2864                     }
2865                   codeview_dent = (struct CV4_DirEnt *) (codeview_dir + 1);
2866
2867                   for(j=0; j < codeview_dir->ndir; j++, codeview_dent++)
2868                     {
2869                       if( codeview_dent->subsect_number == sstAlignSym )
2870                         {
2871                           /*
2872                            * Check the previous entry.  If it is a
2873                            * sstSrcModule, it contains the line number
2874                            * info for this file.
2875                            */
2876                           linetab = NULL;
2877                           if( codeview_dent[1].module_number == codeview_dent[0].module_number
2878                               && codeview_dent[1].subsect_number == sstSrcModule )
2879                             {
2880                               linetab = DEBUG_SnarfLinetab(
2881                                            codeview + codeview_dent[1].offset,
2882                                            codeview_dent[1].size);
2883                             }
2884
2885                           if( codeview_dent[-1].module_number == codeview_dent[0].module_number
2886                               && codeview_dent[-1].subsect_number == sstSrcModule )
2887                             {
2888                               linetab = DEBUG_SnarfLinetab(
2889                                            codeview + codeview_dent[-1].offset,
2890                                            codeview_dent[-1].size);
2891                             }
2892                           /*
2893                            * Now process the CV stuff.
2894                            */
2895                           DEBUG_SnarfCodeView(module, 
2896                                               codeview + codeview_dent->offset + sizeof(DWORD),
2897                                               codeview_dent->size - sizeof(DWORD),
2898                                               linetab);
2899                         }
2900                     }
2901
2902                   break;
2903                 default:
2904                   break;
2905                 }
2906     }
2907 leave:
2908
2909   DEBUG_UnmapDebugInfoFile(hFile, hMap, addr);
2910
2911   return TRUE;
2912 }
2913
2914 static int 
2915 DEBUG_ProcessMSCDebugInfo(DBG_MODULE* module)
2916 {
2917   struct CodeViewDebug       * cvd;
2918   struct MiscDebug           * misc;
2919   char                       * filename;
2920   int                          sts;
2921   
2922   switch (MSC_INFO(module)->dbgdir.Type)
2923      {
2924      case IMAGE_DEBUG_TYPE_COFF:
2925         /*
2926          * Standard COFF debug information that VC++ adds when you
2927          * use /debugtype:both with the linker.
2928          */
2929         DEBUG_Printf(DBG_CHN_TRACE, "Processing COFF symbols...\n");
2930         sts = DEBUG_ProcessCoff(module);
2931         break;
2932      case IMAGE_DEBUG_TYPE_CODEVIEW:
2933         /*
2934          * This is a pointer to a PDB file of some sort.
2935          */
2936         cvd = (struct CodeViewDebug *) MSC_INFO(module)->dbg_info;
2937         
2938         if( strcmp(cvd->cv_nbtype, "NB10") != 0 )
2939            {
2940               /*
2941                * Whatever this is, we don't know how to deal with
2942                * it yet.
2943                */
2944               sts = FALSE;
2945               break;
2946            }
2947         sts = DEBUG_ProcessPDBFile(module, cvd->cv_name);
2948         DEBUG_Printf(DBG_CHN_TRACE, "Processing PDB file %s\n", cvd->cv_name);
2949         break;
2950      case IMAGE_DEBUG_TYPE_MISC:
2951         /*
2952          * A pointer to a .DBG file of some sort.  These files
2953          * can contain either CV4 or COFF information.  Open
2954          * the file, and try to do the right thing with it.
2955          */
2956         misc = (struct MiscDebug *) MSC_INFO(module)->dbg_info;
2957         
2958         filename = strrchr((char *) &misc->Data, '.');
2959         
2960         /*
2961          * Ignore the file if it doesn't have a .DBG extension.
2962          */
2963         if(    (filename == NULL)
2964                || (    (strcmp(filename, ".dbg") != 0)
2965                        && (strcmp(filename, ".DBG") != 0)) )
2966            {
2967               sts = FALSE;
2968               break;
2969            }
2970         
2971         filename = (char *) &misc->Data;
2972         
2973         /*
2974          * Do the dirty deed...
2975          */
2976         sts = DEBUG_ProcessDBGFile(module, filename);
2977         
2978         break;
2979      default:
2980         /*
2981          * We should never get here...
2982          */
2983         sts = FALSE;
2984         break;
2985      }
2986   module->status = (sts) ? DM_STATUS_LOADED : DM_STATUS_ERROR;
2987   return sts;
2988 }
2989
2990
2991