forked from revivalizer/rekkrunchy
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathexepacker.cpp
1300 lines (1084 loc) · 39 KB
/
exepacker.cpp
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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Written by Fabian "ryg" Giesen.
// I hereby place this code in the public domain.
#include "_types.hpp"
#include "_startconsole.hpp"
#include "exepacker.hpp"
#include "rangecoder.hpp"
#include "debuginfo.hpp"
#include "dis.hpp"
#include <stdio.h>
namespace rekkrunchy
{
#define NODEPACK2 0
/****************************************************************************/
extern "C" sU8 depacker[], depacker2[];
extern "C" sU32 depackerSize, depacker2Size;
/****************************************************************************/
struct PEHeader
{
sChar Magic[ 4 ];
sU16 CPU;
sU16 Sections;
sU8 _[ 12 ];
sU16 OptHeaderSize;
sU16 Flags;
sU8 __[ 4 ];
sU32 CodeSize;
sU32 DataSize;
sU32 BSSSize;
sU32 Entry;
sU32 CodeStart;
sU32 DataStart;
sU32 ImageStart;
sU32 ObjectAlign;
sU32 FileAlign;
sU8 ___[ 16 ];
sU32 ImageSize;
sU32 HeaderSize;
sU32 CheckSum;
sU16 SubSystem;
sU16 DllFlags;
sU8 ____[ 20 ];
sU32 DataDirs;
};
struct PESection
{
sChar Name[ 8 ];
sU32 VirtSize;
sU32 VirtAddr;
sU32 Size;
sU32 DataPtr;
sU8 _[ 12 ];
sU32 Flags;
};
struct RSRCDirEntry
{
sU32 NameID;
sU32 Offset;
};
struct RSRCDirectory
{
sU32 Flags;
sU8 _[ 8 ];
sU16 NameEntries;
sU16 IDEntries;
};
struct RSRCDataEntry
{
sU32 RVA;
sU32 Size;
sU32 Codepage;
sU32 Reserved;
};
/****************************************************************************/
KKBlobList::KKBlobList()
{
Blobs.Init();
}
KKBlobList::~KKBlobList()
{
Blobs.Exit();
}
void KKBlobList::AddBlob( void *data, sU32 size )
{
KKBlob *blob;
blob = Blobs.Add();
blob->Data = data;
blob->Size = size;
}
/****************************************************************************/
CodeFragment::CodeFragment()
{
Code = 0;
OriginalCode = 0;
CodeSize = 0;
}
CodeFragment::~CodeFragment()
{
delete[] OriginalCode;
OriginalCode = 0;
}
void CodeFragment::Init( sPtr code, sInt codeSize )
{
if ( OriginalCode )
delete[] OriginalCode;
OriginalCode = new sU8[ codeSize ];
Code = (sU8 *)code;
CodeSize = codeSize;
sCopyMem( OriginalCode, Code, CodeSize );
}
sBool CodeFragment::Patch( sChar *pattern, sU8 *patch, sInt size )
{
sInt i, pos, len;
len = sGetStringLen( pattern );
pos = -1;
for ( i = 0; i < CodeSize - len + 1; i++ )
{
if ( !sCmpMem( OriginalCode + i, pattern, len ) )
{
if ( pos == -1 )
pos = i;
else // not unique!
return sFALSE;
}
}
if ( pos != -1 )
{
sCopyMem( Code + pos, patch, size );
return sTRUE;
}
else
return sFALSE;
}
sBool CodeFragment::PatchDWord( sChar *pattern, sU32 patch )
{
return Patch( pattern, (sU8 *)&patch, sizeof( sU32 ) );
}
sBool CodeFragment::PatchJump( sChar *pattern, sU32 offset, sU32 base )
{
sInt i;
sU32 *pt;
sBool match;
match = sFALSE;
for ( i = 0; i < CodeSize - 3; i++ )
{
if ( !sCmpMem( OriginalCode + i, pattern, 4 ) )
{
if ( match )
return sFALSE;
match = sTRUE;
pt = (sU32 *)( Code + i );
*pt = offset - 4 - i - base;
}
}
return match;
}
sBool CodeFragment::PatchOffsets( sU32 base )
{
sInt i;
sU32 *pt;
for ( i = 0; i < CodeSize - 3; i++ )
{
pt = (sU32 *)( Code + i );
if ( OriginalCode[ i + 2 ] == 'P' && OriginalCode[ i + 3 ] == 'R' )
*pt = ( OriginalCode[ i + 0 ] + OriginalCode[ i + 1 ] * 256 ) + base;
}
return sTRUE;
}
/****************************************************************************/
sU32 EXEPacker::Align( sU32 size, sU32 align )
{
return size + ( align - 1 ) & -(sInt)align;
}
sPtr EXEPacker::AppendImage( sPtr data, sU32 size )
{
sCopyMem( OutImage + OutSize, data, size );
OutSize += size;
sVERIFY( OutSize < OutLimit );
return OutImage + OutSize - size;
}
sPtr EXEPacker::Padding( sU32 size )
{
sSetMem( OutImage + OutSize, 0, size );
OutSize += size;
sVERIFY( OutSize < OutLimit );
return OutImage + OutSize - size;
}
void EXEPacker::AlignmentPadding( sU32 align )
{
Padding( Align( OutSize, align ) - OutSize );
}
sU32 EXEPacker::SourceOffset( sU32 RVA )
{
sInt i;
sS64 relOffs;
for ( i = 0; i < PH->Sections; i++ )
{
relOffs = RVA - Section[ i ].VirtAddr;
if ( RVA >= Section[ i ].VirtAddr && relOffs < sMax( Section[ i ].VirtSize, Section[ i ].Size ) )
return Section[ i ].DataPtr + relOffs;
}
sVERIFYFALSE;
}
sU32 EXEPacker::SourceOffset2( sU32 RVA )
{
sInt i;
// sS64 relOffs;
for ( i = 0; i < PH->Sections; i++ )
{
int size = Section[ i ].VirtSize;
if ( size == 0 )
size = Section[ i ].Size;
if ( RVA >= Section[ i ].VirtAddr && RVA < Section[ i ].VirtAddr + size )
{
int delta = (int)( Section[ i ].VirtAddr - Section[ i ].DataPtr );
return RVA - delta;
}
/*
relOffs = RVA - Section[ i ].VirtAddr;
if ( RVA >= Section[ i ].VirtAddr && relOffs < sMax( Section[ i ].VirtSize, Section[ i ].Size ) )
return Section[ i ].DataPtr + relOffs;
*/
}
sVERIFYFALSE;
}
void EXEPacker::ResizeImports()
{
sU8 *ni;
if ( ImportSize + 512 >= ImportMax )
{
sVERIFY( ImportSize < ImportMax );
ni = new sU8[ ImportMax *= 2 ];
sCopyMem( ni, Imports, ImportSize );
delete[] Imports;
Imports = ni;
}
}
sBool EXEPacker::ProcessImports()
{
sU32 i, j;
sU32 *src, *imp, *iat;
sU8 *str;
ImportSize = 0;
ImportMax = 1024;
Imports = new sU8[ ImportMax ];
Imports[ ImportSize++ ] = 0; // depacker skips first byte
if ( DataDir[ 3 ] )
{
src = (sU32 *)( Source + SourceOffset( DataDir[ 2 ] ) );
for ( i = 0; src[ i * 5 + 4 ]; i++ )
{
ResizeImports();
// copy iat offset
*(sU32 *)( Imports + ImportSize ) = src[ i * 5 + 4 ] + PH->ImageStart; ImportSize += 4;
// copy dll name
str = Source + SourceOffset( src[ i * 5 + 3 ] );
while ( *str )
{
Imports[ ImportSize++ ] = *str;
*str++ = 0;
}
Imports[ ImportSize++ ] = 0;
// dll imports
iat = (sU32 *)( Source + SourceOffset( src[ i * 5 + 4 ] ) );
if ( src[ i * 5 + 0 ] )
imp = (sU32 *)( Source + SourceOffset( src[ i * 5 + 0 ] ) );
else
imp = iat;
for ( j = 0; imp[ j ]; j++ )
{
ResizeImports();
if ( imp[ j ] & 0x80000000 )
{
if ( ( imp[ j ] & 0x7fffffff ) > 0xffff )
{
sSPrintF( Error, 512, "invalid import ordinal" );
return sFALSE;
}
Imports[ ImportSize++ ] = 0xff;
Imports[ ImportSize++ ] = imp[ j ] & 0xff;
Imports[ ImportSize++ ] = ( imp[ j ] >> 8 ) & 0xff;
Imports[ ImportSize++ ] = 0;
}
else
{
str = Source + SourceOffset( imp[ j ] );
*str++ = 0; // overwrite hint with zero
*str++ = 0;
while ( *str )
{
if ( *str >= 128 )
{
sSPrintF( Error, 512, "non-ascii character in imported name" );
return sFALSE;
}
Imports[ ImportSize++ ] = *str;
*str++ = 0;
}
Imports[ ImportSize++ ] = 0;
}
imp[ j ] = iat[ j ] = 0;
}
Imports[ ImportSize++ ] = 0;
}
}
*(sU32 *)( Imports + ImportSize ) = 0; ImportSize += 4;
return sTRUE;
}
void EXEPacker::CleanupUnImage()
{
sU32 i, *pt;
// clear debug info
if ( DataDir[ 13 ] )
{
for ( i = 0; i < DataDir[ 13 ]; i += 28 )
{
pt = (sU32 *)( UnImageVA + DataDir[ 12 ] + i );
sSetMem( UnImageVA + pt[ 5 ], 0, pt[ 4 ] );
}
}
// zero out all data referred to in the data directory, except resources
for ( i = 0; i < PH->DataDirs; i++ )
{
if ( i != 2 && DataDir[ i * 2 + 1 ] )
sSetMem( UnImageVA + DataDir[ i * 2 + 0 ], 0, DataDir[ i * 2 + 1 ] );
}
}
sBool EXEPacker::ProcessResources()
{
if ( ResourcesPresent )
{
// this should *always* be 0
sU32 offs = ProcessResourcesR( Source + SourceOffset( DataDir[ 4 ] ), 0, 0, sTRUE );
return offs == 0;
}
else
return sTRUE;
}
sU32 EXEPacker::ProcessResourcesR( sU8 *start, sU32 offs, sInt level, sBool compress )
{
RSRCDirectory *dir;
RSRCDataEntry *data;
RSRCDirEntry *entry, *targetEntry;
sU16 *str;
sU32 destOffs, dataOffs, size;
sInt i;
sBool compFlag;
// this function is called only for resource directories.
dir = (RSRCDirectory *)( start + offs );
// first, copy this resource directory into the output buffer
destOffs = Resources.Count;
size = sizeof( RSRCDirectory ) + ( dir->IDEntries + dir->NameEntries ) * sizeof( RSRCDirEntry );
Resources.AtLeast( destOffs + size );
sCopyMem( &Resources[ destOffs ], dir, size );
Resources.Count += size;
// clear resource directory in unpacked image
sSetMem( UnImageVA + DataDir[ 4 ] + offs, 0, size );
// then process each child node in turn
entry = (RSRCDirEntry *)( start + offs + sizeof( RSRCDirectory ) );
for ( i = 0; i < dir->NameEntries + dir->IDEntries; i++, entry++ )
{
// decide whether to compress child nodes or not
compFlag = compress;
if ( level == 0 ) // type level
{
// compress everything but icons and manifests
if ( entry->NameID == 3 || entry->NameID == 14 || entry->NameID == 24 )
{
if ( entry->NameID == 24 ) // utter warning for manifests
{
sSPrintF( InfoPtr, 512, "Manifest present and stored uncompressed." );
InfoPtr += sGetStringLen( InfoPtr ) + 1;
}
compFlag = sFALSE;
}
}
// process names
if ( entry->NameID & 0x80000000 ) // is name
{
// copy string
dataOffs = ResourceStrings.Count;
str = (sU16 *)( start + ( entry->NameID & 0x7fffffff ) );
size = ( *str + 1 ) * 2;
ResourceStrings.AtLeast( dataOffs + size );
ResourceStrings.Count += size;
sCopyMem( &ResourceStrings[ dataOffs ], str, size );
// clear string in unpacked image
sSetMem( UnImageVA + DataDir[ 4 ] + ( entry->NameID & 0x7fffffff ), 0, size );
// patch new offset into resource structure
// (relative to strings, we adjust all this in a second pass)
targetEntry = (RSRCDirEntry *)&Resources[ destOffs + sizeof( RSRCDirectory ) ];
targetEntry[ i ].NameID = dataOffs | 0x80000000;
}
if ( entry->Offset & 0x80000000 ) // subdirectory
{
dataOffs = ProcessResourcesR( start, entry->Offset & 0x7fffffff, level + 1, compFlag );
// patch new offset into copied resource structure
targetEntry = (RSRCDirEntry *)&Resources[ destOffs + sizeof( RSRCDirectory ) ];
targetEntry[ i ].Offset = dataOffs | 0x80000000;
}
else // child is a leaf
{
// copy the data entry, then get a pointer to it
dataOffs = Resources.Count;
Resources.AtLeast( dataOffs + sizeof( RSRCDataEntry ) );
sCopyMem( &Resources[ dataOffs ], start + entry->Offset, sizeof( RSRCDataEntry ) );
Resources.Count += sizeof( RSRCDataEntry );
data = (RSRCDataEntry *)&Resources[ dataOffs ];
// adjust entry position
targetEntry = (RSRCDirEntry *)&Resources[ destOffs + sizeof( RSRCDirectory ) ];
targetEntry[ i ].Offset = dataOffs;
if ( compress ) // this will be compressed, so leave it where it is
{
// but all relative addresses will change, so make the address
// absolute, then we can fix it later
data->RVA += PH->ImageStart;
data->Reserved = 1; // we use that field for our own sinister purposes here
}
else // this won't be compressed, move it to the unpacked data range
{
dataOffs = ResourceData.Count;
// copy actual data
ResourceData.AtLeast( dataOffs + ( ( data->Size + 3 ) & ~3 ) );
ResourceData.Count += ( data->Size + 3 ) & ~3;
sCopyMem( &ResourceData[ dataOffs ], Source + SourceOffset( data->RVA ), data->Size );
// clear data in unpacked image
sSetMem( UnImageVA + data->RVA, 0, data->Size );
// update structures
data->RVA = dataOffs; // relative to beginning of resource data here
data->Reserved = 0;
}
}
}
return destOffs;
}
void EXEPacker::FinishResources( sU32 *dataDir )
{
sU32 size, stringpos, datarva;
sU8 *resdata;
if ( ResourcesPresent )
{
// calc size
size = ( Resources.Count + 3 ) & ~3;
stringpos = size;
size += ( ResourceStrings.Count + 3 ) & ~3;
size += ( ResourceData.Count + 3 ) & ~3;
// append data in turn and update data directory
AlignmentPadding( 4 );
dataDir[ 4 ] = OutSize;
dataDir[ 5 ] = size;
resdata = (sU8 *)AppendImage( &Resources[ 0 ], Resources.Count );
AlignmentPadding( 4 );
AppendImage( &ResourceStrings[ 0 ], ResourceStrings.Count );
AlignmentPadding( 4 );
datarva = OutSize;
AppendImage( &ResourceData[ 0 ], ResourceData.Count );
AlignmentPadding( 4 );
// then adjust addresses
AdjustResourcesR( resdata, 0, stringpos, datarva );
}
}
void EXEPacker::AdjustResourcesR( sU8 *start, sU32 offs, sU32 stringrel, sU32 datarel )
{
RSRCDirectory *dir;
RSRCDirEntry *entry;
RSRCDataEntry *data;
sInt i;
// iterate through the entries...
dir = (RSRCDirectory *)( start + offs );
entry = (RSRCDirEntry *)( start + offs + sizeof( RSRCDirectory ) );
for ( i = 0; i < dir->NameEntries + dir->IDEntries; i++, entry++ )
{
if ( entry->NameID & 0x80000000 ) // it's a name, adjust to point to strings
entry->NameID += stringrel;
if ( entry->Offset & 0x80000000 ) // it's a subdirectory, recurse
AdjustResourcesR( start, entry->Offset & 0x7fffffff, stringrel, datarel );
else // leaf
{
data = (RSRCDataEntry *)( start + entry->Offset );
if ( data->Reserved )
{
data->RVA -= OPH->ImageStart; // make address RVA again
data->Reserved = 0;
}
else
data->RVA += datarel;
}
}
}
/****************************************************************************/
// The VC8 runtime library startup code is slightly modified; instead of
// calling GetModuleHandle(0) like it used to be, it now hardcodes the
// ImageBase address. Which means we have a lot of fun work to do to
// support VC8 programs properly. Great.
sU32 EXEPacker::GetVC8RuntimePatchOffset()
{
// default patch address: image base of the old process. "it's safe".
sU32 patchOffs = PH->ImageStart;
// try to find out whether the program seems to be using the VC8 runtime.
// this is kinda involved. (OF COURSE... argh!)
// entry point:
// call ___security_init_cookie
// jmp ___tmainCRTStartup
const sU8 *entry = Source + SourceOffset( PH->Entry );
if ( entry[ 0 ] == 0xe8 && entry[ 5 ] == 0xe9 )
{
sU32 startOffs = PH->Entry + 10 + *( (sU32 *)( entry + 6 ) );
const sU8 *st = Source + SourceOffset( startOffs );
// startup code (first few bytes)
// push 58h
// push offset __sehtable$___tmainCRTStartup
// call __SEH_prolog4
// xor ebx,ebx
// mov dword ptr [ebp-1ch],ebx
// mov dword ptr [ebp-4],ebx
// lea eax,[ebp-68h]
// push eax
if ( st[ 0 ] == 0x6a && st[ 1 ] == 0x58 && st[ 2 ] == 0x68 && st[ 7 ] == 0xe8
&& st[ 12 ] == 0x33 && st[ 13 ] == 0xdb
&& st[ 14 ] == 0x89 && st[ 15 ] == 0x5d && st[ 16 ] == 0xe4
&& st[ 17 ] == 0x89 && st[ 18 ] == 0x5d && st[ 19 ] == 0xfc
&& st[ 20 ] == 0x8d && st[ 21 ] == 0x45 && st[ 22 ] == 0x98
&& st[ 23 ] == 0x50 )
{
// okay, this is starting to look likely.
// ...0x129:
// movzx eax, word ptr [ebp-38h]
// jmp short 132h
// push 0ah
// pop eax
// push eax
// push esi
// push 0
// push offset ___ImageBase
// call _WinMain@16
if ( st[ 0x129 ] == 0x0f && st[ 0x12a ] == 0xb7 && st[ 0x12b ] == 0x45 && st[ 0x12c ] == 0xc8
&& st[ 0x12d ] == 0xeb && st[ 0x12e ] == 0x03
&& st[ 0x12f ] == 0x6a && st[ 0x130 ] == 0x0a
&& st[ 0x131 ] == 0x58 && st[ 0x132 ] == 0x50 && st[ 0x133 ] == 0x56
&& st[ 0x134 ] == 0x6a && st[ 0x135 ] == 0x00
&& st[ 0x136 ] == 0x68
&& st[ 0x13b ] == 0xe8 )
{
sSPrintF( InfoPtr, 512, "VC8 startup code detected and patched." );
InfoPtr += sGetStringLen( InfoPtr ) + 1;
patchOffs = PH->ImageStart + startOffs + 0x137;
}
}
}
return patchOffs;
}
/****************************************************************************/
sU8 *EXEPacker::Pack( sU8 *source, sU32 srcSize, sInt &outSize, DebugInfo *info, PackerCallback cb, KKBlobList *blobs )
{
PESection *outSection;
sU32 *outDir, imageEnd, dataStart, dataSize, *p, iltOffs, depSize, skip;
sU32 depack2Base;
sU8 *buffer;
sInt i, j, inSize, ptrTableO;
DisFilter filter;
CodeFragment depack2;
ReorderBuffer reorder;
double* srcPackData = new double[ srcSize ];
memset( srcPackData, 0, srcSize * sizeof( double ) );
Error[ 0 ] = Warnings[ 0 ] = Info[ 0 ] = 0;
ActualSize = 0;
Source = source;
WarningsPtr = Warnings;
InfoPtr = Info;
Resources.Init();
ResourceStrings.Init();
ResourceData.Init();
// verify the file is actually a packable executable
if ( sCmpMem( source, "MZ", 2 ) )
{
sSPrintF( Error, sizeof( Error ), "file is not executable" );
return 0;
}
PH = (PEHeader *)( source + *(sU32 *)( source + 0x3c ) );
if ( sCmpMem( PH->Magic, "PE\x00\x00", 4 ) )
{
sSPrintF( Error, sizeof( Error ), "file is not a portable executable" );
return 0;
}
// setup some useful pointers
DataDir = (sU32 *)&PH[ 1 ];
Section = (PESection *)( DataDir + PH->DataDirs * 2 );
// perform additional checks to reject files with features we don't support
if ( DataDir[ 1 ] || PH->DataDirs >= 10 && DataDir[ 19 ] )
{
sSPrintF( Error, sizeof( Error ), "files with exports or tls data are not supported" );
return 0;
}
// allocate output image
inSize = PH->HeaderSize;
for ( i = 0; i < PH->Sections; i++ )
inSize += Align( Section[ i ].Size, PH->FileAlign );
if ( blobs )
{
for ( i = 0; i < blobs->Blobs.Count; i++ )
{
inSize = ( inSize + 15 ) & ~15;
inSize += blobs->Blobs[ i ].Size;
}
}
OutLimit = inSize + ( inSize / 8 ) + 4096 + 512;
OutImage = new sU8[ OutLimit + 512 ];
OutSize = 0;
// rebase debug info
if ( info )
info->Rebase( PH->ImageStart );
// check for resources
ResourcesPresent = DataDir[ 5 ] != 0;
// build the image: headers
AppendImage( "MZ", 2 ); // dos stub
//AppendImage("conspiracy", 10); // dos stub
//AppendImage("conspiracyconspiracyconspiracyconspiracyconspiracyconspiracy", 58); // vanity header
//AppendImage("__ ___ ___ 6| _|| ||_ -|4|___||_|_||___|k[Conspiracy]", 58); // vanity header
/*
AppendImage( "--.,---.,---.6"
"| | |`---.4"
"`---'` '`---'k"
"[Conspiracy]", 58 ); // vanity header
*/
unsigned char vanity[ 58 ] = { 0xDE, 0xDB, 0xDB, 0xDC, 0x20, 0xDB, 0xDD, 0xDE,
0xDB, 0x20, 0xDC, 0xDB, 0xDB, 0xDD, 0x20, 0xDB,
0xDD, 0x20, 0xDB, 0xDD, 0xDE, 0xDB, 0xDD, 0xDB,
0xDD, 0xDE, 0xDB, 0xDC, 0x20, 0x20, 0xDE, 0xDB,
0x20, 0xDC, 0xDC, 0x20, 0xDB, 0xDD, 0xDB, 0xDB,
0x20, 0x20, 0x20, 0xDB, 0xDB, 0x20, 0x20, 0xDF,
0xDB, 0xDB, 0xDF, 0xDE, 0xDB, 0x20, 0xDB, 0xDD,
0xDE, 0xDB };
AppendImage( vanity
/*"▐██▄ █▌▐█ ▄██▌ █▌ █▌▐█▌█▌▐█▄ ▐█ ▄▄ █▌██ ██ ▀██▀▐█ █▌▐█"*/, 58 ); // vanity header
int pos = 0x40;
AppendImage( &pos, 4 );
OPH = (PEHeader *)AppendImage( PH, sizeof( PEHeader ) );
OPH->FileAlign = 512; // more is a waste of space
//OPH->DataStart = 12; // position of pe header
OPH->DataDirs = ResourcesPresent ? 16 : 5;
OPH->Sections = 1;
OPH->OptHeaderSize = sizeof( PEHeader ) - 24 + OPH->DataDirs * 8;
if ( OPH->CheckSum != 0 )
{
OPH->CheckSum = 0;
sSPrintF( InfoPtr, 512, "Checksum present, clearing." );
InfoPtr += sGetStringLen( InfoPtr ) + 1;
}
outDir = (sU32 *)AppendImage( DataDir, OPH->DataDirs * 8 );
outSection = (PESection *)AppendImage( Section, sizeof( PESection ) );
OPH->HeaderSize = Section[ 0 ].VirtAddr;
imageEnd = Section[ PH->Sections - 1 ].VirtAddr + Section[ PH->Sections - 1 ].VirtSize;
// account for blobs
if ( blobs )
{
for ( i = 0; i < blobs->Blobs.Count; i++ )
{
imageEnd = ( imageEnd + 15 ) & ~15;
imageEnd += blobs->Blobs[ i ].Size;
}
ptrTableO = -1;
for ( i = 0; i < PH->Sections; i++ )
{
buffer = Source + SourceOffset( Section[ i ].VirtAddr );
for ( j = 0; j < (sInt)( Section[ i ].Size - 8 ); j++ )
{
if ( !sCmpMem( buffer + j, "PTRTABLE", 8 ) )
{
if ( ptrTableO != -1 )
{
sSPrintF( Error, sizeof( Error ), "multiple candidate PTRTABLEs in file" );
delete[] OutImage;
return 0;
}
else
ptrTableO = j + Section[ i ].VirtAddr;
}
}
}
if ( ptrTableO == -1 )
{
sSPrintF( Error, sizeof( Error ), "blobs specified but no PTRTABLE present" );
delete[] OutImage;
return 0;
}
}
dataSize = Align( imageEnd - Section[ 0 ].VirtAddr, PH->FileAlign );
// process import records
if ( !ProcessImports() )
{
delete[] OutImage;
return 0;
}
dataSize += 4 + ImportSize; // 4=import size tag
// build source image for code preprocess
sU8 *sourceImg = new sU8[ dataSize ];
sSetMem( sourceImg, 0, dataSize );
sU32 codeSize = PH->CodeSize;
for ( sInt i = 0; i < PH->Sections; i++ )
{
if ( Section[ i ].Size )
sCopyMem( sourceImg + Section[ i ].VirtAddr - Section[ 0 ].VirtAddr, Source + Section[ i ].DataPtr, sMin( Section[ i ].Size, Section[ i ].VirtSize ) );
}
// broken purebasic executable fix
if ( PH->Sections >= 2
&& !sCmpMem( Section[ 0 ].Name, ".code\0", 6 )
&& !sCmpMem( Section[ 1 ].Name, ".text\0", 6 ) )
{
sSPrintF( WarningsPtr, 512, "This looks like a broken PureBasic executable - adjusting CodeSize." );
WarningsPtr += sGetStringLen( WarningsPtr ) + 1;
codeSize = codeSize - Section[ 0 ].Size + ( Section[ 1 ].VirtAddr - Section[ 0 ].VirtAddr );
}
// filter code section and clear original code section
sU8 *codePtr = sourceImg + PH->CodeStart - Section[ 0 ].VirtAddr;
while ( codeSize && !codePtr[ codeSize - 1 ] )
codeSize--;
filter.Filter( codePtr, codeSize, PH->ImageStart + PH->CodeStart, info );
dataSize += depacker2Size + filter.Output.Size;
int oldAddr = PH->ImageStart + PH->CodeStart;
int newAddr = PH->ImageStart + Section[ 0 ].VirtAddr - filter.Output.Size;
// test unfilter (and build reorder buffer)
buffer = new sU8[ codeSize + 16 ];
DisUnFilter( filter.Output.Data, buffer, oldAddr, newAddr, reorder );
if ( sCmpMem( buffer, codePtr, codeSize ) )
{
delete[] buffer;
delete[] sourceImg;
delete[] OutImage;
sSPrintF( Error, 512, "(internal) unfilter failed" );
return 0;
}
delete[] buffer;
delete[] sourceImg;
// build the (uncompressed) image (data chunk only)
UnImage = new sU8[ dataSize + 8 ];
sSetMem( UnImage, 0, dataSize + 8 );
sS32* UnImageSource = new sS32[ dataSize ];
for ( sU32 x = 0; x < dataSize; x++ )
UnImageSource[ x ] = -2;
UnImage += 8;
#if !NODEPACK2
sCopyMem( UnImage, depacker2, depacker2Size );
depack2.Init( UnImage, depacker2Size );
#endif
*( (sU32 *)( UnImage + depacker2Size ) ) = ImportSize;
sCopyMem( UnImage + depacker2Size + 4, Imports, ImportSize );
ImportSize += 4;
delete[] Imports;
for ( sU32 x = 0; x < depacker2Size + ImportSize; x++ )
UnImageSource[ x ] = -1;
#if !NODEPACK2
for ( int x = 0; x < filter.Output.Size; x++ )
UnImageSource[ depacker2Size + ImportSize + x ] = ( (int*)filter.SourceDataOutput.Data )[ x ] < 0 ? -1 : ( (int*)filter.SourceDataOutput.Data )[ x ] + PH->CodeStart - Section[ 0 ].VirtAddr + Section[ 0 ].DataPtr;
sCopyMem( UnImage + depacker2Size + ImportSize, filter.Output.Data, filter.Output.Size );
#endif
UnImageVA = UnImage + depacker2Size + ImportSize + filter.Output.Size - Section[ 0 ].VirtAddr;
for ( i = 0; i < PH->Sections; i++ )
if ( Section[ i ].DataPtr )
{
sCopyMem( UnImageVA + Section[ i ].VirtAddr, source + Section[ i ].DataPtr, Section[ i ].Size );
for ( sU32 x = 0; x < Section[ i ].Size; x++ )
UnImageSource[ depacker2Size + ImportSize + filter.Output.Size - Section[ 0 ].VirtAddr + Section[ i ].VirtAddr + x ] = Section[ i ].DataPtr + x;
}
// process resources
ProcessResources();
// check for load configuration directory
if ( PH->DataDirs >= 11 && OPH->DataDirs >= 11 && outDir[ 21 ] )
{
sSetMem( UnImageVA + outDir[ 20 ], 0, outDir[ 21 ] );
outDir[ 20 ] = 0;
outDir[ 21 ] = 0;
sSPrintF( WarningsPtr, 512, "Load Configuration Directory cleared." );
WarningsPtr += sGetStringLen( WarningsPtr ) + 1;
}
// clean up
CleanupUnImage();
#if !NODEPACK2
sSetMem( UnImageVA + PH->CodeStart, 0, codeSize );
for ( sU32 x = 0; x < codeSize; x++ )
UnImageSource[ depacker2Size + ImportSize + filter.Output.Size - Section[ 0 ].VirtAddr + PH->CodeStart + x ] = -3;
#endif
// copy blobs (and write blob ptrs to ptrtable)
if ( blobs )
{
j = Section[ PH->Sections - 1 ].VirtAddr + Section[ PH->Sections - 1 ].VirtSize;
for ( i = 0; i < blobs->Blobs.Count; i++ )
{
j = ( j + 15 ) & ~15;
( (sU32 *)( UnImageVA + ptrTableO ) )[ i ] = j + PH->ImageStart;
sCopyMem( UnImageVA + j, blobs->Blobs[ i ].Data, blobs->Blobs[ i ].Size );
j += blobs->Blobs[ i ].Size;
}
}
// set up (stage2) depacker params
#if !NODEPACK2
depack2Base = PH->ImageStart + Section[ 0 ].VirtAddr - depacker2Size - ImportSize - filter.Output.Size;
depack2.PatchOffsets( depack2Base );
depack2.Patch( "DEPACKTABLE", filter.Table, sizeof( filter.Table ) );
depack2.PatchDWord( "DCOD", PH->ImageStart + PH->CodeStart );
depack2.PatchDWord( "KERN", depack2Base + depacker2Size - 23 - 52 + 5 );
depack2.PatchDWord( "MSGB", depack2Base + depacker2Size - 12 - 52 + 5 );
depack2.PatchDWord( "EDLL", depack2Base + depacker2Size - 32 );
depack2.PatchDWord( "ERRR", depack2Base + depacker2Size - 32 - 20 + 5 );
depack2.PatchJump( "ETRY", PH->ImageStart + PH->Entry, depack2Base );
#endif
skip = 0; // trailing zero size
while ( skip < dataSize && !UnImage[ dataSize - skip - 1 ] )
skip++;
// set symbol source offsets and reset symbol packed size
if ( info && info->Symbols.Array )
{
sU32 base = SourceOffset( info->Symbols[ 0 ].VA - PH->ImageStart * 2 );
for ( sS32 i = 0; i < info->Symbols.Count; i++ )
{
info->Symbols[ i ].sourcePos = info->ImageRvaToVa( info->Symbols[ i ].VA - PH->ImageStart * 2 );
info->Symbols[ i ].PackedSize = 0;
if ( !info->Symbols[ i ].sourcePos )
{
info->Symbols[ i ].Size = 0;
continue;
if ( i == 402 )
int z = 0;
if ( info->Symbols[ i ].FileNum >= 0 )
{
info->Symbols[ i ].sourcePos = SourceOffset2( info->Symbols[ i ].VA - PH->ImageStart * 2 ) /*- base*/; // compute offset relative to first symbol
info->Symbols[ i ].PackedSize = 0.0;
}
else
{
if ( i > 0 )
{
info->Symbols[ i ].sourcePos = SourceOffset2( info->Symbols[ i - 1 ].VA - PH->ImageStart * 2 ) /*- base*/ + info->Symbols[ i - 1 ].Size; // compute offset relative to first symbol
info->Symbols[ i ].PackedSize = 0.0;
}
}
}
}