forked from https-github-com-Surachai-kent/runtime
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathwriter.cpp
More file actions
1594 lines (1439 loc) · 60.2 KB
/
writer.cpp
File metadata and controls
1594 lines (1439 loc) · 60.2 KB
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.
//
// writer.cpp
//
#include "ilasmpch.h"
#include "assembler.h"
#include "ceefilegenwriter.h"
#ifndef _MSC_VER
//cloned definition from ntimage.h that is removed for non MSVC builds
typedef VOID
(NTAPI *PIMAGE_TLS_CALLBACK) (
PVOID DllHandle,
ULONG Reason,
PVOID Reserved
);
#endif //_MSC_VER
HRESULT Assembler::InitMetaData()
{
HRESULT hr = E_FAIL;
if(m_fInitialisedMetaData) return S_OK;
if(bClock) bClock->cMDInitBegin = GetTickCount();
hr = MetaDataGetDispenser(CLSID_CorMetaDataDispenser,
IID_IMetaDataDispenserEx2, (void **)&m_pDisp);
if (FAILED(hr))
goto exit;
hr = m_pDisp->DefineScope(CLSID_CorMetaDataRuntime, 0, IID_IMetaDataEmit3,
(IUnknown **)&m_pEmitter);
if (FAILED(hr))
goto exit;
m_pManifest->SetEmitter(m_pEmitter);
if(FAILED(hr = m_pEmitter->QueryInterface(IID_IMetaDataImport2, (void**)&m_pImporter)))
goto exit;
if (m_fGeneratePDB)
{
m_pPortablePdbWriter = new PortablePdbWriter();
if (FAILED(hr = m_pPortablePdbWriter->Init(m_pDisp))) goto exit;
}
//m_Parser = new AsmParse(m_pEmitter);
m_fInitialisedMetaData = TRUE;
hr = S_OK;
exit:
if(bClock) bClock->cMDInitEnd = GetTickCount();
return hr;
}
/*********************************************************************************/
/* if we have any Thread local store data, make the TLS directory record for it */
HRESULT Assembler::CreateTLSDirectory() {
ULONG tlsEnd;
HRESULT hr;
if (FAILED(hr=m_pCeeFileGen->GetSectionDataLen(m_pTLSSection, &tlsEnd))) return(hr);
if (tlsEnd == 0) // No TLS data, we are done
return(S_OK);
// place to put the TLS directory
HCEESECTION tlsDirSec = m_pGlobalDataSection;
if(m_dwCeeFileFlags & ICEE_CREATE_FILE_PE32)
{
DWORD sizeofptr = (DWORD)sizeof(DWORD);
DWORD sizeofdir = (DWORD)sizeof(IMAGE_TLS_DIRECTORY32);
DWORD offsetofStartAddressOfRawData = (DWORD)offsetof(IMAGE_TLS_DIRECTORY32, StartAddressOfRawData);
DWORD offsetofEndAddressOfRawData = (DWORD)offsetof(IMAGE_TLS_DIRECTORY32, EndAddressOfRawData);
DWORD offsetofAddressOfIndex = (DWORD)offsetof(IMAGE_TLS_DIRECTORY32, AddressOfIndex);
DWORD offsetofAddressOfCallBacks = (DWORD)offsetof(IMAGE_TLS_DIRECTORY32, AddressOfCallBacks);
// Get memory for the TLS directory block,as well as a spot for callback chain
IMAGE_TLS_DIRECTORY32* tlsDir;
if(FAILED(hr=m_pCeeFileGen->GetSectionBlock(tlsDirSec, sizeofdir + sizeofptr, sizeofptr, (void**) &tlsDir))) return(hr);
DWORD* callBackChain = (DWORD*) &tlsDir[1];
*callBackChain = 0;
// Find out where the tls directory will end up
ULONG tlsDirOffset;
if(FAILED(hr=m_pCeeFileGen->GetSectionDataLen(tlsDirSec, &tlsDirOffset))) return(hr);
tlsDirOffset -= (sizeofdir + sizeofptr);
// Set the start of the TLS data (offset 0 of hte TLS section)
tlsDir->StartAddressOfRawData = 0;
if(FAILED(hr=m_pCeeFileGen->AddSectionReloc(tlsDirSec, tlsDirOffset + offsetofStartAddressOfRawData, m_pTLSSection, srRelocHighLow))) return(hr);
// Set the end of the TLS data
tlsDir->EndAddressOfRawData = VALPTR(tlsEnd);
if(FAILED(hr=m_pCeeFileGen->AddSectionReloc(tlsDirSec, tlsDirOffset + offsetofEndAddressOfRawData, m_pTLSSection, srRelocHighLow))) return(hr);
// Allocate space for the OS to put the TLS index for this PE file (needs to be Read/Write?)
DWORD* tlsIndex;
if(FAILED(hr=m_pCeeFileGen->GetSectionBlock(m_pGlobalDataSection, sizeof(DWORD), sizeof(DWORD), (void**) &tlsIndex))) return(hr);
*tlsIndex = 0xCCCCCCCC; // Does't really matter, the OS will fill it in
// Find out where tlsIndex index is
ULONG tlsIndexOffset;
if(FAILED(hr=m_pCeeFileGen->GetSectionDataLen(tlsDirSec, &tlsIndexOffset))) return(hr);
tlsIndexOffset -= sizeof(DWORD);
// Set the address of the TLS index
tlsDir->AddressOfIndex = VALPTR(tlsIndexOffset);
if(FAILED(hr=m_pCeeFileGen->AddSectionReloc(tlsDirSec, tlsDirOffset + offsetofAddressOfIndex, m_pGlobalDataSection, srRelocHighLow))) return(hr);
// Set addres of callbacks chain
tlsDir->AddressOfCallBacks = VALPTR((DWORD)(DWORD_PTR)(PIMAGE_TLS_CALLBACK*)(size_t)(tlsDirOffset + sizeofdir));
if(FAILED(hr=m_pCeeFileGen->AddSectionReloc(tlsDirSec, tlsDirOffset + offsetofAddressOfCallBacks, tlsDirSec, srRelocHighLow))) return(hr);
// Set the other fields.
tlsDir->SizeOfZeroFill = 0;
tlsDir->Characteristics = 0;
hr=m_pCeeFileGen->SetDirectoryEntry (m_pCeeFile, tlsDirSec, IMAGE_DIRECTORY_ENTRY_TLS,
sizeofdir, tlsDirOffset);
if (m_dwCeeFileFlags & ICEE_CREATE_MACHINE_I386)
COR_SET_32BIT_REQUIRED(m_dwComImageFlags);
}
else
{
DWORD sizeofptr = (DWORD)sizeof(__int64);
DWORD sizeofdir = (DWORD)sizeof(IMAGE_TLS_DIRECTORY64);
DWORD offsetofStartAddressOfRawData = (DWORD)offsetof(IMAGE_TLS_DIRECTORY64, StartAddressOfRawData);
DWORD offsetofEndAddressOfRawData = (DWORD)offsetof(IMAGE_TLS_DIRECTORY64, EndAddressOfRawData);
DWORD offsetofAddressOfIndex = (DWORD)offsetof(IMAGE_TLS_DIRECTORY64, AddressOfIndex);
DWORD offsetofAddressOfCallBacks = (DWORD)offsetof(IMAGE_TLS_DIRECTORY64, AddressOfCallBacks);
// Get memory for the TLS directory block,as well as a spot for callback chain
IMAGE_TLS_DIRECTORY64* tlsDir;
if(FAILED(hr=m_pCeeFileGen->GetSectionBlock(tlsDirSec, sizeofdir + sizeofptr, sizeofptr, (void**) &tlsDir))) return(hr);
__int64* callBackChain = (__int64*) &tlsDir[1];
*callBackChain = 0;
// Find out where the tls directory will end up
ULONG tlsDirOffset;
if(FAILED(hr=m_pCeeFileGen->GetSectionDataLen(tlsDirSec, &tlsDirOffset))) return(hr);
tlsDirOffset -= (sizeofdir + sizeofptr);
// Set the start of the TLS data (offset 0 of hte TLS section)
tlsDir->StartAddressOfRawData = 0;
if(FAILED(hr=m_pCeeFileGen->AddSectionReloc(tlsDirSec, tlsDirOffset + offsetofStartAddressOfRawData, m_pTLSSection, srRelocHighLow))) return(hr);
// Set the end of the TLS data
tlsDir->EndAddressOfRawData = VALPTR(tlsEnd);
if(FAILED(hr=m_pCeeFileGen->AddSectionReloc(tlsDirSec, tlsDirOffset + offsetofEndAddressOfRawData, m_pTLSSection, srRelocHighLow))) return(hr);
// Allocate space for the OS to put the TLS index for this PE file (needs to be Read/Write?)
DWORD* tlsIndex;
if(FAILED(hr=m_pCeeFileGen->GetSectionBlock(m_pGlobalDataSection, sizeof(DWORD), sizeof(DWORD), (void**) &tlsIndex))) return(hr);
*tlsIndex = 0xCCCCCCCC; // Does't really matter, the OS will fill it in
// Find out where tlsIndex index is
ULONG tlsIndexOffset;
if(FAILED(hr=m_pCeeFileGen->GetSectionDataLen(tlsDirSec, &tlsIndexOffset))) return(hr);
tlsIndexOffset -= sizeof(DWORD);
// Set the address of the TLS index
tlsDir->AddressOfIndex = VALPTR(tlsIndexOffset);
if(FAILED(hr=m_pCeeFileGen->AddSectionReloc(tlsDirSec, tlsDirOffset + offsetofAddressOfIndex, m_pGlobalDataSection, srRelocHighLow))) return(hr);
// Set address of callbacks chain
tlsDir->AddressOfCallBacks = VALPTR((DWORD)(DWORD_PTR)(PIMAGE_TLS_CALLBACK*)(size_t)(tlsDirOffset + sizeofdir));
if(FAILED(hr=m_pCeeFileGen->AddSectionReloc(tlsDirSec, tlsDirOffset + offsetofAddressOfCallBacks, tlsDirSec, srRelocHighLow))) return(hr);
// Set the other fields.
tlsDir->SizeOfZeroFill = 0;
tlsDir->Characteristics = 0;
hr=m_pCeeFileGen->SetDirectoryEntry (m_pCeeFile, tlsDirSec, IMAGE_DIRECTORY_ENTRY_TLS,
sizeofdir, tlsDirOffset);
}
if(m_dwCeeFileFlags & ICEE_CREATE_FILE_STRIP_RELOCS)
{
report->error("Base relocations are emitted, while /STRIPRELOC option has been specified");
}
m_dwComImageFlags &= ~COMIMAGE_FLAGS_ILONLY;
return(hr);
}
HRESULT Assembler::CreateDebugDirectory()
{
HRESULT hr = S_OK;
HCEESECTION sec = m_pILSection;
BYTE *de;
ULONG deOffset;
// Only emit this if we're also emitting debug info.
if (!m_fGeneratePDB)
return S_OK;
IMAGE_DEBUG_DIRECTORY debugDirIDD;
struct Param
{
DWORD debugDirDataSize;
BYTE *debugDirData;
} param;
param.debugDirData = NULL;
// get module ID
DWORD rsds = VAL32(0x53445352);
DWORD pdbAge = VAL32(0x1);
GUID pdbGuid = *m_pPortablePdbWriter->GetGuid();
SwapGuid(&pdbGuid);
DWORD len = sizeof(rsds) + sizeof(GUID) + sizeof(pdbAge) + (DWORD)strlen(m_szPdbFileName) + 1;
BYTE* dbgDirData = new BYTE[len];
DWORD offset = 0;
memcpy_s(dbgDirData + offset, len, &rsds, sizeof(rsds)); // RSDS
offset += sizeof(rsds);
memcpy_s(dbgDirData + offset, len, &pdbGuid, sizeof(GUID)); // PDB GUID
offset += sizeof(GUID);
memcpy_s(dbgDirData + offset, len, &pdbAge, sizeof(pdbAge)); // PDB AGE
offset += sizeof(pdbAge);
memcpy_s(dbgDirData + offset, len, m_szPdbFileName, strlen(m_szPdbFileName) + 1); // PDB PATH
debugDirIDD.Characteristics = 0;
debugDirIDD.TimeDateStamp = VAL32(m_pPortablePdbWriter->GetTimestamp());
debugDirIDD.MajorVersion = VAL16(0x100);
debugDirIDD.MinorVersion = VAL16(0x504d);
debugDirIDD.Type = VAL32(IMAGE_DEBUG_TYPE_CODEVIEW);
debugDirIDD.SizeOfData = VAL32(len);
debugDirIDD.AddressOfRawData = 0; // will be updated bellow
debugDirIDD.PointerToRawData = 0; // will be updated bellow
param.debugDirDataSize = len;
// Make some room for the data.
PAL_TRY(Param*, pParam, ¶m) {
pParam->debugDirData = new BYTE[pParam->debugDirDataSize];
} PAL_EXCEPT(EXCEPTION_EXECUTE_HANDLER) {
hr = E_FAIL;
} PAL_ENDTRY
if (FAILED(hr)) return hr;
param.debugDirData = dbgDirData;
// Grab memory in the section for our stuff.
// Note that UpdateResource doesn't work correctly if the debug directory is
// in the data section. So instead we put it in the text section (same as
// cs compiler).
if (FAILED(hr = m_pCeeFileGen->GetSectionBlock(sec,
sizeof(debugDirIDD) +
param.debugDirDataSize,
4,
(void**) &de)))
goto ErrExit;
// Where did we get that memory?
if (FAILED(hr = m_pCeeFileGen->GetSectionDataLen(sec,
&deOffset)))
goto ErrExit;
deOffset -= (sizeof(debugDirIDD) + param.debugDirDataSize);
// Setup a reloc so that the address of the raw
// data is setup correctly.
debugDirIDD.PointerToRawData = VAL32(deOffset + sizeof(debugDirIDD));
if (FAILED(hr = m_pCeeFileGen->AddSectionReloc(
sec,
deOffset +
offsetof(IMAGE_DEBUG_DIRECTORY,
PointerToRawData),
sec, srRelocFilePos)))
goto ErrExit;
debugDirIDD.AddressOfRawData = VAL32(deOffset + sizeof(debugDirIDD));
if (FAILED(hr = m_pCeeFileGen->AddSectionReloc(
sec,
deOffset +
offsetof(IMAGE_DEBUG_DIRECTORY,
AddressOfRawData),
sec, srRelocAbsolute)))
goto ErrExit;
// Emit the directory entry.
if (FAILED(hr = m_pCeeFileGen->SetDirectoryEntry(m_pCeeFile,
sec,
IMAGE_DIRECTORY_ENTRY_DEBUG,
sizeof(debugDirIDD),
deOffset)))
goto ErrExit;
// Copy the debug directory into the section.
memcpy(de, &debugDirIDD, sizeof(debugDirIDD));
memcpy(de + sizeof(debugDirIDD), param.debugDirData,
param.debugDirDataSize);
if (param.debugDirData)
{
delete [] param.debugDirData;
}
return S_OK;
ErrExit:
if (param.debugDirData)
{
delete [] param.debugDirData;
}
return hr;
}
//#ifdef EXPORT_DIR_ENABLED
HRESULT Assembler::CreateExportDirectory()
{
HRESULT hr = S_OK;
DWORD Nentries = m_EATList.COUNT();
if(Nentries == 0) return S_OK;
IMAGE_EXPORT_DIRECTORY exportDirIDD;
DWORD exportDirDataSize;
EATEntry *pEATE;
unsigned i, L, ordBase = 0xFFFFFFFF, Ldllname;
// get the DLL name from output file name
char* pszDllName;
Ldllname = (unsigned)wcslen(m_wzOutputFileName)*3+3;
NewArrayHolder<char> szOutputFileName(new char[Ldllname]);
memset(szOutputFileName,0,wcslen(m_wzOutputFileName)*3+3);
WszWideCharToMultiByte(CP_ACP,0,m_wzOutputFileName,-1,szOutputFileName,Ldllname,NULL,NULL);
pszDllName = strrchr(szOutputFileName,DIRECTORY_SEPARATOR_CHAR_A);
#ifdef TARGET_WINDOWS
if(pszDllName == NULL) pszDllName = strrchr(szOutputFileName,':');
#endif
if(pszDllName == NULL) pszDllName = szOutputFileName;
Ldllname = (unsigned)strlen(pszDllName)+1;
// Allocate buffer for tables
for(i = 0, L=0; i < Nentries; i++) L += 1+(unsigned)strlen(m_EATList.PEEK(i)->szAlias);
exportDirDataSize = Nentries*5*sizeof(WORD) + L + Ldllname;
NewArrayHolder<BYTE> exportDirData(new BYTE[exportDirDataSize]);
memset(exportDirData,0,exportDirDataSize);
// Export address table
DWORD* pEAT = (DWORD*)(BYTE*)exportDirData;
// Name pointer table
DWORD* pNPT = pEAT + Nentries;
// Ordinal table
WORD* pOT = (WORD*)(pNPT + Nentries);
// Export name table
char* pENT = (char*)(pOT + Nentries);
// DLL name
char* pDLLName = pENT + L;
// sort the names/ordinals
NewArrayHolder<char*> pAlias(new char*[Nentries]);
for(i = 0; i < Nentries; i++)
{
pEATE = m_EATList.PEEK(i);
pOT[i] = (WORD)pEATE->dwOrdinal;
if(pOT[i] < ordBase) ordBase = pOT[i];
pAlias[i] = pEATE->szAlias;
}
bool swapped = true;
char* pch;
while(swapped)
{
swapped = false;
for(i=1; i < Nentries; i++)
{
if(strcmp(pAlias[i-1],pAlias[i]) > 0)
{
swapped = true;
pch = pAlias[i-1];
pAlias[i-1] = pAlias[i];
pAlias[i] = pch;
WORD j = pOT[i-1];
pOT[i-1] = pOT[i];
pOT[i] = j;
}
}
}
// normalize ordinals
for(i = 0; i < Nentries; i++) pOT[i] -= (WORD)ordBase;
// fill the export address table
#ifdef _PREFAST_
#pragma warning(push)
#pragma warning(disable:22008) // "Suppress PREfast warnings about integer overflow"
#endif
for(i = 0; i < Nentries; i++)
{
pEATE = m_EATList.PEEK(i);
pEAT[pEATE->dwOrdinal - ordBase] = pEATE->dwStubRVA;
}
#ifdef _PREFAST_
#pragma warning(pop)
#endif
// fill the export names table
unsigned l, j;
for(i = 0, j = 0; i < Nentries; i++)
{
pNPT[i] = j; // relative offset in the table
l = (unsigned)strlen(pAlias[i])+1;
memcpy(&pENT[j],pAlias[i],l);
j+=l;
}
_ASSERTE(j==L);
// fill the DLL name
memcpy(pDLLName,pszDllName,Ldllname);
// Data blob is ready pending Name Pointer Table values offsetting
memset(&exportDirIDD,0,sizeof(IMAGE_EXPORT_DIRECTORY));
// Grab the timestamp of the PE file.
DWORD fileTimeStamp;
if (FAILED(hr = m_pCeeFileGen->GetFileTimeStamp(m_pCeeFile,&fileTimeStamp))) return hr;
// Fill in the directory entry.
// Characteristics, MajorVersion and MinorVersion play no role and stay 0
exportDirIDD.TimeDateStamp = VAL32(fileTimeStamp);
exportDirIDD.Name = VAL32(exportDirDataSize - Ldllname); // to be offset later
exportDirIDD.Base = VAL32(ordBase);
exportDirIDD.NumberOfFunctions = VAL32(Nentries);
exportDirIDD.NumberOfNames = VAL32(Nentries);
exportDirIDD.AddressOfFunctions = 0; // to be offset later
exportDirIDD.AddressOfNames = VAL32(Nentries*sizeof(DWORD)); // to be offset later
exportDirIDD.AddressOfNameOrdinals = VAL32(Nentries*sizeof(DWORD)*2); // to be offset later
// Grab memory in the section for our stuff.
HCEESECTION sec = m_pGlobalDataSection;
BYTE *de;
if (FAILED(hr = m_pCeeFileGen->GetSectionBlock(sec,
sizeof(IMAGE_EXPORT_DIRECTORY) + exportDirDataSize,
4,
(void**) &de))) return hr;
// Where did we get that memory?
ULONG deOffset, deDataOffset;
if (FAILED(hr = m_pCeeFileGen->GetSectionDataLen(sec, &deDataOffset))) return hr;
deDataOffset -= exportDirDataSize;
deOffset = deDataOffset - sizeof(IMAGE_EXPORT_DIRECTORY);
// Add offsets and set up relocs for header entries
exportDirIDD.Name = VAL32(VAL32(exportDirIDD.Name) + deDataOffset);
if (FAILED(hr = m_pCeeFileGen->AddSectionReloc(sec,deOffset + offsetof(IMAGE_EXPORT_DIRECTORY,Name),
sec, srRelocAbsolute))) return hr;
exportDirIDD.AddressOfFunctions = VAL32(VAL32(exportDirIDD.AddressOfFunctions) + deDataOffset);
if (FAILED(hr = m_pCeeFileGen->AddSectionReloc(sec,deOffset + offsetof(IMAGE_EXPORT_DIRECTORY,AddressOfFunctions),
sec, srRelocAbsolute))) return hr;
exportDirIDD.AddressOfNames = VAL32(VAL32(exportDirIDD.AddressOfNames) + deDataOffset);
if (FAILED(hr = m_pCeeFileGen->AddSectionReloc(sec,deOffset + offsetof(IMAGE_EXPORT_DIRECTORY,AddressOfNames),
sec, srRelocAbsolute))) return hr;
exportDirIDD.AddressOfNameOrdinals = VAL32(VAL32(exportDirIDD.AddressOfNameOrdinals) + deDataOffset);
if (FAILED(hr = m_pCeeFileGen->AddSectionReloc(sec,deOffset + offsetof(IMAGE_EXPORT_DIRECTORY,AddressOfNameOrdinals),
sec, srRelocAbsolute))) return hr;
// Add offsets and set up relocs for Name Pointer Table
j = deDataOffset + Nentries*5*sizeof(WORD); // EA, NP and O Tables come first
for(i = 0; i < Nentries; i++)
{
pNPT[i] += j;
if (FAILED(hr = m_pCeeFileGen->AddSectionReloc(sec,exportDirIDD.AddressOfNames+i*sizeof(DWORD),
sec, srRelocAbsolute))) return hr;
}
// Emit the directory entry.
if (FAILED(hr = m_pCeeFileGen->SetDirectoryEntry(m_pCeeFile, sec, IMAGE_DIRECTORY_ENTRY_EXPORT,
sizeof(IMAGE_EXPORT_DIRECTORY), deOffset))) return hr;
// Copy the debug directory into the section.
memcpy(de, &exportDirIDD, sizeof(IMAGE_EXPORT_DIRECTORY));
memcpy(de + sizeof(IMAGE_EXPORT_DIRECTORY), exportDirData, exportDirDataSize);
return S_OK;
}
static const BYTE ExportStubAMD64Template[] =
{
// Jump through VTFixup table
0x48, 0xA1, // rex.w rex.b mov rax,[following address]
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,//address of VTFixup slot
0xFF, 0xE0 // jmp [rax]
};
static const BYTE ExportStubX86Template[] =
{
// Jump through VTFixup table
0xFF, 0x25, // jmp [following address]
0x00, 0x00, 0x00, 0x00 //address of VTFixup slot
};
static const WORD ExportStubARMTemplate[] =
{
// Jump through VTFixup table
0xf8df, 0xf000, // ldr pc, [pc, #0]
0x0000, 0x0000 //address of VTFixup slot
};
DWORD Assembler::EmitExportStub(DWORD dwVTFSlotRVA)
{
DWORD EXPORT_STUB_SIZE = (DWORD)(sizeof(WORD)+sizeof(DWORD));
DWORD OFFSET_OF_ADDR = (DWORD)sizeof(WORD);
DWORD STUB_ALIGNMENT = 16;
BYTE* STUB_TEMPLATE = NULL;
DWORD PEFileOffset;
BYTE* outBuff;
DWORD* pdwVTFSlotRVA;
if(m_dwCeeFileFlags & ICEE_CREATE_MACHINE_AMD64)
{
STUB_TEMPLATE = (BYTE*)&ExportStubAMD64Template[0];
EXPORT_STUB_SIZE = sizeof(ExportStubAMD64Template);
OFFSET_OF_ADDR = 2;
STUB_ALIGNMENT = 4;
}
else if(m_dwCeeFileFlags & ICEE_CREATE_MACHINE_I386)
{
STUB_TEMPLATE = (BYTE*)&ExportStubX86Template[0];
EXPORT_STUB_SIZE = sizeof(ExportStubX86Template);
OFFSET_OF_ADDR = 2;
}
else if(m_dwCeeFileFlags & ICEE_CREATE_MACHINE_ARM)
{
STUB_TEMPLATE = (BYTE*)&ExportStubARMTemplate[0];
EXPORT_STUB_SIZE = sizeof(ExportStubARMTemplate);
OFFSET_OF_ADDR = 4;
STUB_ALIGNMENT = 4;
}
else
{
report->error("Unmanaged exports are not implemented for unknown platform");
return NULL;
}
// Addr must be aligned, not the stub!
if (FAILED(m_pCeeFileGen->GetSectionDataLen (m_pILSection, &PEFileOffset))) return 0;
if((PEFileOffset + OFFSET_OF_ADDR)&(STUB_ALIGNMENT-1))
{
ULONG L = STUB_ALIGNMENT - ((PEFileOffset + OFFSET_OF_ADDR)&(STUB_ALIGNMENT-1));
if (FAILED(m_pCeeFileGen->GetSectionBlock (m_pILSection, L, 1, (void **) &outBuff))) return 0;
memset(outBuff,0,L);
}
if (FAILED(m_pCeeFileGen->GetSectionBlock (m_pILSection, EXPORT_STUB_SIZE, 1, (void **) &outBuff))) return 0;
memcpy(outBuff,STUB_TEMPLATE,EXPORT_STUB_SIZE);
pdwVTFSlotRVA = (DWORD*)(&outBuff[OFFSET_OF_ADDR]);
*pdwVTFSlotRVA = VAL32(dwVTFSlotRVA);
// The offset where we start, (not where the alignment bytes start!)
if (FAILED(m_pCeeFileGen->GetSectionDataLen (m_pILSection, &PEFileOffset))) return 0;
PEFileOffset -= EXPORT_STUB_SIZE;
_ASSERTE(((PEFileOffset + OFFSET_OF_ADDR)&(STUB_ALIGNMENT-1))==0);
m_pCeeFileGen->AddSectionReloc(m_pILSection, PEFileOffset+OFFSET_OF_ADDR,m_pGlobalDataSection, srRelocHighLow);
if(m_dwCeeFileFlags & ICEE_CREATE_FILE_STRIP_RELOCS)
{
report->error("Base relocations are emitted, while /STRIPRELOC option has been specified");
}
m_pCeeFileGen->GetMethodRVA(m_pCeeFile, PEFileOffset,&PEFileOffset);
return PEFileOffset;
}
//#endif
HRESULT Assembler::GetCAName(mdToken tkCA, _Out_ LPWSTR *ppszName)
{
HRESULT hr = S_OK;
DWORD cchName;
LPWSTR name;
*ppszName = NULL;
if (TypeFromToken(tkCA) == mdtMemberRef)
{
mdToken parent;
if (FAILED(hr = m_pImporter->GetMemberRefProps( tkCA, &parent, NULL, 0, NULL, NULL, NULL)))
return hr;
tkCA = parent;
}
else if (TypeFromToken(tkCA) == mdtMethodDef)
{
mdToken parent;
if (FAILED(hr = m_pImporter->GetMemberProps( tkCA, &parent, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL)))
return hr;
tkCA = parent;
}
if (TypeFromToken(tkCA) == mdtTypeRef)
{
// A TypeRef
if (FAILED(hr = m_pImporter->GetTypeRefProps(tkCA, NULL, NULL, 0, &cchName)))
return hr;
if ((name = new WCHAR[cchName + 1]) == NULL)
return E_OUTOFMEMORY;
hr = m_pImporter->GetTypeRefProps(tkCA, NULL, name, cchName, &cchName);
}
else
{
hr = m_pImporter->GetTypeDefProps(tkCA, NULL, 0, &cchName, NULL, NULL);
if (hr != S_OK)
return hr;
if ((name = new WCHAR[cchName + 1]) == NULL)
return E_OUTOFMEMORY;
hr = m_pImporter->GetTypeDefProps(tkCA, name, cchName, &cchName, NULL, NULL);
}
if (SUCCEEDED(hr))
*ppszName = name;
else
delete [] name;
return hr;
}
BYTE HexToByte (CHAR wc)
{
if (!iswxdigit(wc)) return (BYTE) 0xff;
if (iswdigit(wc)) return (BYTE) (wc - L'0');
if (iswupper(wc)) return (BYTE) (wc - L'A' + 10);
return (BYTE) (wc - L'a' + 10);
}
BOOL Assembler::EmitFieldsMethods(Class* pClass)
{
unsigned n;
BOOL ret = TRUE;
// emit all field definition metadata tokens
if((n = pClass->m_FieldDList.COUNT()))
{
FieldDescriptor* pFD;
if(m_fReportProgress) printf("Fields: %d;\t",n);
for(int j=0; (pFD = pClass->m_FieldDList.PEEK(j)); j++) // can't use POP here: we'll need field list for props
{
if(!EmitField(pFD))
{
if(!OnErrGo) return FALSE;
ret = FALSE;
}
pFD->m_fNew = FALSE;
}
}
// Fields are emitted; emit the class layout
{
COR_FIELD_OFFSET *pOffsets = NULL;
ULONG ul = pClass->m_ulPack;
ULONG N = pClass->m_dwNumFieldsWithOffset;
EmitSecurityInfo(pClass->m_cl,
pClass->m_pPermissions,
pClass->m_pPermissionSets);
pClass->m_pPermissions = NULL;
pClass->m_pPermissionSets = NULL;
if((pClass->m_ulSize != 0xFFFFFFFF)||(ul != 0)||(N != 0))
{
if(IsTdAutoLayout(pClass->m_Attr)) report->warn("Layout specified for auto-layout class\n");
if((ul > 128)||((ul & (ul-1)) !=0 ))
report->error("Invalid packing parameter (%d), must be 1,2,4,8...128\n",pClass->m_ulPack);
if(N)
{
pOffsets = new COR_FIELD_OFFSET[N+1];
ULONG i,j=0;
FieldDescriptor *pFD;
for(i=0; (pFD = pClass->m_FieldDList.PEEK(i)); i++)
{
if(pFD->m_ulOffset != 0xFFFFFFFF)
{
pOffsets[j].ridOfField = RidFromToken(pFD->m_fdFieldTok);
pOffsets[j].ulOffset = pFD->m_ulOffset;
j++;
}
}
_ASSERTE(j == N);
pOffsets[j].ridOfField = mdFieldDefNil;
}
m_pEmitter->SetClassLayout (
pClass->m_cl, // [IN] typedef
ul, // [IN] packing size specified as 1, 2, 4, 8, or 16
pOffsets, // [IN] array of layout specification
pClass->m_ulSize); // [IN] size of the class
if(pOffsets) delete [] pOffsets;
}
}
// emit all method definition metadata tokens
if((n = pClass->m_MethodList.COUNT()))
{
Method* pMethod;
if(m_fReportProgress) printf("Methods: %d;\t",n);
for(int i=0; (pMethod = pClass->m_MethodList.PEEK(i));i++)
{
if(!EmitMethod(pMethod))
{
if(!OnErrGo) return FALSE;
ret = FALSE;
}
pMethod->m_fNew = FALSE;
}
}
if(m_fReportProgress) printf("\n");
return ret;
}
HRESULT Assembler::ResolveLocalMemberRefs()
{
unsigned ulTotal=0, ulDefs=0, ulRefs=0, ulUnres=0;
MemberRefDList* pList[2] = {&m_LocalMethodRefDList,&m_LocalFieldRefDList};
if(pList[0]->COUNT() + pList[1]->COUNT())
{
MemberRefDescriptor* pMRD;
mdToken tkMemberDef = 0;
int i,j,k;
Class *pSearch;
if(m_fReportProgress) printf("Resolving local member refs: ");
for(k=0; k<2; k++)
{
for(i=0; (pMRD = pList[k]->PEEK(i)) != NULL; i++)
{
if(pMRD->m_tkResolved) continue;
tkMemberDef = 0;
Method* pListMD;
char* pMRD_szName = pMRD->m_szName;
DWORD pMRD_dwName = pMRD->m_dwName;
ULONG pMRD_dwCSig = (pMRD->m_pSigBinStr ? pMRD->m_pSigBinStr->length() : 0);
PCOR_SIGNATURE pMRD_pSig = (PCOR_SIGNATURE)(pMRD->m_pSigBinStr ? pMRD->m_pSigBinStr->ptr() : NULL);
CQuickBytes qbSig;
ulTotal++;
pSearch = NULL;
if(pMRD->m_tdClass == mdTokenNil)
pSearch = m_lstClass.PEEK(0);
else if((TypeFromToken(pMRD->m_tdClass) != mdtTypeDef)
||((pSearch = m_lstClass.PEEK(RidFromToken(pMRD->m_tdClass)-1)) == NULL))
{
report->msg("Error: bad parent 0x%08X of local member ref '%s'\n",
pMRD->m_tdClass,pMRD->m_szName);
}
if(pSearch)
{
// MemberRef may reference a method or a field
if(k==0) //methods
{
if((*pMRD_pSig & IMAGE_CEE_CS_CALLCONV_MASK)==IMAGE_CEE_CS_CALLCONV_VARARG)
{
ULONG L;
qbSig.Shrink(0);
_GetFixedSigOfVarArg(pMRD_pSig,pMRD_dwCSig,&qbSig,&L);
pMRD_pSig = (PCOR_SIGNATURE)(qbSig.Ptr());
pMRD_dwCSig = L;
}
for(j=0; (pListMD = pSearch->m_MethodList.PEEK(j)) != NULL; j++)
{
if(pListMD->m_dwName != pMRD_dwName) continue;
if(strcmp(pListMD->m_szName,pMRD_szName)) continue;
if(pListMD->m_dwMethodCSig != pMRD_dwCSig) continue;
if(memcmp(pListMD->m_pMethodSig,pMRD_pSig,pMRD_dwCSig)) continue;
tkMemberDef = pListMD->m_Tok;
ulDefs++;
break;
}
if(tkMemberDef && ((*pMRD_pSig & IMAGE_CEE_CS_CALLCONV_MASK)==IMAGE_CEE_CS_CALLCONV_VARARG))
{
WszMultiByteToWideChar(g_uCodePage,0,pMRD_szName,-1,wzUniBuf,dwUniBuf);
if(IsMdPrivateScope(pListMD->m_Attr))
{
WCHAR* p = wcsstr(wzUniBuf,W("$PST06"));
if(p) *p = 0;
}
m_pEmitter->DefineMemberRef(tkMemberDef, wzUniBuf,
pMRD->m_pSigBinStr->ptr(),
pMRD->m_pSigBinStr->length(),
&tkMemberDef);
ulDefs--;
ulRefs++;
}
}
else // fields
{
FieldDescriptor* pListFD;
for(j=0; (pListFD = pSearch->m_FieldDList.PEEK(j)) != NULL; j++)
{
if(pListFD->m_dwName != pMRD_dwName) continue;
if(strcmp(pListFD->m_szName,pMRD_szName)) continue;
if(pListFD->m_pbsSig)
{
if(pListFD->m_pbsSig->length() != pMRD_dwCSig) continue;
if(memcmp(pListFD->m_pbsSig->ptr(),pMRD_pSig,pMRD_dwCSig)) continue;
}
else if(pMRD_dwCSig) continue;
tkMemberDef = pListFD->m_fdFieldTok;
ulDefs++;
break;
}
}
}
if(tkMemberDef==0)
{ // could not resolve ref to def, make new ref and leave it this way
if((pSearch = pMRD->m_pClass) != NULL)
{
mdToken tkRef = MakeTypeRef(1,pSearch->m_szFQN);
if(RidFromToken(tkRef))
{
WszMultiByteToWideChar(g_uCodePage,0,pMRD_szName,-1,wzUniBuf,dwUniBuf);
m_pEmitter->DefineMemberRef(tkRef, wzUniBuf, pMRD_pSig,
pMRD_dwCSig, &tkMemberDef);
ulRefs++;
}
else
{
report->msg("Error: unresolved member ref '%s' of class 0x%08X\n",pMRD->m_szName,pMRD->m_tdClass);
ulUnres++;
}
}
else
{
report->msg("Error: unresolved global member ref '%s'\n",pMRD->m_szName);
ulUnres++;
}
}
pMRD->m_tkResolved = tkMemberDef;
}
}
for(i=0; (pMRD = m_MethodSpecList.PEEK(i)) != NULL; i++)
{
if(pMRD->m_tkResolved) continue;
tkMemberDef = pMRD->m_tdClass;
if(TypeFromToken(tkMemberDef)==0x99000000)
{
tkMemberDef = m_LocalMethodRefDList.PEEK(RidFromToken(tkMemberDef)-1)->m_tkResolved;
if((TypeFromToken(tkMemberDef)==mdtMethodDef)||(TypeFromToken(tkMemberDef)==mdtMemberRef))
{
ULONG pMRD_dwCSig = (pMRD->m_pSigBinStr ? pMRD->m_pSigBinStr->length() : 0);
PCOR_SIGNATURE pMRD_pSig = (PCOR_SIGNATURE)(pMRD->m_pSigBinStr ? pMRD->m_pSigBinStr->ptr() : NULL);
HRESULT hr = m_pEmitter->DefineMethodSpec(tkMemberDef, pMRD_pSig, pMRD_dwCSig, &(pMRD->m_tkResolved));
if(FAILED(hr))
report->error("Unable to define method instantiation");
}
}
if(RidFromToken(pMRD->m_tkResolved)) ulDefs++;
else ulUnres++;
}
if(m_fReportProgress) printf("%d -> %d defs, %d refs, %d unresolved\n",ulTotal,ulDefs,ulRefs,ulUnres);
}
return (ulUnres ? E_FAIL : S_OK);
}
HRESULT Assembler::DoLocalMemberRefFixups()
{
MemberRefDList* pList;
unsigned Nlmr = m_LocalMethodRefDList.COUNT() + m_LocalFieldRefDList.COUNT(),
Nlmrf = m_LocalMemberRefFixupList.COUNT();
HRESULT hr = S_OK;
if(Nlmr)
{
MemberRefDescriptor* pMRD;
LocalMemberRefFixup* pMRF;
int i;
for(i = 0; (pMRF = m_LocalMemberRefFixupList.PEEK(i)) != NULL; i++)
{
switch(TypeFromToken(pMRF->tk))
{
case 0x99000000: pList = &m_LocalMethodRefDList; break;
case 0x98000000: pList = &m_LocalFieldRefDList; break;
case 0x9A000000: pList = &m_MethodSpecList; break;
default: pList = NULL; break;
}
if(pList)
{
if((pMRD = pList->PEEK(RidFromToken(pMRF->tk)-1)) != NULL)
SET_UNALIGNED_VAL32((void *)(pMRF->offset), pMRD->m_tkResolved);
else
{
report->msg("Error: bad local member ref token 0x%08X in LMR fixup\n",pMRF->tk);
hr = E_FAIL;
}
}
pMRF->m_fNew = FALSE;
}
}
else if(Nlmrf)
{
report->msg("Error: %d local member ref fixups, no local member refs\n",Nlmrf);
hr = E_FAIL;
}
return hr;
}
void Assembler::EmitUnresolvedCustomAttributes()
{
CustomDescr *pCD;
while((pCD = m_CustomDescrList.POP()) != NULL)
{
pCD->tkType = ResolveLocalMemberRef(pCD->tkType);
pCD->tkOwner = ResolveLocalMemberRef(pCD->tkOwner);
// Look for the class'es interfaceimpl if this CA is one of those
if (pCD->tkInterfacePair)
pCD->tkOwner = GetInterfaceImpl(pCD->tkOwner, pCD->tkInterfacePair);
DefineCV(new CustomDescr(pCD->tkOwner,pCD->tkType,pCD->pBlob));
}
}
BOOL Assembler::EmitEventsProps(Class* pClass)
{
unsigned n;
BOOL ret = TRUE;
// emit all event definition metadata tokens
if((n = pClass->m_EventDList.COUNT()))
{
if(m_fReportProgress) printf("Events: %d;\t",n);
EventDescriptor* pED;
for(int j=0; (pED = pClass->m_EventDList.PEEK(j)); j++) // can't use POP here: we'll need event list for props
{
if(!EmitEvent(pED))
{
if(!OnErrGo) return FALSE;
ret = FALSE;
}
pED->m_fNew = FALSE;
}
}
// emit all property definition metadata tokens
if((n = pClass->m_PropDList.COUNT()))
{
if(m_fReportProgress) printf("Props: %d;\t",n);
PropDescriptor* pPD;
for(int j=0; (pPD = pClass->m_PropDList.PEEK(j)); j++)
{
if(!EmitProp(pPD))
{
if(!OnErrGo) return FALSE;
ret = FALSE;
}
pPD->m_fNew = FALSE;
}
}
if(m_fReportProgress) printf("\n");
return ret;
}
HRESULT Assembler::AllocateStrongNameSignature()
{
HRESULT hr = S_OK;
HCEESECTION hSection;
DWORD dwDataLength;
DWORD dwDataOffset;
DWORD dwDataRVA;
VOID *pvBuffer;
AsmManStrongName *pSN = &m_pManifest->m_sStrongName;
// pSN->m_cbPublicKey is the length of the m_pbPublicKey
dwDataLength = ((int)pSN->m_cbPublicKey < 128 + 32) ? 128 : (int)pSN->m_cbPublicKey - 32;
// Grab memory in the section for our stuff.
if (FAILED(hr = m_pCeeFileGen->GetIlSection(m_pCeeFile,
&hSection)))
{
return hr;
}
if (FAILED(hr = m_pCeeFileGen->GetSectionBlock(hSection,
dwDataLength,
4,
&pvBuffer)))
{
return hr;
}
// Where did we get that memory?
if (FAILED(hr = m_pCeeFileGen->GetSectionDataLen(hSection,
&dwDataOffset)))
{
return hr;
}
dwDataOffset -= dwDataLength;
// Convert to an RVA.
if (FAILED(hr = m_pCeeFileGen->GetMethodRVA(m_pCeeFile,
dwDataOffset,
&dwDataRVA)))
{
return hr;
}
// Emit the directory entry.
if (FAILED(hr = m_pCeeFileGen->SetStrongNameEntry(m_pCeeFile,
dwDataLength,
dwDataRVA)))
{
return hr;
}
return S_OK;
}