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