summaryrefslogtreecommitdiff
path: root/src/mscorlib/src/System/Reflection/Emit/DynamicILGenerator.cs
blob: cb2667a104dc80be942c031ee72a77f3a780d0bb (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

// 

namespace System.Reflection.Emit
{

    using System;
    using System.Globalization;
    using System.Diagnostics.SymbolStore;
    using System.Runtime.InteropServices;
    using System.Reflection;
    using System.Collections;
    using System.Collections.Generic;
    using System.Threading;
    using System.Diagnostics;
    using System.Diagnostics.CodeAnalysis;
    using System.Diagnostics.Contracts;
    using System.Security;

    internal class DynamicILGenerator : ILGenerator
    {

        internal DynamicScope m_scope;
        private int m_methodSigToken;

        internal unsafe DynamicILGenerator(DynamicMethod method, byte[] methodSignature, int size)
            : base(method, size)
        {
            m_scope = new DynamicScope();

            m_methodSigToken = m_scope.GetTokenFor(methodSignature);
        }


        internal void GetCallableMethod(RuntimeModule module, DynamicMethod dm)
        {
            dm.m_methodHandle = ModuleHandle.GetDynamicMethod(dm,
                                          module,
                                          m_methodBuilder.Name,
                                          (byte[])m_scope[m_methodSigToken],
                                          new DynamicResolver(this));
        }

#if FEATURE_APPX
        private bool ProfileAPICheck
        {
            get
            {
                return ((DynamicMethod)m_methodBuilder).ProfileAPICheck;
            }
        }
#endif // FEATURE_APPX

        // *** ILGenerator api ***

        public override LocalBuilder DeclareLocal(Type localType, bool pinned)
        {
            LocalBuilder localBuilder;
            if (localType == null)
                throw new ArgumentNullException(nameof(localType));
            Contract.EndContractBlock();

            RuntimeType rtType = localType as RuntimeType;

            if (rtType == null)
                throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"));

#if FEATURE_APPX
            if (ProfileAPICheck && (rtType.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
                throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtType.FullName));
#endif

            localBuilder = new LocalBuilder(m_localCount, localType, m_methodBuilder);
            // add the localType to local signature
            m_localSignature.AddArgument(localType, pinned);
            m_localCount++;
            return localBuilder;
        }

        //
        //
        // Token resolution calls
        //
        //
        public override void Emit(OpCode opcode, MethodInfo meth)
        {
            if (meth == null)
                throw new ArgumentNullException(nameof(meth));
            Contract.EndContractBlock();

            int stackchange = 0;
            int token = 0;
            DynamicMethod dynMeth = meth as DynamicMethod;
            if (dynMeth == null)
            {
                RuntimeMethodInfo rtMeth = meth as RuntimeMethodInfo;
                if (rtMeth == null)
                    throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), nameof(meth));

                RuntimeType declaringType = rtMeth.GetRuntimeType();
                if (declaringType != null && (declaringType.IsGenericType || declaringType.IsArray))
                    token = GetTokenFor(rtMeth, declaringType);
                else
                    token = GetTokenFor(rtMeth);
            }
            else
            {
                // rule out not allowed operations on DynamicMethods
                if (opcode.Equals(OpCodes.Ldtoken) || opcode.Equals(OpCodes.Ldftn) || opcode.Equals(OpCodes.Ldvirtftn))
                {
                    throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOpCodeOnDynamicMethod"));
                }
                token = GetTokenFor(dynMeth);
            }

            EnsureCapacity(7);
            InternalEmit(opcode);

            if (opcode.StackBehaviourPush == StackBehaviour.Varpush
                && meth.ReturnType != typeof(void))
            {
                stackchange++;
            }
            if (opcode.StackBehaviourPop == StackBehaviour.Varpop)
            {
                stackchange -= meth.GetParametersNoCopy().Length;
            }
            // Pop the "this" parameter if the method is non-static,
            //  and the instruction is not newobj/ldtoken/ldftn.
            if (!meth.IsStatic &&
                !(opcode.Equals(OpCodes.Newobj) || opcode.Equals(OpCodes.Ldtoken) || opcode.Equals(OpCodes.Ldftn)))
            {
                stackchange--;
            }

            UpdateStackSize(opcode, stackchange);

            PutInteger4(token);
        }

        public override void Emit(OpCode opcode, ConstructorInfo con)
        {
            if (con == null)
                throw new ArgumentNullException(nameof(con));
            Contract.EndContractBlock();

            RuntimeConstructorInfo rtConstructor = con as RuntimeConstructorInfo;
            if (rtConstructor == null)
                throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), nameof(con));

            RuntimeType declaringType = rtConstructor.GetRuntimeType();
            int token;

            if (declaringType != null && (declaringType.IsGenericType || declaringType.IsArray))
                // need to sort out the stack size story
                token = GetTokenFor(rtConstructor, declaringType);
            else
                token = GetTokenFor(rtConstructor);

            EnsureCapacity(7);
            InternalEmit(opcode);

            // need to sort out the stack size story
            UpdateStackSize(opcode, 1);

            PutInteger4(token);
        }

        public override void Emit(OpCode opcode, Type type)
        {
            if (type == null)
                throw new ArgumentNullException(nameof(type));
            Contract.EndContractBlock();

            RuntimeType rtType = type as RuntimeType;

            if (rtType == null)
                throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"));

            int token = GetTokenFor(rtType);
            EnsureCapacity(7);
            InternalEmit(opcode);
            PutInteger4(token);
        }

        public override void Emit(OpCode opcode, FieldInfo field)
        {
            if (field == null)
                throw new ArgumentNullException(nameof(field));
            Contract.EndContractBlock();

            RuntimeFieldInfo runtimeField = field as RuntimeFieldInfo;
            if (runtimeField == null)
                throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeFieldInfo"), nameof(field));

            int token;
            if (field.DeclaringType == null)
                token = GetTokenFor(runtimeField);
            else
                token = GetTokenFor(runtimeField, runtimeField.GetRuntimeType());

            EnsureCapacity(7);
            InternalEmit(opcode);
            PutInteger4(token);
        }

        public override void Emit(OpCode opcode, String str)
        {
            if (str == null)
                throw new ArgumentNullException(nameof(str));
            Contract.EndContractBlock();

            int tempVal = GetTokenForString(str);
            EnsureCapacity(7);
            InternalEmit(opcode);
            PutInteger4(tempVal);
        }

        //
        //
        // Signature related calls (vararg, calli)
        //
        //
        public override void EmitCalli(OpCode opcode,
                                       CallingConventions callingConvention,
                                       Type returnType,
                                       Type[] parameterTypes,
                                       Type[] optionalParameterTypes)
        {
            int stackchange = 0;
            SignatureHelper sig;
            if (optionalParameterTypes != null)
                if ((callingConvention & CallingConventions.VarArgs) == 0)

                    throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAVarArgCallingConvention"));

            sig = GetMemberRefSignature(callingConvention,
                                        returnType,
                                        parameterTypes,
                                        optionalParameterTypes);

            EnsureCapacity(7);
            Emit(OpCodes.Calli);

            // If there is a non-void return type, push one.
            if (returnType != typeof(void))
                stackchange++;
            // Pop off arguments if any.
            if (parameterTypes != null)
                stackchange -= parameterTypes.Length;
            // Pop off vararg arguments.
            if (optionalParameterTypes != null)
                stackchange -= optionalParameterTypes.Length;
            // Pop the this parameter if the method has a this parameter.
            if ((callingConvention & CallingConventions.HasThis) == CallingConventions.HasThis)
                stackchange--;
            // Pop the native function pointer.
            stackchange--;
            UpdateStackSize(OpCodes.Calli, stackchange);

            int token = GetTokenForSig(sig.GetSignature(true));
            PutInteger4(token);
        }

        public override void EmitCall(OpCode opcode, MethodInfo methodInfo, Type[] optionalParameterTypes)
        {
            if (methodInfo == null)
                throw new ArgumentNullException(nameof(methodInfo));

            if (!(opcode.Equals(OpCodes.Call) || opcode.Equals(OpCodes.Callvirt) || opcode.Equals(OpCodes.Newobj)))
                throw new ArgumentException(Environment.GetResourceString("Argument_NotMethodCallOpcode"), nameof(opcode));

            if (methodInfo.ContainsGenericParameters)
                throw new ArgumentException(Environment.GetResourceString("Argument_GenericsInvalid"), nameof(methodInfo));

            if (methodInfo.DeclaringType != null && methodInfo.DeclaringType.ContainsGenericParameters)
                throw new ArgumentException(Environment.GetResourceString("Argument_GenericsInvalid"), nameof(methodInfo));
            Contract.EndContractBlock();

            int tk;
            int stackchange = 0;

            tk = GetMemberRefToken(methodInfo, optionalParameterTypes);

            EnsureCapacity(7);
            InternalEmit(opcode);

            // Push the return value if there is one.
            if (methodInfo.ReturnType != typeof(void))
                stackchange++;
            // Pop the parameters.
            stackchange -= methodInfo.GetParameterTypes().Length;
            // Pop the this parameter if the method is non-static and the
            // instruction is not newobj.
            if (!(methodInfo is SymbolMethod) && methodInfo.IsStatic == false && !(opcode.Equals(OpCodes.Newobj)))
                stackchange--;
            // Pop the optional parameters off the stack.
            if (optionalParameterTypes != null)
                stackchange -= optionalParameterTypes.Length;
            UpdateStackSize(opcode, stackchange);

            PutInteger4(tk);
        }

        public override void Emit(OpCode opcode, SignatureHelper signature)
        {
            if (signature == null)
                throw new ArgumentNullException(nameof(signature));
            Contract.EndContractBlock();

            int stackchange = 0;
            EnsureCapacity(7);
            InternalEmit(opcode);

            // The only IL instruction that has VarPop behaviour, that takes a
            // Signature token as a parameter is calli.  Pop the parameters and
            // the native function pointer.  To be conservative, do not pop the
            // this pointer since this information is not easily derived from
            // SignatureHelper.
            if (opcode.StackBehaviourPop == StackBehaviour.Varpop)
            {
                Debug.Assert(opcode.Equals(OpCodes.Calli),
                                "Unexpected opcode encountered for StackBehaviour VarPop.");
                // Pop the arguments..
                stackchange -= signature.ArgumentCount;
                // Pop native function pointer off the stack.
                stackchange--;
                UpdateStackSize(opcode, stackchange);
            }

            int token = GetTokenForSig(signature.GetSignature(true)); ;
            PutInteger4(token);
        }

        //
        //
        // Exception related generation
        //
        //
        public override void BeginExceptFilterBlock()
        {
            // Begins an exception filter block. Emits a branch instruction to the end of the current exception block.

            if (CurrExcStackCount == 0)
                throw new NotSupportedException(Environment.GetResourceString("Argument_NotInExceptionBlock"));

            __ExceptionInfo current = CurrExcStack[CurrExcStackCount - 1];

            Label endLabel = current.GetEndLabel();
            Emit(OpCodes.Leave, endLabel);
            UpdateStackSize(OpCodes.Nop, 1);

            current.MarkFilterAddr(ILOffset);
        }

        public override void BeginCatchBlock(Type exceptionType)
        {
            if (CurrExcStackCount == 0)
                throw new NotSupportedException(Environment.GetResourceString("Argument_NotInExceptionBlock"));
            Contract.EndContractBlock();

            __ExceptionInfo current = CurrExcStack[CurrExcStackCount - 1];

            RuntimeType rtType = exceptionType as RuntimeType;

            if (current.GetCurrentState() == __ExceptionInfo.State_Filter)
            {
                if (exceptionType != null)
                {
                    throw new ArgumentException(Environment.GetResourceString("Argument_ShouldNotSpecifyExceptionType"));
                }

                this.Emit(OpCodes.Endfilter);

                current.MarkCatchAddr(ILOffset, null);
            }
            else
            {
                // execute this branch if previous clause is Catch or Fault
                if (exceptionType == null)
                    throw new ArgumentNullException(nameof(exceptionType));

                if (rtType == null)
                    throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"));

                Label endLabel = current.GetEndLabel();
                this.Emit(OpCodes.Leave, endLabel);

                // if this is a catch block the exception will be pushed on the stack and we need to update the stack info
                UpdateStackSize(OpCodes.Nop, 1);

                current.MarkCatchAddr(ILOffset, exceptionType);


                // this is relying on too much implementation details of the base and so it's highly breaking
                // Need to have a more integrated story for exceptions
                current.m_filterAddr[current.m_currentCatch - 1] = GetTokenFor(rtType);
            }
        }

        //
        //
        // debugger related calls. 
        //
        //
        [SuppressMessage("Microsoft.Contracts", "CC1055")]  // Skip extra error checking to avoid *potential* AppCompat problems.
        public override void UsingNamespace(String ns)
        {
            throw new NotSupportedException(Environment.GetResourceString("InvalidOperation_NotAllowedInDynamicMethod"));
        }

        [SuppressMessage("Microsoft.Contracts", "CC1055")]  // Skip extra error checking to avoid *potential* AppCompat problems.
        public override void MarkSequencePoint(ISymbolDocumentWriter document,
                                               int startLine,
                                               int startColumn,
                                               int endLine,
                                               int endColumn)
        {
            throw new NotSupportedException(Environment.GetResourceString("InvalidOperation_NotAllowedInDynamicMethod"));
        }

        public override void BeginScope()
        {
            throw new NotSupportedException(Environment.GetResourceString("InvalidOperation_NotAllowedInDynamicMethod"));
        }

        public override void EndScope()
        {
            throw new NotSupportedException(Environment.GetResourceString("InvalidOperation_NotAllowedInDynamicMethod"));
        }

        private int GetMemberRefToken(MethodBase methodInfo, Type[] optionalParameterTypes)
        {
            Type[] parameterTypes;

            if (optionalParameterTypes != null && (methodInfo.CallingConvention & CallingConventions.VarArgs) == 0)
                throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAVarArgCallingConvention"));

            RuntimeMethodInfo rtMeth = methodInfo as RuntimeMethodInfo;
            DynamicMethod dm = methodInfo as DynamicMethod;

            if (rtMeth == null && dm == null)
                throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), nameof(methodInfo));

            ParameterInfo[] paramInfo = methodInfo.GetParametersNoCopy();
            if (paramInfo != null && paramInfo.Length != 0)
            {
                parameterTypes = new Type[paramInfo.Length];
                for (int i = 0; i < paramInfo.Length; i++)
                    parameterTypes[i] = paramInfo[i].ParameterType;
            }
            else
            {
                parameterTypes = null;
            }

            SignatureHelper sig = GetMemberRefSignature(methodInfo.CallingConvention,
                                                     MethodBuilder.GetMethodBaseReturnType(methodInfo),
                                                     parameterTypes,
                                                     optionalParameterTypes);

            if (rtMeth != null)
                return GetTokenForVarArgMethod(rtMeth, sig);
            else
                return GetTokenForVarArgMethod(dm, sig);
        }

        internal override SignatureHelper GetMemberRefSignature(
                                                CallingConventions call,
                                                Type returnType,
                                                Type[] parameterTypes,
                                                Type[] optionalParameterTypes)
        {
            SignatureHelper sig = SignatureHelper.GetMethodSigHelper(call, returnType);
            if (parameterTypes != null)
            {
                foreach (Type t in parameterTypes)
                    sig.AddArgument(t);
            }
            if (optionalParameterTypes != null && optionalParameterTypes.Length != 0)
            {
                // add the sentinel
                sig.AddSentinel();
                foreach (Type t in optionalParameterTypes)
                    sig.AddArgument(t);
            }
            return sig;
        }

        internal override void RecordTokenFixup()
        {
            // DynamicMethod doesn't need fixup.
        }

        #region GetTokenFor helpers
        private int GetTokenFor(RuntimeType rtType)
        {
#if FEATURE_APPX
            if (ProfileAPICheck && (rtType.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
                throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtType.FullName));
#endif

            return m_scope.GetTokenFor(rtType.TypeHandle);
        }

        private int GetTokenFor(RuntimeFieldInfo runtimeField)
        {
#if FEATURE_APPX
            if (ProfileAPICheck)
            {
                RtFieldInfo rtField = runtimeField as RtFieldInfo;
                if (rtField != null && (rtField.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
                    throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtField.FullName));
            }
#endif

            return m_scope.GetTokenFor(runtimeField.FieldHandle);
        }

        private int GetTokenFor(RuntimeFieldInfo runtimeField, RuntimeType rtType)
        {
#if FEATURE_APPX
            if (ProfileAPICheck)
            {
                RtFieldInfo rtField = runtimeField as RtFieldInfo;
                if (rtField != null && (rtField.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
                    throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtField.FullName));

                if ((rtType.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
                    throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtType.FullName));
            }
#endif

            return m_scope.GetTokenFor(runtimeField.FieldHandle, rtType.TypeHandle);
        }

        private int GetTokenFor(RuntimeConstructorInfo rtMeth)
        {
#if FEATURE_APPX
            if (ProfileAPICheck && (rtMeth.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
                throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtMeth.FullName));
#endif

            return m_scope.GetTokenFor(rtMeth.MethodHandle);
        }

        private int GetTokenFor(RuntimeConstructorInfo rtMeth, RuntimeType rtType)
        {
#if FEATURE_APPX
            if (ProfileAPICheck)
            {
                if ((rtMeth.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
                    throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtMeth.FullName));

                if ((rtType.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
                    throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtType.FullName));
            }
#endif

            return m_scope.GetTokenFor(rtMeth.MethodHandle, rtType.TypeHandle);
        }

        private int GetTokenFor(RuntimeMethodInfo rtMeth)
        {
#if FEATURE_APPX
            if (ProfileAPICheck && (rtMeth.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
                throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtMeth.FullName));
#endif

            return m_scope.GetTokenFor(rtMeth.MethodHandle);
        }

        private int GetTokenFor(RuntimeMethodInfo rtMeth, RuntimeType rtType)
        {
#if FEATURE_APPX
            if (ProfileAPICheck)
            {
                if ((rtMeth.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
                    throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtMeth.FullName));

                if ((rtType.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
                    throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtType.FullName));
            }
#endif

            return m_scope.GetTokenFor(rtMeth.MethodHandle, rtType.TypeHandle);
        }

        private int GetTokenFor(DynamicMethod dm)
        {
            return m_scope.GetTokenFor(dm);
        }

        private int GetTokenForVarArgMethod(RuntimeMethodInfo rtMeth, SignatureHelper sig)
        {
#if FEATURE_APPX
            if (ProfileAPICheck && (rtMeth.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
                throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtMeth.FullName));
#endif
            VarArgMethod varArgMeth = new VarArgMethod(rtMeth, sig);
            return m_scope.GetTokenFor(varArgMeth);
        }

        private int GetTokenForVarArgMethod(DynamicMethod dm, SignatureHelper sig)
        {
            VarArgMethod varArgMeth = new VarArgMethod(dm, sig);
            return m_scope.GetTokenFor(varArgMeth);
        }

        private int GetTokenForString(String s)
        {
            return m_scope.GetTokenFor(s);
        }

        private int GetTokenForSig(byte[] sig)
        {
            return m_scope.GetTokenFor(sig);
        }
        #endregion

    }

    internal class DynamicResolver : Resolver
    {
        #region Private Data Members
        private __ExceptionInfo[] m_exceptions;
        private byte[] m_exceptionHeader;
        private DynamicMethod m_method;
        private byte[] m_code;
        private byte[] m_localSignature;
        private int m_stackSize;
        private DynamicScope m_scope;
        #endregion

        #region Internal Methods
        internal DynamicResolver(DynamicILGenerator ilGenerator)
        {
            m_stackSize = ilGenerator.GetMaxStackSize();
            m_exceptions = ilGenerator.GetExceptions();
            m_code = ilGenerator.BakeByteArray();
            m_localSignature = ilGenerator.m_localSignature.InternalGetSignatureArray();
            m_scope = ilGenerator.m_scope;

            m_method = (DynamicMethod)ilGenerator.m_methodBuilder;
            m_method.m_resolver = this;
        }

        internal DynamicResolver(DynamicILInfo dynamicILInfo)
        {
            m_stackSize = dynamicILInfo.MaxStackSize;
            m_code = dynamicILInfo.Code;
            m_localSignature = dynamicILInfo.LocalSignature;
            m_exceptionHeader = dynamicILInfo.Exceptions;
            //m_exceptions = dynamicILInfo.Exceptions;
            m_scope = dynamicILInfo.DynamicScope;

            m_method = dynamicILInfo.DynamicMethod;
            m_method.m_resolver = this;
        }

        //
        // We can destroy the unmanaged part of dynamic method only after the managed part is definitely gone and thus
        // nobody can call the dynamic method anymore. A call to finalizer alone does not guarantee that the managed 
        // part is gone. A malicious code can keep a reference to DynamicMethod in long weak reference that survives finalization,
        // or we can be running during shutdown where everything is finalized.
        //
        // The unmanaged resolver keeps a reference to the managed resolver in long weak handle. If the long weak handle 
        // is null, we can be sure that the managed part of the dynamic method is definitely gone and that it is safe to 
        // destroy the unmanaged part. (Note that the managed finalizer has to be on the same object that the long weak handle 
        // points to in order for this to work.) Unfortunately, we can not perform the above check when out finalizer 
        // is called - the long weak handle won't be cleared yet. Instead, we create a helper scout object that will attempt 
        // to do the destruction after next GC.
        //
        // The finalization does not have to be done using CriticalFinalizerObject. We have to go over all DynamicMethodDescs 
        // during AppDomain shutdown anyway to avoid leaks e.g. if somebody stores reference to DynamicMethod in static.
        //
        ~DynamicResolver()
        {
            DynamicMethod method = m_method;

            if (method == null)
                return;

            if (method.m_methodHandle == null)
                return;

            DestroyScout scout = null;
            try
            {
                scout = new DestroyScout();
            }
            catch
            {
                // We go over all DynamicMethodDesc during AppDomain shutdown and make sure
                // that everything associated with them is released. So it is ok to skip reregistration
                // for finalization during appdomain shutdown
                if (!Environment.HasShutdownStarted &&
                    !AppDomain.CurrentDomain.IsFinalizingForUnload())
                {
                    // Try again later.
                    GC.ReRegisterForFinalize(this);
                }
                return;
            }

            // We can never ever have two active destroy scouts for the same method. We need to initialize the scout
            // outside the try/reregister block to avoid possibility of reregistration for finalization with active scout.
            scout.m_methodHandle = method.m_methodHandle.Value;
        }

        private class DestroyScout
        {
            internal RuntimeMethodHandleInternal m_methodHandle;

            ~DestroyScout()
            {
                if (m_methodHandle.IsNullHandle())
                    return;

                // It is not safe to destroy the method if the managed resolver is alive.
                if (RuntimeMethodHandle.GetResolver(m_methodHandle) != null)
                {
                    if (!Environment.HasShutdownStarted &&
                        !AppDomain.CurrentDomain.IsFinalizingForUnload())
                    {
                        // Somebody might have been holding a reference on us via weak handle.
                        // We will keep trying. It will be hopefully released eventually.
                        GC.ReRegisterForFinalize(this);
                    }
                    return;
                }

                RuntimeMethodHandle.Destroy(m_methodHandle);
            }
        }

        // Keep in sync with vm/dynamicmethod.h
        [Flags]
        internal enum SecurityControlFlags
        {
            Default = 0x0,
            SkipVisibilityChecks = 0x1,
            RestrictedSkipVisibilityChecks = 0x2,
            HasCreationContext = 0x4,
            CanSkipCSEvaluation = 0x8,
        }

        internal override RuntimeType GetJitContext(ref int securityControlFlags)
        {
            RuntimeType typeOwner;

            SecurityControlFlags flags = SecurityControlFlags.Default;

            if (m_method.m_restrictedSkipVisibility)
                flags |= SecurityControlFlags.RestrictedSkipVisibilityChecks;
            else if (m_method.m_skipVisibility)
                flags |= SecurityControlFlags.SkipVisibilityChecks;

            typeOwner = m_method.m_typeOwner;


            securityControlFlags = (int)flags;

            return typeOwner;
        }

        private static int CalculateNumberOfExceptions(__ExceptionInfo[] excp)
        {
            int num = 0;
            if (excp == null)
                return 0;
            for (int i = 0; i < excp.Length; i++)
                num += excp[i].GetNumberOfCatches();
            return num;
        }

        internal override byte[] GetCodeInfo(
            ref int stackSize, ref int initLocals, ref int EHCount)
        {
            stackSize = m_stackSize;
            if (m_exceptionHeader != null && m_exceptionHeader.Length != 0)
            {
                if (m_exceptionHeader.Length < 4)
                    throw new FormatException();

                byte header = m_exceptionHeader[0];

                if ((header & 0x40) != 0) // Fat
                {
                    byte[] size = new byte[4];
                    for (int q = 0; q < 3; q++)
                        size[q] = m_exceptionHeader[q + 1];
                    EHCount = (BitConverter.ToInt32(size, 0) - 4) / 24;
                }
                else
                    EHCount = (m_exceptionHeader[1] - 2) / 12;
            }
            else
            {
                EHCount = CalculateNumberOfExceptions(m_exceptions);
            }
            initLocals = (m_method.InitLocals) ? 1 : 0;
            return m_code;
        }

        internal override byte[] GetLocalsSignature()
        {
            return m_localSignature;
        }

        internal override unsafe byte[] GetRawEHInfo()
        {
            return m_exceptionHeader;
        }

        internal override unsafe void GetEHInfo(int excNumber, void* exc)
        {
            CORINFO_EH_CLAUSE* exception = (CORINFO_EH_CLAUSE*)exc;
            for (int i = 0; i < m_exceptions.Length; i++)
            {
                int excCount = m_exceptions[i].GetNumberOfCatches();
                if (excNumber < excCount)
                {
                    // found the right exception block
                    exception->Flags = m_exceptions[i].GetExceptionTypes()[excNumber];
                    exception->TryOffset = m_exceptions[i].GetStartAddress();
                    if ((exception->Flags & __ExceptionInfo.Finally) != __ExceptionInfo.Finally)
                        exception->TryLength = m_exceptions[i].GetEndAddress() - exception->TryOffset;
                    else
                        exception->TryLength = m_exceptions[i].GetFinallyEndAddress() - exception->TryOffset;
                    exception->HandlerOffset = m_exceptions[i].GetCatchAddresses()[excNumber];
                    exception->HandlerLength = m_exceptions[i].GetCatchEndAddresses()[excNumber] - exception->HandlerOffset;
                    // this is cheating because the filter address is the token of the class only for light code gen
                    exception->ClassTokenOrFilterOffset = m_exceptions[i].GetFilterAddresses()[excNumber];
                    break;
                }
                excNumber -= excCount;
            }
        }

        internal override String GetStringLiteral(int token) { return m_scope.GetString(token); }


        internal override void ResolveToken(int token, out IntPtr typeHandle, out IntPtr methodHandle, out IntPtr fieldHandle)
        {
            typeHandle = new IntPtr();
            methodHandle = new IntPtr();
            fieldHandle = new IntPtr();

            Object handle = m_scope[token];

            if (handle == null)
                throw new InvalidProgramException();

            if (handle is RuntimeTypeHandle)
            {
                typeHandle = ((RuntimeTypeHandle)handle).Value;
                return;
            }

            if (handle is RuntimeMethodHandle)
            {
                methodHandle = ((RuntimeMethodHandle)handle).Value;
                return;
            }

            if (handle is RuntimeFieldHandle)
            {
                fieldHandle = ((RuntimeFieldHandle)handle).Value;
                return;
            }

            DynamicMethod dm = handle as DynamicMethod;
            if (dm != null)
            {
                methodHandle = dm.GetMethodDescriptor().Value;
                return;
            }

            GenericMethodInfo gmi = handle as GenericMethodInfo;
            if (gmi != null)
            {
                methodHandle = gmi.m_methodHandle.Value;
                typeHandle = gmi.m_context.Value;
                return;
            }

            GenericFieldInfo gfi = handle as GenericFieldInfo;
            if (gfi != null)
            {
                fieldHandle = gfi.m_fieldHandle.Value;
                typeHandle = gfi.m_context.Value;
                return;
            }

            VarArgMethod vaMeth = handle as VarArgMethod;
            if (vaMeth != null)
            {
                if (vaMeth.m_dynamicMethod == null)
                {
                    methodHandle = vaMeth.m_method.MethodHandle.Value;
                    typeHandle = vaMeth.m_method.GetDeclaringTypeInternal().GetTypeHandleInternal().Value;
                }
                else
                    methodHandle = vaMeth.m_dynamicMethod.GetMethodDescriptor().Value;

                return;
            }
        }

        internal override byte[] ResolveSignature(int token, int fromMethod)
        {
            return m_scope.ResolveSignature(token, fromMethod);
        }

        internal override MethodInfo GetDynamicMethod()
        {
            return m_method.GetMethodInfo();
        }
        #endregion
    }


    internal class DynamicILInfo
    {
        #region Private Data Members
        private DynamicMethod m_method;
        private DynamicScope m_scope;
        private byte[] m_exceptions;
        private byte[] m_code;
        private byte[] m_localSignature;
        private int m_maxStackSize;
        private int m_methodSignature;
        #endregion

        #region Internal Methods
        internal void GetCallableMethod(RuntimeModule module, DynamicMethod dm)
        {
            dm.m_methodHandle = ModuleHandle.GetDynamicMethod(dm,
                module, m_method.Name, (byte[])m_scope[m_methodSignature], new DynamicResolver(this));
        }

        internal byte[] LocalSignature
        {
            get
            {
                if (m_localSignature == null)
                    m_localSignature = SignatureHelper.GetLocalVarSigHelper().InternalGetSignatureArray();

                return m_localSignature;
            }
        }
        internal byte[] Exceptions { get { return m_exceptions; } }
        internal byte[] Code { get { return m_code; } }
        internal int MaxStackSize { get { return m_maxStackSize; } }
        #endregion

        #region Public ILGenerator Methods
        public DynamicMethod DynamicMethod { get { return m_method; } }
        internal DynamicScope DynamicScope { get { return m_scope; } }

#endregion
#region Public Scope Methods
        #endregion
    }

    internal class DynamicScope
    {
        #region Private Data Members
        internal List<Object> m_tokens;
        #endregion

        #region Constructor
        internal unsafe DynamicScope()
        {
            m_tokens = new List<Object>();
            m_tokens.Add(null);
        }
        #endregion

        #region Internal Methods
        internal object this[int token]
        {
            get
            {
                token &= 0x00FFFFFF;

                if (token < 0 || token > m_tokens.Count)
                    return null;

                return m_tokens[token];
            }
        }

        internal int GetTokenFor(VarArgMethod varArgMethod)
        {
            m_tokens.Add(varArgMethod);
            return m_tokens.Count - 1 | (int)MetadataTokenType.MemberRef;
        }
        internal string GetString(int token) { return this[token] as string; }

        internal byte[] ResolveSignature(int token, int fromMethod)
        {
            if (fromMethod == 0)
                return (byte[])this[token];

            VarArgMethod vaMethod = this[token] as VarArgMethod;

            if (vaMethod == null)
                return null;

            return vaMethod.m_signature.GetSignature(true);
        }
        #endregion

        #region Public Methods
        public int GetTokenFor(RuntimeMethodHandle method)
        {
            IRuntimeMethodInfo methodReal = method.GetMethodInfo();
            RuntimeMethodHandleInternal rmhi = methodReal.Value;

            if (methodReal != null && !RuntimeMethodHandle.IsDynamicMethod(rmhi))
            {
                RuntimeType type = RuntimeMethodHandle.GetDeclaringType(rmhi);
                if ((type != null) && RuntimeTypeHandle.HasInstantiation(type))
                {
                    // Do we really need to retrieve this much info just to throw an exception?
                    MethodBase m = RuntimeType.GetMethodBase(methodReal);
                    Type t = m.DeclaringType.GetGenericTypeDefinition();

                    throw new ArgumentException(String.Format(
                        CultureInfo.CurrentCulture, Environment.GetResourceString("Argument_MethodDeclaringTypeGenericLcg"), m, t));
                }
            }

            m_tokens.Add(method);
            return m_tokens.Count - 1 | (int)MetadataTokenType.MethodDef;
        }
        public int GetTokenFor(RuntimeMethodHandle method, RuntimeTypeHandle typeContext)
        {
            m_tokens.Add(new GenericMethodInfo(method, typeContext));
            return m_tokens.Count - 1 | (int)MetadataTokenType.MethodDef;
        }
        public int GetTokenFor(DynamicMethod method)
        {
            m_tokens.Add(method);
            return m_tokens.Count - 1 | (int)MetadataTokenType.MethodDef;
        }
        public int GetTokenFor(RuntimeFieldHandle field)
        {
            m_tokens.Add(field);
            return m_tokens.Count - 1 | (int)MetadataTokenType.FieldDef;
        }
        public int GetTokenFor(RuntimeFieldHandle field, RuntimeTypeHandle typeContext)
        {
            m_tokens.Add(new GenericFieldInfo(field, typeContext));
            return m_tokens.Count - 1 | (int)MetadataTokenType.FieldDef;
        }
        public int GetTokenFor(RuntimeTypeHandle type)
        {
            m_tokens.Add(type);
            return m_tokens.Count - 1 | (int)MetadataTokenType.TypeDef;
        }
        public int GetTokenFor(string literal)
        {
            m_tokens.Add(literal);
            return m_tokens.Count - 1 | (int)MetadataTokenType.String;
        }
        public int GetTokenFor(byte[] signature)
        {
            m_tokens.Add(signature);
            return m_tokens.Count - 1 | (int)MetadataTokenType.Signature;
        }
        #endregion
    }

    internal sealed class GenericMethodInfo
    {
        internal RuntimeMethodHandle m_methodHandle;
        internal RuntimeTypeHandle m_context;

        internal GenericMethodInfo(RuntimeMethodHandle methodHandle, RuntimeTypeHandle context)
        {
            m_methodHandle = methodHandle;
            m_context = context;
        }
    }

    internal sealed class GenericFieldInfo
    {
        internal RuntimeFieldHandle m_fieldHandle;
        internal RuntimeTypeHandle m_context;

        internal GenericFieldInfo(RuntimeFieldHandle fieldHandle, RuntimeTypeHandle context)
        {
            m_fieldHandle = fieldHandle;
            m_context = context;
        }
    }

    internal sealed class VarArgMethod
    {
        internal RuntimeMethodInfo m_method;
        internal DynamicMethod m_dynamicMethod;
        internal SignatureHelper m_signature;

        internal VarArgMethod(DynamicMethod dm, SignatureHelper signature)
        {
            m_dynamicMethod = dm;
            m_signature = signature;
        }

        internal VarArgMethod(RuntimeMethodInfo method, SignatureHelper signature)
        {
            m_method = method;
            m_signature = signature;
        }
    }

}