-
Notifications
You must be signed in to change notification settings - Fork 4.5k
/
pewriter.cpp
1837 lines (1506 loc) · 58.1 KB
/
pewriter.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#include "stdafx.h"
#include "blobfetcher.h"
#include "pedecoder.h"
#ifdef _DEBUG
#define LOGGING
#endif
#ifdef LOGGING
#include "log.h"
static const char* const RelocName[] = {
"Absolute", "Unk1", "Unk2", "HighLow", "Unk4", "MapToken",
"Relative", "FilePos", "CodeRel", "Movl64", "Dir64", "PcRel25", "PcRel64",
"AbsTag" };
static const char RelocSpaces[] = " ";
static INT64 s_minPcRel25;
static INT64 s_maxPcRel25;
#endif
/* This is the stub program that says it can't be run in DOS mode */
/* it is x86 specific, but so is dos so I suppose that is OK */
static const unsigned char x86StubPgm[] = {
0x0e, 0x1f, 0xba, 0x0e, 0x00, 0xb4, 0x09, 0xcd, 0x21, 0xb8, 0x01, 0x4c, 0xcd, 0x21, 0x54, 0x68,
0x69, 0x73, 0x20, 0x70, 0x72, 0x6f, 0x67, 0x72, 0x61, 0x6d, 0x20, 0x63, 0x61, 0x6e, 0x6e, 0x6f,
0x74, 0x20, 0x62, 0x65, 0x20, 0x72, 0x75, 0x6e, 0x20, 0x69, 0x6e, 0x20, 0x44, 0x4f, 0x53, 0x20,
0x6d, 0x6f, 0x64, 0x65, 0x2e, 0x0d, 0x0d, 0x0a, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
/* number of pad bytes to make 'len' bytes align to 'align' */
inline static unsigned roundUp(unsigned len, unsigned align) {
return((len + align-1) & ~(align-1));
}
inline static unsigned padLen(unsigned len, unsigned align) {
return(roundUp(len, align) - len);
}
#ifndef IMAGE_DLLCHARACTERISTICS_NO_SEH
#define IMAGE_DLLCHARACTERISTICS_NO_SEH 0x400
#endif
#ifndef IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE
#define IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE 0x0040
#endif
#ifndef IMAGE_DLLCHARACTERISTICS_NX_COMPAT
#define IMAGE_DLLCHARACTERISTICS_NX_COMPAT 0x0100
#endif
#define COPY_AND_ADVANCE(target, src, size) { \
::memcpy((void *) (target), (const void *) (src), (size)); \
(char *&) (target) += (size); }
/******************************************************************/
int __cdecl relocCmp(const void* a_, const void* b_) {
const PESectionReloc* a = (const PESectionReloc*) a_;
const PESectionReloc* b = (const PESectionReloc*) b_;
return (a->offset > b->offset ? 1 : (a->offset == b->offset ? 0 : -1));
}
PERelocSection::PERelocSection(PEWriterSection *pBaseReloc)
{
section = pBaseReloc;
relocPage = (unsigned) -1;
relocSize = 0;
relocSizeAddr = NULL;
pages = 0;
#ifdef _DEBUG
lastRVA = 0;
#endif
}
void PERelocSection::AddBaseReloc(unsigned rva, int type, unsigned short highAdj)
{
#ifdef _DEBUG
// Guarantee that we're adding relocs in strict increasing order.
_ASSERTE(rva > lastRVA);
lastRVA = rva;
#endif
if (relocPage != (rva & ~0xFFF)) {
if (relocSizeAddr) {
if ((relocSize & 1) == 1) { // pad to an even number
short *ps = (short*) section->getBlock(2);
if(ps) {
*ps = 0;
relocSize++;
}
}
*relocSizeAddr = VAL32(relocSize*2 + sizeof(IMAGE_BASE_RELOCATION));
}
IMAGE_BASE_RELOCATION* base = (IMAGE_BASE_RELOCATION*) section->getBlock(sizeof(IMAGE_BASE_RELOCATION));
if(base) {
relocPage = (rva & ~0xFFF);
relocSize = 0;
base->VirtualAddress = VAL32(relocPage);
// Size needs to be fixed up when we know it - save address here
relocSizeAddr = &base->SizeOfBlock;
pages++;
}
}
relocSize++;
unsigned short* offset = (unsigned short*) section->getBlock(2);
if(offset) {
*offset = VAL16((unsigned short)(rva & 0xFFF) | (unsigned short)(type << 12));
}
}
void PERelocSection::Finish(bool isPE32)
{
// fixup the last reloc block (if there was one)
if (relocSizeAddr) {
if ((relocSize & 1) == 1) { // pad to an even number
short* psh = (short*) section->getBlock(2);
if(psh)
{
*psh = 0;
relocSize++;
}
}
*relocSizeAddr = VAL32(relocSize*2 + sizeof(IMAGE_BASE_RELOCATION));
}
}
#define GET_UNALIGNED_INT32(_ptr) ((INT32) GET_UNALIGNED_VAL32(_ptr))
static inline HRESULT SignedFitsIn31Bits(INT64 immediate)
{
INT64 hiBits = immediate >> 31;
if ((hiBits == 0) || (hiBits == -1))
{
return S_OK;
}
else
{
return E_FAIL;
}
}
static inline HRESULT UnsignedFitsIn32Bits(UINT64 immediate)
{
UINT64 hiBits = immediate >> 32;
if (hiBits == 0)
{
return S_OK;
}
else
{
return E_FAIL;
}
}
static inline HRESULT AddOvf_RVA(DWORD& a, DWORD b)
{
DWORD r = a + b;
if (r < a) // Check for overflow
return E_FAIL;
a = r;
return S_OK;
}
static inline HRESULT AddOvf_S_U32(INT64 & a, unsigned int b)
{
INT64 r = a + b;
if (r < a) // Check for overflow
return E_FAIL;
a = r;
return S_OK;
}
static inline HRESULT AddOvf_S_S32(INT64 & a, int b)
{
INT64 r = a + b;
if ( ((r >= a) && (b >= 0)) ||
((r < a) && (b < 0)) )
{
a = r;
return S_OK;
}
return E_FAIL;
}
static inline HRESULT AddOvf_U_U32(UINT64 & a, unsigned int b)
{
UINT64 r = a + b;
if (r < a) // Check for overflow
return E_FAIL;
a = r;
return S_OK;
}
static inline HRESULT AddOvf_U_U(UINT64 & a, UINT64 b)
{
UINT64 r = a + b;
if (r < a) // Check for overflow
return E_FAIL;
a = r;
return S_OK;
}
static inline HRESULT SubOvf_S_U32(INT64 & a, unsigned int b)
{
INT64 r = a - b;
if (r > a) // Check for overflow
return E_FAIL;
a = r;
return S_OK;
}
static inline HRESULT SubOvf_S_U(INT64 & a, UINT64 b)
{
INT64 r = a - b;
if (r > a) // Check for overflow
return E_FAIL;
a = r;
return S_OK;
}
static inline HRESULT SubOvf_U_U32(UINT64 & a, unsigned int b)
{
UINT64 r = a - b;
if (r > a) // Check for overflow
return E_FAIL;
a = r;
return S_OK;
}
#ifndef HOST_AMD64
/* subtract two unsigned pointers yielding a signed pointer sized int */
static inline HRESULT SubOvf_U_U(INT64 & r, UINT64 a, UINT64 b)
{
r = a - b;
if ( ((a >= b) && (r >= 0)) ||
((a < b) && (r < 0)))
{
return S_OK;
}
return E_FAIL;
}
#endif
/******************************************************************/
/* apply the relocs for this section.
*/
HRESULT PEWriterSection::applyRelocs(IMAGE_NT_HEADERS * pNtHeaders,
PERelocSection * pBaseRelocSection,
CeeGenTokenMapper * pTokenMapper,
DWORD dataRvaBase,
DWORD rdataRvaBase,
DWORD codeRvaBase)
{
HRESULT hr;
_ASSERTE(pBaseRelocSection); // need section to write relocs
#ifdef LOGGING
// Ensure that if someone adds a value to CeeSectionRelocType in cor.h,
// that they also add an entry to RelocName.
static_assert_no_msg(ARRAY_SIZE(RelocName) == srRelocSentinel);
#ifdef _DEBUG
for (unsigned int i = 0; i < srRelocSentinel; i++)
{
_ASSERTE(strlen(RelocName[i]) <= strlen(RelocSpaces));
}
#endif // _DEBUG
#endif // LOGGING
if (m_relocCur == m_relocStart)
return S_OK;
bool isPE32 = (pNtHeaders->OptionalHeader.Magic == VAL16(IMAGE_NT_OPTIONAL_HDR32_MAGIC));
#ifdef LOGGING
LOG((LF_ZAP, LL_INFO100000,
"APPLYING section relocs for section %s start RVA = 0x%x\n",
m_name, m_baseRVA));
#endif
UINT64 imageBase = isPE32 ? VAL32(((IMAGE_NT_HEADERS32 *) pNtHeaders)->OptionalHeader.ImageBase)
: VAL64(((IMAGE_NT_HEADERS64 *) pNtHeaders)->OptionalHeader.ImageBase);
// sort them to make the baseRelocs pretty
qsort(m_relocStart, (m_relocCur - m_relocStart), sizeof(PESectionReloc), relocCmp);
for (PESectionReloc * cur = m_relocStart; cur < m_relocCur; cur++)
{
_ASSERTE((cur->offset + 4) <= m_blobFetcher.GetDataLen());
int curType = cur->type;
DWORD curOffset = cur->offset;
bool isRelocPtr = ((curType & srRelocPtr) != 0);
bool noBaseBaseReloc = ((curType & srNoBaseReloc) != 0);
UINT64 targetOffset = 0;
int slotNum = 0;
INT64 oldStarPos;
// If cur->section is NULL then this is a pointer outside the module.
bool externalAddress = (cur->section == NULL);
curType &= ~(srRelocPtr | srNoBaseReloc);
/* If we see any srRelocHighLow's in a PE64 file we convert them into DIR64 relocs */
if (!isPE32 && (curType == srRelocHighLow))
curType = srRelocDir64;
/* If we have an IA64 instruction fixup then extract the slot number and adjust curOffset */
if ((curType == srRelocIA64PcRel25) || (curType == srRelocIA64Imm64) || (curType == srRelocIA64PcRel64))
{
_ASSERTE((curOffset & 0x3) == 0);
slotNum = (curOffset & 0xf) >> 2;
curOffset &= ~0xf;
}
DWORD curRVA = m_baseRVA; // RVA in the PE image of the reloc site
IfFailRet(AddOvf_RVA(curRVA, curOffset));
DWORD UNALIGNED * pos = (DWORD *) m_blobFetcher.ComputePointer(curOffset);
PREFIX_ASSUME(pos != NULL);
#ifdef LOGGING
LOG((LF_ZAP, LL_INFO1000000,
" Reloc %s%s%s at %-7s+%04x (RVA=%08x) at" FMT_ADDR,
RelocName[curType], (isRelocPtr) ? "Ptr" : " ",
&RelocSpaces[strlen(RelocName[curType])],
m_name, curOffset, curRVA, DBG_ADDR(pos)));
#endif
//
// 'pos' is the site of the reloc
// Compute 'targetOffset' from pointer if necessary
//
if (isRelocPtr)
{
// Calculate the value of ptr to pass to computeOffset
char * ptr = (char *) pos;
if (curType == srRelocRelative) {
//
// Here we add sizeof(int) because we need to calculate
// ptr as the true call target address (x86 pc-rel)
// We need to true call target address since pass it
// to computeOffset and this function would fall if
// the address we pass is before the start of a section
//
oldStarPos = (SSIZE_T) ptr;
IfFailRet(AddOvf_S_S32(oldStarPos, GET_UNALIGNED_INT32(pos)));
IfFailRet(AddOvf_S_U32(oldStarPos, sizeof(int)));
ptr = (char *) oldStarPos;
targetOffset = externalAddress ? (size_t) ptr
: cur->section->computeOffset(ptr);
// We subtract off the four bytes that we added previous
// since the code below depends upon this
IfFailRet(SubOvf_U_U32(targetOffset, sizeof(int)));
IfFailRet(UnsignedFitsIn32Bits(targetOffset)); // Check for overflow
SET_UNALIGNED_VAL32(pos, targetOffset);
}
else if (curType == srRelocIA64Imm64) {
_ASSERTE(slotNum == 1);
ptr = (char *) ((intptr_t) GetIA64Imm64((UINT64 *) ptr));
oldStarPos = (SSIZE_T) ptr;
targetOffset = externalAddress ? (size_t) ptr
: cur->section->computeOffset(ptr);
_ASSERTE(!isPE32);
PutIA64Imm64((UINT64 *)pos, targetOffset);
}
else if (curType == srRelocIA64PcRel64) {
_ASSERTE(slotNum == 1);
ptr = (char *) ((intptr_t) GetIA64Rel64((UINT64 *) ptr));
oldStarPos = (SSIZE_T) ptr;
targetOffset = externalAddress ? (size_t) ptr
: cur->section->computeOffset(ptr);
_ASSERTE(!isPE32);
PutIA64Rel64((UINT64 *)pos, targetOffset);
}
else {
_ASSERTE(curType != srRelocIA64PcRel25);
ptr = (char *) GET_UNALIGNED_VALPTR(ptr);
oldStarPos = (SSIZE_T) ptr;
targetOffset = externalAddress ? (size_t) ptr
: cur->section->computeOffset(ptr);
IfFailRet(UnsignedFitsIn32Bits(targetOffset)); // Check for overflow
SET_UNALIGNED_VAL32(pos, targetOffset);
/* Zero the upper 32-bits for a machine with 64-bit pointers */
if (!isPE32)
SET_UNALIGNED_VAL32(pos+1, 0);
}
}
#ifdef LOGGING
else
{
if (curType == srRelocIA64PcRel25)
{
oldStarPos = GetIA64Rel25((UINT64 *) pos, slotNum);
}
else
{
if (curType == srRelocIA64PcRel64)
{
_ASSERTE(slotNum == 1);
oldStarPos = GetIA64Rel64((UINT64 *) pos);
}
else if (curType == srRelocIA64Imm64)
{
oldStarPos = GetIA64Imm64((UINT64 *)pos);
}
else
{
oldStarPos = GET_UNALIGNED_VAL32(pos);
}
}
}
#endif
//
// 'targetOffset' has now been computed. Write out the appropriate value.
// Record base relocs as necessary.
//
bool fBaseReloc = false;
bool fNeedBrl = false;
INT64 newStarPos = 0; // oldStarPos gets updated to newStarPos
if (curType == srRelocAbsolute || curType == srRelocAbsoluteTagged) {
_ASSERTE(!externalAddress);
newStarPos = GET_UNALIGNED_INT32(pos);
if (curType == srRelocAbsoluteTagged)
newStarPos = (newStarPos & ~0x80000001) >> 1;
if (rdataRvaBase > 0 && ! strcmp((const char *)(cur->section->m_name), ".rdata"))
IfFailRet(AddOvf_S_U32(newStarPos, rdataRvaBase));
else if (dataRvaBase > 0 && ! strcmp((const char *)(cur->section->m_name), ".data"))
IfFailRet(AddOvf_S_U32(newStarPos, dataRvaBase));
else
IfFailRet(AddOvf_S_U32(newStarPos, cur->section->m_baseRVA));
if (curType == srRelocAbsoluteTagged)
newStarPos = (newStarPos << 1) | 0x80000001;
SET_UNALIGNED_VAL32(pos, newStarPos);
}
else if (curType == srRelocMapToken)
{
mdToken newToken;
if (pTokenMapper != NULL && pTokenMapper->HasTokenMoved((mdToken)GET_UNALIGNED_VAL32(pos), newToken)) {
// we have a mapped token
SET_UNALIGNED_VAL32(pos, newToken);
}
newStarPos = GET_UNALIGNED_VAL32(pos);
}
else if (curType == srRelocFilePos)
{
_ASSERTE(!externalAddress);
newStarPos = GET_UNALIGNED_VAL32(pos);
IfFailRet(AddOvf_S_U32(newStarPos, cur->section->m_filePos));
SET_UNALIGNED_VAL32(pos, newStarPos);
}
else if (curType == srRelocRelative)
{
if (externalAddress) {
#if defined(HOST_AMD64)
newStarPos = GET_UNALIGNED_INT32(pos);
#else // x86
UINT64 targetAddr = GET_UNALIGNED_VAL32(pos);
IfFailRet(SubOvf_U_U(newStarPos, targetAddr, imageBase));
#endif
}
else {
newStarPos = GET_UNALIGNED_INT32(pos);
IfFailRet(AddOvf_S_U32(newStarPos, cur->section->m_baseRVA));
}
IfFailRet(SubOvf_S_U32(newStarPos, curRVA));
IfFailRet(SignedFitsIn31Bits(newStarPos)); // Check for overflow
SET_UNALIGNED_VAL32(pos, newStarPos);
}
else if (curType == srRelocCodeRelative)
{
newStarPos = GET_UNALIGNED_INT32(pos);
IfFailRet(SubOvf_S_U32(newStarPos, codeRvaBase));
if (externalAddress)
IfFailRet(SubOvf_S_U(newStarPos, imageBase));
else
IfFailRet(AddOvf_S_U32(newStarPos, cur->section->m_baseRVA));
IfFailRet(SignedFitsIn31Bits(newStarPos)); // Check for overflow
SET_UNALIGNED_VAL32(pos, newStarPos);
}
else if (curType == srRelocIA64PcRel25)
{
_ASSERTE((m_baseRVA & 15) == 0);
_ASSERTE((cur->section->m_baseRVA & 15) == 0);
newStarPos = GetIA64Rel25((UINT64 *) pos, slotNum);
IfFailRet(SubOvf_S_U32(newStarPos, curRVA));
if (externalAddress)
IfFailRet(SubOvf_S_U(newStarPos, imageBase));
else
IfFailRet(AddOvf_S_U32(newStarPos, cur->section->m_baseRVA));
INT64 hiBits = newStarPos >> 24;
_ASSERTE((hiBits==0) || (hiBits==-1));
IfFailRet(AddOvf_S_U32(newStarPos, GetIA64Rel25((UINT64 *) pos, slotNum)));
hiBits = newStarPos >> 24;
_ASSERTE((hiBits==0) || (hiBits==-1));
INT32 delta32 = (INT32) newStarPos;
PutIA64Rel25((UINT64 *) pos, slotNum, delta32);
_ASSERTE(GetIA64Rel25((UINT64 *) pos, slotNum) == delta32);
#ifdef LOGGING
if (newStarPos < s_minPcRel25)
s_minPcRel25 = newStarPos;
if (newStarPos > s_maxPcRel25)
s_maxPcRel25 = newStarPos;
#endif
}
else if (curType == srRelocIA64PcRel64)
{
_ASSERTE((m_baseRVA & 15) == 0);
_ASSERTE(slotNum == 1);
newStarPos = GetIA64Rel64((UINT64 *) pos);
IfFailRet(SubOvf_S_U32(newStarPos, m_baseRVA));
if (externalAddress)
IfFailRet(SubOvf_S_U(newStarPos, imageBase));
else
{
_ASSERTE((cur->section->m_baseRVA & 15) == 0);
IfFailRet(AddOvf_S_U32(newStarPos, cur->section->m_baseRVA));
}
INT64 hiBits = newStarPos >> 24;
fNeedBrl = (hiBits != 0) && (hiBits != -1);
/* Can we convert the brl.call into a br.call? */
if (!fNeedBrl)
{
INT32 delta32 = (INT32) newStarPos;
UINT64 temp0 = ((UINT64 *) pos)[0];
UINT64 temp1 = ((UINT64 *) pos)[1];
#ifdef _DEBUG
//
// make certain we're decoding a brl opcode, with template 4 or 5
//
UINT64 templa = (temp0 >> 0) & 0x1f;
UINT64 opcode = (temp1 >> 60) & 0xf;
_ASSERTE(((opcode == 0xC) || (opcode == 0xD)) &&
((templa == 0x4) || (templa == 0x5)));
#endif
const UINT64 mask0 = UI64(0x00003FFFFFFFFFE1);
const UINT64 mask1 = UI64(0x7700000FFF800000);
/* Clear all bits used as part of the slot1 and slot2 */
temp0 &= mask0; // opcode becomes 4 or 5
temp1 &= mask1;
temp0 |= 0x10; // template becomes 0x10 or 0x11
temp1 |= 0x200; // slot 1 becomes nop.i
((UINT64 *) pos)[0] = temp0;
((UINT64 *) pos)[1] = temp1;
PutIA64Rel25((UINT64 *) pos, 2, delta32);
_ASSERTE(GetIA64Rel25((UINT64 *) pos, 2) == delta32);
}
else
{
PutIA64Rel64((UINT64 *) pos, newStarPos);
_ASSERTE(GetIA64Rel64((UINT64 *) pos) == newStarPos);
}
}
else if (curType == srRelocHighLow)
{
_ASSERTE(isPE32);
// we have a 32-bit value at pos
UINT64 value = GET_UNALIGNED_VAL32(pos);
if (!externalAddress)
{
IfFailRet(AddOvf_U_U32(value, cur->section->m_baseRVA));
IfFailRet(AddOvf_U_U(value, imageBase));
}
IfFailRet(UnsignedFitsIn32Bits(value)); // Check for overflow
SET_UNALIGNED_VAL32(pos, value);
newStarPos = value;
fBaseReloc = true;
}
else if (curType == srRelocDir64)
{
_ASSERTE(!isPE32);
// we have a 64-bit value at pos
UINT64 UNALIGNED * p_value = (UINT64 *) pos;
targetOffset = *p_value;
if (!externalAddress)
{
// The upper bits of targetOffset must be zero
IfFailRet(UnsignedFitsIn32Bits(targetOffset));
IfFailRet(AddOvf_U_U32(targetOffset, cur->section->m_baseRVA));
IfFailRet(AddOvf_U_U(targetOffset, imageBase));
}
*p_value = targetOffset;
newStarPos = targetOffset;
fBaseReloc = true;
}
else if (curType == srRelocIA64Imm64)
{
_ASSERTE(!isPE32);
_ASSERTE((curRVA & 15) == 0); // This reloc should be 16-byte aligned
// we have a 64-bit value encoded in the instruction at pos
targetOffset = GetIA64Imm64((UINT64 *)pos);
if (!externalAddress)
{
// The upper bits of targetOffset must be zero
IfFailRet(UnsignedFitsIn32Bits(targetOffset));
IfFailRet(AddOvf_U_U32(targetOffset, cur->section->m_baseRVA));
IfFailRet(AddOvf_U_U(targetOffset, imageBase));
}
PutIA64Imm64((UINT64 *)pos, targetOffset);
newStarPos = targetOffset;
fBaseReloc = true;
}
else
{
_ASSERTE(!"Unknown Relocation type");
}
if (fBaseReloc && !noBaseBaseReloc)
{
pBaseRelocSection->AddBaseReloc(curRVA, curType);
}
#ifdef LOGGING
const char* sectionName;
if (externalAddress)
{
sectionName = "external";
}
else
{
sectionName = cur->section->m_name;
}
LOG((LF_ZAP, LL_INFO1000000,
"to %-7s+%04x, old =" FMT_ADDR "new =" FMT_ADDR "%s%s\n",
sectionName, targetOffset,
DBG_ADDR(oldStarPos), DBG_ADDR(newStarPos),
fBaseReloc ? "(BASE RELOC)" : "",
fNeedBrl ? "(BRL)" : "" ));
#endif
}
return S_OK;
}
/******************************************************************/
HRESULT PEWriter::Init(PESectionMan *pFrom, DWORD createFlags)
{
if (pFrom)
*(PESectionMan*)this = *pFrom;
else {
HRESULT hr = PESectionMan::Init();
if (FAILED(hr))
return hr;
}
time_t now;
time(&now);
#ifdef LOGGING
InitializeLogging();
#endif
// Save the timestamp so that we can give it out if someone needs
// it.
m_peFileTimeStamp = (DWORD) now;
// We must be creating either a PE32 or a PE64 file
if (createFlags & ICEE_CREATE_FILE_PE64)
{
m_ntHeaders = (IMAGE_NT_HEADERS *) new (nothrow) IMAGE_NT_HEADERS64;
m_ntHeadersSize = sizeof(IMAGE_NT_HEADERS64);
if (!m_ntHeaders) return E_OUTOFMEMORY;
memset(m_ntHeaders, 0, m_ntHeadersSize);
m_ntHeaders->OptionalHeader.Magic = VAL16(IMAGE_NT_OPTIONAL_HDR64_MAGIC);
m_ntHeaders->FileHeader.SizeOfOptionalHeader = VAL16(sizeof(IMAGE_OPTIONAL_HEADER64));
}
else
{
_ASSERTE(createFlags & ICEE_CREATE_FILE_PE32);
m_ntHeaders = (IMAGE_NT_HEADERS *) new (nothrow) IMAGE_NT_HEADERS32;
m_ntHeadersSize = sizeof(IMAGE_NT_HEADERS32);
if (!m_ntHeaders) return E_OUTOFMEMORY;
memset(m_ntHeaders, 0, m_ntHeadersSize);
m_ntHeaders->OptionalHeader.Magic = VAL16(IMAGE_NT_OPTIONAL_HDR32_MAGIC);
m_ntHeaders->FileHeader.SizeOfOptionalHeader = VAL16(sizeof(IMAGE_OPTIONAL_HEADER32));
}
// Record whether we should create the CorExeMain and CorDllMain stubs
m_createCorMainStub = ((createFlags & ICEE_CREATE_FILE_CORMAIN_STUB) != 0);
// We must have a valid target machine selected
if ((createFlags & ICEE_CREATE_MACHINE_MASK) == ICEE_CREATE_MACHINE_I386)
{
m_ntHeaders->FileHeader.Machine = VAL16(IMAGE_FILE_MACHINE_I386);
}
else if ((createFlags & ICEE_CREATE_MACHINE_MASK) == ICEE_CREATE_MACHINE_IA64)
{
m_ntHeaders->FileHeader.Machine = VAL16(IMAGE_FILE_MACHINE_IA64);
}
else if ((createFlags & ICEE_CREATE_MACHINE_MASK) == ICEE_CREATE_MACHINE_AMD64)
{
m_ntHeaders->FileHeader.Machine = VAL16(IMAGE_FILE_MACHINE_AMD64);
}
else if ((createFlags & ICEE_CREATE_MACHINE_MASK) == ICEE_CREATE_MACHINE_ARM)
{
m_ntHeaders->FileHeader.Machine = VAL16(IMAGE_FILE_MACHINE_ARMNT);
// The OS loader already knows how to initialize pure managed assemblies and we have no legacy OS
// support to worry about on ARM so don't ever create the stub for ARM binaries.
m_createCorMainStub = false;
}
else if ((createFlags & ICEE_CREATE_MACHINE_MASK) == ICEE_CREATE_MACHINE_ARM64)
{
m_ntHeaders->FileHeader.Machine = VAL16(IMAGE_FILE_MACHINE_ARM64);
// The OS loader already knows how to initialize pure managed assemblies and we have no legacy OS
// support to worry about on ARM64 so don't ever create the stub for ARM64 binaries.
m_createCorMainStub = false;
}
else
{
_ASSERTE(!"Invalid target machine");
}
cEntries = IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR + 1;
pEntries = new (nothrow) directoryEntry[cEntries];
if (pEntries == NULL) return E_OUTOFMEMORY;
memset(pEntries, 0, sizeof(*pEntries) * cEntries);
m_ntHeaders->Signature = VAL32(IMAGE_NT_SIGNATURE);
m_ntHeaders->FileHeader.TimeDateStamp = VAL32((ULONG) now);
m_ntHeaders->FileHeader.Characteristics = VAL16(0);
if (createFlags & ICEE_CREATE_FILE_STRIP_RELOCS)
{
m_ntHeaders->FileHeader.Characteristics |= VAL16(IMAGE_FILE_RELOCS_STRIPPED);
}
// Linker version should be consistent with current VC level
m_ntHeaders->OptionalHeader.MajorLinkerVersion = 11;
m_ntHeaders->OptionalHeader.MinorLinkerVersion = 0;
m_ntHeaders->OptionalHeader.SectionAlignment = VAL32(IMAGE_NT_OPTIONAL_HDR_SECTION_ALIGNMENT);
m_ntHeaders->OptionalHeader.FileAlignment = VAL32(0);
m_ntHeaders->OptionalHeader.AddressOfEntryPoint = VAL32(0);
m_ntHeaders->OptionalHeader.MajorOperatingSystemVersion = VAL16(4);
m_ntHeaders->OptionalHeader.MinorOperatingSystemVersion = VAL16(0);
m_ntHeaders->OptionalHeader.MajorImageVersion = VAL16(0);
m_ntHeaders->OptionalHeader.MinorImageVersion = VAL16(0);
m_ntHeaders->OptionalHeader.MajorSubsystemVersion = VAL16(4);
m_ntHeaders->OptionalHeader.MinorSubsystemVersion = VAL16(0);
m_ntHeaders->OptionalHeader.Win32VersionValue = VAL32(0);
m_ntHeaders->OptionalHeader.Subsystem = VAL16(0);
m_ntHeaders->OptionalHeader.DllCharacteristics = VAL16(0);
m_ntHeaders->OptionalHeader.CheckSum = VAL32(0);
setDllCharacteristics(IMAGE_DLLCHARACTERISTICS_NO_SEH |
IMAGE_DLLCHARACTERISTICS_NX_COMPAT |
IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE |
IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE);
if (isPE32())
{
IMAGE_NT_HEADERS32* p_ntHeaders32 = ntHeaders32();
p_ntHeaders32->OptionalHeader.ImageBase = VAL32(CEE_IMAGE_BASE_32);
p_ntHeaders32->OptionalHeader.SizeOfStackReserve = VAL32(0x100000);
p_ntHeaders32->OptionalHeader.SizeOfStackCommit = VAL32(0x1000);
p_ntHeaders32->OptionalHeader.SizeOfHeapReserve = VAL32(0x100000);
p_ntHeaders32->OptionalHeader.SizeOfHeapCommit = VAL32(0x1000);
p_ntHeaders32->OptionalHeader.LoaderFlags = VAL32(0);
p_ntHeaders32->OptionalHeader.NumberOfRvaAndSizes = VAL32(16);
}
else
{
IMAGE_NT_HEADERS64* p_ntHeaders64 = ntHeaders64();
// FIX what are the correct values for PE+ (64-bit) ?
p_ntHeaders64->OptionalHeader.ImageBase = VAL64(CEE_IMAGE_BASE_64);
p_ntHeaders64->OptionalHeader.SizeOfStackReserve = VAL64(0x400000);
p_ntHeaders64->OptionalHeader.SizeOfStackCommit = VAL64(0x4000);
p_ntHeaders64->OptionalHeader.SizeOfHeapReserve = VAL64(0x100000);
p_ntHeaders64->OptionalHeader.SizeOfHeapCommit = VAL64(0x2000);
p_ntHeaders64->OptionalHeader.LoaderFlags = VAL32(0);
p_ntHeaders64->OptionalHeader.NumberOfRvaAndSizes = VAL32(16);
}
m_ilRVA = (DWORD) -1;
m_dataRvaBase = 0;
m_rdataRvaBase = 0;
m_codeRvaBase = 0;
virtualPos = 0;
filePos = 0;
reloc = NULL;
strtab = NULL;
headers = NULL;
headersEnd = NULL;
m_file = INVALID_HANDLE_VALUE;
return S_OK;
}
/******************************************************************/
HRESULT PEWriter::Cleanup() {
if (isPE32())
{
delete ntHeaders32();
}
else
{
delete ntHeaders64();
}
if (headers != NULL)
delete [] headers;
if (pEntries != NULL)
delete [] pEntries;
return PESectionMan::Cleanup();
}
HRESULT PEWriter::newSection(const char* name, PESection **section,
unsigned flags, unsigned estSize,
unsigned estRelocs)
{
PEWriterSection * ret = new (nothrow) PEWriterSection(name, flags, estSize, estRelocs);
*section = ret;
TESTANDRETURNMEMORY(ret);
return S_OK;
}
ULONG PEWriter::getIlRva()
{
// assume that pe optional header is less than size of section alignment. So this
// gives out the rva for the .text section, which is merged after the .text0 section
// This is verified in debug build when actually write out the file
_ASSERTE(m_ilRVA > 0);
return m_ilRVA;
}
void PEWriter::setIlRva(ULONG offset)
{
// assume that pe optional header is less than size of section alignment. So this
// gives out the rva for the .text section, which is merged after the .text0 section
// This is verified in debug build when actually write out the file
m_ilRVA = roundUp(VAL32(m_ntHeaders->OptionalHeader.SectionAlignment) + offset, SUBSECTION_ALIGN);
}
HRESULT PEWriter::setDirectoryEntry(PEWriterSection *section, ULONG entry, ULONG size, ULONG offset)
{
if (entry >= cEntries)
{
USHORT cNewEntries = (USHORT)max((ULONG)cEntries * 2, entry + 1);
if (cNewEntries <= cEntries) return E_OUTOFMEMORY; // Integer overflow
if (cNewEntries <= entry) return E_OUTOFMEMORY; // Integer overflow
directoryEntry *pNewEntries = new (nothrow) directoryEntry [ cNewEntries ];
if (pNewEntries == NULL) return E_OUTOFMEMORY;
CopyMemory(pNewEntries, pEntries, cEntries * sizeof(*pNewEntries));
ZeroMemory(pNewEntries + cEntries, (cNewEntries - cEntries) * sizeof(*pNewEntries));
delete [] pEntries;
pEntries = pNewEntries;
cEntries = cNewEntries;
}
pEntries[entry].section = section;
pEntries[entry].offset = offset;
pEntries[entry].size = size;
return S_OK;
}
//-----------------------------------------------------------------------------
// These 2 write functions must be implemented here so that they're in the same
// .obj file as whoever creates the FILE struct. We can't pass a FILE struct
// across a dll boundary and use it.
//-----------------------------------------------------------------------------
HRESULT PEWriterSection::write(HANDLE file)
{
return m_blobFetcher.Write(file);
}
//-----------------------------------------------------------------------------
// Write out the section to the stream
//-----------------------------------------------------------------------------
HRESULT CBlobFetcher::Write(HANDLE file)
{
// Must write out each pillar (including idx = m_nIndexUsed), one after the other
unsigned idx;
for(idx = 0; idx <= m_nIndexUsed; idx ++) {
if (m_pIndex[idx].GetDataLen() > 0)
{
ULONG length = m_pIndex[idx].GetDataLen();
DWORD dwWritten = 0;
if (!WriteFile(file, m_pIndex[idx].GetRawDataStart(), length, &dwWritten, NULL))
{
return HRESULT_FROM_GetLastError();
}
_ASSERTE(dwWritten == length);
}
}
return S_OK;
}
//-----------------------------------------------------------------------------
// These 2 write functions must be implemented here so that they're in the same
// .obj file as whoever creates the FILE struct. We can't pass a FILE struct
// across a dll boundary and use it.
//-----------------------------------------------------------------------------
unsigned PEWriterSection::writeMem(void **ppMem)
{
HRESULT hr;
hr = m_blobFetcher.WriteMem(ppMem);
_ASSERTE(SUCCEEDED(hr));
return m_blobFetcher.GetDataLen();
}
//-----------------------------------------------------------------------------
// Write out the section to memory
//-----------------------------------------------------------------------------
HRESULT CBlobFetcher::WriteMem(void **ppMem)
{
char **ppDest = (char **)ppMem;
// Must write out each pillar (including idx = m_nIndexUsed), one after the other
unsigned idx;
for(idx = 0; idx <= m_nIndexUsed; idx ++) {
if (m_pIndex[idx].GetDataLen() > 0)
{
// WARNING: macro - must enclose in curly braces
COPY_AND_ADVANCE(*ppDest, m_pIndex[idx].GetRawDataStart(), m_pIndex[idx].GetDataLen());
}
}
return S_OK;
}
/******************************************************************/
//
// Intermediate table to sort to help determine section order
//
struct entry {
const char * name; // full name of the section
unsigned char nameLength; // length of the text part of the name