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