summaryrefslogtreecommitdiffstats
path: root/private/sdktools/imagehlp/editsym.c
blob: d019e2159418de04b994b828102488cc2ecf3558 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
/*++

Copyright (c) 1992  Microsoft Corporation

Module Name:

    editsym.c

Abstract:

    This is the main source file for the EDITSYM utility program.  This
    program can be used to extract the debugging information contained in
    a separate .DBG file and put it back to the original image file.

Author:

    HonWah Chan 21-March-1994

Revision History:

--*/

#include <private.h>


BOOL fVerbose;

LPSTR FilePart;

UCHAR CurrentImageName[ MAX_PATH ];

UCHAR DbgFileName[ MAX_PATH ];


void
Usage( void )
{
    fputs( "Function: Extract debugging information contained in .dbg file\n"
           "\tand put it back in the original image file\n\n"
           "Usage: EDITSYM [-?] [-s symbol-filename] image-name\n"
           "\t\t[-?] display this message\n"
           "\t\t[-s symbol-filename] - name of the .DBG file.  Default is the same\n"
           "\t\t                        name and location as the image file.\n\n"
           "\tE.G.  EditSym -s Perfmon.dbg Perfmon.exe\n", stderr );
    exit( 1 );
}

BOOL EditSymbols(
    LPSTR pImageName,
    LPSTR pDbgFileName
    )
{
    PIMAGE_NT_HEADERS NtHeaders;
    HANDLE FileHandle, SymbolFileHandle;
    HANDLE hMappedFile;
    LPVOID ImageBase;
    PIMAGE_DEBUG_DIRECTORY DebugDirectories;
    PIMAGE_DEBUG_DIRECTORY DebugDirectoriesSave;
    DWORD DebugDirectorySize, NumberOfDebugDirectories;
    DWORD SavedErrorCode;
    PIMAGE_DEBUG_DIRECTORY DebugDirectory;
    DWORD i;
    DWORD NewFileSize, HeaderSum, CheckSum;
    DWORD ImageNameOffset, DebugDataSize;
    LPBYTE DebugData;
    IMAGE_SEPARATE_DEBUG_HEADER DbgFileHeader;

    ImageBase = NULL;
    hMappedFile = 0;
    FileHandle = SymbolFileHandle = 0;
    DebugDirectoriesSave = NULL;

    //
    // open and map the file.
    //
    FileHandle = CreateFile( pImageName,
                             GENERIC_READ | GENERIC_WRITE,
                             FILE_SHARE_READ,
                             NULL,
                             OPEN_EXISTING,
                             0,
                             NULL
                           );

    if (FileHandle == INVALID_HANDLE_VALUE) {
        return FALSE;
        }


    hMappedFile = CreateFileMapping( FileHandle,
                                     NULL,
                                     PAGE_READWRITE,
                                     0,
                                     0,
                                     NULL
                                   );
    if (!hMappedFile) {
        CloseHandle( FileHandle );
        return FALSE;
        }

    ImageBase = MapViewOfFile( hMappedFile,
                               FILE_MAP_WRITE,
                               0,
                               0,
                               0
                             );
    if (!ImageBase) {
        CloseHandle( hMappedFile );
        CloseHandle( FileHandle );
        return FALSE;
        }

    //
    // Everything is mapped. Now check the image and find nt image headers
    //

    NtHeaders = ImageNtHeader( ImageBase );
    if (NtHeaders == NULL) {
        SetLastError( ERROR_BAD_EXE_FORMAT );
        goto nosyms;
        }

    if ((NtHeaders->OptionalHeader.MajorLinkerVersion < 3) &&
        (NtHeaders->OptionalHeader.MinorLinkerVersion < 5)
       ) {
        SetLastError( ERROR_BAD_EXE_FORMAT );
        goto nosyms;
        }

    if (!(NtHeaders->FileHeader.Characteristics & IMAGE_FILE_DEBUG_STRIPPED)) {
        SetLastError( ERROR_ALREADY_ASSIGNED );
        goto nosyms;
        }

    DebugDirectories = (PIMAGE_DEBUG_DIRECTORY) ImageDirectoryEntryToData( ImageBase,
                                                  FALSE,
                                                  IMAGE_DIRECTORY_ENTRY_DEBUG,
                                                  &DebugDirectorySize
                                                );
    if (!DebugDirectoryIsUseful(DebugDirectories, DebugDirectorySize)) {
        SetLastError( ERROR_BAD_EXE_FORMAT );
        goto nosyms;
    }

    NumberOfDebugDirectories = DebugDirectorySize / sizeof( IMAGE_DEBUG_DIRECTORY );

    SymbolFileHandle = CreateFile( pDbgFileName,
                                   GENERIC_READ | GENERIC_WRITE,
                                   FILE_SHARE_READ,
                                   NULL,
                                   OPEN_EXISTING,
                                   0,
                                   NULL
                                 );
    if (SymbolFileHandle == INVALID_HANDLE_VALUE)
        goto nosyms;

    if (!ReadFile( SymbolFileHandle,
            &DbgFileHeader,
            sizeof(DbgFileHeader),
            &DebugDataSize,
            NULL) ||
        DebugDataSize != sizeof(DbgFileHeader)) {
        SetLastError( ERROR_BAD_EXE_FORMAT );
        goto nosyms;
        }

    if (DbgFileHeader.Signature != IMAGE_SEPARATE_DEBUG_SIGNATURE ||
        (DbgFileHeader.Flags & ~IMAGE_SEPARATE_DEBUG_FLAGS_MASK) != 0 ||
        DbgFileHeader.Machine != NtHeaders->FileHeader.Machine ||
        DbgFileHeader.Characteristics != NtHeaders->FileHeader.Characteristics ||
        DbgFileHeader.TimeDateStamp != NtHeaders->FileHeader.TimeDateStamp ||
        DbgFileHeader.CheckSum != NtHeaders->OptionalHeader.CheckSum ||
        DbgFileHeader.ImageBase != NtHeaders->OptionalHeader.ImageBase ||
        DbgFileHeader.SizeOfImage != NtHeaders->OptionalHeader.SizeOfImage) {
        SetLastError( ERROR_BAD_EXE_FORMAT );
        goto nosyms;
        }

    if (DbgFileHeader.Flags & IMAGE_SEPARATE_DEBUG_MISMATCH) {
        fprintf(stderr, "Warning: %s updated unsafely; symbols may be wrong\n",
                pDbgFileName);
    }


    // check if this is the right dbg file

    // save the DebugDirectory and get ready to write the
    // debug data to the image file.
    DebugDirectoriesSave = (PIMAGE_DEBUG_DIRECTORY) malloc( DebugDirectorySize );
    if (DebugDirectoriesSave == NULL)
        goto nosyms;

    RtlMoveMemory( DebugDirectoriesSave,
                   DebugDirectories,
                   DebugDirectorySize);

    DebugDirectory = DebugDirectoriesSave;
    NewFileSize = SetFilePointer( FileHandle, 0, NULL, FILE_END );
    NewFileSize = (NewFileSize + 3) & ~3;

    for (i=0; i<NumberOfDebugDirectories; i++) {
        // Is it one of the debug sections we need to special case?
        if (DebugDirectory->Type == IMAGE_DEBUG_TYPE_MISC) {
            // fix the mage name
            ImageNameOffset = (DWORD) ((PCHAR) ImageBase +
               DebugDirectory->PointerToRawData +
               FIELD_OFFSET( IMAGE_DEBUG_MISC, Data ));

            RtlCopyMemory((LPVOID)ImageNameOffset,
                          FilePart,
                          strlen(FilePart) + 1);

        }
        else if (DebugDirectory->Type != IMAGE_DEBUG_TYPE_FPO) {
            DebugData = (LPBYTE) malloc( DebugDirectory->SizeOfData );
            if (SetFilePointer( SymbolFileHandle,
                    DebugDirectory->PointerToRawData,
                    NULL,
                    FILE_BEGIN ) != DebugDirectory->PointerToRawData) {
                SetLastError( ERROR_BAD_EXE_FORMAT );
                goto nosyms;
                }

            if (ReadFile( SymbolFileHandle,
                          DebugData,
                          DebugDirectory->SizeOfData,
                          &DebugDataSize,
                          NULL) &&
                DebugDataSize == DebugDirectory->SizeOfData) {
                if (WriteFile( FileHandle,
                               DebugData,
                               DebugDirectory->SizeOfData,
                               &DebugDataSize,
                               NULL) &&
                    DebugDataSize == DebugDirectory->SizeOfData) {
                    DebugDirectory->PointerToRawData = NewFileSize;
                    NewFileSize += DebugDataSize;
                    NewFileSize = (NewFileSize + 3) & ~3;
                }
                else {
                    SetLastError( ERROR_WRITE_FAULT );
                    free( DebugData );
                    goto nosyms;
                }
            }
            else {
                SetLastError( ERROR_BAD_EXE_FORMAT );
                free( DebugData );
                goto nosyms;
            }
            free( DebugData );
        }
        DebugDirectory += 1;
    }


    // somehow I needed to close the file and re-open it again.
    // otherwise it would AV inside CheckSumMappedFile.
    UnmapViewOfFile( ImageBase );
    CloseHandle( hMappedFile );
    ImageBase = NULL;
    hMappedFile = 0;

    SetFilePointer( FileHandle, NewFileSize, NULL, FILE_BEGIN );
    SetEndOfFile( FileHandle );
    CloseHandle( FileHandle );


    //
    // re-open and map the file.
    //
    FileHandle = CreateFile( pImageName,
                             GENERIC_READ | GENERIC_WRITE,
                             FILE_SHARE_READ,
                             NULL,
                             OPEN_EXISTING,
                             0,
                             NULL
                           );


    hMappedFile = CreateFileMapping( FileHandle,
                                     NULL,
                                     PAGE_READWRITE,
                                     0,
                                     0,
                                     NULL
                                   );
    if (!hMappedFile) {
        goto nosyms;
        }

    ImageBase = MapViewOfFile( hMappedFile,
                               FILE_MAP_WRITE,
                               0,
                               0,
                               0
                             );
    if (!ImageBase) {
        goto nosyms;
        }

    NtHeaders = ImageNtHeader( ImageBase );
    if (NtHeaders == NULL) {
        SetLastError( ERROR_BAD_EXE_FORMAT );
        goto nosyms;
        }

    DebugDirectories = (PIMAGE_DEBUG_DIRECTORY) ImageDirectoryEntryToData( ImageBase,
                                                  FALSE,
                                                  IMAGE_DIRECTORY_ENTRY_DEBUG,
                                                  &DebugDirectorySize
                                                );

    if (DebugDirectories == NULL || DebugDirectorySize == 0) {
        SetLastError( ERROR_BAD_EXE_FORMAT );
        goto nosyms;
        }


    RtlMoveMemory( DebugDirectories,
                   DebugDirectoriesSave,
                   DebugDirectorySize);

    free( DebugDirectoriesSave );

    NtHeaders->FileHeader.Characteristics &= ~IMAGE_FILE_DEBUG_STRIPPED;

    CheckSumMappedFile( ImageBase,
                        NewFileSize,
                        &HeaderSum,
                        &CheckSum
                      );

    NtHeaders->OptionalHeader.CheckSum = CheckSum;


    CloseHandle( SymbolFileHandle );

    UnmapViewOfFile( ImageBase );
    CloseHandle( hMappedFile );
    CloseHandle( FileHandle );

    return TRUE;

nosyms:
    SavedErrorCode = GetLastError();

    if (DebugDirectoriesSave)
        free( DebugDirectoriesSave );

    if (SymbolFileHandle && SymbolFileHandle != INVALID_HANDLE_VALUE) {
        CloseHandle( SymbolFileHandle );
    }

    if (ImageBase)
        UnmapViewOfFile( ImageBase );

    if (hMappedFile)
        CloseHandle( hMappedFile );

    if (FileHandle && FileHandle != INVALID_HANDLE_VALUE) {
        CloseHandle( FileHandle );
    }

    SetLastError( SavedErrorCode );
    return FALSE;
}

int _CRTAPI1
main(
    int argc,
    char *argv[],
    char *envp[]
    )
{
    char c, *s;
    LPSTR DbgFilePart;

    if (argc <= 1) {
        Usage();
        }

    DbgFileName[ 0 ] = '\0';
    while (--argc) {
        s = *++argv;
        if (*s == '/' || *s == '-') {
            while (c = *++s)
                switch (toupper( c )) {
                case '?':
                    Usage();
                    break;

                case 'V':
                    fVerbose = TRUE;
                    break;

                case 'S':
                    if (--argc) {
                        strcpy( (PCHAR) DbgFileName, *++argv );
                        }
                    else {
                        fprintf( stderr, "EDITSYM: Argument to /%c switch missing\n", c );
                        Usage();
                        }
                    break;

                default:
                    fprintf( stderr, "EDITSYM: Invalid switch - /%c\n", c );
                    Usage();
                    break;
                }
            }
        else {
            FilePart = (PCHAR) CurrentImageName;
            if (!GetFullPathNameA( s, sizeof( CurrentImageName ), (PCHAR) CurrentImageName, &FilePart )) {
                fprintf( stderr, "EDITSYM: invalid file name - %s (%u)\n", s, GetLastError() );
                }
            else {
                if (DbgFileName[0] == '\0') {
                    PCHAR  pDbgName;

                    RtlCopyMemory(DbgFileName,
                          CurrentImageName,
                          strlen((PCHAR) CurrentImageName) + 1);
                    pDbgName = (PCHAR) DbgFileName + strlen ((PCHAR) DbgFileName);
                    while (pDbgName > (PCHAR) DbgFileName) {
                        if (*pDbgName == '.') {
                            break;
                        }
                        pDbgName --;
                    }
                    if (*pDbgName != '.') {
                        fprintf( stderr, "EDITSYM: invalid exe file name - %s\n", CurrentImageName );
                    }
                    strcpy (pDbgName, ".DBG");
                }
                else if (!GetFullPathNameA( (PCHAR) DbgFileName, sizeof( DbgFileName ), (PCHAR) DbgFileName, &DbgFilePart )) {
                    fprintf( stderr, "EDITSYM: invalid Dbg file name - %s (%u)\n", s, GetLastError() );
                }

                if (EditSymbols( (PCHAR) CurrentImageName, (PCHAR) DbgFileName )) {
                    if (fVerbose) {
                        fprintf( stdout,
                                 "EDITSYM: %s symbols restored into %s\n",
                                 DbgFileName,
                                 FilePart
                               );
                        }
                    }
                else
                    fprintf( stderr, "EDITSYM: Unable to restore symbols from '%s' into '%s' (%u)\n",
                             CurrentImageName,
                             DbgFileName,
                             GetLastError()
                           );
                }
            }
        }

    exit( 0 );
    return 0;
}