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