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