summaryrefslogtreecommitdiff
path: root/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilder.cs
blob: 9331ae193c2d30dece4e50335362a2d31e8f4ff0 (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
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
// 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.


//*************************************************************************************************************
// For each dynamic assembly there will be two AssemblyBuilder objects: the "internal" 
// AssemblyBuilder object and the "external" AssemblyBuilder object.
//  1.  The "internal" object is the real assembly object that the VM creates and knows about. However, 
//      you can perform RefEmit operations on it only if you have its granted permission. From the AppDomain 
//      and other "internal" objects like the "internal" ModuleBuilders and runtime types, you can only
//      get the "internal" objects. This is to prevent low-trust code from getting a hold of the dynamic
//      AssemblyBuilder/ModuleBuilder/TypeBuilder/MethodBuilder/etc other people have created by simply 
//      enumerating the AppDomain and inject code in it.
//  2.  The "external" object is merely an wrapper of the "internal" object and all operations on it
//      are directed to the internal object. This is the one you get by calling DefineDynamicAssembly
//      on AppDomain and the one you can always perform RefEmit operations on. You can get other "external"
//      objects from the "external" AssemblyBuilder, ModuleBuilder, TypeBuilder, MethodBuilder, etc. Note
//      that VM doesn't know about this object. So every time we call into the VM we need to pass in the
//      "internal" object.
//
// "internal" and "external" ModuleBuilders are similar
//*************************************************************************************************************

namespace System.Reflection.Emit
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Diagnostics.Contracts;
    using System.Diagnostics.SymbolStore;
    using CultureInfo = System.Globalization.CultureInfo;
    using System.IO;
    using System.Reflection;
    using System.Resources;
    using System.Runtime.CompilerServices;
    using System.Runtime.InteropServices;
    using System.Runtime.Serialization;
    using System.Runtime.Versioning;
    using System.Security;
    using System.Security.Permissions;
    using System.Security.Policy;
    using System.Threading;

    // These must match the definitions in Assembly.hpp
    [Flags]
    internal enum DynamicAssemblyFlags
    {
        None = 0x00000000,

        // Security attributes which affect the module security descriptor
        AllCritical             = 0x00000001,
        Aptca                   = 0x00000002,
        Critical                = 0x00000004,
        Transparent             = 0x00000008,
        TreatAsSafe             = 0x00000010,
    }

    // When the user calls AppDomain.DefineDynamicAssembly the loader creates a new InternalAssemblyBuilder. 
    // This InternalAssemblyBuilder can be retrieved via a call to Assembly.GetAssemblies() by untrusted code.
    // In the past, when InternalAssemblyBuilder was AssemblyBuilder, the untrusted user could down cast the
    // Assembly to an AssemblyBuilder and emit code with the elevated permissions of the trusted code which 
    // origionally created the AssemblyBuilder via DefineDynamicAssembly. Today, this can no longer happen
    // because the Assembly returned via AssemblyGetAssemblies() will be an InternalAssemblyBuilder.
    
    // Only the caller of DefineDynamicAssembly will get an AssemblyBuilder. 
    // There is a 1-1 relationship between InternalAssemblyBuilder and AssemblyBuilder. 
    // AssemblyBuilder is composed of its InternalAssemblyBuilder.
    // The AssemblyBuilder data members (e.g. m_foo) were changed to properties which then delegate 
    // the access to the composed InternalAssemblyBuilder. This way, AssemblyBuilder simply wraps 
    // InternalAssemblyBuilder and still operates on InternalAssemblyBuilder members. 
    // This also makes the change transparent to the loader. This is good because most of the complexity
    // of Assembly building is in the loader code so not touching that code reduces the chance of 
    // introducing new bugs.
    internal sealed class InternalAssemblyBuilder : RuntimeAssembly
    {
        private InternalAssemblyBuilder() { }

        #region object overrides
        public override bool Equals(object obj)
        {
            if (obj == null)
                return false;

            if (obj is InternalAssemblyBuilder)
                return ((object)this == obj);

            return obj.Equals(this);
        }
        // Need a dummy GetHashCode to pair with Equals
        public override int GetHashCode() { return base.GetHashCode(); }
        #endregion

        // Assembly methods that are overridden by AssemblyBuilder should be overridden by InternalAssemblyBuilder too
        #region Methods inherited from Assembly
        public override String[] GetManifestResourceNames()
        {
            throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicAssembly"));
        }

        public override FileStream GetFile(String name)
        {
            throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicAssembly"));
        }

        public override FileStream[] GetFiles(bool getResourceModules)
        {
            throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicAssembly"));
        }

        public override Stream GetManifestResourceStream(Type type, String name)
        {
            throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicAssembly"));
        }

        public override Stream GetManifestResourceStream(String name)
        {
            throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicAssembly"));
        }

        public override ManifestResourceInfo GetManifestResourceInfo(String resourceName)
        {
            throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicAssembly"));
        }

        public override String Location
        {
            get
            {
                throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicAssembly"));
            }
        }

        public override String CodeBase
        {
            get
            {
                throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicAssembly"));
            }
        }

        public override Type[] GetExportedTypes()
        {
            throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicAssembly"));
        }

        public override String ImageRuntimeVersion
        {
            get
            {
                return RuntimeEnvironment.GetSystemVersion();
            }
        }
        #endregion
    }

    // AssemblyBuilder class.
    // deliberately not [serializable]
    [ClassInterface(ClassInterfaceType.None)]
    [ComDefaultInterface(typeof(_AssemblyBuilder))]
    [ComVisible(true)]
    public sealed class AssemblyBuilder : Assembly, _AssemblyBuilder
    {
        #region FCALL
        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        private static extern RuntimeModule GetInMemoryAssemblyModule(RuntimeAssembly assembly);

        private Module nGetInMemoryAssemblyModule()
        {
            return AssemblyBuilder.GetInMemoryAssemblyModule(GetNativeHandle());
        }

        #endregion

        #region Internal Data Members
        // This is only valid in the "external" AssemblyBuilder
        internal AssemblyBuilderData m_assemblyData;
        private InternalAssemblyBuilder m_internalAssemblyBuilder;
        private ModuleBuilder m_manifestModuleBuilder;
        // Set to true if the manifest module was returned by code:DefineDynamicModule to the user
        private bool m_fManifestModuleUsedAsDefinedModule;
        internal const string MANIFEST_MODULE_NAME = "RefEmit_InMemoryManifestModule";

#if FEATURE_APPX
        private bool m_profileAPICheck;
#endif

        internal ModuleBuilder GetModuleBuilder(InternalModuleBuilder module)
        {
            Contract.Requires(module != null);
            Debug.Assert(this.InternalAssembly == module.Assembly);

            lock(SyncRoot)
            {
                // in CoreCLR there is only one module in each dynamic assembly, the manifest module
                if (m_manifestModuleBuilder.InternalModule == module)
                    return m_manifestModuleBuilder;

                throw new ArgumentException(null, nameof(module));
            }
        }

        internal object SyncRoot
        {
            get
            {
                return InternalAssembly.SyncRoot;
            }
        }

        internal InternalAssemblyBuilder InternalAssembly
        {
            get
            {
                return m_internalAssemblyBuilder;
            }
        }

        internal RuntimeAssembly GetNativeHandle()
        {
            return InternalAssembly.GetNativeHandle();
        }

        internal Version GetVersion()
        {
            return InternalAssembly.GetVersion();
        }

#if FEATURE_APPX
        internal bool ProfileAPICheck
        {
            get
            {
                return m_profileAPICheck;
            }
        }
#endif
        #endregion

        #region Constructor
        internal AssemblyBuilder(AppDomain domain,
                                 AssemblyName name,
                                 AssemblyBuilderAccess access,
                                 String dir,
                                 Evidence evidence,
                                 PermissionSet requiredPermissions,
                                 PermissionSet optionalPermissions,
                                 PermissionSet refusedPermissions,
                                 ref StackCrawlMark stackMark,
                                 IEnumerable<CustomAttributeBuilder> unsafeAssemblyAttributes,
                                 SecurityContextSource securityContextSource)
        {
            if (name == null)
                throw new ArgumentNullException(nameof(name));

            if (access != AssemblyBuilderAccess.Run
#if FEATURE_REFLECTION_ONLY_LOAD
                && access != AssemblyBuilderAccess.ReflectionOnly
#endif // FEATURE_REFLECTION_ONLY_LOAD
#if FEATURE_COLLECTIBLE_TYPES
                && access != AssemblyBuilderAccess.RunAndCollect
#endif // FEATURE_COLLECTIBLE_TYPES
                )
            {
                throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)access), nameof(access));
            }

            if (securityContextSource < SecurityContextSource.CurrentAppDomain ||
                securityContextSource > SecurityContextSource.CurrentAssembly)
            {
                throw new ArgumentOutOfRangeException(nameof(securityContextSource));
            }

            // Clone the name in case the caller modifies it underneath us.
            name = (AssemblyName)name.Clone();

            // If the caller is trusted they can supply identity
            // evidence for the new assembly. Otherwise we copy the
            // current grant and deny sets from the caller's assembly,
            // inject them into the new assembly and mark policy as
            // resolved. If/when the assembly is persisted and
            // reloaded, the normal rules for gathering evidence will
            // be used.
            if (evidence != null)
#pragma warning disable 618
                new SecurityPermission(SecurityPermissionFlag.ControlEvidence).Demand();
#pragma warning restore 618

            // Scan the assembly level attributes for any attributes which modify how we create the
            // assembly. Currently, we look for any attribute which modifies the security transparency
            // of the assembly.
            List<CustomAttributeBuilder> assemblyAttributes = null;
            DynamicAssemblyFlags assemblyFlags = DynamicAssemblyFlags.None;
            byte[] securityRulesBlob = null;
            byte[] aptcaBlob = null;
            if (unsafeAssemblyAttributes != null)
            {
                // Create a copy to ensure that it cannot be modified from another thread
                // as it is used further below.
                assemblyAttributes = new List<CustomAttributeBuilder>(unsafeAssemblyAttributes);

#pragma warning disable 618 // We deal with legacy attributes here as well for compat
                foreach (CustomAttributeBuilder attribute in assemblyAttributes)
                {
                    if (attribute.m_con.DeclaringType == typeof(SecurityTransparentAttribute))
                    {
                        assemblyFlags |= DynamicAssemblyFlags.Transparent;
                    }
                    else if (attribute.m_con.DeclaringType == typeof(SecurityCriticalAttribute))
                    {
                        {
                            assemblyFlags |= DynamicAssemblyFlags.AllCritical;
                        }
                    }
                }
#pragma warning restore 618
            }

            m_internalAssemblyBuilder = (InternalAssemblyBuilder)nCreateDynamicAssembly(domain,
                                                                                        name,
                                                                                        evidence,
                                                                                        ref stackMark,
                                                                                        requiredPermissions,
                                                                                        optionalPermissions,
                                                                                        refusedPermissions,
                                                                                        securityRulesBlob,
                                                                                        aptcaBlob,
                                                                                        access,
                                                                                        assemblyFlags,
                                                                                        securityContextSource);

            m_assemblyData = new AssemblyBuilderData(m_internalAssemblyBuilder,
                                                     name.Name,
                                                     access,
                                                     dir);
            m_assemblyData.AddPermissionRequests(requiredPermissions,
                                                 optionalPermissions,
                                                 refusedPermissions);

#if FEATURE_APPX
            if (AppDomain.ProfileAPICheck)
            {
                RuntimeAssembly creator = RuntimeAssembly.GetExecutingAssembly(ref stackMark);
                if (creator != null && !creator.IsFrameworkAssembly())
                    m_profileAPICheck = true;
            }
#endif
            // Make sure that ManifestModule is properly initialized
            // We need to do this before setting any CustomAttribute
            InitManifestModule();

            if (assemblyAttributes != null)
            {
                foreach (CustomAttributeBuilder assemblyAttribute in assemblyAttributes)
                    SetCustomAttribute(assemblyAttribute);
            }
        }

        private void InitManifestModule()
        {
            InternalModuleBuilder modBuilder = (InternalModuleBuilder)nGetInMemoryAssemblyModule();

            // Note that this ModuleBuilder cannot be used for RefEmit yet
            // because it hasn't been initialized.
            // However, it can be used to set the custom attribute on the Assembly
            m_manifestModuleBuilder = new ModuleBuilder(this, modBuilder);
            
            // We are only setting the name in the managed ModuleBuilderData here.
            // The name in the underlying metadata will be set when the
            // manifest module is created during nCreateDynamicAssembly.

            // This name needs to stay in sync with that used in
            // Assembly::Init to call ReflectionModule::Create (in VM)
            m_manifestModuleBuilder.Init(AssemblyBuilder.MANIFEST_MODULE_NAME, null, 0);

            m_fManifestModuleUsedAsDefinedModule = false;
        }
        #endregion

        #region DefineDynamicAssembly

        /**********************************************
        * If an AssemblyName has a public key specified, the assembly is assumed
        * to have a strong name and a hash will be computed when the assembly
        * is saved.
        **********************************************/
        [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
        public static AssemblyBuilder DefineDynamicAssembly(
            AssemblyName name,
            AssemblyBuilderAccess access)
        {
            Contract.Ensures(Contract.Result<AssemblyBuilder>() != null);

            StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
            return InternalDefineDynamicAssembly(name, access, null,
                                                 null, null, null, null, ref stackMark, null, SecurityContextSource.CurrentAssembly);
        }

        [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
        public static AssemblyBuilder DefineDynamicAssembly(
            AssemblyName name,
            AssemblyBuilderAccess access,
            IEnumerable<CustomAttributeBuilder> assemblyAttributes)
        {
            Contract.Ensures(Contract.Result<AssemblyBuilder>() != null);

            StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
            return InternalDefineDynamicAssembly(name,
                                                 access,
                                                 null, null, null, null, null,
                                                 ref stackMark,
                                                 assemblyAttributes, SecurityContextSource.CurrentAssembly);
        }


        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        private static extern Assembly nCreateDynamicAssembly(AppDomain domain,
                                                              AssemblyName name,
                                                              Evidence identity,
                                                              ref StackCrawlMark stackMark,
                                                              PermissionSet requiredPermissions,
                                                              PermissionSet optionalPermissions,
                                                              PermissionSet refusedPermissions,
                                                              byte[] securityRulesBlob,
                                                              byte[] aptcaBlob,
                                                              AssemblyBuilderAccess access,
                                                              DynamicAssemblyFlags flags,
                                                              SecurityContextSource securityContextSource);

        private class AssemblyBuilderLock { }

        internal static AssemblyBuilder InternalDefineDynamicAssembly(
            AssemblyName name,
            AssemblyBuilderAccess access,
            String dir,
            Evidence evidence,
            PermissionSet requiredPermissions,
            PermissionSet optionalPermissions,
            PermissionSet refusedPermissions,
            ref StackCrawlMark stackMark,
            IEnumerable<CustomAttributeBuilder> unsafeAssemblyAttributes,
            SecurityContextSource securityContextSource)
        {
            lock (typeof(AssemblyBuilderLock))
            {
                // we can only create dynamic assemblies in the current domain
                return new AssemblyBuilder(AppDomain.CurrentDomain,
                                           name,
                                           access,
                                           dir,
                                           evidence,
                                           requiredPermissions,
                                           optionalPermissions,
                                           refusedPermissions,
                                           ref stackMark,
                                           unsafeAssemblyAttributes,
                                           securityContextSource);
            } //lock(typeof(AssemblyBuilderLock))
        }
        #endregion

        #region DefineDynamicModule
        /**********************************************
        *
        * Defines a named dynamic module. It is an error to define multiple 
        * modules within an Assembly with the same name. This dynamic module is
        * a transient module.
        * 
        **********************************************/
        [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
        public ModuleBuilder DefineDynamicModule(
            String      name)
        {
            Contract.Ensures(Contract.Result<ModuleBuilder>() != null);

            StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
            return DefineDynamicModuleInternal(name, false, ref stackMark);
        }

        [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
        public ModuleBuilder DefineDynamicModule(
            String      name,
            bool        emitSymbolInfo)         // specify if emit symbol info or not
        {
            Contract.Ensures(Contract.Result<ModuleBuilder>() != null);

            StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
            return DefineDynamicModuleInternal( name, emitSymbolInfo, ref stackMark );
        }

        private ModuleBuilder DefineDynamicModuleInternal(
            String      name,
            bool        emitSymbolInfo,         // specify if emit symbol info or not
            ref StackCrawlMark stackMark)
        {
            lock(SyncRoot)
            {
                return DefineDynamicModuleInternalNoLock(name, emitSymbolInfo, ref stackMark);
            }
        }

        private ModuleBuilder DefineDynamicModuleInternalNoLock(
            String      name,
            bool        emitSymbolInfo,         // specify if emit symbol info or not
            ref StackCrawlMark stackMark)
        {
            if (name == null)
                throw new ArgumentNullException(nameof(name));
            if (name.Length == 0)
                throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(name));
            if (name[0] == '\0')
                throw new ArgumentException(Environment.GetResourceString("Argument_InvalidName"), nameof(name));
            Contract.Ensures(Contract.Result<ModuleBuilder>() != null);
            Contract.EndContractBlock();

            BCLDebug.Log("DYNIL", "## DYNIL LOGGING: AssemblyBuilder.DefineDynamicModule( " + name + " )");

            Debug.Assert(m_assemblyData != null, "m_assemblyData is null in DefineDynamicModuleInternal");

            ModuleBuilder dynModule;
            ISymbolWriter writer = null;
            IntPtr pInternalSymWriter = new IntPtr();

            // create the dynamic module- only one ModuleBuilder per AssemblyBuilder can be created
            if (m_fManifestModuleUsedAsDefinedModule == true)
                throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NoMultiModuleAssembly"));

            // Init(...) has already been called on m_manifestModuleBuilder in InitManifestModule()
            dynModule = m_manifestModuleBuilder;

            // Create the symbol writer
            if (emitSymbolInfo)
            {
                writer = SymWrapperCore.SymWriter.CreateSymWriter();
                // Set the underlying writer for the managed writer
                // that we're using.  Note that this function requires
                // unmanaged code access.
#pragma warning disable 618
                new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert();
#pragma warning restore 618

                String fileName = "Unused"; // this symfile is never written to disk so filename does not matter.
                
                // Pass the "real" module to the VM
                pInternalSymWriter = ModuleBuilder.nCreateISymWriterForDynamicModule(dynModule.InternalModule, fileName);

                // In Telesto, we took the SetUnderlyingWriter method private as it's a very rickety method.
                // This might someday be a good move for the desktop CLR too.
                ((SymWrapperCore.SymWriter)writer).InternalSetUnderlyingWriter(pInternalSymWriter);
            } // Creating the symbol writer

            dynModule.SetSymWriter(writer);
            m_assemblyData.AddModule(dynModule);

            if (dynModule == m_manifestModuleBuilder)
            {   // We are reusing manifest module as user-defined dynamic module
                m_fManifestModuleUsedAsDefinedModule = true;
            }

            return dynModule;
        } // DefineDynamicModuleInternalNoLock
        #endregion

        private Assembly LoadISymWrapper()
        {
            if (m_assemblyData.m_ISymWrapperAssembly != null)
                return m_assemblyData.m_ISymWrapperAssembly;

            Assembly assem = Assembly.Load("ISymWrapper, Version=" + ThisAssembly.Version +
                ", Culture=neutral, PublicKeyToken=" + AssemblyRef.MicrosoftPublicKeyToken);

            m_assemblyData.m_ISymWrapperAssembly = assem;
            return assem;
        }

        internal void CheckContext(params Type[][] typess)
        {
            if (typess == null)
                return;
            
            foreach(Type[] types in typess)
                if (types != null)
                    CheckContext(types);
        }

        internal void CheckContext(params Type[] types)
        {
            if (types == null)
                return;
        
            foreach (Type type in types)
            {
                if (type == null)
                    continue;

                if (type.Module == null || type.Module.Assembly == null)
                    throw new ArgumentException(Environment.GetResourceString("Argument_TypeNotValid"));

                if (type.Module.Assembly == typeof(object).Module.Assembly)
                    continue;

                if (type.Module.Assembly.ReflectionOnly && !ReflectionOnly)
                    throw new InvalidOperationException(Environment.GetResourceString("Arugment_EmitMixedContext1", type.AssemblyQualifiedName));

                if (!type.Module.Assembly.ReflectionOnly && ReflectionOnly)
                    throw new InvalidOperationException(Environment.GetResourceString("Arugment_EmitMixedContext2", type.AssemblyQualifiedName));
            }
        }

        #region object overrides
        public override bool Equals(object obj)
        {
            return InternalAssembly.Equals(obj);
        }
        // Need a dummy GetHashCode to pair with Equals
        public override int GetHashCode() { return InternalAssembly.GetHashCode(); }
        #endregion

        #region ICustomAttributeProvider Members
        public override Object[] GetCustomAttributes(bool inherit)
        {
            return InternalAssembly.GetCustomAttributes(inherit);
        }

        public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
        {
            return InternalAssembly.GetCustomAttributes(attributeType, inherit);
        }

        public override bool IsDefined(Type attributeType, bool inherit)
        {
            return InternalAssembly.IsDefined(attributeType, inherit);
        }

        public override IList<CustomAttributeData> GetCustomAttributesData()
        {
            return InternalAssembly.GetCustomAttributesData();
        }
        #endregion

        #region Assembly overrides
        // Returns the names of all the resources
        public override String[] GetManifestResourceNames()
        {
            return InternalAssembly.GetManifestResourceNames();
        }
        
        public override FileStream GetFile(String name)
        {
            return InternalAssembly.GetFile(name);
        }
        
        public override FileStream[] GetFiles(bool getResourceModules)
        {
            return InternalAssembly.GetFiles(getResourceModules);
        }
        
        public override Stream GetManifestResourceStream(Type type, String name)
        {
            return InternalAssembly.GetManifestResourceStream(type, name);
        }
        
        public override Stream GetManifestResourceStream(String name)
        {
            return InternalAssembly.GetManifestResourceStream(name);
        }
                      
        public override ManifestResourceInfo GetManifestResourceInfo(String resourceName)
        {
            return InternalAssembly.GetManifestResourceInfo(resourceName);
        }

        public override String Location
        {
            get
            {
                return InternalAssembly.Location;
            }
        }

        public override String ImageRuntimeVersion
        {
            get
            {
                return InternalAssembly.ImageRuntimeVersion;
            }
        }
        
        public override String CodeBase
        {
            get
            {
                return InternalAssembly.CodeBase;
            }
        }

        // Override the EntryPoint method on Assembly.
        // This doesn't need to be synchronized because it is simple enough
        public override MethodInfo EntryPoint 
        {
            get 
            {
                return m_assemblyData.m_entryPointMethod;
            }
        }

        // Get an array of all the public types defined in this assembly
        public override Type[] GetExportedTypes()
        {
            return InternalAssembly.GetExportedTypes();
        }

        public override AssemblyName GetName(bool copiedName)
        {
            return InternalAssembly.GetName(copiedName);
        }

        public override String FullName
        {
            get
            {
                return InternalAssembly.FullName;
            }
        }

        public override Type GetType(String name, bool throwOnError, bool ignoreCase)
        {
            return InternalAssembly.GetType(name, throwOnError, ignoreCase);
        }

        public override Module ManifestModule
        {
            get
            {
                return m_manifestModuleBuilder.InternalModule;
            }
        }

        public override bool ReflectionOnly
        {
            get
            {
                return InternalAssembly.ReflectionOnly;
            }
        }

        public override Module GetModule(String name)
        {
            return InternalAssembly.GetModule(name);
        }

        public override AssemblyName[] GetReferencedAssemblies()
        {
            return InternalAssembly.GetReferencedAssemblies();
        }

        public override bool GlobalAssemblyCache
        {
            get
            {
                return InternalAssembly.GlobalAssemblyCache;
            }
        }

        public override Int64 HostContext
        {
            get
            {
                return InternalAssembly.HostContext;
            }
        }

        public override Module[] GetModules(bool getResourceModules)
        {
            return InternalAssembly.GetModules(getResourceModules);
        }

        public override Module[] GetLoadedModules(bool getResourceModules)
        {
            return InternalAssembly.GetLoadedModules(getResourceModules);
        }

        [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
        public override Assembly GetSatelliteAssembly(CultureInfo culture)
        {
            StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
            return InternalAssembly.InternalGetSatelliteAssembly(culture, null, ref stackMark);
        }

        // Useful for binding to a very specific version of a satellite assembly
        [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
        public override Assembly GetSatelliteAssembly(CultureInfo culture, Version version)
        {
            StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
            return InternalAssembly.InternalGetSatelliteAssembly(culture, version, ref stackMark);
        }

        public override bool IsDynamic
        {
            get {
                return true;
            }
        }
        #endregion


        /**********************************************
        *
        * return a dynamic module with the specified name.
        *
        **********************************************/
        public ModuleBuilder GetDynamicModule(
            String      name)                   // the name of module for the look up
        {
            lock(SyncRoot)
            {
                return GetDynamicModuleNoLock(name);
            }
        }

        private ModuleBuilder GetDynamicModuleNoLock(
            String      name)                   // the name of module for the look up
        {
            if (name == null)
                throw new ArgumentNullException(nameof(name));
            if (name.Length == 0)
                throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(name));
            Contract.EndContractBlock();

            BCLDebug.Log("DYNIL", "## DYNIL LOGGING: AssemblyBuilder.GetDynamicModule( " + name + " )");
            int size = m_assemblyData.m_moduleBuilderList.Count;
            for (int i = 0; i < size; i++)
            {
                ModuleBuilder moduleBuilder = (ModuleBuilder) m_assemblyData.m_moduleBuilderList[i];
                if (moduleBuilder.m_moduleData.m_strModuleName.Equals(name))
                {
                    return moduleBuilder;
                }
            }
            return null;
        }
    
        /**********************************************
        *
        * Setting the entry point if the assembly builder is building
        * an exe.
        *
        **********************************************/
        public void SetEntryPoint(
            MethodInfo  entryMethod) 
        {
            SetEntryPoint(entryMethod, PEFileKinds.ConsoleApplication);
        }
        public void SetEntryPoint(
            MethodInfo  entryMethod,        // entry method for the assembly. We use this to determine the entry module
            PEFileKinds fileKind)           // file kind for the assembly.
        {
            lock(SyncRoot)
            {
                SetEntryPointNoLock(entryMethod, fileKind);
            }
        }

        private void SetEntryPointNoLock(
            MethodInfo  entryMethod,        // entry method for the assembly. We use this to determine the entry module
            PEFileKinds fileKind)           // file kind for the assembly.
        {

            if (entryMethod == null)
                throw new ArgumentNullException(nameof(entryMethod));
            Contract.EndContractBlock();

            BCLDebug.Log("DYNIL", "## DYNIL LOGGING: AssemblyBuilder.SetEntryPoint");

            Module tmpModule = entryMethod.Module;
            if (tmpModule == null || !InternalAssembly.Equals(tmpModule.Assembly))
                throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EntryMethodNotDefinedInAssembly"));

            m_assemblyData.m_entryPointMethod = entryMethod;
            m_assemblyData.m_peFileKind = fileKind;
        }


        /**********************************************
        * Use this function if client decides to form the custom attribute blob themselves
        **********************************************/
        [System.Runtime.InteropServices.ComVisible(true)]
        public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
        {
            if (con == null)
                throw new ArgumentNullException(nameof(con));
            if (binaryAttribute == null)
                throw new ArgumentNullException(nameof(binaryAttribute));
            Contract.EndContractBlock();
    
            lock(SyncRoot)
            {
                SetCustomAttributeNoLock(con, binaryAttribute);
            }
        }

        private void SetCustomAttributeNoLock(ConstructorInfo con, byte[] binaryAttribute)
        {
            TypeBuilder.DefineCustomAttribute(
                m_manifestModuleBuilder,     // pass in the in-memory assembly module
                AssemblyBuilderData.m_tkAssembly,           // This is the AssemblyDef token
                m_manifestModuleBuilder.GetConstructorToken(con).Token,
                binaryAttribute,
                false,
                typeof(System.Diagnostics.DebuggableAttribute) == con.DeclaringType);

            // Track the CA for persistence
            if (m_assemblyData.m_access != AssemblyBuilderAccess.Run)
            {
                // tracking the CAs for persistence
                m_assemblyData.AddCustomAttribute(con, binaryAttribute);
            }
        }

        /**********************************************
        * Use this function if client wishes to build CustomAttribute using CustomAttributeBuilder
        **********************************************/
        public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
        {
            if (customBuilder == null)
            {
                throw new ArgumentNullException(nameof(customBuilder));
            }
            Contract.EndContractBlock();

            lock(SyncRoot)
            {
                SetCustomAttributeNoLock(customBuilder);
            }
        }

        private void SetCustomAttributeNoLock(CustomAttributeBuilder customBuilder)
        {
            customBuilder.CreateCustomAttribute(
                m_manifestModuleBuilder, 
                AssemblyBuilderData.m_tkAssembly);          // This is the AssemblyDef token 

            // Track the CA for persistence
            if (m_assemblyData.m_access != AssemblyBuilderAccess.Run)
            {
                m_assemblyData.AddCustomAttribute(customBuilder);
            }
        }


        /**********************************************
        *
        * Saves the assembly to disk. Also saves all dynamic modules defined
        * in this dynamic assembly. Assembly file name can be the same as one of 
        * the module's name. If so, assembly info is stored within that module.
        * Assembly file name can be different from all of the modules underneath. In
        * this case, assembly is stored stand alone. 
        *
        **********************************************/

        public void Save(String assemblyFileName)       // assembly file name
        {
            Save(assemblyFileName, System.Reflection.PortableExecutableKinds.ILOnly, System.Reflection.ImageFileMachine.I386);
        }
            
        public void Save(String assemblyFileName, 
            PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine)
        {
            lock(SyncRoot)
            {
                SaveNoLock(assemblyFileName, portableExecutableKind, imageFileMachine);
            }
        }

        private void SaveNoLock(String assemblyFileName, 
            PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine)
        {
            // AssemblyBuilderAccess.Save can never be set in CoreCLR
            throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CantSaveTransientAssembly"));
        }

        internal bool IsPersistable()
        {
            {
                return false;
            }
        }
    
        /**********************************************
        *
        * Internal helper to walk the nested type hierachy
        *
        **********************************************/
        private int DefineNestedComType(Type type, int tkResolutionScope, int tkTypeDef)
        {
            Type        enclosingType = type.DeclaringType;
            if (enclosingType == null)
            {
                // Use full type name for non-nested types.
                return AddExportedTypeOnDisk(GetNativeHandle(), type.FullName, tkResolutionScope, tkTypeDef, type.Attributes);
            }

            tkResolutionScope = DefineNestedComType(enclosingType, tkResolutionScope, tkTypeDef);
            // Use simple name for nested types.
            return AddExportedTypeOnDisk(GetNativeHandle(), type.Name, tkResolutionScope, tkTypeDef, type.Attributes);
        }

        internal int DefineExportedTypeInMemory(Type type, int tkResolutionScope, int tkTypeDef)
        {
            Type enclosingType = type.DeclaringType;
            if (enclosingType == null)
            {
                // Use full type name for non-nested types.
                return AddExportedTypeInMemory(GetNativeHandle(), type.FullName, tkResolutionScope, tkTypeDef, type.Attributes);
            }

            tkResolutionScope = DefineExportedTypeInMemory(enclosingType, tkResolutionScope, tkTypeDef);
            // Use simple name for nested types.
            return AddExportedTypeInMemory(GetNativeHandle(), type.Name, tkResolutionScope, tkTypeDef, type.Attributes);
        }

        /**********************************************
         * 
         * Private methods
         * 
         **********************************************/
    
        /**********************************************
         * Make a private constructor so these cannot be constructed externally.
         * @internonly
         **********************************************/
        private AssemblyBuilder() {}

        // Create a new module in which to emit code. This module will not contain the manifest.
        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
        [SuppressUnmanagedCodeSecurity]
        static private extern void DefineDynamicModule(RuntimeAssembly containingAssembly,
                                                       bool emitSymbolInfo,
                                                       String name,
                                                       String filename,
                                                       StackCrawlMarkHandle stackMark,
                                                       ref IntPtr pInternalSymWriter,
                                                       ObjectHandleOnStack retModule,
                                                       bool fIsTransient,
                                                       out int tkFile);

        private static Module DefineDynamicModule(RuntimeAssembly containingAssembly, 
                                           bool emitSymbolInfo,
                                           String name,
                                           String filename,
                                           ref StackCrawlMark stackMark,
                                           ref IntPtr pInternalSymWriter,
                                           bool fIsTransient,
                                           out int tkFile)
        {
            RuntimeModule retModule = null;

            DefineDynamicModule(containingAssembly.GetNativeHandle(),
                                emitSymbolInfo,
                                name,
                                filename,
                                JitHelpers.GetStackCrawlMarkHandle(ref stackMark),
                                ref pInternalSymWriter,
                                JitHelpers.GetObjectHandleOnStack(ref retModule),
                                fIsTransient,
                                out tkFile);

            return retModule;
        }

        // The following functions are native helpers for creating on-disk manifest
        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
        [SuppressUnmanagedCodeSecurity]
        static private extern void PrepareForSavingManifestToDisk(RuntimeAssembly assembly, RuntimeModule assemblyModule);  // module to contain assembly information if assembly is embedded

        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
        [SuppressUnmanagedCodeSecurity]
        static private extern void SaveManifestToDisk(RuntimeAssembly assembly,
                                                String strFileName, 
                                                int entryPoint,
                                                int fileKind,
                                                int portableExecutableKind, 
                                                int ImageFileMachine);

        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
        [SuppressUnmanagedCodeSecurity]
        static private extern int AddFile(RuntimeAssembly assembly, String strFileName);

        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
        [SuppressUnmanagedCodeSecurity]
        static private extern void SetFileHashValue(RuntimeAssembly assembly,
                                                    int tkFile, 
                                                    String strFullFileName);

        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
        [SuppressUnmanagedCodeSecurity]
        static private extern int AddExportedTypeInMemory(RuntimeAssembly assembly,
                                                          String strComTypeName,
                                                          int tkAssemblyRef,
                                                          int tkTypeDef,
                                                          TypeAttributes flags);

        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
        [SuppressUnmanagedCodeSecurity]
        static private extern int AddExportedTypeOnDisk(RuntimeAssembly assembly, 
                                                        String strComTypeName, 
                                                        int tkAssemblyRef, 
                                                        int tkTypeDef, 
                                                        TypeAttributes flags);

        // Add an entry to assembly's manifestResource table for a stand alone resource.
        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
        [SuppressUnmanagedCodeSecurity]
        static private extern void AddStandAloneResource(RuntimeAssembly assembly,
                                                         String strName,
                                                         String strFileName,
                                                         String strFullFileName,
                                                         int attribute);

        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
        [SuppressUnmanagedCodeSecurity]
#pragma warning disable 618
        static private extern void AddDeclarativeSecurity(RuntimeAssembly assembly, SecurityAction action, byte[] blob, int length);
#pragma warning restore 618

        // Functions for defining unmanaged resources.
        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
        [SuppressUnmanagedCodeSecurity]
        static private extern void CreateVersionInfoResource(String filename, String title, String iconFilename, String description,
                                                             String copyright, String trademark, String company, String product,
                                                             String productVersion, String fileVersion, int lcid, bool isDll,
                                                             StringHandleOnStack retFileName);
    }
}