Added a memset() to prevent a debugger segfault caused by
[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  *
7  * Note - this handles reading debug information for 32 bit applications
8  * that run under Windows-NT for example.  I doubt that this would work well
9  * for 16 bit applications, but I don't think it really matters since the
10  * file format is different, and we should never get in here in such cases.
11  *
12  * TODO:
13  *      Get 16 bit CV stuff working.
14  *      Add symbol size to internal symbol table.
15  */
16
17 #include <stdio.h>
18 #include <stdlib.h>
19
20 #include <sys/types.h>
21 #include <sys/mman.h>
22 #include <fcntl.h>
23 #include <sys/stat.h>
24 #include <limits.h>
25 #include <string.h>
26 #include <unistd.h>
27 #ifndef PATH_MAX
28 #define PATH_MAX _MAX_PATH
29 #endif
30 #include "win.h"
31 #include "pe_image.h"
32 #include "peexe.h"
33 #include "debugger.h"
34 #include "peexe.h"
35 #include "xmalloc.h"
36
37
38 /*
39  * This is an index we use to keep track of the debug information
40  * when we have multiple sources.  We use the same database to also
41  * allow us to do an 'info shared' type of deal, and we use the index
42  * to eliminate duplicates.
43  */
44 static int DEBUG_next_index = 0;
45
46 union any_size
47 {
48   char           * c;
49   short          * s;
50   int            * i;
51   unsigned int   * ui;
52 };
53
54 /*
55  * This is a convenience structure used to map portions of the
56  * line number table.
57  */
58 struct startend
59 {
60   unsigned int    start;
61   unsigned int    end;
62 };
63
64 /*
65  * This is how we reference the various record types.
66  */
67 union codeview_symbol
68 {
69   struct
70   {
71     short int   len;
72     short int   id;
73   } generic;
74
75   struct
76   {
77         short int       len;
78         short int       id;
79         unsigned int    offset;
80         unsigned short  seg;
81         unsigned short  symtype;
82         unsigned char   namelen;
83         unsigned char   name[1];
84   } data;
85
86   struct
87   {
88         short int       len;
89         short int       id;
90         unsigned int    pparent;
91         unsigned int    pend;
92         unsigned int    next;
93         unsigned int    offset;
94         unsigned short  segment;
95         unsigned short  thunk_len;
96         unsigned char   thtype;
97         unsigned char   namelen;
98         unsigned char   name[1];
99   } thunk;
100   struct
101   {
102         short int       len;
103         short int       id;
104         unsigned int    pparent;
105         unsigned int    pend;
106         unsigned int    next;
107         unsigned int    proc_len;
108         unsigned int    debug_start;
109         unsigned int    debug_end;
110         unsigned int    offset;
111         unsigned short  segment;
112         unsigned short  proctype;
113         unsigned char   flags;
114         unsigned char   namelen;
115         unsigned char   name[1];
116   } proc;
117   struct
118   {
119         short int       len;    /* Total length of this entry */
120         short int       id;             /* Always S_BPREL32 */
121         unsigned int    offset; /* Stack offset relative to BP */
122         unsigned short  symtype;
123         unsigned char   namelen;
124         unsigned char   name[1];
125   } stack;
126 };
127
128 union codeview_type
129 {
130   struct
131   {
132     short int   len;
133     short int   id;
134   } generic;
135
136   struct
137   {
138     short int           len;
139     short int           id;
140     short int           attribute;
141     short int           datatype;
142     unsigned char       variant[1];
143   } pointer;
144
145   struct
146   {
147     short int           len;
148     short int           id;
149     unsigned char       nbits;
150     unsigned char       bitoff;
151     unsigned short      type;
152   } bitfield;
153
154   struct
155   {
156     short int           len;
157     short int           id;
158     short int           elemtype;
159     short int           idxtype;
160     unsigned char       arrlen;
161     unsigned char       namelen;
162     unsigned char       name[1];
163   } array;
164
165   struct
166   {
167     short int           len;
168     short int           id;
169     short int           n_element;
170     short int           fieldlist;
171     short int           property;
172     short int           derived;
173     short int           vshape;
174     unsigned short      structlen;
175     unsigned char       namelen;
176     unsigned char       name[1];
177   } structure;
178
179   struct
180   {
181     short int           len;
182     short int           id;
183     short int           count;
184     short int           field;
185     short int           property;
186     unsigned short      un_len;
187     unsigned char       namelen;
188     unsigned char       name[1];
189   } t_union;
190
191   struct
192   {
193     short int           len;
194     short int           id;
195     short int           count;
196     short int           type;
197     short int           field;
198     short int           property;
199     unsigned char       namelen;
200     unsigned char       name[1];
201   } enumeration;
202
203   struct
204   {
205     short int           id;
206     short int           attribute;
207     unsigned short int  value;
208     unsigned char       namelen;
209     unsigned char       name[1];
210   } enumerate;
211
212   struct
213   {
214     short int           id;
215     short int           type;
216     short int           attribute;
217     unsigned short int  offset;
218     unsigned char       namelen;
219     unsigned char       name[1];
220   } member;
221
222   struct
223   {
224     short int           len;
225     short int           id;
226     short int           count;
227     short int           type;
228     short int           field;
229     short int           property;
230     unsigned char       namelen;
231     unsigned char       name[1];
232   } fieldlist;
233
234 };
235
236 #define S_BPREL32       0x200
237 #define S_LDATA32       0x201
238 #define S_GDATA32       0x202
239 #define S_PUB32         0x203
240 #define S_LPROC32       0x204
241 #define S_GPROC32       0x205
242 #define S_THUNK32       0x206
243 #define S_BLOCK32       0x207
244 #define S_WITH32        0x208
245 #define S_LABEL32       0x209
246
247 #define S_PROCREF       0x400
248 #define S_DATAREF       0x401
249 #define S_ALIGN         0x402
250 #define S_UNKNOWN       0x403
251
252 /*
253  * This covers the basic datatypes that VC++ seems to be using these days.
254  * 32 bit mode only.  There are additional numbers for the pointers in 16
255  * bit mode.  There are many other types listed in the documents, but these
256  * are apparently not used by the compiler, or represent pointer types
257  * that are not used.
258  */
259 #define T_NOTYPE        0x0000  /* Notype */
260 #define T_ABS           0x0001  /* Abs */
261 #define T_VOID          0x0003  /* Void */
262 #define T_CHAR          0x0010  /* signed char */
263 #define T_SHORT         0x0011  /* short */
264 #define T_LONG          0x0012  /* long */
265 #define T_QUAD          0x0013  /* long long */
266 #define T_UCHAR         0x0020  /* unsigned  char */
267 #define T_USHORT        0x0021  /* unsigned short */
268 #define T_ULONG         0x0022  /* unsigned long */
269 #define T_UQUAD         0x0023  /* unsigned long long */
270 #define T_REAL32        0x0040  /* float */
271 #define T_REAL64        0x0041  /* double */
272 #define T_RCHAR         0x0070  /* real char */
273 #define T_WCHAR         0x0071  /* wide char */
274 #define T_INT4          0x0074  /* int */
275 #define T_UINT4         0x0075  /* unsigned int */
276
277 #define T_32PVOID       0x0403  /* 32 bit near pointer to void */
278 #define T_32PCHAR       0x0410  /* 16:32 near pointer to signed char */
279 #define T_32PSHORT      0x0411  /* 16:32 near pointer to short */
280 #define T_32PLONG       0x0412  /* 16:32 near pointer to int */
281 #define T_32PQUAD       0x0413  /* 16:32 near pointer to long long */
282 #define T_32PUCHAR      0x0420  /* 16:32 near pointer to unsigned char */
283 #define T_32PUSHORT     0x0421  /* 16:32 near pointer to unsigned short */
284 #define T_32PULONG      0x0422  /* 16:32 near pointer to unsigned int */
285 #define T_32PUQUAD      0x0423  /* 16:32 near pointer to long long */
286 #define T_32PREAL32     0x0440  /* 16:32 near pointer to float */
287 #define T_32PREAL64     0x0441  /* 16:32 near pointer to float */
288 #define T_32PRCHAR      0x0470  /* 16:32 near pointer to real char */
289 #define T_32PWCHAR      0x0471  /* 16:32 near pointer to real char */
290 #define T_32PINT4       0x0474  /* 16:32 near pointer to int */
291 #define T_32PUINT4      0x0475  /* 16:32 near pointer to unsigned int */
292
293 #define LF_MODIFIER     0x1
294 #define LF_POINTER      0x2
295 #define LF_ARRAY        0x3
296 #define LF_CLASS        0x4
297 #define LF_STRUCTURE    0x5
298 #define LF_UNION        0x6
299 #define LF_ENUMERATION  0x7
300 #define LF_PROCEDURE    0x8
301 #define LF_MFUNCTION    0x9
302 #define LF_VTSHAPE      0xa
303 #define LF_BARRAY       0xd
304 #define LF_DIMARRAY     0x11
305 #define LF_VFTPATH      0x12
306
307 #define LF_SKIP         0x200
308 #define LF_ARGLIST      0x201
309 #define LF_FIELDLIST    0x204
310 #define LF_DERIVED      0x205
311 #define LF_BITFIELD     0x206
312
313 #define LF_BCLASS       0x400
314 #define LF_VBCLASS      0x401
315 #define LF_IVBCLASS     0x402
316 #define LF_ENUMERATE    0x403
317 #define LF_FRIENDFCN    0x404
318 #define LF_INDEX        0x405
319 #define LF_MEMBER       0x406
320 #define LF_STMEMBER     0x407
321 #define LF_METHOD       0x408
322 #define LF_NESTEDTYPE   0x409
323 #define LF_VFUNCTAB     0x40a
324 #define LF_FRIENDCLS    0x40b
325 #define LF_ONEMETHOD    0x40c
326 #define LF_FUNCOFF      0x40d
327
328 #define MAX_BUILTIN_TYPES       0x480
329 static struct datatype * cv_basic_types[MAX_BUILTIN_TYPES];
330 static int num_cv_defined_types = 0;
331 static struct datatype **cv_defined_types = NULL;
332
333 /*
334  * For the type CODEVIEW debug directory entries, the debug directory
335  * points to a structure like this.  The cv_name field is the name
336  * of an external .PDB file.
337  */
338 struct CodeViewDebug
339 {
340         char                cv_nbtype[8];
341         unsigned int        cv_timestamp;
342         char                cv_unknown[4];
343         char                cv_name[1];
344 };
345
346 struct MiscDebug {
347     unsigned int       DataType;
348     unsigned int       Length;
349     char               Unicode;
350     char               Reserved[3];
351     char               Data[1];
352 };
353
354 /*
355  * This is the header that the COFF variety of debug header points to.
356  */
357 struct CoffDebug {
358     unsigned int   N_Sym;
359     unsigned int   SymbolOffset;
360     unsigned int   N_Linenum;
361     unsigned int   LinenumberOffset;
362     unsigned int   Unused[4];
363 };
364
365 struct CoffLinenum {
366         unsigned int            VirtualAddr;
367         unsigned short int      Linenum;
368 };
369
370 struct CoffFiles {
371         unsigned int    startaddr;
372         unsigned int    endaddr;
373         char          * filename;
374         int             linetab_offset;
375         int             linecnt;
376         struct name_hash **entries;
377         int                    neps;
378         int              neps_alloc;
379 };
380
381
382 struct CoffSymbol {
383     union {
384         char    ShortName[8];
385         struct {
386             unsigned int   NotLong;
387             unsigned int   StrTaboff;
388         } Name;
389     } N;
390     unsigned int   Value;
391     short          SectionNumber;
392     short          Type;
393     char           StorageClass;
394     unsigned char  NumberOfAuxSymbols;
395 };
396
397 struct CoffAuxSection{
398   unsigned int   Length;
399   unsigned short NumberOfRelocations;
400   unsigned short NumberOfLinenumbers;
401   unsigned int   CheckSum;
402   short          Number;
403   char           Selection;
404 } Section;
405
406 /*
407  * These two structures are used in the directory within a .DBG file
408  * to locate the individual important bits that we might want to see.
409  */
410 struct CV4_DirHead {
411   short unsigned int       dhsize;
412   short unsigned int       desize;
413   unsigned int             ndir;
414   unsigned int             next_offset;
415   unsigned int             flags;
416 };
417
418 struct CV4_DirEnt {
419   short unsigned int       subsect_number;
420   short unsigned int       module_number;
421   unsigned int             offset;
422   unsigned int             size;
423 };
424
425 /*
426  * These are the values of interest that the subsect_number field takes.
427  */
428 #define sstAlignSym             0x125
429 #define sstSrcModule            0x127
430
431 struct codeview_linetab_hdr
432 {
433   unsigned int             nline;
434   unsigned int             segno;
435   unsigned int             start;
436   unsigned int             end;
437   char                   * sourcefile;
438   unsigned short         * linetab;
439   unsigned int           * offtab;
440 };
441
442 struct codeview_pdb_hdr
443 {
444   char          ident[44];
445   unsigned int  blocksize;         /* Extent size */
446   unsigned short loc_freelist;   /* freelist. */
447   unsigned short alloc_filesize; /* # extents allocated. */
448   unsigned int  toc_len;
449   unsigned int  unknown;
450   unsigned short toc_ext[1];       /* array of extent #'s for toc. */
451 };
452
453 /*
454  * This is our own structure that we use to keep track of the contents
455  * of a PDB file.
456  */
457 struct file_list
458 {
459         int             record_len;
460         int             nextents;
461         short int     * extent_list;
462         unsigned int    linetab_offset;
463         unsigned int    linetab_len;
464 };
465
466 /*
467  * These are the structures that represent how the file table is set up
468  * within the PDB file.
469  */
470 struct filetab_hdr
471 {
472   unsigned short        tab1_file;
473   unsigned short        tab2_file;
474   unsigned short        gsym_file;
475   unsigned short        padding;
476   unsigned int          ftab_len;
477   unsigned int          fofftab_len;
478   unsigned int          hash_len;
479   unsigned int          strtab_len;
480 };
481
482 struct file_ent
483 {
484   unsigned int          reserved1;
485   unsigned short        datasect_segment;
486   unsigned short        reserved2;
487   unsigned int          datasect_offset;
488   unsigned int          datasect_size;
489   unsigned int          datasect_flags;
490   unsigned short        reserved3;
491   unsigned short        index;
492   unsigned short        num6a;
493   unsigned short        file_number;
494   unsigned int          linetab_offset;
495   unsigned int          linetab_len;
496   unsigned int          num9;
497   unsigned int          num10;
498   unsigned int          num11;
499   unsigned char         filename[1];
500 };
501
502 /*
503  ********************************************************************
504  */
505 struct deferred_debug_info
506 {
507         struct deferred_debug_info      * next;
508         char                            * load_addr;
509         char                            * module_name;
510         char                            * dbg_info;
511         int                               dbg_size;
512         HMODULE32                         module;
513         LPIMAGE_DEBUG_DIRECTORY           dbgdir;
514         LPIMAGE_SECTION_HEADER            sectp;
515         int                               nsect;
516         short int                         dbg_index;                    
517         char                              loaded;
518 };
519
520 struct deferred_debug_info * dbglist = NULL;
521
522 /*
523  * A simple macro that tells us whether a given COFF symbol is a
524  * function or not.
525  */
526 #define N_TMASK                             0x0030
527 #define IMAGE_SYM_DTYPE_FUNCTION            2
528 #define N_BTSHFT                            4
529 #define ISFCN(x) (((x) & N_TMASK) == (IMAGE_SYM_DTYPE_FUNCTION << N_BTSHFT))
530
531
532 /*
533  * This is what we are looking for in the COFF symbols.
534  */
535 #define IMAGE_SYM_CLASS_EXTERNAL            0x2
536 #define IMAGE_SYM_CLASS_STATIC              0x3
537 #define IMAGE_SYM_CLASS_FILE                0x67
538
539 static 
540 struct datatype * DEBUG_GetCVType(int typeno)
541 {
542   struct datatype * dt = NULL;
543
544   /*
545    * Convert Codeview type numbers into something we can grok internally.
546    * Numbers < 0x1000 are all fixed builtin types.  Numbers from 0x1000 and
547    * up are all user defined (structs, etc).
548    */
549   if( typeno < 0x1000 )
550     {
551       if( typeno < MAX_BUILTIN_TYPES )
552         {
553           dt = cv_basic_types[typeno];
554         }
555     }
556   else
557     {
558       if( typeno - 0x1000 < num_cv_defined_types )
559         {
560           dt = cv_defined_types[typeno - 0x1000];
561         } 
562     }
563
564   return dt;
565 }
566
567 static int
568 DEBUG_ParseTypeTable(char * table, int len)
569 {
570   int                             arr_max;
571   int                             curr_type;
572   enum debug_type                 fieldtype;
573   int                             elem_size;
574   union any_size                  ptr;
575   union any_size                  ptr2;
576   struct datatype               * subtype;
577   char                            symname[256];
578   union codeview_type           * type;
579   union codeview_type           * type2;
580   struct datatype               * typeptr;
581
582   curr_type = 0x1000;
583
584   ptr = (union any_size) (table + 16);
585   while( ptr.c - table < len )
586     {
587       type = (union codeview_type *) ptr.c;
588
589       if( curr_type - 0x1000 >= num_cv_defined_types )
590         {
591           num_cv_defined_types += 0x100;
592           cv_defined_types = (struct datatype **) realloc(cv_defined_types,
593                   num_cv_defined_types * sizeof(struct datatype *));
594           memset(cv_defined_types + num_cv_defined_types - 0x100,
595                  0,
596                  0x100 * sizeof(struct datatype *));
597           if( cv_defined_types == NULL )
598             {
599               return FALSE;
600             }
601         }
602
603       switch(type->generic.id)
604         {
605         case LF_POINTER:
606           cv_defined_types[curr_type - 0x1000] = 
607             DEBUG_FindOrMakePointerType(DEBUG_GetCVType(type->pointer.datatype));
608           break;
609         case LF_ARRAY:
610           if( type->array.arrlen >= 0x8000 )
611             {
612               /*
613                * This is a numeric leaf, I am too lazy to handle this right
614                * now.
615                */
616               fprintf(stderr, "Ignoring large numberic leaf.\n");
617               break;
618             }
619           if( type->array.namelen != 0 )
620             {
621               memset(symname, 0, sizeof(symname));
622               memcpy(symname, type->array.name, type->array.namelen);
623               typeptr = DEBUG_NewDataType(ARRAY, symname);
624             }
625           else
626             {
627               typeptr = DEBUG_NewDataType(ARRAY, NULL);
628             }
629           cv_defined_types[curr_type - 0x1000] = typeptr;
630
631           subtype = DEBUG_GetCVType(type->array.elemtype);
632           if(    (subtype == NULL)
633               || (elem_size = DEBUG_GetObjectSize(subtype)) == 0 )
634             {
635               arr_max = 0;
636             }
637           else
638             {
639               arr_max = type->array.arrlen / DEBUG_GetObjectSize(subtype);
640             }
641
642           DEBUG_SetArrayParams(typeptr, 0, arr_max, subtype);
643           break;
644         case LF_FIELDLIST:
645           /*
646            * This is where the basic list of fields is defined for
647            * structures and classes.
648            *
649            * First, we need to look ahead and see whether we are building
650            * a fieldlist for an enum or a struct.
651            */
652           ptr2.i = ptr.i + 1;
653           type2 = (union codeview_type *) ptr2.c;
654           if( type2->member.id == LF_MEMBER )
655             {
656               typeptr = DEBUG_NewDataType(STRUCT, NULL);
657               fieldtype = STRUCT;
658             }
659           else if( type2->member.id == LF_ENUMERATE )
660             {
661               typeptr = DEBUG_NewDataType(ENUM, NULL);
662               fieldtype = ENUM;
663             }
664           else
665             {
666               break;
667             }
668
669           cv_defined_types[curr_type - 0x1000] = typeptr;
670           while( ptr2.c < (ptr.c + ((type->generic.len + 3) & ~3)) )
671             {
672               type2 = (union codeview_type *) ptr2.c;
673               if( type2->member.id == LF_MEMBER && fieldtype == STRUCT )
674                 {
675                   memset(symname, 0, sizeof(symname));
676                   memcpy(symname, type2->member.name, type2->member.namelen);
677                   
678                   subtype = DEBUG_GetCVType(type2->member.type);
679                   elem_size = 0;
680                   if( subtype != NULL )
681                     {
682                       elem_size = DEBUG_GetObjectSize(subtype);
683                     }
684                   
685                   if( type2->member.offset >= 0x8000 )
686                     {
687                       /*
688                        * This is a numeric leaf, I am too lazy to handle this right
689                        * now.
690                        */
691                       fprintf(stderr, "Ignoring large numberic leaf.\n");
692                     }
693                   else
694                     {
695                       DEBUG_AddStructElement(typeptr, symname, subtype, 
696                                              type2->member.offset << 3,
697                                              elem_size << 3);
698                     }
699                 }
700               else if( type2->member.id == LF_ENUMERATE && fieldtype == ENUM )
701                 {
702                   memset(symname, 0, sizeof(symname));
703                   memcpy(symname, type2->enumerate.name, type2->enumerate.namelen);
704                   
705                   if( type2->enumerate.value >= 0x8000 )
706                     {
707                       /*
708                        * This is a numeric leaf, I am too lazy to handle this right
709                        * now.
710                        */
711                       fprintf(stderr, "Ignoring large numberic leaf.\n");
712                     }
713                   else
714                     {
715                       DEBUG_AddStructElement(typeptr, symname, NULL, 
716                                              type2->enumerate.value, 0);
717                     }
718                 }
719               else
720                 {
721                   /*
722                    * Something else I have never seen before.  Either wrong type of
723                    * object in the fieldlist, or some other problem which I wouldn't
724                    * really know how to handle until it came up.
725                    */
726                   fprintf(stderr, "Unexpected entry in fieldlist\n");
727                   break;
728                 }
729
730
731               ptr2.c += ((type2->member.namelen + 9 + 3) & ~3);
732             }
733           break;
734         case LF_STRUCTURE:
735         case LF_CLASS:
736           if( type->structure.structlen >= 0x8000 )
737             {
738               /*
739                * This is a numeric leaf, I am too lazy to handle this right
740                * now.
741                */
742               fprintf(stderr, "Ignoring large numberic leaf.\n");
743               break;
744             }
745           memset(symname, 0, sizeof(symname));
746           memcpy(symname, type->structure.name, type->structure.namelen);
747           if( strcmp(symname, "__unnamed") == 0 )
748             {
749               typeptr = DEBUG_NewDataType(STRUCT, NULL);
750             }
751           else
752             {
753               typeptr = DEBUG_NewDataType(STRUCT, symname);
754             }
755           cv_defined_types[curr_type - 0x1000] = typeptr;
756
757           /*
758            * Now copy the relevant bits from the fieldlist that we specified.
759            */
760           subtype = DEBUG_GetCVType(type->structure.fieldlist);
761
762           if( subtype != NULL )
763             {
764               DEBUG_SetStructSize(typeptr, type->structure.structlen);
765               DEBUG_CopyFieldlist(typeptr, subtype);
766             }
767           break;
768         case LF_UNION:
769           if( type->t_union.un_len >= 0x8000 )
770             {
771               /*
772                * This is a numeric leaf, I am too lazy to handle this right
773                * now.
774                */
775               fprintf(stderr, "Ignoring large numberic leaf.\n");
776               break;
777             }
778           memset(symname, 0, sizeof(symname));
779           memcpy(symname, type->t_union.name, type->t_union.namelen);
780
781           if( strcmp(symname, "__unnamed") == 0 )
782             {
783               typeptr = DEBUG_NewDataType(STRUCT, NULL);
784             }
785           else
786             {
787               typeptr = DEBUG_NewDataType(STRUCT, symname);
788             }
789
790           cv_defined_types[curr_type - 0x1000] = typeptr;
791
792           /*
793            * Now copy the relevant bits from the fieldlist that we specified.
794            */
795           subtype = DEBUG_GetCVType(type->t_union.field);
796
797           if( subtype != NULL )
798             {
799               DEBUG_SetStructSize(typeptr, type->t_union.un_len);
800               DEBUG_CopyFieldlist(typeptr, subtype);
801             }
802           break;
803         case LF_BITFIELD:
804           typeptr = DEBUG_NewDataType(BITFIELD, NULL);
805           cv_defined_types[curr_type - 0x1000] = typeptr;
806           DEBUG_SetBitfieldParams(typeptr, type->bitfield.bitoff,
807                                   type->bitfield.nbits, 
808                                   DEBUG_GetCVType(type->bitfield.type));
809           break;
810         case LF_ENUMERATION:
811           memset(symname, 0, sizeof(symname));
812           memcpy(symname, type->enumeration.name, type->enumeration.namelen);
813           typeptr = DEBUG_NewDataType(ENUM, symname);
814           cv_defined_types[curr_type - 0x1000] = typeptr;
815
816           /*
817            * Now copy the relevant bits from the fieldlist that we specified.
818            */
819           subtype = DEBUG_GetCVType(type->enumeration.field);
820
821           if( subtype != NULL )
822             {
823               DEBUG_CopyFieldlist(typeptr, subtype);
824             }
825           break;
826         case LF_DIMARRAY:
827         default:
828           break;
829         }
830       curr_type++;
831       ptr.c += (type->generic.len + 3) & ~3;
832     }
833
834   return TRUE;
835 }
836
837 void
838 DEBUG_InitCVDataTypes()
839 {
840   /*
841    * These are the common builtin types that are used by VC++.
842    */
843   cv_basic_types[T_NOTYPE] = NULL;
844   cv_basic_types[T_ABS] = NULL;
845   cv_basic_types[T_VOID] = DEBUG_NewDataType(BASIC, "void");
846   cv_basic_types[T_CHAR] = DEBUG_NewDataType(BASIC, "char");
847   cv_basic_types[T_SHORT] = DEBUG_NewDataType(BASIC, "short int");
848   cv_basic_types[T_LONG] = DEBUG_NewDataType(BASIC, "long int");
849   cv_basic_types[T_QUAD] = DEBUG_NewDataType(BASIC, "long long int");
850   cv_basic_types[T_UCHAR] = DEBUG_NewDataType(BASIC, "unsigned char");
851   cv_basic_types[T_USHORT] = DEBUG_NewDataType(BASIC, "short unsigned int");
852   cv_basic_types[T_ULONG] = DEBUG_NewDataType(BASIC, "long unsigned int");
853   cv_basic_types[T_UQUAD] = DEBUG_NewDataType(BASIC, "long long unsigned int");
854   cv_basic_types[T_REAL32] = DEBUG_NewDataType(BASIC, "float");
855   cv_basic_types[T_REAL64] = DEBUG_NewDataType(BASIC, "double");
856   cv_basic_types[T_RCHAR] = DEBUG_NewDataType(BASIC, "char");
857   cv_basic_types[T_WCHAR] = DEBUG_NewDataType(BASIC, "short");
858   cv_basic_types[T_INT4] = DEBUG_NewDataType(BASIC, "int");
859   cv_basic_types[T_UINT4] = DEBUG_NewDataType(BASIC, "unsigned int");
860
861   cv_basic_types[T_32PVOID] = DEBUG_FindOrMakePointerType(cv_basic_types[T_VOID]);
862   cv_basic_types[T_32PCHAR] = DEBUG_FindOrMakePointerType(cv_basic_types[T_CHAR]);
863   cv_basic_types[T_32PSHORT] = DEBUG_FindOrMakePointerType(cv_basic_types[T_SHORT]);
864   cv_basic_types[T_32PLONG] = DEBUG_FindOrMakePointerType(cv_basic_types[T_LONG]);
865   cv_basic_types[T_32PQUAD] = DEBUG_FindOrMakePointerType(cv_basic_types[T_QUAD]);
866   cv_basic_types[T_32PUCHAR] = DEBUG_FindOrMakePointerType(cv_basic_types[T_UCHAR]);
867   cv_basic_types[T_32PUSHORT] = DEBUG_FindOrMakePointerType(cv_basic_types[T_USHORT]);
868   cv_basic_types[T_32PULONG] = DEBUG_FindOrMakePointerType(cv_basic_types[T_ULONG]);
869   cv_basic_types[T_32PUQUAD] = DEBUG_FindOrMakePointerType(cv_basic_types[T_UQUAD]);
870   cv_basic_types[T_32PREAL32] = DEBUG_FindOrMakePointerType(cv_basic_types[T_REAL32]);
871   cv_basic_types[T_32PREAL64] = DEBUG_FindOrMakePointerType(cv_basic_types[T_REAL64]);
872   cv_basic_types[T_32PRCHAR] = DEBUG_FindOrMakePointerType(cv_basic_types[T_RCHAR]);
873   cv_basic_types[T_32PWCHAR] = DEBUG_FindOrMakePointerType(cv_basic_types[T_WCHAR]);
874   cv_basic_types[T_32PINT4] = DEBUG_FindOrMakePointerType(cv_basic_types[T_INT4]);
875   cv_basic_types[T_32PUINT4] = DEBUG_FindOrMakePointerType(cv_basic_types[T_UINT4]);
876 }
877
878 /*
879  * In this function, we keep track of deferred debugging information
880  * that we may need later if we were to need to use the internal debugger.
881  * We don't fully process it here for performance reasons.
882  */
883 int
884 DEBUG_RegisterDebugInfo( HMODULE32 hModule, const char *module_name,
885                          u_long v_addr, u_long size)
886 {
887   int                     has_codeview = FALSE;
888   int                     rtn = FALSE;
889   int                     orig_size;
890   LPIMAGE_DEBUG_DIRECTORY dbgptr;
891   struct deferred_debug_info * deefer;
892
893   orig_size = size;
894   dbgptr = (LPIMAGE_DEBUG_DIRECTORY) (hModule + v_addr);
895   for(; size >= sizeof(*dbgptr); size -= sizeof(*dbgptr), dbgptr++ )
896     {
897       switch(dbgptr->Type)
898         {
899         case IMAGE_DEBUG_TYPE_CODEVIEW:
900         case IMAGE_DEBUG_TYPE_MISC:
901           has_codeview = TRUE;
902           break;
903         }
904     }
905
906   size = orig_size;
907   dbgptr = (LPIMAGE_DEBUG_DIRECTORY) (hModule + v_addr);
908   for(; size >= sizeof(*dbgptr); size -= sizeof(*dbgptr), dbgptr++ )
909     {
910       switch(dbgptr->Type)
911         {
912         case IMAGE_DEBUG_TYPE_COFF:
913           /*
914            * If we have both codeview and COFF debug info, ignore the
915            * coff debug info as  it would just confuse us, and it is 
916            * less complete.
917            *
918            * FIXME - this is broken - if we cannot find the PDB file, then
919            * we end up with no debugging info at all.  In this case, we
920            * should use the COFF info as a backup.
921            */
922           if( has_codeview )
923             {
924               break;
925             }
926         case IMAGE_DEBUG_TYPE_CODEVIEW:
927         case IMAGE_DEBUG_TYPE_MISC:
928           /*
929            * This is usually an indirection to a .DBG file.
930            * This is similar to (but a slightly older format) from the
931            * PDB file.
932            *
933            * First check to see if the image was 'stripped'.  If so, it
934            * means that this entry points to a .DBG file.  Otherwise,
935            * it just points to itself, and we can ignore this.
936            */
937           if(    (dbgptr->Type == IMAGE_DEBUG_TYPE_MISC)
938               && (PE_HEADER(hModule)->FileHeader.Characteristics & IMAGE_FILE_DEBUG_STRIPPED) == 0 )
939             {
940               break;
941             }
942
943           deefer = (struct deferred_debug_info *) xmalloc(sizeof(*deefer));
944           deefer->module    = hModule;
945           deefer->load_addr = (char *)hModule;
946           deefer->dbg_info  = NULL;
947           deefer->dbg_size  = 0;
948
949           /*
950            * Read the important bits.  What we do after this depends
951            * upon the type, but this is always enough so we are able
952            * to proceed if we know what we need to do next.
953            */
954           deefer->dbg_size = dbgptr->SizeOfData;
955           deefer->dbg_info = (char *)(hModule + dbgptr->PointerToRawData);
956           deefer->dbgdir = dbgptr;
957           deefer->next = dbglist;
958           deefer->loaded = FALSE;
959           deefer->dbg_index = DEBUG_next_index;
960           deefer->module_name = xstrdup(module_name);
961
962           deefer->sectp = PE_SECTIONS(hModule);
963           deefer->nsect = PE_HEADER(hModule)->FileHeader.NumberOfSections;
964
965           dbglist = deefer;
966           break;
967         default:
968         }
969     }
970
971   DEBUG_next_index++;
972
973   return (rtn);
974
975 }
976
977 /*
978  * ELF modules are also entered into the list - this is so that we
979  * can make 'info shared' types of displays possible.
980  */
981 int
982 DEBUG_RegisterELFDebugInfo(int load_addr, u_long size, char * name)
983 {
984   struct deferred_debug_info * deefer;
985
986   deefer = (struct deferred_debug_info *) xmalloc(sizeof(*deefer));
987   deefer->module = 0;
988   
989   /*
990    * Read the important bits.  What we do after this depends
991    * upon the type, but this is always enough so we are able
992    * to proceed if we know what we need to do next.
993    */
994   deefer->dbg_size = size;
995   deefer->dbg_info = (char *) NULL;
996   
997   deefer->load_addr = (char *) load_addr;
998   deefer->dbgdir = NULL;
999   deefer->next = dbglist;
1000   deefer->loaded = TRUE;
1001   deefer->dbg_index = DEBUG_next_index;
1002   deefer->module_name = xstrdup(name);
1003   dbglist = deefer;
1004
1005   DEBUG_next_index++;
1006
1007   return (TRUE);
1008 }
1009
1010
1011
1012 /*
1013  * Process COFF debugging information embedded in a Win32 application.
1014  *
1015  */
1016 static
1017 int
1018 DEBUG_ProcessCoff(struct deferred_debug_info * deefer)
1019 {
1020   struct CoffAuxSection * aux;
1021   struct CoffDebug   * coff;
1022   struct CoffFiles   * coff_files = NULL;
1023   struct CoffLinenum * coff_linetab;
1024   char               * coff_strtab;
1025   struct CoffSymbol  * coff_sym;
1026   struct CoffSymbol  * coff_symbol;
1027   struct CoffFiles   * curr_file = NULL;
1028   int                  i;
1029   int                  j;
1030   int                  k;
1031   struct CoffLinenum * linepnt;
1032   int                  linetab_indx;
1033   char                 namebuff[9];
1034   char               * nampnt;
1035   int                  naux;
1036   DBG_ADDR             new_addr;
1037   int                  nfiles = 0;
1038   int                  nfiles_alloc = 0;
1039   struct CoffFiles     orig_file;
1040   int                  rtn = FALSE;
1041   char               * this_file = NULL;
1042
1043   coff = (struct CoffDebug *) deefer->dbg_info;
1044
1045   coff_symbol = (struct CoffSymbol *) ((unsigned int) coff + coff->SymbolOffset);
1046   coff_linetab = (struct CoffLinenum *) ((unsigned int) coff + coff->LinenumberOffset);
1047   coff_strtab = (char *) ((unsigned int) coff_symbol + 18*coff->N_Sym);
1048
1049   linetab_indx = 0;
1050
1051   for(i=0; i < coff->N_Sym; i++ )
1052     {
1053       /*
1054        * We do this because some compilers (i.e. gcc) incorrectly
1055        * pad the structure up to a 4 byte boundary.  The structure
1056        * is really only 18 bytes long, so we have to manually make sure
1057        * we get it right.
1058        *
1059        * FIXME - there must be a way to have autoconf figure out the
1060        * correct compiler option for this.  If it is always gcc, that
1061        * makes life simpler, but I don't want to force this.
1062        */
1063       coff_sym = (struct CoffSymbol *) ((unsigned int) coff_symbol + 18*i);
1064       naux = coff_sym->NumberOfAuxSymbols;
1065
1066       if( coff_sym->StorageClass == IMAGE_SYM_CLASS_FILE )
1067         {
1068           if( nfiles + 1 >= nfiles_alloc )
1069             {
1070               nfiles_alloc += 10;
1071               coff_files = (struct CoffFiles *) realloc( coff_files,
1072                         nfiles_alloc * sizeof(struct CoffFiles));
1073             }
1074           curr_file = coff_files + nfiles;
1075           nfiles++;
1076           curr_file->startaddr = 0xffffffff;
1077           curr_file->endaddr   = 0;
1078           curr_file->filename =  ((char *) coff_sym) + 18;
1079           curr_file->linetab_offset = -1;
1080           curr_file->linecnt = 0;
1081           curr_file->entries = NULL;
1082           curr_file->neps = curr_file->neps_alloc = 0;
1083 #if 0
1084           fprintf(stderr,"New file %s\n", curr_file->filename);
1085 #endif
1086           i += naux;
1087           continue;
1088         }
1089
1090       /*
1091        * This guy marks the size and location of the text section
1092        * for the current file.  We need to keep track of this so
1093        * we can figure out what file the different global functions
1094        * go with.
1095        */
1096       if(    (coff_sym->StorageClass == IMAGE_SYM_CLASS_STATIC)
1097           && (naux != 0)
1098           && (coff_sym->Type == 0)
1099           && (coff_sym->SectionNumber == 1) )
1100         {
1101           aux = (struct CoffAuxSection *) ((unsigned int) coff_sym + 18);
1102
1103           if( curr_file->linetab_offset != -1 )
1104             {
1105 #if 0
1106               fprintf(stderr, "Duplicating sect from %s: %x %x %x %d %d\n",
1107                       curr_file->filename,
1108                       aux->Length,
1109                       aux->NumberOfRelocations,
1110                       aux->NumberOfLinenumbers,
1111                       aux->Number,
1112                       aux->Selection);
1113               fprintf(stderr, "More sect %d %x %d %d %d\n", 
1114                       coff_sym->SectionNumber,
1115                       coff_sym->Value,
1116                       coff_sym->Type,
1117                       coff_sym->StorageClass,
1118                       coff_sym->NumberOfAuxSymbols);
1119 #endif
1120
1121               /*
1122                * Save this so we can copy bits from it.
1123                */
1124               orig_file = *curr_file;
1125
1126               /*
1127                * Duplicate the file entry.  We have no way to describe
1128                * multiple text sections in our current way of handling things.
1129                */
1130               if( nfiles + 1 >= nfiles_alloc )
1131                 {
1132                   nfiles_alloc += 10;
1133                   coff_files = (struct CoffFiles *) realloc( coff_files,
1134                                                              nfiles_alloc * sizeof(struct CoffFiles));
1135                 }
1136               curr_file = coff_files + nfiles;
1137               nfiles++;
1138               curr_file->startaddr = 0xffffffff;
1139               curr_file->endaddr   = 0;
1140               curr_file->filename = orig_file.filename;
1141               curr_file->linetab_offset = -1;
1142               curr_file->linecnt = 0;
1143               curr_file->entries = NULL;
1144               curr_file->neps = curr_file->neps_alloc = 0;
1145             }
1146 #if 0
1147           else
1148             {
1149               fprintf(stderr, "New text sect from %s: %x %x %x %d %d\n",
1150                       curr_file->filename,
1151                       aux->Length,
1152                       aux->NumberOfRelocations,
1153                       aux->NumberOfLinenumbers,
1154                       aux->Number,
1155                       aux->Selection);
1156             }
1157 #endif
1158
1159           if( curr_file->startaddr > coff_sym->Value )
1160             {
1161               curr_file->startaddr = coff_sym->Value;
1162             }
1163           
1164           if( curr_file->startaddr > coff_sym->Value )
1165             {
1166               curr_file->startaddr = coff_sym->Value;
1167             }
1168           
1169           if( curr_file->endaddr < coff_sym->Value + aux->Length )
1170             {
1171               curr_file->endaddr = coff_sym->Value + aux->Length;
1172             }
1173           
1174           curr_file->linetab_offset = linetab_indx;
1175           curr_file->linecnt = aux->NumberOfLinenumbers;
1176           linetab_indx += aux->NumberOfLinenumbers;
1177           i += naux;
1178           continue;
1179         }
1180
1181       if(    (coff_sym->StorageClass == IMAGE_SYM_CLASS_STATIC)
1182           && (naux == 0)
1183           && (coff_sym->SectionNumber == 1) )
1184         {
1185           /*
1186            * This is a normal static function when naux == 0.
1187            * Just register it.  The current file is the correct
1188            * one in this instance.
1189            */
1190           if( coff_sym->N.Name.NotLong )
1191             {
1192               memcpy(namebuff, coff_sym->N.ShortName, 8);
1193               namebuff[8] = '\0';
1194               nampnt = &namebuff[0];
1195             }
1196           else
1197             {
1198               nampnt = coff_strtab + coff_sym->N.Name.StrTaboff;
1199             }
1200
1201           if( nampnt[0] == '_' )
1202             {
1203               nampnt++;
1204             }
1205
1206           new_addr.seg = 0;
1207           new_addr.off = (int) (deefer->load_addr + coff_sym->Value);
1208
1209           if( curr_file->neps + 1 >= curr_file->neps_alloc )
1210             {
1211               curr_file->neps_alloc += 10;
1212               curr_file->entries = (struct name_hash **) 
1213                 realloc( curr_file->entries, 
1214                          curr_file->neps_alloc * sizeof(struct name_hash *));
1215             }
1216 #if 0
1217           fprintf(stderr,"\tAdding static symbol %s\n", nampnt);
1218 #endif
1219           curr_file->entries[curr_file->neps++] =
1220             DEBUG_AddSymbol( nampnt, &new_addr, this_file, SYM_WIN32 );
1221           i += naux;
1222           continue;
1223         }
1224
1225       if(    (coff_sym->StorageClass == IMAGE_SYM_CLASS_EXTERNAL)
1226           && ISFCN(coff_sym->Type)
1227           && (coff_sym->SectionNumber > 0) )
1228         {
1229           if( coff_sym->N.Name.NotLong )
1230             {
1231               memcpy(namebuff, coff_sym->N.ShortName, 8);
1232               namebuff[8] = '\0';
1233               nampnt = &namebuff[0];
1234             }
1235           else
1236             {
1237               nampnt = coff_strtab + coff_sym->N.Name.StrTaboff;
1238             }
1239
1240
1241           if( nampnt[0] == '_' )
1242             {
1243               nampnt++;
1244             }
1245
1246           new_addr.seg = 0;
1247           new_addr.off = (int) (deefer->load_addr + coff_sym->Value);
1248
1249 #if 0
1250           fprintf(stderr, "%d: %x %s\n", i, new_addr.off, nampnt);
1251
1252           fprintf(stderr,"\tAdding global symbol %s\n", nampnt);
1253 #endif
1254
1255           /*
1256            * Now we need to figure out which file this guy belongs to.
1257            */
1258           this_file = NULL;
1259           for(j=0; j < nfiles; j++)
1260             {
1261               if( coff_files[j].startaddr <= coff_sym->Value
1262                   && coff_files[j].endaddr > coff_sym->Value )
1263                 {
1264                   this_file = coff_files[j].filename;
1265                   break;
1266                 }
1267             }
1268           if( coff_files[j].neps + 1 >= coff_files[j].neps_alloc )
1269             {
1270               coff_files[j].neps_alloc += 10;
1271               coff_files[j].entries = (struct name_hash **) 
1272                 realloc( coff_files[j].entries, 
1273                          coff_files[j].neps_alloc * sizeof(struct name_hash *));
1274             }
1275           coff_files[j].entries[coff_files[j].neps++] =
1276             DEBUG_AddSymbol( nampnt, &new_addr, this_file, SYM_WIN32 );
1277           i += naux;
1278           continue;
1279         }
1280
1281       if(    (coff_sym->StorageClass == IMAGE_SYM_CLASS_EXTERNAL)
1282           && (coff_sym->SectionNumber > 0) )
1283         {
1284           /*
1285            * Similar to above, but for the case of data symbols.
1286            * These aren't treated as entrypoints.
1287            */
1288           if( coff_sym->N.Name.NotLong )
1289             {
1290               memcpy(namebuff, coff_sym->N.ShortName, 8);
1291               namebuff[8] = '\0';
1292               nampnt = &namebuff[0];
1293             }
1294           else
1295             {
1296               nampnt = coff_strtab + coff_sym->N.Name.StrTaboff;
1297             }
1298
1299
1300           if( nampnt[0] == '_' )
1301             {
1302               nampnt++;
1303             }
1304
1305           new_addr.seg = 0;
1306           new_addr.off = (int) (deefer->load_addr + coff_sym->Value);
1307
1308 #if 0
1309           fprintf(stderr, "%d: %x %s\n", i, new_addr.off, nampnt);
1310
1311           fprintf(stderr,"\tAdding global data symbol %s\n", nampnt);
1312 #endif
1313
1314           /*
1315            * Now we need to figure out which file this guy belongs to.
1316            */
1317           DEBUG_AddSymbol( nampnt, &new_addr, NULL, SYM_WIN32 );
1318           i += naux;
1319           continue;
1320         }
1321           
1322       if(    (coff_sym->StorageClass == IMAGE_SYM_CLASS_STATIC)
1323           && (naux == 0) )
1324         {
1325           /*
1326            * Ignore these.  They don't have anything to do with
1327            * reality.
1328            */
1329           i += naux;
1330           continue;
1331         }
1332
1333 #if 0
1334       fprintf(stderr,"Skipping unknown entry %d %d %d\n", coff_sym->StorageClass, 
1335               coff_sym->SectionNumber, naux);
1336 #endif
1337
1338       /*
1339        * For now, skip past the aux entries.
1340        */
1341       i += naux;
1342       
1343     }
1344     
1345   /*
1346    * OK, we now should have a list of files, and we should have a list
1347    * of entrypoints.  We need to sort the entrypoints so that we are
1348    * able to tie the line numbers with the given functions within the
1349    * file.
1350    */
1351   if( coff_files != NULL )
1352     {
1353       for(j=0; j < nfiles; j++)
1354         {
1355           if( coff_files[j].entries != NULL )
1356             {
1357               qsort(coff_files[j].entries, coff_files[j].neps,
1358                     sizeof(struct name_hash *), DEBUG_cmp_sym);
1359             }
1360         }
1361
1362       /*
1363        * Now pick apart the line number tables, and attach the entries
1364        * to the given functions.
1365        */
1366       for(j=0; j < nfiles; j++)
1367         {
1368           i = 0;
1369           for(k=0; k < coff_files[j].linecnt; k++)
1370             {
1371               /*
1372                * Another monstrosity caused by the fact that we are using
1373                * a 6 byte structure, and gcc wants to pad structures to 4 byte
1374                * boundaries.  Otherwise we could just index into an array.
1375                */
1376               linepnt = (struct CoffLinenum *) 
1377                 ((unsigned int) coff_linetab + 
1378                  6*(coff_files[j].linetab_offset + k));
1379               /*
1380                * If we have spilled onto the next entrypoint, then
1381                * bump the counter..
1382                */
1383               while(TRUE)
1384                 {
1385                   DEBUG_GetSymbolAddr(coff_files[j].entries[i+1], &new_addr);
1386                   if(   (i+1 < coff_files[j].neps)
1387                         && (   ((unsigned int) deefer->load_addr + linepnt->VirtualAddr)
1388                                >= new_addr.off) )
1389                     {
1390                       i++;
1391                     }
1392                   else
1393                     {
1394                       break;
1395                     }
1396                 }
1397
1398               /*
1399                * Add the line number.  This is always relative to the
1400                * start of the function, so we need to subtract that offset
1401                * first.
1402                */
1403               DEBUG_GetSymbolAddr(coff_files[j].entries[i], &new_addr);
1404               DEBUG_AddLineNumber(coff_files[j].entries[i], 
1405                                   linepnt->Linenum,
1406                                   (unsigned int) deefer->load_addr 
1407                                   + linepnt->VirtualAddr 
1408                                   - new_addr.off);
1409             }
1410         }
1411     }
1412
1413   rtn = TRUE;
1414
1415   if( coff_files != NULL )
1416     {
1417       for(j=0; j < nfiles; j++)
1418         {
1419           if( coff_files[j].entries != NULL )
1420             {
1421               free(coff_files[j].entries);
1422             }
1423         }
1424       free(coff_files);
1425     }
1426
1427   return (rtn);
1428
1429 }
1430
1431 /*
1432  * Process a codeview line number table.  Digestify the thing so that
1433  * we can easily reference the thing when we process the rest of
1434  * the information.
1435  */
1436 static struct codeview_linetab_hdr *
1437 DEBUG_SnarfLinetab(char                      * linetab,
1438                    int                         size)
1439 {
1440   int                             file_segcount;
1441   char                            filename[PATH_MAX];
1442   unsigned int                  * filetab;
1443   char                          * fn;
1444   int                             i;
1445   int                             k;
1446   struct codeview_linetab_hdr   * lt_hdr;
1447   unsigned int                  * lt_ptr;
1448   int                             nfile;
1449   int                             nseg;
1450   union any_size                  pnt;
1451   union any_size                  pnt2;
1452   struct startend               * start;
1453   int                             this_seg;
1454
1455   /*
1456    * Now get the important bits.
1457    */
1458   pnt = (union any_size) linetab;
1459   nfile = *pnt.s++;
1460   nseg = *pnt.s++;
1461
1462   filetab = (unsigned int *) pnt.c;
1463
1464   /*
1465    * Now count up the number of segments in the file.
1466    */
1467   nseg = 0;
1468   for(i=0; i<nfile; i++)
1469     {
1470       pnt2 = (union any_size) (linetab + filetab[i]);
1471       nseg += *pnt2.s;
1472     }
1473
1474   /*
1475    * Next allocate the header we will be returning.
1476    * There is one header for each segment, so that we can reach in
1477    * and pull bits as required.
1478    */
1479   lt_hdr = (struct codeview_linetab_hdr *) 
1480     xmalloc((nseg + 1) * sizeof(*lt_hdr));
1481   if( lt_hdr == NULL )
1482     {
1483       goto leave;
1484     }
1485
1486   memset(lt_hdr, 0, sizeof(*lt_hdr) * (nseg+1));
1487
1488   /*
1489    * Now fill the header we will be returning, one for each segment.
1490    * Note that this will basically just contain pointers into the existing
1491    * line table, and we do not actually copy any additional information
1492    * or allocate any additional memory.
1493    */
1494
1495   this_seg = 0;
1496   for(i=0; i<nfile; i++)
1497     {
1498       /*
1499        * Get the pointer into the segment information.
1500        */
1501       pnt2 = (union any_size) (linetab + filetab[i]);
1502       file_segcount = *pnt2.s;
1503
1504       pnt2.ui++;
1505       lt_ptr = (unsigned int *) pnt2.c;
1506       start = (struct startend *) (lt_ptr + file_segcount);
1507
1508       /*
1509        * Now snarf the filename for all of the segments for this file.
1510        */
1511       fn = (unsigned char *) (start + file_segcount);
1512       memset(filename, 0, sizeof(filename));
1513       memcpy(filename, fn + 1, *fn);
1514       fn = strdup(filename);
1515
1516       for(k = 0; k < file_segcount; k++, this_seg++)
1517         {
1518           pnt2 = (union any_size) (linetab + lt_ptr[k]);
1519           lt_hdr[this_seg].start      = start[k].start;
1520           lt_hdr[this_seg].end        = start[k].end;
1521           lt_hdr[this_seg].sourcefile = fn;
1522           lt_hdr[this_seg].segno      = *pnt2.s++;
1523           lt_hdr[this_seg].nline      = *pnt2.s++;
1524           lt_hdr[this_seg].offtab     =  pnt2.ui;
1525           lt_hdr[this_seg].linetab    = (unsigned short *) 
1526             (pnt2.ui + lt_hdr[this_seg].nline);
1527         }
1528     }
1529
1530 leave:
1531
1532   return lt_hdr;
1533
1534 }
1535
1536 static int
1537 DEBUG_SnarfCodeView(      struct deferred_debug_info * deefer,
1538                           char                       * cv_data,
1539                           int                          size,
1540                           struct codeview_linetab_hdr * linetab)
1541 {
1542   struct name_hash      * curr_func = NULL;
1543   struct wine_locals    * curr_sym = NULL;
1544   int                     i;
1545   int                     j;
1546   int                     len;
1547   DBG_ADDR                new_addr;
1548   int                     nsect;
1549   union any_size          ptr;
1550   IMAGE_SECTION_HEADER  * sectp;
1551   union codeview_symbol * sym;
1552   char                    symname[PATH_MAX];
1553   struct name_hash      * thunk_sym = NULL;
1554
1555   ptr = (union any_size) cv_data;
1556   nsect = deefer->nsect;
1557   sectp = deefer->sectp;
1558
1559   /*
1560    * Skip over the first word.  Don't really know what it means, but
1561    * it is useless.
1562    */
1563   ptr.ui++;
1564
1565   /*
1566    * Loop over the different types of records and whenever we
1567    * find something we are interested in, record it and move on.
1568    */
1569   while( ptr.c - cv_data < size )
1570     {
1571       sym = (union codeview_symbol *) ptr.c;
1572
1573       if( sym->generic.len - sizeof(int) == (ptr.c - cv_data) )
1574         {
1575           /*
1576            * This happens when we have indirect symbols that VC++ 4.2
1577            * sometimes uses when there isn't a line number table.
1578            * We ignore it - we will process and enter all of the
1579            * symbols in the global symbol table anyways, so there
1580            * isn't much point in keeping track of all of this crap.
1581            */
1582           break;
1583         }
1584
1585       memset(symname, 0, sizeof(symname));
1586       switch(sym->generic.id)
1587         {
1588         case S_GDATA32:
1589         case S_LDATA32:
1590         case S_PUB32:
1591           /*
1592            * First, a couple of sanity checks.
1593            */
1594           if( sym->data.namelen == 0 )
1595             {
1596               break;
1597             }
1598
1599           if( sym->data.seg == 0 || sym->data.seg > nsect )
1600             {
1601               break;
1602             }
1603
1604           /*
1605            * Global and local data symbols.  We don't associate these
1606            * with any given source file.
1607            */
1608
1609           memcpy(symname, sym->data.name, sym->data.namelen);
1610           new_addr.seg = 0;
1611           new_addr.type = DEBUG_GetCVType(sym->data.symtype);
1612           new_addr.off = (unsigned int) deefer->load_addr + 
1613             sectp[sym->data.seg - 1].VirtualAddress + 
1614             sym->data.offset;
1615           DEBUG_AddSymbol( symname, &new_addr, NULL, SYM_WIN32 | SYM_DATA );
1616           break;
1617         case S_THUNK32:
1618           /*
1619            * Sort of like a global function, but it just points
1620            * to a thunk, which is a stupid name for what amounts to
1621            * a PLT slot in the normal jargon that everyone else uses.
1622            */
1623           memcpy(symname, sym->thunk.name, sym->thunk.namelen);
1624           new_addr.seg = 0;
1625           new_addr.type = NULL;
1626           new_addr.off = (unsigned int) deefer->load_addr + 
1627             sectp[sym->thunk.segment - 1].VirtualAddress + 
1628             sym->thunk.offset;
1629           thunk_sym = DEBUG_AddSymbol( symname, &new_addr, NULL, 
1630                                        SYM_WIN32 | SYM_FUNC);
1631           DEBUG_SetSymbolSize(thunk_sym, sym->thunk.thunk_len);
1632           break;
1633         case S_GPROC32:
1634         case S_LPROC32:
1635           /*
1636            * Global and static functions.
1637            */
1638           memcpy(symname, sym->proc.name, sym->proc.namelen);
1639           new_addr.seg = 0;
1640           new_addr.type = DEBUG_GetCVType(sym->proc.proctype);
1641           new_addr.off = (unsigned int) deefer->load_addr + 
1642             sectp[sym->proc.segment - 1].VirtualAddress + 
1643             sym->proc.offset;
1644           /*
1645            * See if we can find a segment that this goes with.  If so,
1646            * it means that we also may have line number information
1647            * for this function.
1648            */
1649           for(i=0; linetab[i].linetab != NULL; i++)
1650             {
1651               if(     ((unsigned int) deefer->load_addr 
1652                        + sectp[linetab[i].segno - 1].VirtualAddress 
1653                        + linetab[i].start <= new_addr.off)
1654                   &&  ((unsigned int) deefer->load_addr 
1655                        + sectp[linetab[i].segno - 1].VirtualAddress 
1656                        + linetab[i].end > new_addr.off) )
1657                 {
1658                   break;
1659                 }
1660             }
1661
1662           DEBUG_Normalize(curr_func);
1663           if( linetab[i].linetab == NULL )
1664             {
1665               curr_func = DEBUG_AddSymbol( symname, &new_addr, NULL,
1666                                            SYM_WIN32 | SYM_FUNC);
1667             }
1668           else
1669             {
1670               /*
1671                * First, create the entry.  Then dig through the linetab
1672                * and add whatever line numbers are appropriate for this
1673                * function.
1674                */
1675               curr_func = DEBUG_AddSymbol( symname, &new_addr, 
1676                                            linetab[i].sourcefile,
1677                                            SYM_WIN32 | SYM_FUNC);
1678               for(j=0; j < linetab[i].nline; j++)
1679                 {
1680                   if( linetab[i].offtab[j] >= sym->proc.offset 
1681                       && linetab[i].offtab[j] < sym->proc.offset 
1682                       + sym->proc.proc_len )
1683                     {
1684                       DEBUG_AddLineNumber(curr_func, linetab[i].linetab[j],
1685                                           linetab[i].offtab[j] - sym->proc.offset);
1686                     }
1687                 }
1688
1689             }
1690
1691           /*
1692            * Add information about where we should set breakpoints
1693            * in this function.
1694            */
1695           DEBUG_SetSymbolBPOff(curr_func, sym->proc.debug_start);
1696           DEBUG_SetSymbolSize(curr_func, sym->proc.proc_len);
1697           break;
1698         case S_BPREL32:
1699           /*
1700            * Function parameters and stack variables.
1701            */
1702           memcpy(symname, sym->stack.name, sym->stack.namelen);
1703           curr_sym = DEBUG_AddLocal(curr_func, 
1704                          0, 
1705                          sym->stack.offset, 
1706                          0, 
1707                          0, 
1708                          symname);
1709           DEBUG_SetLocalSymbolType(curr_sym, DEBUG_GetCVType(sym->stack.symtype));
1710           
1711           break;
1712         default:
1713           break;
1714         }
1715
1716       /*
1717        * Adjust pointer to point to next entry, rounding up to a word
1718        * boundary.  MS preserving alignment?  Stranger things have
1719        * happened.
1720        */
1721       if( sym->generic.id == S_PROCREF
1722           || sym->generic.id == S_DATAREF
1723           || sym->generic.id == S_UNKNOWN )
1724         {
1725           len = (sym->generic.len + 3) & ~3;
1726           len += ptr.c[16] + 1;
1727           ptr.c += (len + 3) & ~3;
1728         }
1729       else
1730         {
1731           ptr.c += (sym->generic.len + 3) & ~3;
1732         }
1733     }
1734
1735   if( linetab != NULL )
1736     {
1737       free(linetab);
1738     }
1739
1740   return TRUE;
1741 }
1742
1743
1744 /*
1745  * Process PDB file which contains debug information.
1746  *
1747  * These are really weird beasts.  They are intended to be incrementally
1748  * updated by the incremental linker, and this means that you need to 
1749  * be able to remove and add information.  Thus the PDB file is sort of
1750  * like a block structured device, with a freelist and lists of extent numbers
1751  * that are used to get the relevant pieces.  In all cases seen so far, the
1752  * blocksize is always 0x400 bytes.  The header has a field which apparently
1753  * holds the blocksize, so if it ever changes we are safe.
1754  *
1755  * In general, every time we need to extract something from the pdb file,
1756  * it is easier to copy it into another buffer so we have the information
1757  * in one contiguous block rather than attempt to try and keep track of when
1758  * we need to grab another extent from the pdb file.
1759  *
1760  * The thing that is a real pain about some MS stuff is that they choose
1761  * data structures which are not representable in C.  Thus we have to
1762  * hack around and diddle pointers.
1763  */
1764 /* static */
1765 int
1766 DEBUG_ProcessPDBFile(struct deferred_debug_info * deefer, char * full_filename)
1767 {
1768   char                        * addr = (char *) 0xffffffff;
1769   unsigned int                  blocksize;
1770   unsigned int                  bufflen = 0;
1771   char                        * buffer = NULL;
1772   unsigned short              * extent_table;
1773   int                           fd = -1;
1774   struct file_ent             * fent;
1775   char                        * filename;
1776   struct file_list            * filelist = NULL;
1777   unsigned int                  gsym_record = 0;
1778   char                        * gsymtab = NULL;
1779   struct filetab_hdr          * hd;
1780   int                           i;
1781   int                           j;
1782   unsigned int                  last_extent;
1783   struct codeview_linetab_hdr * linetab;
1784   unsigned int                  nblocks;
1785   unsigned int                  npair;
1786   unsigned int                  offset;
1787   struct codeview_pdb_hdr     * pdbhdr;
1788   unsigned int                * pnt;
1789   struct stat                   statbuf;
1790   int                           status;
1791   unsigned short              * table;
1792   char                        * toc;
1793   unsigned int                  toc_blocks;
1794   
1795   /*
1796    * FIXME - we should use some kind of search path mechanism to locate
1797    * PDB files.  Right now we just look in the current working directory,
1798    * which works much of the time, I guess.  Ideally we should be able to
1799    * map the filename back using the settings in wine.ini and perhaps
1800    * we could find it there.  This bit of coding is left as an exercise
1801    * for the reader. :-).
1802    */
1803   filename = strrchr(full_filename, '\\');
1804   if( filename == NULL )
1805     {
1806       filename = full_filename;
1807     }
1808   else
1809     {
1810       filename++;
1811     }
1812
1813   status = stat(filename, &statbuf);
1814   if( status == -1 )
1815     {
1816       fprintf(stderr, "Unable to open .PDB file %s\n", filename);
1817       goto leave;
1818     }
1819
1820   /*
1821    * Now open the file, so that we can mmap() it.
1822    */
1823   fd = open(filename, O_RDONLY);
1824   if( fd == -1 )
1825     {
1826       fprintf(stderr, "Unable to open .DBG file %s\n", filename);
1827       goto leave;
1828     }
1829
1830
1831   /*
1832    * Now mmap() the file.
1833    */
1834   addr = mmap(0, statbuf.st_size, PROT_READ, 
1835               MAP_PRIVATE, fd, 0);
1836   if( addr == (char *) 0xffffffff )
1837     {
1838       fprintf(stderr, "Unable to mmap .DBG file %s\n", filename);
1839       goto leave;
1840     }
1841
1842   /*
1843    * Now that we have the formalities over and done with, we need
1844    * to find the table of contents for the PDB file.
1845    */
1846   pdbhdr = (struct codeview_pdb_hdr *) addr;
1847   blocksize = pdbhdr->blocksize;
1848   last_extent = (statbuf.st_size + blocksize - 1) / blocksize;
1849
1850   /*
1851    * The TOC itself isn't always contiguous, so we need to extract a few
1852    * extents from the file to form the TOC.
1853    */
1854   toc_blocks = (pdbhdr->toc_len + blocksize - 1) / blocksize;
1855   toc = (char *) xmalloc(toc_blocks * blocksize);
1856   table = pdbhdr->toc_ext;
1857   for(i=0; i < toc_blocks; i++)
1858     {
1859       memcpy(toc + blocksize*i, addr + table[i]*blocksize, blocksize);
1860     }
1861
1862   /*
1863    * Next build our own table which will have the size and extent block
1864    * list for each record in the PDB file.
1865    *
1866    * The TOC starts out with the number of files.  Then it is followed by
1867    * (npair * 2*sizeof(int)) bytes of information, which are pairs of ints.
1868    * The first one is the size of the record (in bytes), and the second one
1869    * is something else which I haven't figured out yet.
1870    */
1871   pnt = (unsigned int *) toc;
1872   npair = *pnt++;
1873   extent_table = (unsigned short *) ((unsigned int) toc +
1874                                      npair * 2 * sizeof(int) + sizeof(int));
1875
1876   /*
1877    * Sanity check.
1878    */
1879   if( sizeof(int) + 2*sizeof(int)*npair > pdbhdr->toc_len )
1880     {
1881       goto leave;
1882     }
1883   
1884   filelist = (struct file_list *) xmalloc(npair * sizeof(*filelist));
1885   if( filelist == NULL )
1886     {
1887       goto leave;
1888     }
1889   memset(filelist, 0, npair * sizeof(*filelist));
1890
1891   nblocks = 0;
1892   for(i=0; i < npair; i++)
1893     {
1894       filelist[i].record_len = pnt[i*2];
1895       filelist[i].nextents   = (filelist[i].record_len + blocksize - 1) 
1896         / blocksize;
1897       filelist[i].extent_list = extent_table + nblocks;
1898       nblocks += filelist[i].nextents;
1899
1900       /*
1901        * These get filled in later when we parse one of the records.
1902        */
1903       filelist[i].linetab_offset = 0;
1904       filelist[i].linetab_len = 0;
1905     }
1906
1907   /*
1908    * OK, now walk through the various records and pick out the bits we
1909    * really want to see.  Some of the records are extra special, and
1910    * we need to handle these a little bit differently.
1911    */
1912   for(i=0; i < npair; i++)
1913     {
1914       if( filelist[i].record_len == 0xffffffff )
1915         {
1916           continue;
1917         }
1918
1919       /*
1920        * Make sure our buffer is large enough to hold the record.
1921        */
1922       if( bufflen < filelist[i].nextents * blocksize )
1923         {
1924           bufflen = filelist[i].nextents * blocksize;
1925           buffer = (char *) realloc(buffer, bufflen);
1926         }
1927
1928       /*
1929        * Do this just for completeness.  It makes debugging easier
1930        * if we have a clean indication of where the record ends.
1931        */
1932       memset(buffer, 0, filelist[i].nextents * blocksize);
1933
1934       /*
1935        * Next, build the record using the extent list.
1936        */
1937       for(j=0; j < filelist[i].nextents; j++)
1938         {
1939           memcpy(buffer + j * blocksize,
1940                  addr + filelist[i].extent_list[j] * blocksize,
1941                  blocksize);
1942         }
1943
1944       pnt = (unsigned int *) buffer;
1945
1946       /*
1947        * OK, now figure out what to do with it.
1948        */
1949
1950       /*
1951        * Always ignore the first entry.  It seems to contain a backup copy
1952        * of the TOC (the last time the file was modified??)
1953        */
1954       if( i == 0 )
1955         {
1956           continue;
1957         }
1958
1959       /* 
1960        * The second entry as a id block.  It contains a magic number
1961        * to identify the compiler, plus it also contains the timestamp
1962        * which must match the timestamp in the executable.  
1963        */
1964       if( i == 1 )
1965         {
1966
1967           if( ((*pnt != 19950623) && (*pnt != 19950814))
1968               || (filelist[i].record_len != 0x24)
1969               || (pnt[1] != ((struct CodeViewDebug *)(deefer->dbg_info))->cv_timestamp) )
1970             {
1971               goto leave;
1972             }
1973         }
1974
1975       /*
1976        * The third entry contains pointers to the global symbol table,
1977        * plus it also contains additional information about each record
1978        * in the PDB file.
1979        */
1980       if( i == 3 )
1981         {
1982           hd = (struct filetab_hdr *) buffer;
1983
1984           gsym_record = hd->gsym_file;
1985           gsymtab = (char *) xmalloc( filelist[gsym_record].nextents 
1986                                       * blocksize);
1987           memset(gsymtab, 0, filelist[gsym_record].nextents * blocksize);
1988           
1989           for(j=0; j < filelist[gsym_record].nextents; j++)
1990             {
1991               memcpy(gsymtab + j * blocksize,
1992                      addr + filelist[gsym_record].extent_list[j] * blocksize,
1993                      blocksize);
1994             }
1995
1996           /*
1997            * This record also contains information about where in the
1998            * remaining records we will be able to find the start of the
1999            * line number table.  We could locate that bit using heuristics,
2000            * but since we have the info handy, we might as well use it.
2001            */
2002           offset = sizeof(*hd);
2003           while(1==1)
2004             {
2005               fent = (struct file_ent *) (buffer + offset);
2006               if( offset > hd->ftab_len )
2007                 {
2008                   break;
2009                 }
2010
2011               if( fent->file_number == 0 || fent->file_number >= npair )
2012                 {
2013                   break;
2014                 }
2015
2016               filelist[fent->file_number].linetab_offset = 
2017                 fent->linetab_offset;
2018               filelist[fent->file_number].linetab_len = 
2019                 fent->linetab_len;
2020               /*
2021                * Figure out the offset of the next entry.
2022                * There is a fixed part of the record and a variable
2023                * length filename which we must also skip past.
2024                */
2025               offset += ((unsigned int) &fent->filename - (unsigned int) fent)
2026                 + strlen(fent->filename) + 1;
2027               offset += strlen(buffer+offset) + 1;
2028               offset = (offset + 3) & ~3;
2029             }
2030         }
2031       
2032
2033       /*
2034        * Two different magic numbers used as dates.
2035        * These indicate the 'type' table.
2036        */
2037       if(       *pnt == 19950410
2038              || *pnt == 19951122 )
2039         {
2040           DEBUG_ParseTypeTable(buffer, filelist[i].record_len);
2041           continue;
2042         }
2043
2044       /*
2045        * This is something we really want to look at, since it contains
2046        * real debug info.  Anything that doesn't match this can be
2047        * ignored for now.
2048        */
2049       if( *pnt == 1 )
2050         {
2051           /*
2052            * First, snag the line table, if we have one.  This always
2053            * occurs at the end of the record, so we take the linetab
2054            * offset as the end of the normal part of the record.
2055            */
2056           linetab = NULL;
2057           if( filelist[i].linetab_len != 0 )
2058             {
2059               linetab = DEBUG_SnarfLinetab(buffer + filelist[i].linetab_offset,
2060                                            filelist[i].linetab_len);
2061               DEBUG_SnarfCodeView(deefer, buffer,
2062                                   filelist[i].linetab_offset,
2063                                   linetab);
2064             }
2065           else
2066             {
2067               DEBUG_SnarfCodeView(deefer, buffer,
2068                                   filelist[i].record_len,
2069                                   linetab);
2070             }
2071           continue;
2072         }
2073     }
2074
2075   /*
2076    * Finally, process the global symbol table itself.  There isn't
2077    * a line number component to this, so we just toss everything
2078    * into the mix and it all should work out.
2079    */
2080   if( gsym_record != 0 )
2081     {
2082       DEBUG_SnarfCodeView(deefer, gsymtab - sizeof(int), 
2083                           filelist[gsym_record].record_len,
2084                           NULL);
2085     }
2086   
2087 leave:
2088
2089   if( gsymtab != NULL )
2090     {
2091       free(gsymtab);
2092       gsymtab = NULL;
2093     }
2094
2095   if( buffer != NULL )
2096     {
2097       free(buffer);
2098     }
2099
2100   if( filelist != NULL )
2101     {
2102       free(filelist);
2103     }
2104
2105   if( addr != (char *) 0xffffffff )
2106     {
2107       munmap(addr, statbuf.st_size);
2108     }
2109
2110   if( fd != -1 )
2111     {
2112       close(fd);
2113     }
2114
2115   return TRUE;
2116 }
2117
2118 /*
2119  * Process DBG file which contains debug information.
2120  */
2121 /* static */
2122 int
2123 DEBUG_ProcessDBGFile(struct deferred_debug_info * deefer, char * filename)
2124 {
2125   char                        * addr = (char *) 0xffffffff;
2126   char                        * codeview;
2127   struct CV4_DirHead          * codeview_dir;
2128   struct CV4_DirEnt           * codeview_dent;
2129   LPIMAGE_DEBUG_DIRECTORY       dbghdr;
2130   struct deferred_debug_info    deefer2;
2131   int                           fd = -1;
2132   int                           i;
2133   int                           j;
2134   struct codeview_linetab_hdr * linetab;
2135   int                           nsect;
2136   LPIMAGE_SEPARATE_DEBUG_HEADER pdbg = NULL;
2137   IMAGE_SECTION_HEADER        * sectp;
2138   struct stat                   statbuf;
2139   int                           status;
2140   
2141   status = stat(filename, &statbuf);
2142   if( status == -1 )
2143     {
2144       fprintf(stderr, "Unable to open .DBG file %s\n", filename);
2145       goto leave;
2146     }
2147
2148   /*
2149    * Now open the file, so that we can mmap() it.
2150    */
2151   fd = open(filename, O_RDONLY);
2152   if( fd == -1 )
2153     {
2154       fprintf(stderr, "Unable to open .DBG file %s\n", filename);
2155       goto leave;
2156     }
2157
2158
2159   /*
2160    * Now mmap() the file.
2161    */
2162   addr = mmap(0, statbuf.st_size, PROT_READ, 
2163               MAP_PRIVATE, fd, 0);
2164   if( addr == (char *) 0xffffffff )
2165     {
2166       fprintf(stderr, "Unable to mmap .DBG file %s\n", filename);
2167       goto leave;
2168     }
2169
2170   pdbg = (LPIMAGE_SEPARATE_DEBUG_HEADER) addr;
2171
2172   if( pdbg->TimeDateStamp != deefer->dbgdir->TimeDateStamp )
2173     {
2174       fprintf(stderr, "Warning - %s has incorrect internal timestamp\n",
2175               filename);
2176       goto leave;
2177    }
2178
2179   fprintf(stderr, "Processing symbols from %s...\n", filename);
2180
2181   dbghdr = (LPIMAGE_DEBUG_DIRECTORY) (  addr + sizeof(*pdbg) 
2182                  + pdbg->NumberOfSections * sizeof(IMAGE_SECTION_HEADER) 
2183                  + pdbg->ExportedNamesSize);
2184
2185   sectp = (LPIMAGE_SECTION_HEADER) ((char *) pdbg + sizeof(*pdbg));
2186   nsect = pdbg->NumberOfSections;
2187
2188   for( i=0; i < pdbg->DebugDirectorySize / sizeof(*pdbg); i++, dbghdr++ )
2189     {
2190       switch(dbghdr->Type)
2191                 {
2192                 case IMAGE_DEBUG_TYPE_COFF:
2193                   /*
2194                    * Dummy up a deferred debug header to handle the
2195                    * COFF stuff embedded within the DBG file.
2196                    */
2197                   memset((char *) &deefer2, 0, sizeof(deefer2));
2198                   deefer2.dbg_info = (addr + dbghdr->PointerToRawData);
2199                   deefer2.dbg_size = dbghdr->SizeOfData;
2200                   deefer2.load_addr = deefer->load_addr;
2201
2202                   DEBUG_ProcessCoff(&deefer2);
2203                   break;
2204                 case IMAGE_DEBUG_TYPE_CODEVIEW:
2205                   /*
2206                    * This is the older format by which codeview stuff is 
2207                    * stored, known as the 'NB09' format.  Newer executables
2208                    * and dlls created by VC++ use PDB files instead, which
2209                    * have lots of internal similarities, but the overall
2210                    * format and structure is quite different.
2211                    */
2212                   codeview = (addr + dbghdr->PointerToRawData);
2213
2214                   /*
2215                    * The first thing in the codeview section should be
2216                    * an 'NB09' identifier.  As a sanity check, make sure
2217                    * it is there.
2218                    */
2219                   if( *((unsigned int*) codeview) != 0x3930424e )
2220                     {
2221                       break;
2222                     }
2223                   
2224                   /*
2225                    * Next we need to find the directory.  This is easy too.
2226                    */
2227                   codeview_dir = (struct CV4_DirHead *) 
2228                     (codeview + ((unsigned int*) codeview)[1]);
2229
2230                   /*
2231                    * Some more sanity checks.  Make sure that everything
2232                    * is as we expect it.
2233                    */
2234                   if( codeview_dir->next_offset != 0 
2235                       || codeview_dir->dhsize != sizeof(*codeview_dir)
2236                       || codeview_dir->desize != sizeof(*codeview_dent) )
2237                     {
2238                       break;
2239                     }
2240                   codeview_dent = (struct CV4_DirEnt *) (codeview_dir + 1);
2241
2242                   for(j=0; j < codeview_dir->ndir; j++, codeview_dent++)
2243                     {
2244                       if( codeview_dent->subsect_number == sstAlignSym )
2245                         {
2246                           /*
2247                            * Check the previous entry.  If it is a
2248                            * sstSrcModule, it contains the line number
2249                            * info for this file.
2250                            */
2251                           linetab = NULL;
2252                           if( codeview_dent[1].module_number == codeview_dent[0].module_number
2253                               && codeview_dent[1].subsect_number == sstSrcModule )
2254                             {
2255                               linetab = DEBUG_SnarfLinetab(
2256                                            codeview + codeview_dent[1].offset,
2257                                            codeview_dent[1].size);
2258                             }
2259
2260                           if( codeview_dent[-1].module_number == codeview_dent[0].module_number
2261                               && codeview_dent[-1].subsect_number == sstSrcModule )
2262                             {
2263                               linetab = DEBUG_SnarfLinetab(
2264                                            codeview + codeview_dent[-1].offset,
2265                                            codeview_dent[-1].size);
2266                             }
2267                           /*
2268                            * Now process the CV stuff.
2269                            */
2270                           DEBUG_SnarfCodeView(deefer, 
2271                                               codeview + codeview_dent->offset,
2272                                               codeview_dent->size,
2273                                               linetab);
2274                         }
2275                     }
2276
2277                   break;
2278                 default:
2279                   break;
2280                 }
2281     }
2282 leave:
2283
2284   if( addr != (char *) 0xffffffff )
2285     {
2286       munmap(addr, statbuf.st_size);
2287     }
2288
2289   if( fd != -1 )
2290     {
2291       close(fd);
2292     }
2293
2294   return TRUE;
2295 }
2296
2297 int
2298 DEBUG_ProcessDeferredDebug()
2299 {
2300   struct deferred_debug_info * deefer;
2301   struct CodeViewDebug       * cvd;
2302   struct MiscDebug           * misc;
2303   char                       * filename;
2304   int                          last_proc = -1;
2305
2306   DEBUG_InitCVDataTypes();
2307
2308   for(deefer = dbglist; deefer; deefer = deefer->next)
2309     {
2310       if( deefer->loaded )
2311         {
2312           continue;
2313         }
2314
2315       if( last_proc != deefer->dbg_index )
2316         {
2317           fprintf(stderr, " %s",deefer->module_name);
2318           last_proc = deefer->dbg_index;
2319         }
2320
2321       switch(deefer->dbgdir->Type)
2322         {
2323         case IMAGE_DEBUG_TYPE_COFF:
2324           /*
2325            * Standard COFF debug information that VC++ adds when you
2326            * use /debugtype:both with the linker.
2327            */
2328 #if 0
2329           fprintf(stderr, "Processing COFF symbols...\n");
2330 #endif
2331           DEBUG_ProcessCoff(deefer);
2332           break;
2333         case IMAGE_DEBUG_TYPE_CODEVIEW:
2334           /*
2335            * This is a pointer to a PDB file of some sort.
2336            */
2337           cvd = (struct CodeViewDebug *) deefer->dbg_info;
2338
2339           if( strcmp(cvd->cv_nbtype, "NB10") != 0 )
2340             {
2341               /*
2342                * Whatever this is, we don't know how to deal with
2343                * it yet.
2344                */
2345               break;
2346             }
2347           DEBUG_ProcessPDBFile(deefer, cvd->cv_name);
2348 #if 0
2349           fprintf(stderr, "Processing PDB file %s\n", cvd->cv_name);
2350 #endif
2351           break;
2352         case IMAGE_DEBUG_TYPE_MISC:
2353           /*
2354            * A pointer to a .DBG file of some sort.  These files
2355            * can contain either CV4 or COFF information.  Open
2356            * the file, and try to do the right thing with it.
2357            */
2358           misc = (struct MiscDebug *) deefer->dbg_info;
2359
2360           filename = strrchr((char *) &misc->Data, '.');
2361
2362           /*
2363            * Ignore the file if it doesn't have a .DBG extension.
2364            */
2365           if(    (filename == NULL)
2366               || (    (strcmp(filename, ".dbg") != 0)
2367                    && (strcmp(filename, ".DBG") != 0)) )
2368             {
2369               break;
2370             }
2371
2372           filename = (char *) &misc->Data;
2373
2374           /*
2375            * Do the dirty deed...
2376            */
2377           DEBUG_ProcessDBGFile(deefer, filename);
2378       
2379           break;
2380         default:
2381           /*
2382            * We should never get here...
2383            */
2384           break;
2385         }
2386     }
2387   return TRUE;
2388
2389 }
2390
2391 /***********************************************************************
2392  *           DEBUG_InfoShare
2393  *
2394  * Display shared libarary information.
2395  */
2396 void DEBUG_InfoShare(void)
2397 {
2398   struct deferred_debug_info * deefer;
2399
2400   fprintf(stderr,"Address\t\tModule\tName\n");
2401
2402   for(deefer = dbglist; deefer; deefer = deefer->next)
2403   {
2404       fprintf(stderr,"0x%8.8x\t(%s)\t%s\n", (unsigned int) deefer->load_addr,
2405               deefer->module ? "Win32" : "ELF", deefer->module_name);
2406   }
2407 }
2408