This repository has been archived by the owner on Mar 15, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 153
/
reader.cpp
8424 lines (7152 loc) · 290 KB
/
reader.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
//===---- lib/Reader/reader.cpp ---------------------------------*- C++ -*-===//
//
// LLILC
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license.
// See LICENSE file in the project root for full license information.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief Common code for converting MSIL bytecode into some other
/// representation.
///
/// The common reader's operation revolves around two central classes.
/// ReaderBase:: the common reader class
/// GenIR:: an opaque vessel for holding the client's state
///
/// The GenIR class is opaque to the common reader class, all manipulations of
/// GenIR are performed by client implemented code.
///
/// The common reader generates code through the methods that are implemented in
/// this file, and static member functions that are implemented by the client.
///
//===----------------------------------------------------------------------===//
#include "earlyincludes.h"
#include "reader.h"
#include "newvstate.h"
#include "imeta.h"
#include <climits>
#include <algorithm>
#include <list>
extern int _cdecl dbPrint(const char *Form, ...);
// --------------------------------------------------------------
// private functions and data used by common reader.
// --------------------------------------------------------------
#define BADCODE(Message) (ReaderBase::verGlobalError(Message))
// Max elements per entry in FlowGraphNodeListArray.
#define FLOW_GRAPH_NODE_LIST_ARRAY_STRIDE 32
// OPCODE REMAP
ReaderBaseNS::CallOpcode remapCallOpcode(ReaderBaseNS::OPCODE Op) {
ReaderBaseNS::CallOpcode CallOp = (ReaderBaseNS::CallOpcode)OpcodeRemap[Op];
ASSERTNR(CallOp >= 0 && CallOp < ReaderBaseNS::LastCallOpcode);
return CallOp;
}
/// \brief Reads a value of type #Type from the given buffer.
///
/// \param[in] ILCursor The buffer to read from.
/// \param[out] Value When this function returns, the decoded value.
///
/// \returns The number of bytes read from the buffer.
template <typename Type>
size_t readValue(const uint8_t *ILCursor, Type *Value) {
// MSIL contains little-endian values; swap the bytes around when compiled
// for big-endian platforms.
#if defined(BIGENDIAN)
for (uint32_t I = 0; I < sizeof(Type); ++I)
((uint8_t *)Value)[I] = ILCursor[sizeof(Type) - I - 1];
#else
*Value = *(UNALIGNED const Type *)ILCursor;
#endif
return sizeof(Type);
}
/// \brief Reads a value of type #Type from the given buffer.
///
/// \param[in] ILCursor The buffer to read from.
///
/// \returns The decoded value.
template <typename Type> Type readValue(const uint8_t *ILCursor) {
Type Value;
readValue(ILCursor, &Value);
return Value;
}
/// This higher level read method will read the number of switch cases from an
/// operand and then increment the buffer to the first case.
///
/// \param[in, out] The buffer to read from. After this function returns,
/// holds the address of the first switch case.
///
/// \returns The decoded number of switch cases.
static inline uint32_t readNumberOfSwitchCases(uint8_t **ILCursor) {
uint32_t Val;
*ILCursor += readValue(*ILCursor, &Val);
return Val;
}
/// This higher level read method will read a switch case from an operand
/// and then increment the buffer to the next case.
///
/// \param[in, out] The buffer to read from. After this function returns,
/// holds the address of the next switch case.
///
/// \returns The decoded switch case.
static inline int readSwitchCase(uint8_t **ILCursor) {
int32_t Val;
*ILCursor += readValue(*ILCursor, &Val);
return Val;
}
// FlowGraphNodeOffsetList - maintains a list of byte offsets at which branches
// need to be inserted along with the associated labels. Used for building
// flow graph.
class FlowGraphNodeOffsetList {
FlowGraphNodeOffsetList *Next;
FlowGraphNode *Node;
uint32_t Offset;
IRNode *ReaderStack;
public:
FlowGraphNodeOffsetList *getNext(void) const { return Next; }
void setNext(FlowGraphNodeOffsetList *N) { Next = N; }
FlowGraphNode *getNode(void) const { return Node; }
void setNode(FlowGraphNode *N) { Node = N; }
uint32_t getOffset(void) const { return Offset; }
void setOffset(uint32_t O) { Offset = O; }
IRNode *getStack(void) const { return ReaderStack; }
void setStack(IRNode *RS) { ReaderStack = RS; }
};
class ReaderBitVector {
private:
// Some class constants
typedef uint8_t BitVectorElement;
static const int ElementSize = 8 * sizeof(BitVectorElement);
BitVectorElement *BitVector;
ReaderBitVector(){};
#if !defined(NODBUG)
uint32_t BitVectorLength;
uint32_t NumBits;
#endif
public:
void allocateBitVector(uint32_t Size, ReaderBase *Reader) {
// Allocate and zero the backing storage.
uint32_t Length = (Size + ElementSize - 1) / ElementSize;
BitVector = (BitVectorElement *)Reader->getTempMemory(
sizeof(BitVectorElement) * Length);
memset(BitVector, 0, (sizeof(BitVectorElement) * Length));
#if !defined(NODBUG)
BitVectorLength = Length;
NumBits = Size;
#endif
}
void setBit(uint32_t BitNum) {
ASSERTDBG(BitNum < NumBits);
uint32_t Elem = BitNum / ElementSize;
BitVectorElement Mask = 1 << (BitNum % ElementSize);
ASSERTDBG(Elem < BitVectorLength);
BitVector[Elem] |= Mask;
}
bool getBit(uint32_t BitNum) {
ASSERTDBG(BitNum < NumBits);
uint32_t Elem = BitNum / ElementSize;
BitVectorElement Mask = 1 << (BitNum % ElementSize);
ASSERTDBG(Elem < BitVectorLength);
return ((BitVector[Elem] & Mask) != 0);
}
void clrBit(uint32_t BitNum) {
ASSERTDBG(BitNum < NumBits);
uint32_t Elem = BitNum / ElementSize;
BitVectorElement Mask = 1 << (BitNum % ElementSize);
ASSERTDBG(Elem < BitVectorLength);
BitVector[Elem] &= ~Mask;
}
};
ReaderBase::ReaderBase(ICorJitInfo *JitInfo, CORINFO_METHOD_INFO *MethodInfo,
uint32_t Flags) {
// Zero-Initialize all class data.
memset(&this->MethodInfo, 0,
((char *)&DummyLastBaseField - (char *)&this->MethodInfo));
this->JitInfo = JitInfo;
this->MethodInfo = MethodInfo;
this->Flags = Flags;
MethodBeingCompiled = this->MethodInfo->ftn;
ExactContext = MAKE_METHODCONTEXT(MethodBeingCompiled);
IsVerifiableCode = true;
}
bool fgEdgeIteratorMoveNextSuccessorActual(FlowGraphEdgeIterator &Iterator) {
bool HasEdge = fgEdgeIteratorMoveNextSuccessor(Iterator);
while (HasEdge && fgEdgeIsNominal(Iterator)) {
HasEdge = fgEdgeIteratorMoveNextSuccessor(Iterator);
}
return HasEdge;
}
bool fgEdgeIteratorMoveNextPredecessorActual(FlowGraphEdgeIterator &Iterator) {
bool HasEdge = fgEdgeIteratorMoveNextPredecessor(Iterator);
while (HasEdge && fgEdgeIsNominal(Iterator)) {
HasEdge = fgEdgeIteratorMoveNextPredecessor(Iterator);
}
return HasEdge;
}
FlowGraphEdgeIterator ReaderBase::fgNodeGetSuccessorsActual(FlowGraphNode *Fg) {
FlowGraphEdgeIterator Iterator = fgNodeGetSuccessors(Fg);
bool HasEdge = !fgEdgeIteratorIsEnd(Iterator);
while (HasEdge && fgEdgeIsNominal(Iterator)) {
HasEdge = fgEdgeIteratorMoveNextSuccessor(Iterator);
}
return Iterator;
}
FlowGraphEdgeIterator
ReaderBase::fgNodeGetPredecessorsActual(FlowGraphNode *Fg) {
FlowGraphEdgeIterator Iterator = fgNodeGetPredecessors(Fg);
bool HasEdge = !fgEdgeIteratorIsEnd(Iterator);
while (HasEdge && fgEdgeIsNominal(Iterator)) {
HasEdge = fgEdgeIteratorMoveNextPredecessor(Iterator);
}
return Iterator;
}
// getMSILInstrLength
//
// Returns the length of an instruction given an op code and a pointer
// to the operand. It assumes the only variable length opcode is CEE_SWITCH.
uint32_t getMSILInstrLength(ReaderBaseNS::OPCODE Opcode, uint8_t *Operand) {
// Table that maps opcode enum to operand size in bytes.
// -1 indicates either an undefined opcode, or an operand
// with variable length, in both cases the table should
// not be used.
static const int8_t OperandSizeMap[] = {
#define OPDEF_HELPER OPDEF_OPERANDSIZE
#include "ophelper.def"
#undef OPDEF_HELPER
};
uint32_t Length;
if (Opcode == ReaderBaseNS::CEE_SWITCH) {
ASSERTNR(nullptr != Operand);
// Length of a switch is the 4 bytes + 4 bytes * the value of the first 4
// bytes
uint32_t NumCases = readNumberOfSwitchCases(&Operand);
Length = sizeof(uint32_t) + (NumCases * sizeof(uint32_t));
} else {
Length = (uint32_t)OperandSizeMap[Opcode - ReaderBaseNS::CEE_NOP];
}
return Length;
}
/// \brief Parses a single MSIL opcode from the given buffer, reading at most
/// (ILInputSize - CurrentOffset) bytes from the input.
///
/// \param[in] ILInput The buffer from which to parse an opcode.
/// \param ILOffset The current offset into the input buffer.
/// \param ILSize The total size of the input buffer in bytes.
/// \param[in] Reader The #ReaderBase instance responsible for
/// handling parse errors, if any occur.
/// \param[out] Opcode When this method returns, the parsed opcode.
/// \param[out] Operand When this method returns, the address of the
/// returned opcode's operand.
/// \param ReportError Indicates whether or not to report parse errors.
///
/// \returns The offset into the input buffer of the next MSIL opcode.
uint32_t parseILOpcode(uint8_t *ILInput, uint32_t ILOffset, uint32_t ILSize,
ReaderBase *Reader, ReaderBaseNS::OPCODE *Opcode,
uint8_t **Operand, bool ReportErrors = true) {
// Illegal opcodes are currently marked as CEE_ILLEGAL. These should
// cause verification errors.
#include "bytecodetowvmcode.def"
uint32_t ILCursor = ILOffset;
uint32_t OperandOffset = 0;
uint8_t ByteCode = 0;
ReaderBaseNS::OPCODE TheOpcode = ReaderBaseNS::CEE_ILLEGAL;
*Opcode = ReportErrors ? ReaderBaseNS::CEE_ILLEGAL : ReaderBaseNS::CEE_NOP;
*Operand = ReportErrors ? nullptr : &ILInput[ILCursor];
// We need to make sure that we're not going to parse outside the buffer.
// Note that only the opcode itself is parsed, so we can check whether
// any operands would exceed the buffer by checking BytesRemaining after
// the opcode has been parsed.
//
// This leaves two cases:
// 1) 2-byte opcode = 0xFE then actual op (no symbolic name?)
// 2) switch opcode = CEE_SWITCH then 4-byte length field
// We must have at least one byte.
if (ILCursor >= ILSize) {
goto underflow;
}
ByteCode = ILInput[ILCursor++];
if (ByteCode == 0xFE) {
// This is case (1): a 2-byte opcode. Make sure we have at least one byte
// remaining.
if (ILCursor == ILSize) {
goto underflow;
}
ByteCode = ILInput[ILCursor++];
if (ByteCode <= sizeof(PrefixedByteCodes) / sizeof(PrefixedByteCodes[0])) {
TheOpcode = PrefixedByteCodes[ByteCode];
} else {
TheOpcode = ReaderBaseNS::CEE_ILLEGAL;
}
} else {
TheOpcode = ByteCodes[ByteCode];
}
// Ensure that the opcode isn't CEE_ILLEGAL.
if (TheOpcode == ReaderBaseNS::CEE_ILLEGAL) {
if (ReportErrors) {
if (Reader == nullptr) {
dbPrint("parseILOpcode: Bad Opcode\n");
} else {
Reader->verGlobalError(MVER_E_UNKNOWN_OPCODE);
}
}
return ILSize;
}
// This is case (2): a switch opcode. Make sure we have at least four bytes
// remaining s.t. getMSILInstrLength can read the number of switch cases.
if (TheOpcode == ReaderBaseNS::CEE_SWITCH && (ILSize - ILCursor) < 4) {
goto underflow;
}
OperandOffset = ILCursor;
ILCursor += getMSILInstrLength(TheOpcode, &ILInput[OperandOffset]);
if (ILCursor > ILSize) {
goto underflow;
}
*Opcode = TheOpcode;
*Operand = &ILInput[OperandOffset];
return ILCursor;
underflow:
if (ReportErrors) {
if (Reader == nullptr) {
dbPrint("parseILOpcode: Underflow\n");
} else {
Reader->verGlobalError(MVER_E_METHOD_END);
}
}
return ILSize;
}
const char *OpcodeName[] = {
#define OPDEF_HELPER OPDEF_OPCODENAME
#include "ophelper.def"
#undef OPDEF_HELPER
};
void ReaderBase::printMSIL() {
printMSIL(MethodInfo->ILCode, 0, MethodInfo->ILCodeSize);
}
void ReaderBase::printMSIL(uint8_t *Buf, uint32_t StartOffset,
uint32_t EndOffset) {
uint8_t *Operand;
ReaderBaseNS::OPCODE Opcode;
uint32_t Offset = StartOffset;
uint64_t OperandSize;
uint32_t NumBytes;
if (StartOffset >= EndOffset)
return;
NumBytes = EndOffset - StartOffset;
while (Offset < NumBytes) {
dbPrint("0x%-4x: ", StartOffset + Offset);
Offset = parseILOpcode(Buf, Offset, NumBytes, nullptr, &Opcode, &Operand);
dbPrint("%d: %-10s ", Offset, OpcodeName[Opcode]);
switch (Opcode) {
default:
OperandSize = (Buf + Offset) - Operand;
switch (OperandSize) {
case 0:
break;
case 1:
dbPrint("0x%x", readValue<int8_t>(Operand));
break;
case 2:
dbPrint("0x%x", readValue<int16_t>(Operand));
break;
case 4:
if (Opcode == ReaderBaseNS::CEE_LDC_R4) {
dbPrint("%f", readValue<float>(Operand));
} else {
dbPrint("0x%x", readValue<int32_t>(Operand));
}
break;
case 8:
if (Opcode == ReaderBaseNS::CEE_LDC_R8) {
dbPrint("%f", readValue<double>(Operand));
} else {
dbPrint("0x%I64x", readValue<int64_t>(Operand));
}
break;
}
break;
case ReaderBaseNS::CEE_SWITCH: {
uint32_t NumCases = readNumberOfSwitchCases(&Operand);
dbPrint("%-4d cases\n", NumCases);
for (uint32_t I = 0; I < NumCases; I++) {
dbPrint(" case %d: 0x%x\n", I, readSwitchCase(&Operand));
}
} break;
}
dbPrint("\n");
}
}
//////////////////////////////////////////////////////////////////////////
//
// EE Data Accessor Methods.
//
// GenIR does not have access to JitInfo or MethodInfo. It must
// ask the reader to fetch metadata.
//
//////////////////////////////////////////////////////////////////////////
bool ReaderBase::isPrimitiveType(CORINFO_CLASS_HANDLE Handle) {
return isPrimitiveType(JitInfo->asCorInfoType((CORINFO_CLASS_HANDLE)Handle));
}
bool ReaderBase::isPrimitiveType(CorInfoType CorInfoType) {
return (CORINFO_TYPE_BOOL <= CorInfoType &&
CorInfoType <= CORINFO_TYPE_DOUBLE);
}
void *ReaderBase::getHelperDescr(CorInfoHelpFunc HelpFuncId, bool *IsIndirect) {
void *HelperHandle, *IndirectHelperHandle;
ASSERTNR(IsIndirect != nullptr);
HelperHandle = JitInfo->getHelperFtn(HelpFuncId, &IndirectHelperHandle);
if (HelperHandle != nullptr) {
*IsIndirect = false;
return HelperHandle;
}
ASSERTNR(IndirectHelperHandle != nullptr);
*IsIndirect = true;
return IndirectHelperHandle;
}
CorInfoHelpFunc
ReaderBase::getNewHelper(CORINFO_RESOLVED_TOKEN *ResolvedToken) {
return JitInfo->getNewHelper(ResolvedToken, getCurrentMethodHandle());
}
void *ReaderBase::getVarArgsHandle(CORINFO_SIG_INFO *Sig, bool *IsIndirect) {
CORINFO_VARARGS_HANDLE *IndirectVarCookie;
CORINFO_VARARGS_HANDLE VarCookie;
VarCookie = JitInfo->getVarArgsHandle(Sig, (void **)&IndirectVarCookie);
ASSERTNR((!VarCookie) != (!IndirectVarCookie));
if (VarCookie != nullptr) {
*IsIndirect = false;
return VarCookie;
} else {
*IsIndirect = true;
return IndirectVarCookie;
}
}
bool ReaderBase::canGetVarArgsHandle(CORINFO_SIG_INFO *Sig) {
return JitInfo->canGetVarArgsHandle(Sig);
}
//////////////////////////////////////////////////////////////////////////
//
// Properties of current method.
//
//////////////////////////////////////////////////////////////////////////
bool ReaderBase::isZeroInitLocals(void) {
return ((MethodInfo->options & CORINFO_OPT_INIT_LOCALS) != 0);
}
uint32_t ReaderBase::getCurrentMethodNumAutos(void) {
return MethodInfo->locals.numArgs;
}
CORINFO_CLASS_HANDLE
ReaderBase::getCurrentMethodClass(void) {
return JitInfo->getMethodClass(getCurrentMethodHandle());
}
CORINFO_METHOD_HANDLE
ReaderBase::getCurrentMethodHandle(void) { return MethodInfo->ftn; }
CORINFO_METHOD_HANDLE
ReaderBase::getCurrentContext(void) { return ExactContext; }
// Returns the EE's hash code for the method being compiled.
uint32_t ReaderBase::getCurrentMethodHash(void) {
return JitInfo->getMethodHash(getCurrentMethodHandle());
}
uint32_t ReaderBase::getCurrentMethodAttribs(void) {
return JitInfo->getMethodAttribs(getCurrentMethodHandle());
}
const char *ReaderBase::getCurrentMethodName(const char **ModuleName) {
return JitInfo->getMethodName(getCurrentMethodHandle(), ModuleName);
}
mdToken ReaderBase::getMethodDefFromMethod(CORINFO_METHOD_HANDLE Handle) {
return JitInfo->getMethodDefFromMethod(Handle);
}
void ReaderBase::getFunctionEntryPoint(CORINFO_METHOD_HANDLE Handle,
CORINFO_CONST_LOOKUP *Result,
CORINFO_ACCESS_FLAGS AccessFlags) {
JitInfo->getFunctionEntryPoint(Handle, Result, AccessFlags);
}
void ReaderBase::getFunctionFixedEntryPoint(CORINFO_METHOD_HANDLE Handle,
CORINFO_CONST_LOOKUP *Result) {
JitInfo->getFunctionFixedEntryPoint(Handle, Result);
}
CORINFO_MODULE_HANDLE
ReaderBase::getCurrentModuleHandle(void) { return MethodInfo->scope; }
void ReaderBase::embedGenericHandle(CORINFO_RESOLVED_TOKEN *ResolvedToken,
bool ShouldEmbedParent,
CORINFO_GENERICHANDLE_RESULT *Result) {
JitInfo->embedGenericHandle(ResolvedToken, ShouldEmbedParent, Result);
}
//////////////////////////////////////////////////////////////////////////
//
// Properties of current jitinfo.
// These functions assume the context of the current module and method info.
//
//////////////////////////////////////////////////////////////////////////
//
// class
//
CORINFO_CLASS_HANDLE
ReaderBase::getMethodClass(CORINFO_METHOD_HANDLE Handle) {
return JitInfo->getMethodClass(Handle);
}
void ReaderBase::getMethodVTableOffset(CORINFO_METHOD_HANDLE Handle,
uint32_t *OffsetOfIndirection,
uint32_t *OffsetAfterIndirection) {
JitInfo->getMethodVTableOffset(Handle, OffsetOfIndirection,
OffsetAfterIndirection);
}
bool ReaderBase::checkMethodModifier(
CORINFO_METHOD_HANDLE Method,
LPCSTR Modifier, // name of the modifier to check for
bool IsOptional // true for modopt, false for modreqd
) {
return JitInfo->checkMethodModifier(Method, Modifier, IsOptional);
}
const char *ReaderBase::getClassName(CORINFO_CLASS_HANDLE Class) {
return JitInfo->getClassName(Class);
}
int ReaderBase::appendClassName(char16_t **Buffer, int32_t *BufferLen,
CORINFO_CLASS_HANDLE Class,
bool IncludeNamespace, bool FullInst,
bool IncludeAssembly) {
int IntBufferLen = *BufferLen, Return;
Return = JitInfo->appendClassName(
(WCHAR **)Buffer, &IntBufferLen, Class, IncludeNamespace ? TRUE : FALSE,
FullInst ? TRUE : FALSE, IncludeAssembly ? TRUE : FALSE);
*BufferLen = IntBufferLen;
return Return;
}
// Construct The GC Layout from CoreCLR Type
GCLayout *ReaderBase::getClassGCLayout(CORINFO_CLASS_HANDLE Class) {
// The actual size of the byte array the runtime is expecting (gcLayoutSize)
// is one byte for every sizeof(void*) slot in the valueclass.
// Note that we round this computation up.
const uint32_t PointerSize = getPointerByteSize();
const uint32_t ClassSize = JitInfo->getClassSize(Class);
const uint32_t GcLayoutSize = ((ClassSize + PointerSize - 1) / PointerSize);
// Our internal data structures prepend the number of GC pointers
// before the struct. Therefore we add the size of the
// GCLAYOUT_STRUCT to our computed size above.
GCLayout *GCLayoutInfo =
(GCLayout *)calloc(GcLayoutSize + sizeof(GCLayout), sizeof(uint8_t));
uint32_t NumGCVars =
JitInfo->getClassGClayout(Class, GCLayoutInfo->GCPointers);
if (NumGCVars > 0) {
// We cache away the number of GC vars.
GCLayoutInfo->NumGCPointers = NumGCVars;
} else {
// If we had no GC pointers, then we won't bother returning the
// GCLayout. It is our convention that if you have a GCLayout,
// then you have pointers. This allows us to do only one check
// when we want to know if a MB has GC pointers.
free(GCLayoutInfo);
GCLayoutInfo = nullptr;
}
return GCLayoutInfo;
}
bool ReaderBase::classHasGCPointers(CORINFO_CLASS_HANDLE Class) {
GCLayout *Layout = getClassGCLayout(Class);
free(Layout);
return Layout != nullptr;
}
uint32_t ReaderBase::getClassAttribs(CORINFO_CLASS_HANDLE Class) {
return JitInfo->getClassAttribs(Class);
}
uint32_t ReaderBase::getClassSize(CORINFO_CLASS_HANDLE Class) {
return JitInfo->getClassSize(Class);
}
uint32_t ReaderBase::getClassAlignmentRequirement(CORINFO_CLASS_HANDLE Class) {
// Class must be value (a non-primitive value class, a multibyte)
ASSERTNR(Class && (getClassAttribs(Class) & CORINFO_FLG_VALUECLASS));
#if !defined(NODEBUG)
// Make sure that classes which contain GC refs also have sufficient
// alignment requirements.
if (classHasGCPointers(Class)) {
const uint32_t PointerSize = getPointerByteSize();
ASSERTNR(JitInfo->getClassAlignmentRequirement(Class) >= PointerSize);
}
#endif // !NODEBUG
return JitInfo->getClassAlignmentRequirement(Class);
}
ReaderAlignType
ReaderBase::getMinimumClassAlignment(CORINFO_CLASS_HANDLE Class,
ReaderAlignType Alignment) {
ReaderAlignType AlignRequired;
AlignRequired = (ReaderAlignType)getClassAlignmentRequirement(Class);
if (AlignRequired != 0 &&
(Alignment == Reader_AlignNatural || Alignment > AlignRequired)) {
Alignment = AlignRequired;
}
// Unaligned GC pointers are not supported by the CLR.
// Simply ignore users that specify otherwise
if (classHasGCPointers(Class)) {
Alignment = Reader_AlignNatural;
}
return Alignment;
}
CorInfoType ReaderBase::getClassType(CORINFO_CLASS_HANDLE Class) {
return JitInfo->asCorInfoType(Class);
}
// Size and pRetSig are 0/nullptr if type is non-value or primitive.
void ReaderBase::getClassType(CORINFO_CLASS_HANDLE Class, uint32_t ClassAttribs,
CorInfoType *CorInfoType, uint32_t *Size) {
if ((ClassAttribs & CORINFO_FLG_VALUECLASS) == 0) {
// If non-value class then create pointer temp
*CorInfoType = CORINFO_TYPE_PTR;
*Size = 0;
} else if (isPrimitiveType(Class)) {
// If primitive value type then create temp of that type
*CorInfoType = JitInfo->asCorInfoType(Class);
*Size = 0;
} else {
// else class is non-primitive value class, a multibyte
*CorInfoType = CORINFO_TYPE_VALUECLASS;
*Size = getClassSize(Class);
}
}
bool ReaderBase::canInlineTypeCheckWithObjectVTable(
CORINFO_CLASS_HANDLE Class) {
return JitInfo->canInlineTypeCheckWithObjectVTable(Class);
}
bool ReaderBase::accessStaticFieldRequiresClassConstructor(
CORINFO_FIELD_HANDLE FieldHandle) {
return (initClass(FieldHandle, getCurrentMethodHandle(),
getCurrentContext()) &
CORINFO_INITCLASS_USE_HELPER) != 0;
}
void ReaderBase::classMustBeLoadedBeforeCodeIsRun(CORINFO_CLASS_HANDLE Handle) {
JitInfo->classMustBeLoadedBeforeCodeIsRun(Handle);
}
CorInfoInitClassResult ReaderBase::initClass(CORINFO_FIELD_HANDLE Field,
CORINFO_METHOD_HANDLE Method,
CORINFO_CONTEXT_HANDLE Context,
bool Speculative) {
return JitInfo->initClass(Field, Method, Context, Speculative);
}
//
// field
//
const char *ReaderBase::getFieldName(CORINFO_FIELD_HANDLE Field,
const char **ModuleName) {
return JitInfo->getFieldName(Field, ModuleName);
}
// Returns a handle to a field that can be embedded in the JITed code
CORINFO_FIELD_HANDLE
ReaderBase::embedFieldHandle(CORINFO_FIELD_HANDLE Field, bool *IsIndirect) {
CORINFO_FIELD_HANDLE DirectFieldHandle, IndirectFieldHandle;
DirectFieldHandle =
JitInfo->embedFieldHandle(Field, (void **)&IndirectFieldHandle);
if (DirectFieldHandle != nullptr) {
ASSERTNR(IndirectFieldHandle == nullptr);
*IsIndirect = false;
return DirectFieldHandle;
} else {
ASSERTNR(IndirectFieldHandle != nullptr);
*IsIndirect = true;
return IndirectFieldHandle;
}
}
CORINFO_CLASS_HANDLE
ReaderBase::getFieldClass(CORINFO_FIELD_HANDLE Field) {
return JitInfo->getFieldClass(Field);
}
CorInfoType ReaderBase::getFieldType(
CORINFO_FIELD_HANDLE Field, CORINFO_CLASS_HANDLE *Class,
CORINFO_CLASS_HANDLE Owner /* optional: for verification */
) {
return JitInfo->getFieldType(Field, Class, Owner);
}
uint32_t ReaderBase::getClassNumInstanceFields(CORINFO_CLASS_HANDLE Class) {
return JitInfo->getClassNumInstanceFields(Class);
}
CORINFO_FIELD_HANDLE
ReaderBase::getFieldInClass(CORINFO_CLASS_HANDLE Class, uint32_t Ordinal) {
return JitInfo->getFieldInClass(Class, Ordinal);
}
void ReaderBase::getFieldInfo(CORINFO_RESOLVED_TOKEN *ResolvedToken,
CORINFO_ACCESS_FLAGS AccessFlags,
CORINFO_FIELD_INFO *FieldInfo) {
if (Flags & CORJIT_FLG_READYTORUN) {
// CORINFO_ACCESS_ATYPICAL_CALLSITE means that we can't guarantee
// that we'll be able to generate call [rel32] form of the helper call so
// crossgen shouldn't try to disassemble the call instruction.
AccessFlags =
(CORINFO_ACCESS_FLAGS)(AccessFlags | CORINFO_ACCESS_ATYPICAL_CALLSITE);
}
JitInfo->getFieldInfo(ResolvedToken, getCurrentMethodHandle(), AccessFlags,
FieldInfo);
}
CorInfoType ReaderBase::getFieldInfo(CORINFO_CLASS_HANDLE Class,
uint32_t Ordinal, uint32_t *FieldOffset,
CORINFO_CLASS_HANDLE *FieldClass) {
CORINFO_FIELD_HANDLE Field;
Field = JitInfo->getFieldInClass(Class, Ordinal);
if (FieldOffset) {
*FieldOffset = JitInfo->getFieldOffset(Field);
}
return JitInfo->getFieldType(Field, FieldClass);
}
CorInfoIsAccessAllowedResult
ReaderBase::canAccessClass(CORINFO_RESOLVED_TOKEN *ResolvedToken,
CORINFO_METHOD_HANDLE Caller,
CORINFO_HELPER_DESC *ThrowHelper) {
return JitInfo->canAccessClass(ResolvedToken, Caller, ThrowHelper);
}
uint32_t ReaderBase::getFieldOffset(CORINFO_FIELD_HANDLE Field) {
return JitInfo->getFieldOffset(Field);
}
void *ReaderBase::getStaticFieldAddress(CORINFO_FIELD_HANDLE Field,
bool *IsIndirect) {
*IsIndirect = false;
void *IndirectFieldAddress;
void *FieldAddress =
(void *)JitInfo->getFieldAddress(Field, &IndirectFieldAddress);
ASSERTNR(((FieldAddress != nullptr) && (IndirectFieldAddress == nullptr)) ||
((FieldAddress == nullptr) && (IndirectFieldAddress != nullptr)));
if (FieldAddress == nullptr) {
*IsIndirect = true;
return IndirectFieldAddress;
}
return FieldAddress;
}
void *ReaderBase::getJustMyCodeHandle(CORINFO_METHOD_HANDLE Handle,
bool *IsIndirect) {
CORINFO_JUST_MY_CODE_HANDLE DebugHandle, *IndirectDebugHandle = nullptr;
DebugHandle = JitInfo->getJustMyCodeHandle(Handle, &IndirectDebugHandle);
ASSERTNR(!(DebugHandle && IndirectDebugHandle)); // both can't be non-null
if (DebugHandle) {
*IsIndirect = false;
return DebugHandle;
} else {
*IsIndirect = true;
return IndirectDebugHandle;
}
}
void *ReaderBase::getMethodSync(bool *IsIndirect) {
void *CriticalSection = 0, *IndirectCriticalSection = 0;
CriticalSection = JitInfo->getMethodSync(getCurrentMethodHandle(),
&IndirectCriticalSection);
ASSERT((!CriticalSection) != (!IndirectCriticalSection));
if (CriticalSection) {
*IsIndirect = false;
return CriticalSection;
} else {
*IsIndirect = true;
return IndirectCriticalSection;
}
}
void *ReaderBase::getCookieForPInvokeCalliSig(CORINFO_SIG_INFO *SigTarget,
bool *IsIndirect) {
void *CalliCookie, *IndirectCalliCookie = nullptr;
CalliCookie =
JitInfo->GetCookieForPInvokeCalliSig(SigTarget, &IndirectCalliCookie);
ASSERTNR((!CalliCookie) != (!IndirectCalliCookie)); // both can't be non-null
if (CalliCookie) {
*IsIndirect = false;
return CalliCookie;
} else {
*IsIndirect = true;
return IndirectCalliCookie;
}
}
bool ReaderBase::canGetCookieForPInvokeCalliSig(CORINFO_SIG_INFO *SigTarget) {
return JitInfo->canGetCookieForPInvokeCalliSig(SigTarget);
}
void *ReaderBase::getAddressOfPInvokeFixup(CORINFO_METHOD_HANDLE Method,
InfoAccessType *AccessType) {
ASSERTNR(AccessType);
void *IndirectAddress;
void *Address = JitInfo->getAddressOfPInvokeFixup(Method, &IndirectAddress);
if (Address) {
*AccessType = IAT_VALUE;
return Address;
} else {
ASSERTNR(IndirectAddress);
*AccessType = IAT_PVALUE;
return IndirectAddress;
}
}
void *ReaderBase::getPInvokeUnmanagedTarget(CORINFO_METHOD_HANDLE Method) {
void *Unused = nullptr;
// Always retuns the entry point of the call or null.
return JitInfo->getPInvokeUnmanagedTarget(Method, &Unused);
}
bool ReaderBase::pInvokeMarshalingRequired(CORINFO_METHOD_HANDLE Method,
CORINFO_SIG_INFO *Sig) {
return JitInfo->pInvokeMarshalingRequired(Method, Sig) ? true : false;
}
//
// method
//
const char *ReaderBase::getMethodName(CORINFO_METHOD_HANDLE Method,
const char **ModuleName) {
return JitInfo->getMethodName(Method, ModuleName);
}
// Find the attribs of the method handle
uint32_t ReaderBase::getMethodAttribs(CORINFO_METHOD_HANDLE Method) {
return JitInfo->getMethodAttribs(Method);
}
void ReaderBase::setMethodAttribs(CORINFO_METHOD_HANDLE Method,
CorInfoMethodRuntimeFlags Flags) {
return JitInfo->setMethodAttribs(Method, Flags);
}
void ReaderBase::getMethodSig(CORINFO_METHOD_HANDLE Method,
CORINFO_SIG_INFO *Sig) {
JitInfo->getMethodSig(Method, Sig);
}
const char *ReaderBase::getMethodRefInfo(CORINFO_METHOD_HANDLE Method,
CorInfoCallConv *CallingConvention,
CorInfoType *CorType,
CORINFO_CLASS_HANDLE *RetTypeClass,
const char **ModuleName) {
CORINFO_SIG_INFO Sig;
// Fetch Signature.
JitInfo->getMethodSig(Method, &Sig);
// Get the calling convention
*CallingConvention = Sig.getCallConv();
// Get the return type
*CorType = Sig.retType;
*RetTypeClass = Sig.retTypeClass;
// Get method and module name.
return JitInfo->getMethodName(Method, ModuleName);
}
void ReaderBase::getMethodSigData(CorInfoCallConv *CallingConvention,
CorInfoType *ReturnType,
CORINFO_CLASS_HANDLE *ReturnClass,
uint32_t *TotalILArgs, bool *IsVarArg,
bool *HasThis, uint8_t *RetSig) {
CORINFO_SIG_INFO Sig;
JitInfo->getMethodSig(getCurrentMethodHandle(), &Sig);
*CallingConvention = Sig.getCallConv();
*ReturnType = Sig.retType;
*ReturnClass = Sig.retTypeClass;
*TotalILArgs = (uint32_t)Sig.totalILArgs();
*IsVarArg = Sig.isVarArg();
*HasThis = Sig.hasThis();
*RetSig = 0;
}
void ReaderBase::getMethodInfo(CORINFO_METHOD_HANDLE Method,
CORINFO_METHOD_INFO *Info) {
JitInfo->getMethodInfo(Method, Info);
}
void ReaderBase::methodMustBeLoadedBeforeCodeIsRun(
CORINFO_METHOD_HANDLE Method) {
JitInfo->methodMustBeLoadedBeforeCodeIsRun(Method);
}
LONG ReaderBase::eeJITFilter(PEXCEPTION_POINTERS ExceptionPointersPtr,
void *Param) {
JITFilterParam *TheJITFilterParam = (JITFilterParam *)Param;
ICorJitInfo *JitInfo = TheJITFilterParam->JitInfo;
TheJITFilterParam->ExceptionPointers = *ExceptionPointersPtr;
int Answer = JitInfo->FilterException(ExceptionPointersPtr);
#ifdef CC_PEVERIFY
verLastError = JitInfo->GetErrorHRESULT(ExceptionPointersPtr);
#endif
return Answer;
}
// Finds name of MemberRef or MethodDef token
void ReaderBase::findNameOfToken(mdToken Token, char *Buffer,
size_t BufferSize) {
findNameOfToken(getCurrentModuleHandle(), Token, Buffer, BufferSize);
}