-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
pefile.cpp
3213 lines (2783 loc) · 102 KB
/
pefile.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
/* pefile.cpp --
This file is part of the UPX executable compressor.
Copyright (C) 1996-2020 Markus Franz Xaver Johannes Oberhumer
Copyright (C) 1996-2020 Laszlo Molnar
All Rights Reserved.
UPX and the UCL library are free software; you can redistribute them
and/or modify them under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; see the file COPYING.
If not, write to the Free Software Foundation, Inc.,
59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
Markus F.X.J. Oberhumer Laszlo Molnar
<markus@oberhumer.com> <ezerotven+github@gmail.com>
*/
#include "conf.h"
#include "file.h"
#include "filter.h"
#include "packer.h"
#include "pefile.h"
#include "linker.h"
#define FILLVAL 0
/*************************************************************************
//
**************************************************************************/
#include "bptr.h"
#define IPTR(type, var) BoundedPtr<type> var(ibuf, ibuf.getSize())
#define OPTR(type, var) BoundedPtr<type> var(obuf, obuf.getSize())
#define IPTR_I_D(type, var, disp) \
BoundedPtr<type> var(ibuf + (disp), ibuf.getSize() - (disp), ibuf + (disp))
#define IPTR_I(type, var, v) BoundedPtr<type> var(ibuf, ibuf.getSize(), v)
#define OPTR_I(type, var, v) BoundedPtr<type> var(obuf, obuf.getSize(), v)
#define IPTR_C(type, var, v) const BoundedPtr<type> var(ibuf, ibuf.getSize(), v)
#define OPTR_C(type, var, v) const BoundedPtr<type> var(obuf, obuf.getSize(), v)
static void xcheck(const void *p)
{
if (!p)
throwCantUnpack("unexpected NULL pointer; take care!");
}
static void xcheck(const void *p, size_t plen, const void *b, size_t blen)
{
const char *pp = (const char *) p;
const char *bb = (const char *) b;
if (pp < bb || pp > bb + blen || pp + plen > bb + blen)
throwCantUnpack("pointer out of range; take care!");
}
#if 0
static void xcheck(size_t poff, size_t plen, const void *b, size_t blen)
{
ACC_UNUSED(b);
if (poff > blen || poff + plen > blen)
throwCantUnpack("pointer out of range; take care!");
}
#endif
#define ICHECK(x, size) xcheck(x, size, ibuf, ibuf.getSize())
#define OCHECK(x, size) xcheck(x, size, obuf, obuf.getSize())
#define imemset(a,b,c) ICHECK(a,c), memset(a,b,c)
#define omemset(a,b,c) OCHECK(a,c), memset(a,b,c)
#define imemcpy(a,b,c) ICHECK(a,c), memcpy(a,b,c)
#define omemcpy(a,b,c) OCHECK(a,c), memcpy(a,b,c)
/*************************************************************************
//
**************************************************************************/
PeFile::PeFile(InputFile *f) : super(f)
{
bele = &N_BELE_RTP::le_policy;
COMPILE_TIME_ASSERT(sizeof(ddirs_t) == 8)
COMPILE_TIME_ASSERT(sizeof(pe_section_t) == 40)
COMPILE_TIME_ASSERT_ALIGNED1(ddirs_t)
COMPILE_TIME_ASSERT_ALIGNED1(pe_section_t)
COMPILE_TIME_ASSERT(RT_LAST == TABLESIZE(opt->win32_pe.compress_rt))
isection = NULL;
oimport = NULL;
oimpdlls = NULL;
orelocs = NULL;
oexport = NULL;
otls = NULL;
oresources = NULL;
oxrelocs = NULL;
icondir_offset = 0;
icondir_count = 0;
importbyordinal = false;
kernel32ordinal = false;
tlsindex = 0;
big_relocs = 0;
sorelocs = 0;
soxrelocs = 0;
sotls = 0;
isdll = false;
ilinker = NULL;
use_tls_callbacks = false;
oloadconf = NULL;
soloadconf = 0;
use_dep_hack = true;
use_clear_dirty_stack = true;
isrtm = false;
}
bool PeFile::testUnpackVersion(int version) const
{
if (version != ph_version && ph_version != -1)
throwCantUnpack("program has been modified; run a virus checker!");
if (!canUnpackVersion(version))
throwCantUnpack("this program is packed with an obsolete version and cannot be unpacked");
return true;
}
/*************************************************************************
// util
**************************************************************************/
int PeFile::readFileHeader()
{
__packed_struct(exe_header_t)
LE16 mz;
LE16 m512;
LE16 p512;
char _[18];
LE16 relocoffs;
char __[34];
LE32 nexepos;
__packed_struct_end()
COMPILE_TIME_ASSERT(sizeof(exe_header_t) == 64)
COMPILE_TIME_ASSERT_ALIGNED1(exe_header_t)
COMPILE_TIME_ASSERT(sizeof(((exe_header_t*)0)->_) == 18)
COMPILE_TIME_ASSERT(sizeof(((exe_header_t*)0)->__) == 34)
exe_header_t h;
int ic;
pe_offset = 0;
for (ic = 0; ic < 20; ic++)
{
fi->seek(pe_offset,SEEK_SET);
fi->readx(&h,sizeof(h));
if (h.mz == 'M' + 'Z'*256) // dos exe
{
unsigned const delta = (h.relocoffs >= 0x40)
? h.nexepos // new format exe
: (h.p512*512+h.m512 - h.m512 ? 512 : h.nexepos);
if ((pe_offset + delta) < delta // wrap-around
|| (pe_offset + delta) > (unsigned)file_size) {
char buf[64]; snprintf(buf, sizeof(buf),
"bad PE delta %#x at offset %#x", delta, pe_offset);
throwCantPack(buf);
}
pe_offset += delta;
}
else if (get_le32(&h) == 'P' + 'E'*256)
break;
else
return 0;
}
if (ic == 20)
return 0;
fi->seek(pe_offset,SEEK_SET);
readPeHeader();
fi->seek(0x200,SEEK_SET);
fi->readx(&h,6);
return getFormat();
}
/*************************************************************************
// interval handling
**************************************************************************/
PeFile::Interval::Interval(void *b) : capacity(0),base(b),ivarr(NULL),ivnum(0)
{}
PeFile::Interval::~Interval()
{
free(ivarr);
}
void PeFile::Interval::add(const void *start,unsigned len)
{
add(ptr_diff(start,base),len);
}
void PeFile::Interval::add(const void *start,const void *end)
{
add(ptr_diff(start,base),ptr_diff(end,start));
}
int __acc_cdecl_qsort PeFile::Interval::compare(const void *p1,const void *p2)
{
const interval *i1 = (const interval*) p1;
const interval *i2 = (const interval*) p2;
if (i1->start < i2->start) return -1;
if (i1->start > i2->start) return 1;
if (i1->len < i2->len) return 1;
if (i1->len > i2->len) return -1;
return 0;
}
void PeFile::Interval::add(unsigned start,unsigned len)
{
if (ivnum == capacity)
ivarr = (interval*) realloc(ivarr,(capacity += 15) * sizeof (interval));
ivarr[ivnum].start = start;
ivarr[ivnum++].len = len;
}
void PeFile::Interval::add(const Interval *iv)
{
for (unsigned ic = 0; ic < iv->ivnum; ic++)
add(iv->ivarr[ic].start,iv->ivarr[ic].len);
}
void PeFile::Interval::flatten()
{
if (!ivnum)
return;
qsort(ivarr,ivnum,sizeof (interval),Interval::compare);
for (unsigned ic = 0; ic < ivnum - 1; ic++)
{
unsigned jc;
for (jc = ic + 1; jc < ivnum && ivarr[ic].start + ivarr[ic].len >= ivarr[jc].start; jc++)
if (ivarr[ic].start + ivarr[ic].len < ivarr[jc].start + ivarr[jc].len)
ivarr[ic].len = ivarr[jc].start + ivarr[jc].len - ivarr[ic].start;
if (jc > ic + 1)
{
memmove(ivarr + ic + 1, ivarr + jc,sizeof(interval) * (ivnum - jc));
ivnum -= jc - ic - 1;
}
}
}
void PeFile::Interval::clear()
{
for (unsigned ic = 0; ic < ivnum; ic++)
memset((char*) base + ivarr[ic].start,0,ivarr[ic].len);
}
void PeFile::Interval::dump() const
{
printf("%d intervals:\n",ivnum);
for (unsigned ic = 0; ic < ivnum; ic++)
printf("%x %x\n",ivarr[ic].start,ivarr[ic].len);
}
/*************************************************************************
// relocation handling
**************************************************************************/
__packed_struct(PeFile::Reloc::reloc)
LE32 pagestart;
LE32 size;
__packed_struct_end()
void PeFile::Reloc::newRelocPos(void *p)
{
rel = (reloc*) p;
rel1 = (LE16*) ((char*) p + sizeof (reloc));
}
PeFile::Reloc::Reloc(upx_byte *s,unsigned si) :
start(s), size(si), rel(NULL), rel1(NULL)
{
COMPILE_TIME_ASSERT(sizeof(reloc) == 8)
COMPILE_TIME_ASSERT_ALIGNED1(reloc)
memset(counts,0,sizeof(counts));
unsigned pos,type;
while (next(pos,type))
counts[type]++;
}
PeFile::Reloc::Reloc(unsigned rnum) :
start(NULL), size(0), rel(NULL), rel1(NULL)
{
start = new upx_byte[mem_size(4, rnum, 8192)];
counts[0] = 0;
}
bool PeFile::Reloc::next(unsigned &pos,unsigned &type)
{
if (!rel)
newRelocPos(start);
if (ptr_diff(rel, start) >= (int) size || rel->pagestart == 0)
return rel = 0,false; // rewind
pos = rel->pagestart + (*rel1 & 0xfff);
type = *rel1++ >> 12;
//printf("%x %d\n",pos,type);
if (ptr_diff(rel1,rel) >= (int) rel->size)
newRelocPos(rel1);
return type == 0 ? next(pos,type) : true;
}
void PeFile::Reloc::add(unsigned pos,unsigned type)
{
set_le32(start + 1024 + 4 * counts[0]++,(pos << 4) + type);
}
void PeFile::Reloc::finish(upx_byte *&p,unsigned &siz)
{
unsigned prev = 0xffffffff;
set_le32(start + 1024 + 4 * counts[0]++,0xf0000000);
qsort(start + 1024,counts[0],4,le32_compare);
rel = (reloc*) start;
rel1 = (LE16*) start;
for (unsigned ic = 0; ic < counts[0]; ic++)
{
unsigned pos = get_le32(start + 1024 + 4 * ic);
if ((pos ^ prev) >= 0x10000)
{
prev = pos;
*rel1 = 0;
rel->size = ALIGN_UP(ptr_diff(rel1,rel), 4);
newRelocPos((char *)rel + rel->size);
rel->pagestart = (pos >> 4) &~ 0xfff;
}
*rel1++ = (pos << 12) + ((pos >> 4) & 0xfff);
}
p = start;
siz = ptr_diff(rel1,start) &~ 3;
siz -= 8;
// siz can be 0 in 64-bit mode // assert(siz > 0);
start = 0; // safety
}
void PeFile::processRelocs(Reloc *rel) // pass2
{
rel->finish(oxrelocs,soxrelocs);
if (opt->win32_pe.strip_relocs && !isdll /*FIXME ASLR*/)
soxrelocs = 0;
}
void PeFile32::processRelocs() // pass1
{
big_relocs = 0;
unsigned const take1 = IDSIZE(PEDIR_RELOC);
unsigned const skip1 = IDADDR(PEDIR_RELOC);
Reloc rel(ibuf.subref("bad reloc %#x", skip1, take1), take1);
const unsigned *counts = rel.getcounts();
const unsigned rnum = counts[1] + counts[2] + counts[3];
if ((opt->win32_pe.strip_relocs && !isdll) || rnum == 0)
{
if (IDSIZE(PEDIR_RELOC))
ibuf.fill(IDADDR(PEDIR_RELOC), IDSIZE(PEDIR_RELOC), FILLVAL);
orelocs = new upx_byte [1];
sorelocs = 0;
return;
}
unsigned ic;
for (ic = 15; ic > 3; ic--)
if (counts[ic])
infoWarning("skipping unsupported relocation type %d (%d)",ic,counts[ic]);
LE32 *fix[4];
for (; ic; ic--)
fix[ic] = New(LE32, counts[ic]);
unsigned xcounts[4];
memset(xcounts, 0, sizeof(xcounts));
// prepare sorting
unsigned pos,type;
while (rel.next(pos,type))
{
if (pos >= ih.imagesize)
continue; // skip out-of-bounds record
if (type < 4)
fix[type][xcounts[type]++] = pos - rvamin;
}
// remove duplicated records
for (ic = 1; ic <= 3; ic++)
{
qsort(fix[ic], xcounts[ic], 4, le32_compare);
unsigned prev = ~0u;
unsigned jc = 0;
for (unsigned kc = 0; kc < xcounts[ic]; kc++)
if (fix[ic][kc] != prev)
prev = fix[ic][jc++] = fix[ic][kc];
//printf("xcounts[%u] %u->%u\n", ic, xcounts[ic], jc);
xcounts[ic] = jc;
}
// preprocess "type 3" relocation records
for (ic = 0; ic < xcounts[3]; ic++)
{
pos = fix[3][ic] + rvamin;
unsigned w = get_le32(ibuf.subref("bad reloc type 3 %#x", pos, sizeof(LE32)));
set_le32(ibuf + pos, w - ih.imagebase - rvamin);
}
ibuf.fill(IDADDR(PEDIR_RELOC), IDSIZE(PEDIR_RELOC), FILLVAL);
orelocs = new upx_byte [mem_size(4, rnum, 1024)]; // 1024 - safety
sorelocs = ptr_diff(optimizeReloc32((upx_byte*) fix[3], xcounts[3],
orelocs, ibuf + rvamin, 1, &big_relocs),
orelocs);
delete [] fix[3];
// Malware that hides behind UPX often has PE header info that is
// deliberately corrupt. Sometimes it is even tuned to cause us trouble!
// Use an extra check to avoid AccessViolation (SIGSEGV) when appending
// the relocs into one array.
if ((rnum * 4 + 1024) < (sorelocs + 4*(2 + xcounts[2] + xcounts[1])))
throwCantUnpack("Invalid relocs");
// append relocs type "LOW" then "HIGH"
for (ic = 2; ic ; ic--)
{
memcpy(orelocs + sorelocs,fix[ic],4 * xcounts[ic]);
sorelocs += 4 * xcounts[ic];
delete [] fix[ic];
set_le32(orelocs + sorelocs,0);
if (xcounts[ic])
{
sorelocs += 4;
big_relocs |= 2 * ic;
}
}
info("Relocations: original size: %u bytes, preprocessed size: %u bytes",(unsigned) IDSIZE(PEDIR_RELOC),sorelocs);
}
// FIXME - this is too similar to PeFile32::processRelocs
void PeFile64::processRelocs() // pass1
{
big_relocs = 0;
unsigned const take = IDSIZE(PEDIR_RELOC);
unsigned const skip = IDADDR(PEDIR_RELOC);
Reloc rel(ibuf.subref("bad reloc %#x", skip, take), take);
const unsigned *counts = rel.getcounts();
unsigned rnum = 0;
unsigned ic;
for (ic = 1; ic < 16; ic++)
rnum += counts[ic];
if ((opt->win32_pe.strip_relocs && !isdll) || rnum == 0)
{
if (IDSIZE(PEDIR_RELOC))
ibuf.fill(IDADDR(PEDIR_RELOC), IDSIZE(PEDIR_RELOC), FILLVAL);
orelocs = new upx_byte [1];
sorelocs = 0;
return;
}
for (ic = 15; ic; ic--)
if (ic != 10 && counts[ic])
infoWarning("skipping unsupported relocation type %d (%d)",ic,counts[ic]);
LE32 *fix[16];
for (ic = 15; ic; ic--)
fix[ic] = New(LE32, counts[ic]);
unsigned xcounts[16];
memset(xcounts, 0, sizeof(xcounts));
// prepare sorting
unsigned pos,type;
while (rel.next(pos,type))
{
// FIXME add check for relocations which try to modify the
// PE header or other relocation records
if (pos >= ih.imagesize)
continue; // skip out-of-bounds record
if (type < 16)
fix[type][xcounts[type]++] = pos - rvamin;
}
// remove duplicated records
for (ic = 1; ic <= 15; ic++)
{
qsort(fix[ic], xcounts[ic], 4, le32_compare);
unsigned prev = ~0u;
unsigned jc = 0;
for (unsigned kc = 0; kc < xcounts[ic]; kc++)
if (fix[ic][kc] != prev)
prev = fix[ic][jc++] = fix[ic][kc];
//printf("xcounts[%u] %u->%u\n", ic, xcounts[ic], jc);
xcounts[ic] = jc;
}
// preprocess "type 10" relocation records
for (ic = 0; ic < xcounts[10]; ic++)
{
pos = fix[10][ic] + rvamin;
upx_uint64_t w = get_le64(ibuf.subref("bad reloc 10 %#x", pos, sizeof(LE64)));
set_le64(ibuf + pos, w - ih.imagebase - rvamin);
}
ibuf.fill(IDADDR(PEDIR_RELOC), IDSIZE(PEDIR_RELOC), FILLVAL);
orelocs = new upx_byte [mem_size(4, rnum, 1024)]; // 1024 - safety
sorelocs = ptr_diff(optimizeReloc64((upx_byte*) fix[10], xcounts[10],
orelocs, ibuf + rvamin, 1, &big_relocs),
orelocs);
for (ic = 15; ic; ic--)
delete [] fix[ic];
#if 0
// Malware that hides behind UPX often has PE header info that is
// deliberately corrupt. Sometimes it is even tuned to cause us trouble!
// Use an extra check to avoid AccessViolation (SIGSEGV) when appending
// the relocs into one array.
if ((rnum * 4 + 1024) < (sorelocs + 4*(2 + xcounts[2] + xcounts[1])))
throwCantUnpack("Invalid relocs");
// append relocs type "LOW" then "HIGH"
for (ic = 2; ic ; ic--)
{
memcpy(orelocs + sorelocs,fix[ic],4 * xcounts[ic]);
sorelocs += 4 * xcounts[ic];
delete [] fix[ic];
set_le32(orelocs + sorelocs,0);
if (xcounts[ic])
{
sorelocs += 4;
big_relocs |= 2 * ic;
}
}
#endif
info("Relocations: original size: %u bytes, preprocessed size: %u bytes",(unsigned) IDSIZE(PEDIR_RELOC),sorelocs);
}
/*************************************************************************
// import handling
**************************************************************************/
LE32& PeFile::IDSIZE(unsigned x) { return iddirs[x].size; }
LE32& PeFile::IDADDR(unsigned x) { return iddirs[x].vaddr; }
LE32& PeFile::ODSIZE(unsigned x) { return oddirs[x].size; }
LE32& PeFile::ODADDR(unsigned x) { return oddirs[x].vaddr; }
/*
ImportLinker: 32 and 64 bit import table building.
Import entries (dll name + proc name/ordinal pairs) can be
added in arbitrary order.
Internally it works by creating sections with special names,
and adding relocation entries between those sections. The special
names ensure that when the import table is built in the memory
from those sections, a correct table can be generated simply by
sorting the sections by name, and adding all of them to the output
in the sorted order.
*/
class PeFile::ImportLinker : public ElfLinkerAMD64
{
struct tstr : private ::noncopyable
{
char *s;
explicit tstr(char *str) : s(str) {}
~tstr() { delete [] s; }
operator char *() const { return s; }
};
// encoding of dll and proc names are required, so that our special
// control characters in the name of sections can work as intended
static char *encode_name(const char *name, char *buf)
{
char *b = buf;
while (*name)
{
*b++ = 'a' + ((*name >> 4) & 0xf);
*b++ = 'a' + (*name & 0xf);
name++;
}
*b = 0;
return buf;
}
static char *name_for_dll(const char *dll, char first_char)
{
assert(dll);
unsigned l = strlen(dll);
assert(l > 0);
char *name = New(char, 3 * l + 2);
assert(name);
name[0] = first_char;
char *n = name + 1 + 2 * l;
do {
*n++ = tolower(*dll);
} while(*dll++);
return encode_name(name + 1 + 2 * l, name + 1) - 1;
}
static char *name_for_proc(const char *dll, const char *proc,
char first_char, char separator)
{
unsigned len = 1 + 2 * strlen(dll) + 1 + 2 * strlen(proc) + 1 + 1;
tstr dlln(name_for_dll(dll, first_char));
char *procn = New(char, len);
upx_snprintf(procn, len, "%s%c", (const char*) dlln, separator);
encode_name(proc, procn + strlen(procn));
return procn;
}
static const char zeros[sizeof(import_desc)];
enum {
// the order of identifiers is very important below!!
descriptor_id = 'D',
thunk_id,
dll_name_id,
proc_name_id,
ordinal_id,
thunk_separator_first,
thunk_separator,
thunk_separator_last,
procname_separator,
};
unsigned thunk_size; // 4 or 8 bytes
void add(const char *dll, const char *proc, unsigned ordinal)
{
tstr sdll(name_for_dll(dll, dll_name_id));
tstr desc_name(name_for_dll(dll, descriptor_id));
char tsep = thunk_separator;
if (findSection(sdll, false) == NULL)
{
tsep = thunk_separator_first;
addSection(sdll, dll, strlen(dll) + 1, 0); // name of the dll
addSymbol(sdll, sdll, 0);
addSection(desc_name, zeros, sizeof(zeros), 0); // descriptor
addRelocation(desc_name, offsetof(import_desc, dllname),
"R_X86_64_32", sdll, 0);
}
tstr thunk(name_for_proc(dll, proc, thunk_id, tsep));
if (findSection(thunk, false) != NULL)
return; // we already have this dll/proc
addSection(thunk, zeros, thunk_size, 0);
addSymbol(thunk, thunk, 0);
if (tsep == thunk_separator_first)
{
addRelocation(desc_name, offsetof(import_desc, iat),
"R_X86_64_32", thunk, 0);
tstr last_thunk(name_for_proc(dll, "X", thunk_id, thunk_separator_last));
addSection(last_thunk, zeros, thunk_size, 0);
}
const char *reltype = thunk_size == 4 ? "R_X86_64_32" : "R_X86_64_64";
if (ordinal != 0u)
{
addRelocation(thunk, 0, reltype, "*UND*",
ordinal | (1ull << (thunk_size * 8 - 1)));
}
else
{
tstr proc_name(name_for_proc(dll, proc, proc_name_id, procname_separator));
addSection(proc_name, zeros, 2, 1); // 2 bytes of word aligned "hint"
addSymbol(proc_name, proc_name, 0);
addRelocation(thunk, 0, reltype, proc_name, 0);
strcat(proc_name, "X");
addSection(proc_name, proc, strlen(proc), 0); // the name of the symbol
}
}
static int __acc_cdecl_qsort compare(const void *p1, const void *p2)
{
const Section *s1 = * (const Section * const *) p1;
const Section *s2 = * (const Section * const *) p2;
return strcmp(s1->name, s2->name);
}
virtual void alignCode(unsigned len) { alignWithByte(len, 0); }
const Section *getThunk(const char *dll, const char *proc, char tsep) const
{
assert(dll);
assert(proc);
tstr thunk(name_for_proc(dll, proc, thunk_id, tsep));
return findSection(thunk, false);
}
public:
explicit ImportLinker(unsigned thunk_size_) : thunk_size(thunk_size_)
{
assert(thunk_size == 4 || thunk_size == 8);
addSection("*UND*", NULL, 0, 0);
addSymbol("*UND*", "*UND*", 0);
addSection("*ZSTART", NULL, 0, 0);
addSymbol("*ZSTART", "*ZSTART", 0);
Section *s = addSection("Dzero", zeros, sizeof(import_desc), 0);
assert(s->name[0] == descriptor_id);
// one trailing 00 byte after the last proc name
addSection("Zzero", zeros, 1, 0);
}
template <typename C>
void add(const C *dll, unsigned ordinal)
{
ACC_COMPILE_TIME_ASSERT(sizeof(C) == 1) // "char" or "unsigned char"
assert(ordinal > 0 && ordinal < 0x10000);
char ord[1+5+1];
upx_snprintf(ord, sizeof(ord), "%c%05u", ordinal_id, ordinal);
add((const char*) dll, ord, ordinal);
}
template <typename C1, typename C2>
void add(const C1 *dll, const C2 *proc)
{
ACC_COMPILE_TIME_ASSERT(sizeof(C1) == 1) // "char" or "unsigned char"
ACC_COMPILE_TIME_ASSERT(sizeof(C2) == 1) // "char" or "unsigned char"
assert(proc);
add((const char*) dll, (const char*) proc, 0);
}
unsigned build()
{
assert(output == NULL);
int osize = 4 + 2 * nsections; // upper limit for alignments
for (unsigned ic = 0; ic < nsections; ic++)
osize += sections[ic]->size;
output = New(upx_byte, osize);
outputlen = 0;
// sort the sections by name before adding them all
qsort(sections, nsections, sizeof (Section*), ImportLinker::compare);
for (unsigned ic = 0; ic < nsections; ic++)
addLoader(sections[ic]->name);
addLoader("+40D");
assert(outputlen <= osize);
//OutputFile::dump("il0.imp", output, outputlen);
return outputlen;
}
void relocate_import(unsigned myimport)
{
assert(nsections > 0);
assert(output);
defineSymbol("*ZSTART", /*0xffffffffff1000ull + 0 * */ myimport);
ElfLinkerAMD64::relocate();
//OutputFile::dump("il1.imp", output, outputlen);
}
template <typename C1, typename C2>
upx_uint64_t getAddress(const C1 *dll, const C2 *proc) const
{
ACC_COMPILE_TIME_ASSERT(sizeof(C1) == 1) // "char" or "unsigned char"
ACC_COMPILE_TIME_ASSERT(sizeof(C2) == 1) // "char" or "unsigned char"
const Section *s = getThunk((const char*) dll, (const char*) proc,
thunk_separator_first);
if (s == NULL && (s = getThunk((const char*) dll,(const char*) proc,
thunk_separator)) == NULL)
throwInternalError("entry not found");
return s->offset;
}
template <typename C>
upx_uint64_t getAddress(const C *dll, unsigned ordinal) const
{
ACC_COMPILE_TIME_ASSERT(sizeof(C) == 1) // "char" or "unsigned char"
assert(ordinal > 0 && ordinal < 0x10000);
char ord[1+5+1];
upx_snprintf(ord, sizeof(ord), "%c%05u", ordinal_id, ordinal);
const Section *s = getThunk((const char*) dll, ord, thunk_separator_first);
if (s == NULL
&& (s = getThunk((const char*) dll, ord, thunk_separator)) == NULL)
throwInternalError("entry not found");
return s->offset;
}
template <typename C>
upx_uint64_t getAddress(const C *dll) const
{
ACC_COMPILE_TIME_ASSERT(sizeof(C) == 1) // "char" or "unsigned char"
tstr sdll(name_for_dll((const char*) dll, dll_name_id));
return findSection(sdll, true)->offset;
}
template <typename C>
upx_uint64_t hasDll(const C *dll) const
{
ACC_COMPILE_TIME_ASSERT(sizeof(C) == 1) // "char" or "unsigned char"
tstr sdll(name_for_dll((const char*) dll, dll_name_id));
return findSection(sdll, false) != NULL;
}
};
const char PeFile::ImportLinker::zeros[sizeof(import_desc)] = { 0 };
void PeFile::addKernelImport(const char *name)
{
ilinker->add(kernelDll(), name);
}
void PeFile::addStubImports()
{
addKernelImport("LoadLibraryA");
addKernelImport("GetProcAddress");
if (!isdll)
addKernelImport("ExitProcess");
addKernelImport("VirtualProtect");
}
void PeFile::processImports2(unsigned myimport, unsigned) // pass 2
{
COMPILE_TIME_ASSERT(sizeof(import_desc) == 20);
ilinker->relocate_import(myimport);
int len;
oimpdlls = ilinker->getLoader(&len);
assert(len == (int) soimpdlls);
//OutputFile::dump("x1.imp", oimpdlls, soimpdlls);
}
template <typename LEXX, typename ord_mask_t>
unsigned PeFile::processImports0(ord_mask_t ord_mask) // pass 1
{
unsigned dllnum = 0;
unsigned const take = IDSIZE(PEDIR_IMPORT);
unsigned const skip = IDADDR(PEDIR_IMPORT);
import_desc *im = (import_desc*)ibuf.subref("bad import %#x", skip, take);
import_desc * const im_save = im;
if (IDADDR(PEDIR_IMPORT))
{
for (;; ++dllnum, ++im) {
unsigned const skip2 = ptr_diff(im, ibuf);
(void)ibuf.subref("bad import %#x", skip2, sizeof(*im));
if (!im->dllname)
break;
}
im = im_save;
}
struct udll
{
const upx_byte *name;
const upx_byte *shname;
unsigned ordinal;
unsigned iat;
LEXX *lookupt;
unsigned original_position;
bool isk32;
static int __acc_cdecl_qsort compare(const void *p1, const void *p2)
{
const udll *u1 = * (const udll * const *) p1;
const udll *u2 = * (const udll * const *) p2;
if (u1->isk32) return -1;
if (u2->isk32) return 1;
if (!*u1->lookupt) return 1;
if (!*u2->lookupt) return -1;
int rc = strcasecmp(u1->name,u2->name);
if (rc) return rc;
if (u1->ordinal) return -1;
if (u2->ordinal) return 1;
if (!u1->shname) return 1;
if (!u2->shname) return -1;
rc = (int) (upx_strlen(u1->shname) - upx_strlen(u2->shname));
if (rc) return rc;
return strcmp(u1->shname, u2->shname);
}
};
// +1 for dllnum=0
Array(struct udll, dlls, dllnum+1);
Array(struct udll *, idlls, dllnum+1);
soimport = 1024; // safety
unsigned ic;
for (ic = 0; dllnum && im->dllname; ic++, im++)
{
idlls[ic] = dlls + ic;
dlls[ic].name = ibuf.subref("bad dllname %#x", im->dllname, 1);
dlls[ic].shname = NULL;
dlls[ic].ordinal = 0;
dlls[ic].iat = im->iat;
unsigned const skip2 = (im->oft ? im->oft : im->iat);
dlls[ic].lookupt = (LEXX*)ibuf.subref("bad dll lookupt %#x", skip2, sizeof(LEXX));
dlls[ic].original_position = ic;
dlls[ic].isk32 = strcasecmp(kernelDll(), (const char*)dlls[ic].name) == 0;
soimport += strlen(dlls[ic].name) + 1 + 4;
for (IPTR_I(LEXX, tarr, dlls[ic].lookupt); *tarr; tarr += 1)
{
if (*tarr & ord_mask)
{
importbyordinal = true;
soimport += 2; // ordinal num: 2 bytes
dlls[ic].ordinal = *tarr & 0xffff;
}
else //it's an import by name
{
IPTR_I(const upx_byte, n, ibuf + *tarr + 2);
unsigned len = strlen(n);
soimport += len + 1;
if (dlls[ic].shname == NULL || len < strlen (dlls[ic].shname))
dlls[ic].shname = ibuf + *tarr + 2;
}
soimport++; // separator
}
}
oimport = New(upx_byte, soimport);
memset(oimport,0,soimport);
qsort(idlls,dllnum,sizeof (udll*),udll::compare);
info("Processing imports: %d DLLs", dllnum);
ilinker = new ImportLinker(sizeof(LEXX));
// create the new import table
addStubImports();
for (ic = 0; ic < dllnum; ic++)
{
if (idlls[ic]->isk32)
{
// for kernel32.dll we need to put all the imported
// ordinals into the output import table, as on
// some versions of windows GetProcAddress does not resolve them
if (strcasecmp((const char*)idlls[ic]->name, "kernel32.dll"))
continue;
if (idlls[ic]->ordinal)
for (LEXX *tarr = idlls[ic]->lookupt; *tarr; tarr++)
if (*tarr & ord_mask)
{
ilinker->add(kernelDll(), *tarr & 0xffff);
kernel32ordinal = true;
}
}
else if (!ilinker->hasDll(idlls[ic]->name))
{
if (idlls[ic]->ordinal)
ilinker->add(idlls[ic]->name, idlls[ic]->ordinal);
else if (idlls[ic]->shname)
ilinker->add(idlls[ic]->name, idlls[ic]->shname);
else
throwInternalError("should not happen");
}
}
soimpdlls = ilinker->build();
Interval names(ibuf),iats(ibuf),lookups(ibuf);
// create the preprocessed data
upx_byte *ppi = oimport; // preprocessed imports
for (ic = 0; ic < dllnum; ic++)
{
LEXX *tarr = idlls[ic]->lookupt;
#if 0 && ENABLE_THIS_AND_UNCOMPRESSION_WILL_BREAK // FIXME
if (!*tarr) // no imports from this dll
continue;
#endif
set_le32(ppi, ilinker->getAddress(idlls[ic]->name));
set_le32(ppi+4,idlls[ic]->iat - rvamin);
ppi += 8;
for (; *tarr; tarr++)
if (*tarr & ord_mask)
{
unsigned ord = *tarr & 0xffff;
if (idlls[ic]->isk32 && kernel32ordinal)
{