/
peimagelayout.cpp
1247 lines (1032 loc) · 38.2 KB
/
peimagelayout.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 "common.h"
#include "peimagelayout.h"
#include "peimagelayout.inl"
#if defined(TARGET_WINDOWS)
#include "amsi.h"
#endif
#if defined(CORECLR_EMBEDDED)
extern "C"
{
#include "pal_zlib.h"
}
#endif
#ifndef DACCESS_COMPILE
PEImageLayout* PEImageLayout::CreateFromByteArray(PEImage* pOwner, const BYTE* array, COUNT_T size)
{
STANDARD_VM_CONTRACT;
return new FlatImageLayout(pOwner, array, size);
}
#ifndef TARGET_UNIX
PEImageLayout* PEImageLayout::CreateFromHMODULE(HMODULE hModule, PEImage* pOwner)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
}
CONTRACTL_END;
PEImageLayout* pLoadLayout;
if (WszGetModuleHandle(NULL) == hModule)
{
return new LoadedImageLayout(pOwner, hModule);
}
else
{
HRESULT loadFailure = S_OK;
pLoadLayout = new LoadedImageLayout(pOwner, &loadFailure);
if (pLoadLayout == NULL)
{
loadFailure = FAILED(loadFailure) ? loadFailure : COR_E_BADIMAGEFORMAT;
EEFileLoadException::Throw(pOwner->GetPathForErrorMessages(), loadFailure);
}
}
return pLoadLayout;
}
#endif
PEImageLayout* PEImageLayout::LoadConverted(PEImage* pOwner, bool disableMapping)
{
STANDARD_VM_CONTRACT;
_ASSERTE(!pOwner->HasLoadedLayout());
ReleaseHolder<FlatImageLayout> pFlat;
if (pOwner->IsOpened())
{
pFlat = (FlatImageLayout*)pOwner->GetFlatLayout();
pFlat->AddRef();
}
else if (pOwner->IsFile())
{
pFlat = new FlatImageLayout(pOwner);
}
if (pFlat == NULL || !pFlat->CheckILOnlyFormat())
EEFileLoadException::Throw(pOwner->GetPathForErrorMessages(), COR_E_BADIMAGEFORMAT);
// TODO: enable on OSX eventually
// right now we have binaries that will trigger this in a singlefile bundle.
#ifdef TARGET_LINUX
// we should not see R2R files here on Unix.
// ConvertedImageLayout may be able to handle them, but the fact that we were unable to
// load directly implies that MAPMapPEFile could not consume what crossgen produced.
// that is suspicious, one or another might have a bug.
_ASSERTE(!pOwner->IsFile() || !pFlat->HasReadyToRunHeader() || disableMapping);
#endif
// ignore R2R if the image is not a file.
if ((pFlat->HasReadyToRunHeader() && pOwner->IsFile()) ||
pFlat->HasWriteableSections())
{
return new ConvertedImageLayout(pFlat, disableMapping);
}
// we can use flat layout for this
return pFlat.Extract();
}
PEImageLayout* PEImageLayout::Load(PEImage* pOwner, HRESULT* loadFailure)
{
STANDARD_VM_CONTRACT;
bool disableMapping = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_PELoader_DisableMapping);
if (pOwner->IsFile())
{
if (!pOwner->IsInBundle()
#if defined(TARGET_UNIX)
|| (pOwner->GetUncompressedSize() == 0)
#endif
)
{
#if defined(TARGET_UNIX)
if (!disableMapping)
#endif
{
PEImageLayoutHolder pAlloc(new LoadedImageLayout(pOwner, loadFailure));
if (pAlloc->GetBase() != NULL)
return pAlloc.Extract();
#if TARGET_WINDOWS
// For regular PE files always use OS loader on Windows.
// If a file cannot be loaded, do not try any further.
// Even if we may be able to load it, we do not want to support such files.
return NULL;
#endif
}
}
}
return PEImageLayout::LoadConverted(pOwner, disableMapping);
}
PEImageLayout* PEImageLayout::LoadFlat(PEImage* pOwner)
{
STANDARD_VM_CONTRACT;
return new FlatImageLayout(pOwner);
}
PEImageLayout *PEImageLayout::LoadNative(LPCWSTR fullPath)
{
STANDARD_VM_CONTRACT;
return new NativeImageLayout(fullPath);
}
#ifdef TARGET_UNIX
DWORD SectionCharacteristicsToPageProtection(UINT characteristics)
{
_ASSERTE((characteristics & VAL32(IMAGE_SCN_MEM_READ)) != 0);
DWORD pageProtection;
if ((characteristics & VAL32(IMAGE_SCN_MEM_WRITE)) != 0)
{
if ((characteristics & VAL32(IMAGE_SCN_MEM_EXECUTE)) != 0)
{
pageProtection = PAGE_EXECUTE_READWRITE;
}
else
{
pageProtection = PAGE_READWRITE;
}
}
else
{
if ((characteristics & VAL32(IMAGE_SCN_MEM_EXECUTE)) != 0)
{
pageProtection = PAGE_EXECUTE_READ;
}
else
{
pageProtection = PAGE_READONLY;
}
}
return pageProtection;
}
#endif // TARGET_UNIX
// IMAGE_REL_BASED_PTR is architecture specific reloc of virtual address
#ifdef TARGET_64BIT
#define IMAGE_REL_BASED_PTR IMAGE_REL_BASED_DIR64
#else // !TARGET_64BIT
#define IMAGE_REL_BASED_PTR IMAGE_REL_BASED_HIGHLOW
#endif // !TARGET_64BIT
//To force base relocation on Vista (which uses ASLR), unmask IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE
//(0x40) for OptionalHeader.DllCharacteristics
void PEImageLayout::ApplyBaseRelocations(bool relocationMustWriteCopy)
{
STANDARD_VM_CONTRACT;
SetRelocated();
//
// Note that this is not a univeral routine for applying relocations. It handles only the subset
// required by NGen images. Also, it assumes that the image format is valid.
//
SSIZE_T delta = (SIZE_T) GetBase() - (SIZE_T) GetPreferredBase();
// Nothing to do - image is loaded at preferred base
if (delta == 0)
return;
LOG((LF_LOADER, LL_INFO100, "PEImage: Applying base relocations (preferred: %x, actual: %x)\n",
GetPreferredBase(), GetBase()));
COUNT_T dirSize;
TADDR dir = GetDirectoryEntryData(IMAGE_DIRECTORY_ENTRY_BASERELOC, &dirSize);
// Minimize number of calls to VirtualProtect by keeping a whole section unprotected at a time.
BYTE * pWriteableRegion = NULL;
SIZE_T cbWriteableRegion = 0;
DWORD dwOldProtection = 0;
BYTE * pFlushRegion = NULL;
SIZE_T cbFlushRegion = 0;
// The page size of PE file relocs is always 4096 bytes
const SIZE_T cbPageSize = 4096;
COUNT_T dirPos = 0;
while (dirPos < dirSize)
{
PIMAGE_BASE_RELOCATION r = (PIMAGE_BASE_RELOCATION)(dir + dirPos);
COUNT_T fixupsSize = VAL32(r->SizeOfBlock);
USHORT *fixups = (USHORT *) (r + 1);
_ASSERTE(fixupsSize > sizeof(IMAGE_BASE_RELOCATION));
_ASSERTE((fixupsSize - sizeof(IMAGE_BASE_RELOCATION)) % 2 == 0);
COUNT_T fixupsCount = (fixupsSize - sizeof(IMAGE_BASE_RELOCATION)) / 2;
_ASSERTE((BYTE *)(fixups + fixupsCount) <= (BYTE *)(dir + dirSize));
DWORD rva = VAL32(r->VirtualAddress);
BYTE * pageAddress = (BYTE *)GetBase() + rva;
// Check whether the page is outside the unprotected region
if ((SIZE_T)(pageAddress - pWriteableRegion) >= cbWriteableRegion)
{
// Restore the protection
if (dwOldProtection != 0)
{
#if defined(__APPLE__) && defined(HOST_ARM64)
BOOL bExecRegion = (dwOldProtection & (PAGE_EXECUTE | PAGE_EXECUTE_READ |
PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY)) != 0;
// Disable writing on Apple Silicon
if (bExecRegion)
PAL_JitWriteProtect(false);
#else
if (!ClrVirtualProtect(pWriteableRegion, cbWriteableRegion,
dwOldProtection, &dwOldProtection))
ThrowLastError();
#endif // __APPLE__ && HOST_ARM64
dwOldProtection = 0;
}
USHORT fixup = VAL16(fixups[0]);
IMAGE_SECTION_HEADER *pSection = RvaToSection(rva + (fixup & 0xfff));
PREFIX_ASSUME(pSection != NULL);
pWriteableRegion = (BYTE*)GetRvaData(VAL32(pSection->VirtualAddress));
cbWriteableRegion = VAL32(pSection->SizeOfRawData);
// Unprotect the section if it is not writable
if (((pSection->Characteristics & VAL32(IMAGE_SCN_MEM_WRITE)) == 0))
{
DWORD dwNewProtection = relocationMustWriteCopy ? PAGE_WRITECOPY : PAGE_READWRITE;
#if defined(TARGET_UNIX)
if (((pSection->Characteristics & VAL32(IMAGE_SCN_MEM_EXECUTE)) != 0))
{
#if defined(__APPLE__) && defined(HOST_ARM64)
// Enable writing on Apple Silicon
PAL_JitWriteProtect(true);
#else
// On SELinux, we cannot change protection that doesn't have execute access rights
// to one that has it, so we need to set the protection to RWX instead of RW
dwNewProtection = PAGE_EXECUTE_READWRITE;
#endif
}
#endif // TARGET_UNIX
#if !(defined(__APPLE__) && defined(HOST_ARM64))
if (!ClrVirtualProtect(pWriteableRegion, cbWriteableRegion,
dwNewProtection, &dwOldProtection))
ThrowLastError();
#endif // __APPLE__ && HOST_ARM64
#ifdef TARGET_UNIX
dwOldProtection = SectionCharacteristicsToPageProtection(pSection->Characteristics);
#endif // TARGET_UNIX
}
}
BYTE* pEndAddressToFlush = NULL;
for (COUNT_T fixupIndex = 0; fixupIndex < fixupsCount; fixupIndex++)
{
USHORT fixup = VAL16(fixups[fixupIndex]);
BYTE * address = pageAddress + (fixup & 0xfff);
switch (fixup>>12)
{
case IMAGE_REL_BASED_PTR:
*(TADDR *)address += delta;
pEndAddressToFlush = max(pEndAddressToFlush, address + sizeof(TADDR));
break;
#ifdef TARGET_ARM
case IMAGE_REL_BASED_THUMB_MOV32:
PutThumb2Mov32((UINT16 *)address, GetThumb2Mov32((UINT16 *)address) + (INT32)delta);
pEndAddressToFlush = max(pEndAddressToFlush, address + 8);
break;
#endif
case IMAGE_REL_BASED_ABSOLUTE:
//no adjustment
break;
default:
_ASSERTE(!"Unhandled reloc type!");
}
}
BOOL bExecRegion = (dwOldProtection & (PAGE_EXECUTE | PAGE_EXECUTE_READ |
PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY)) != 0;
if (bExecRegion && pEndAddressToFlush != NULL)
{
// If the current page is not next to the pending region to flush, flush the current pending region and start a new one
if (pageAddress >= pFlushRegion + cbFlushRegion + cbPageSize || pageAddress < pFlushRegion)
{
if (pFlushRegion != NULL)
{
ClrFlushInstructionCache(pFlushRegion, cbFlushRegion);
}
pFlushRegion = pageAddress;
}
cbFlushRegion = pEndAddressToFlush - pFlushRegion;
}
dirPos += fixupsSize;
}
_ASSERTE(dirSize == dirPos);
if (dwOldProtection != 0)
{
#if defined(__APPLE__) && defined(HOST_ARM64)
BOOL bExecRegion = (dwOldProtection & (PAGE_EXECUTE | PAGE_EXECUTE_READ |
PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY)) != 0;
// Disable writing on Apple Silicon
if (bExecRegion)
PAL_JitWriteProtect(false);
#else
// Restore the protection
if (!ClrVirtualProtect(pWriteableRegion, cbWriteableRegion,
dwOldProtection, &dwOldProtection))
ThrowLastError();
#endif // __APPLE__ && HOST_ARM64
}
#ifdef TARGET_UNIX
PAL_LOADMarkSectionAsNotNeeded((void*)dir);
#endif // TARGET_UNIX
if (pFlushRegion != NULL)
{
ClrFlushInstructionCache(pFlushRegion, cbFlushRegion);
}
}
static SIZE_T AllocatedPart(PVOID part)
{
return (SIZE_T)part + 1;
}
static SIZE_T MappedPart(PVOID part)
{
return (SIZE_T)part;
}
static PVOID PtrFromPart(SIZE_T part)
{
return (PVOID)(part & ~1);
}
static SIZE_T IsAllocatedPart(SIZE_T part)
{
return part & 1;
}
void ConvertedImageLayout::FreeImageParts()
{
for (int i = 0; i < ConvertedImageLayout::MAX_PARTS; i++)
{
SIZE_T imagePart = this->m_imageParts[i];
if (imagePart == 0)
break;
// memory projected into placeholders is page-aligned.
// we are using "+1" to distinguish committed memory from mapped views, so that we know how to free them
if (IsAllocatedPart(imagePart))
{
ClrVirtualFree(PtrFromPart(imagePart), 0, MEM_RELEASE);
}
else
{
CLRUnmapViewOfFile(PtrFromPart(imagePart));
}
this->m_imageParts[i] = NULL;
}
}
ConvertedImageLayout::ConvertedImageLayout(FlatImageLayout* source, bool disableMapping)
{
CONTRACTL
{
CONSTRUCTOR_CHECK;
STANDARD_VM_CHECK;
}
CONTRACTL_END;
_ASSERTE(source->CheckILOnlyFormat());
m_pOwner = source->m_pOwner;
m_pExceptionDir = NULL;
memset(m_imageParts, 0, sizeof(m_imageParts));
bool relocationMustWriteCopy = false;
void* loadedImage = NULL;
LOG((LF_LOADER, LL_INFO100, "PEImage: Opening manually mapped stream\n"));
#ifdef TARGET_WINDOWS
if (!disableMapping)
{
loadedImage = source->LoadImageByMappingParts(this->m_imageParts);
if (loadedImage == NULL)
{
FreeImageParts();
}
else
{
relocationMustWriteCopy = true;
}
}
#endif //TARGET_WINDOWS
if (loadedImage == NULL)
{
loadedImage = source->LoadImageByCopyingParts(this->m_imageParts);
}
IfFailThrow(Init(loadedImage));
if (m_pOwner->IsFile() && IsNativeMachineFormat() && g_fAllowNativeImages)
{
// Do base relocation and exception hookup, if necessary.
// otherwise R2R will be disabled for this image.
ApplyBaseRelocations(relocationMustWriteCopy);
// Check if there is a static function table and install it. (Windows only, except x86)
#if !defined(TARGET_UNIX) && !defined(TARGET_X86)
COUNT_T cbSize = 0;
PT_RUNTIME_FUNCTION pExceptionDir = (PT_RUNTIME_FUNCTION)GetDirectoryEntryData(IMAGE_DIRECTORY_ENTRY_EXCEPTION, &cbSize);
DWORD tableSize = cbSize / sizeof(T_RUNTIME_FUNCTION);
if (pExceptionDir != NULL)
{
// the only native code that we expect here is from R2R images
_ASSERTE(HasReadyToRunHeader());
if (!RtlAddFunctionTable(pExceptionDir, tableSize, (DWORD64)this->GetBase()))
ThrowLastError();
m_pExceptionDir = pExceptionDir;
}
#endif //TARGET_X86
}
}
ConvertedImageLayout::~ConvertedImageLayout()
{
CONTRACTL
{
NOTHROW;
GC_TRIGGERS;
MODE_ANY;
}
CONTRACTL_END;
FreeImageParts();
#if !defined(TARGET_UNIX) && !defined(TARGET_X86)
if (m_pExceptionDir)
{
RtlDeleteFunctionTable(m_pExceptionDir);
}
#endif
}
LoadedImageLayout::LoadedImageLayout(PEImage* pOwner, HRESULT* loadFailure)
{
CONTRACTL
{
CONSTRUCTOR_CHECK;
STANDARD_VM_CHECK;
PRECONDITION(CheckPointer(pOwner));
}
CONTRACTL_END;
m_pOwner = pOwner;
_ASSERTE(pOwner->GetUncompressedSize() == 0);
#ifndef TARGET_UNIX
_ASSERTE(!pOwner->IsInBundle());
m_Module = CLRLoadLibraryEx(pOwner->GetPath(), NULL, GetLoadWithAlteredSearchPathFlag());
if (m_Module == NULL)
{
// Fetch the HRESULT upfront before anybody gets a chance to corrupt it
*loadFailure = HRESULT_FROM_GetLastError();
return;
}
IfFailThrow(Init(m_Module, true));
#ifdef LOGGING
SString ownerPath{ pOwner->GetPath() };
LOG((LF_LOADER, LL_INFO1000, "PEImage: Opened HMODULE %s\n", ownerPath.GetUTF8()));
#endif // LOGGING
#else
HANDLE hFile = pOwner->GetFileHandle();
INT64 offset = pOwner->GetOffset();
m_LoadedFile = PAL_LOADLoadPEFile(hFile, offset);
if (m_LoadedFile == NULL)
{
// Fetch the HRESULT upfront before anybody gets a chance to corrupt it
*loadFailure = HRESULT_FROM_GetLastError();
return;
}
#ifdef LOGGING
SString ownerPath{ pOwner->GetPath() };
LOG((LF_LOADER, LL_INFO1000, "PEImage: image %s (hFile %p) mapped @ %p\n",
ownerPath.GetUTF8(), hFile, (void*)m_LoadedFile));
#endif // LOGGING
IfFailThrow(Init((void*)m_LoadedFile));
if (!HasCorHeader())
{
*loadFailure = COR_E_BADIMAGEFORMAT;
Reset();
return;
}
if (HasReadyToRunHeader() && g_fAllowNativeImages)
{
//Do base relocation for PE, if necessary.
if (!IsNativeMachineFormat())
{
*loadFailure = COR_E_BADIMAGEFORMAT;
Reset();
return;
}
// Unix specifies write sharing at map time (i.e. MAP_PRIVATE implies writecopy).
ApplyBaseRelocations(/* relocationMustWriteCopy*/ false);
SetRelocated();
}
#endif
}
#if !defined(TARGET_UNIX)
LoadedImageLayout::LoadedImageLayout(PEImage* pOwner, HMODULE hModule)
{
m_pOwner = pOwner;
PEDecoder::Init((void*)hModule, /* relocated */ true);
}
#endif // !TARGET_UNIX
LoadedImageLayout::~LoadedImageLayout()
{
CONTRACTL
{
NOTHROW;
GC_TRIGGERS;
MODE_ANY;
}
CONTRACTL_END;
#if !defined(TARGET_UNIX)
if (m_Module)
CLRFreeLibrary(m_Module);
#endif // !TARGET_UNIX
}
FlatImageLayout::FlatImageLayout(PEImage* pOwner)
{
CONTRACTL
{
CONSTRUCTOR_CHECK;
STANDARD_VM_CHECK;
PRECONDITION(CheckPointer(pOwner));
}
CONTRACTL_END;
m_pOwner=pOwner;
HANDLE hFile = pOwner->GetFileHandle();
INT64 offset = pOwner->GetOffset();
INT64 size = pOwner->GetSize();
#ifdef LOGGING
SString ownerPath{ pOwner->GetPath() };
LOG((LF_LOADER, LL_INFO100, "PEImage: Opening flat %s\n", ownerPath.GetUTF8()));
#endif // LOGGING
// If a size is not specified, load the whole file
if (size == 0)
{
size = SafeGetFileSize(hFile, NULL);
if (size == 0xffffffff && GetLastError() != NOERROR)
{
ThrowLastError();
}
}
LPVOID addr = 0;
// It's okay if resource files are length zero
if (size > 0)
{
INT64 uncompressedSize = pOwner->GetUncompressedSize();
DWORD mapAccess = PAGE_READONLY;
#if !defined(TARGET_UNIX)
// to map sections into executable views on Windows the mapping must have EXECUTE permissions
if (uncompressedSize == 0)
{
mapAccess = PAGE_EXECUTE_READ;
}
#endif
m_FileMap.Assign(WszCreateFileMapping(hFile, NULL, mapAccess, 0, 0, NULL));
if (m_FileMap == NULL)
ThrowLastError();
// - Windows - MapViewOfFileEx requires offset to be allocation granularity aligned (typically 64KB)
// - Linux/OSX - mmap requires offset to be page aligned (PAL sets allocation granularity to page size)
UINT32 alignment = g_SystemInfo.dwAllocationGranularity;
UINT64 mapBegin = AlignDown((UINT64)offset, alignment);
UINT64 mapSize = ((UINT64)(offset + size)) - mapBegin;
_ASSERTE((offset - mapBegin) < alignment);
_ASSERTE((offset - mapBegin) < mapSize);
_ASSERTE(mapSize >= (UINT64)size);
LPVOID view = CLRMapViewOfFile(m_FileMap, FILE_MAP_READ, mapBegin >> 32, (DWORD)mapBegin, (DWORD)mapSize);
if (view == NULL)
ThrowLastError();
m_FileView.Assign(view);
addr = (LPVOID)((size_t)view + offset - mapBegin);
if (uncompressedSize > 0)
{
#if defined(CORECLR_EMBEDDED)
// The mapping we have just created refers to the region in the bundle that contains compressed data.
// We will create another anonymous memory-only mapping and uncompress file there.
// The flat image will refer to the anonymous mapping instead and we will release the original mapping.
HandleHolder anonMap = WszCreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, uncompressedSize >> 32, (DWORD)uncompressedSize, NULL);
if (anonMap == NULL)
ThrowLastError();
LPVOID anonView = CLRMapViewOfFile(anonMap, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0);
if (anonView == NULL)
ThrowLastError();
//NB: PE cannot be larger than 4GB and we are decompressing a managed assembly, which is a PE image,
// thus converting sizes to uint32 is ok.
PAL_ZStream zStream;
zStream.nextIn = (uint8_t*)addr;
zStream.availIn = (uint32_t)size;
zStream.nextOut = (uint8_t*)anonView;
zStream.availOut = (uint32_t)uncompressedSize;
// we match the compression side here. 15 is the window sise, negative means no zlib header.
const int Deflate_DefaultWindowBits = -15;
if (CompressionNative_InflateInit2_(&zStream, Deflate_DefaultWindowBits) != PAL_Z_OK)
ThrowHR(COR_E_BADIMAGEFORMAT);
int ret = CompressionNative_Inflate(&zStream, PAL_Z_NOFLUSH);
// decompression should have consumed the entire input
// and the entire output budgets
if ((ret < 0) ||
!(zStream.availIn == 0 && zStream.availOut == 0))
{
CompressionNative_InflateEnd(&zStream);
ThrowHR(COR_E_BADIMAGEFORMAT);
}
CompressionNative_InflateEnd(&zStream);
addr = anonView;
size = uncompressedSize;
// Replace file handles with the handles to anonymous map. This will release the handles to the original view and map.
m_FileView.Assign(anonView);
m_FileMap.Assign(anonMap);
#else
_ASSERTE(!"Failure extracting contents of the application bundle. Compressed files used with a standalone (not singlefile) apphost.");
ThrowHR(E_FAIL); // we don't have any indication of what kind of failure. Possibly a corrupt image.
#endif
}
}
Init(addr, (COUNT_T)size);
}
FlatImageLayout::FlatImageLayout(PEImage* pOwner, const BYTE* array, COUNT_T size)
{
CONTRACTL
{
CONSTRUCTOR_CHECK;
THROWS;
GC_TRIGGERS;
MODE_ANY;
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACTL_END;
m_pOwner = pOwner;
if (size == 0)
{
Init((void*)array, size);
}
else
{
DWORD mapAccess = PAGE_READWRITE;
#if defined(TARGET_WINDOWS)
if (Amsi::IsBlockedByAmsiScan((void*)array, size))
{
// This is required to throw a BadImageFormatException for compatibility, but
// use the message from ERROR_VIRUS_INFECTED to give better insight on what's wrong
SString virusHrString;
GetHRMsg(HRESULT_FROM_WIN32(ERROR_VIRUS_INFECTED), virusHrString);
ThrowHR(COR_E_BADIMAGEFORMAT, virusHrString);
}
// to map sections into executable views on Windows the mapping must have EXECUTE permissions
mapAccess = PAGE_EXECUTE_READWRITE;
#endif // defined(TARGET_WINDOWS)
m_FileMap.Assign(WszCreateFileMapping(INVALID_HANDLE_VALUE, NULL, mapAccess, 0, size, NULL));
if (m_FileMap == NULL)
ThrowLastError();
m_FileView.Assign(CLRMapViewOfFile(m_FileMap, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0));
if (m_FileView == NULL)
ThrowLastError();
memcpy(m_FileView, array, size);
Init((void*)m_FileView, size);
}
}
void* FlatImageLayout::LoadImageByCopyingParts(SIZE_T* m_imageParts) const
{
CONTRACTL
{
INSTANCE_CHECK;
THROWS;
GC_NOTRIGGER;
}
CONTRACTL_END;
void* preferredBase = NULL;
#ifdef FEATURE_ENABLE_NO_ADDRESS_SPACE_RANDOMIZATION
if (g_useDefaultBaseAddr)
{
preferredBase = (void*)GetPreferredBase();
}
#endif // FEATURE_ENABLE_NO_ADDRESS_SPACE_RANDOMIZATION
DWORD allocationType = MEM_RESERVE | MEM_COMMIT;
#ifdef HOST_UNIX
// Tell PAL to use the executable memory allocator to satisfy this request for virtual memory.
// This is required on MacOS and otherwise will allow us to place native R2R code close to the
// coreclr library and thus improve performance by avoiding jump stubs in managed code.
allocationType |= MEM_RESERVE_EXECUTABLE;
#endif
COUNT_T allocSize = ALIGN_UP(this->GetVirtualSize(), g_SystemInfo.dwAllocationGranularity);
LPVOID base = ClrVirtualAlloc(preferredBase, allocSize, allocationType, PAGE_READWRITE);
if (base == NULL && preferredBase != NULL)
base = ClrVirtualAlloc(NULL, allocSize, allocationType, PAGE_READWRITE);
if (base == NULL)
ThrowLastError();
// when loading by copying we have only one part to free.
m_imageParts[0] = AllocatedPart(base);
// We're going to copy everything first, and write protect what we need to later.
// First, copy headers
CopyMemory(base, (void*)GetBase(), VAL32(FindNTHeaders()->OptionalHeader.SizeOfHeaders));
// Now, copy all sections to appropriate virtual address
IMAGE_SECTION_HEADER* sectionStart = IMAGE_FIRST_SECTION(FindNTHeaders());
IMAGE_SECTION_HEADER* sectionEnd = sectionStart + VAL16(FindNTHeaders()->FileHeader.NumberOfSections);
IMAGE_SECTION_HEADER* section = sectionStart;
while (section < sectionEnd)
{
// Raw data may be less than section size if tail is zero, but may be more since VirtualSize is
// not padded.
DWORD size = min(VAL32(section->SizeOfRawData), VAL32(section->Misc.VirtualSize));
CopyMemory((BYTE*)base + VAL32(section->VirtualAddress), (BYTE*)GetBase() + VAL32(section->PointerToRawData), size);
// Note that our memory is zeroed already, so no need to initialize any tail.
section++;
}
// Apply write protection to copied headers
DWORD oldProtection;
if (!ClrVirtualProtect((void*)base, VAL32(FindNTHeaders()->OptionalHeader.SizeOfHeaders),
PAGE_READONLY, &oldProtection))
ThrowLastError();
// Finally, apply proper protection to copied sections
for (section = sectionStart; section < sectionEnd; section++)
{
DWORD executableProtection = PAGE_EXECUTE_READ;
#if defined(__APPLE__) && defined(HOST_ARM64)
executableProtection = PAGE_EXECUTE_READWRITE;
#endif
// Add appropriate page protection.
DWORD newProtection = section->Characteristics & IMAGE_SCN_MEM_EXECUTE ?
executableProtection :
section->Characteristics & IMAGE_SCN_MEM_WRITE ?
PAGE_READWRITE :
PAGE_READONLY;
if (!ClrVirtualProtect((void*)((BYTE*)base + VAL32(section->VirtualAddress)),
VAL32(section->Misc.VirtualSize),
newProtection, &oldProtection))
{
ThrowLastError();
}
}
return base;
}
#ifdef TARGET_WINDOWS
// VirtualAlloc2
typedef PVOID(WINAPI* VirtualAlloc2Fn)(
HANDLE Process,
PVOID BaseAddress,
SIZE_T Size,
ULONG AllocationType,
ULONG PageProtection,
MEM_EXTENDED_PARAMETER* ExtendedParameters,
ULONG ParameterCount);
VirtualAlloc2Fn pVirtualAlloc2 = NULL;
// MapViewOfFile3
typedef PVOID(WINAPI* MapViewOfFile3Fn)(
HANDLE FileMapping,
HANDLE Process,
PVOID BaseAddress,
ULONG64 Offset,
SIZE_T ViewSize,
ULONG AllocationType,
ULONG PageProtection,
MEM_EXTENDED_PARAMETER* ExtendedParameters,
ULONG ParameterCount);
MapViewOfFile3Fn pMapViewOfFile3 = NULL;
static bool HavePlaceholderAPI()
{
const MapViewOfFile3Fn INVALID_ADDRESS_SENTINEL = (MapViewOfFile3Fn)1;
if (pMapViewOfFile3 == INVALID_ADDRESS_SENTINEL)
{
return false;
}
if (pMapViewOfFile3 == NULL)
{
HMODULE hm = WszLoadLibrary(W("kernelbase.dll"), NULL, LOAD_LIBRARY_SEARCH_SYSTEM32);
if (hm != NULL)
{
pVirtualAlloc2 = (VirtualAlloc2Fn)GetProcAddress(hm, "VirtualAlloc2");
pMapViewOfFile3 = (MapViewOfFile3Fn)GetProcAddress(hm, "MapViewOfFile3");
FreeLibrary(hm);
}
if (pMapViewOfFile3 == NULL || pVirtualAlloc2 == NULL)
{
pMapViewOfFile3 = INVALID_ADDRESS_SENTINEL;
return false;
}
}
return true;
}
static PVOID AllocPlaceholder(PVOID BaseAddress, SIZE_T Size)
{
return pVirtualAlloc2(
::GetCurrentProcess(),
BaseAddress,
Size,
MEM_RESERVE | MEM_RESERVE_PLACEHOLDER,
PAGE_NOACCESS,
NULL,
0);
}
static PVOID MapIntoPlaceholder(
HANDLE FileMapping,
ULONG64 FromOffset,
PVOID ToAddress,
SIZE_T ViewSize,
ULONG PageProtection
)
{
return pMapViewOfFile3(FileMapping, ::GetCurrentProcess(), ToAddress, FromOffset, ViewSize, MEM_REPLACE_PLACEHOLDER, PageProtection, NULL, 0);
}
static PVOID CommitIntoPlaceholder(
PVOID ToAddress,
SIZE_T Size,
ULONG PageProtection
)
{
return pVirtualAlloc2(::GetCurrentProcess(), ToAddress, Size, MEM_COMMIT | MEM_RESERVE | MEM_REPLACE_PLACEHOLDER, PageProtection, NULL, 0);
}
static PVOID SplitPlaceholder(
PVOID& placeholderStart,
PVOID placeholderEnd,
SIZE_T size
)
{
_ASSERTE((char*)placeholderStart + size <= placeholderEnd);
if ((char*)placeholderStart + size < placeholderEnd)
{
if (!VirtualFree(placeholderStart, size, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER))
{
return NULL;
}
}
PVOID result = placeholderStart;
placeholderStart = (char*)placeholderStart + size;
return result;
}
static SIZE_T OffsetWithinPage(SIZE_T addr)
{
return addr & (GetOsPageSize() - 1);
}
static SIZE_T RoundToPage(SIZE_T size, SIZE_T offset)
{
size_t result = size + OffsetWithinPage(offset);
_ASSERTE(result >= size);
return ROUND_UP_TO_PAGE(result);
}
void* FlatImageLayout::LoadImageByMappingParts(SIZE_T* m_imageParts) const
{
CONTRACTL
{