3 // Copyright (c) Microsoft Corporation. All rights reserved.
6 ////////////////////////////////////////////////////////////////////////////////
7 ////////////////////////////////////////////////////////////////////////////////
9 // Activator is an object that contains the Activation (CreateInstance/New)
10 // methods for late bound support.
18 using System.Reflection;
19 using System.Runtime.Remoting;
21 using System.Runtime.Remoting.Activation;
22 // using Message = System.Runtime.Remoting.Messaging.Message;
24 using System.Security;
25 using CultureInfo = System.Globalization.CultureInfo;
26 using Evidence = System.Security.Policy.Evidence;
27 using StackCrawlMark = System.Threading.StackCrawlMark;
28 using System.Runtime.InteropServices;
29 using System.Runtime.CompilerServices;
30 using System.Security.Permissions;
31 using AssemblyHashAlgorithm = System.Configuration.Assemblies.AssemblyHashAlgorithm;
32 using System.Runtime.Versioning;
33 using System.Diagnostics.Contracts;
35 // Only statics, does not need to be marked with the serializable attribute
36 [ClassInterface(ClassInterfaceType.None)]
37 [ComDefaultInterface(typeof(_Activator))]
38 [System.Runtime.InteropServices.ComVisible(true)]
39 public sealed class Activator : _Activator
41 internal const int LookupMask = 0x000000FF;
42 internal const BindingFlags ConLookup = (BindingFlags) (BindingFlags.Instance | BindingFlags.Public);
43 internal const BindingFlags ConstructorDefault= BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance;
45 // This class only contains statics, so hide the worthless constructor
51 // The following methods will create a new instance of an Object
52 // Full Binding Support
53 // For all of these methods we need to get the underlying RuntimeType and
54 // call the Impl version.
55 static public Object CreateInstance(Type type,
56 BindingFlags bindingAttr,
61 return CreateInstance(type, bindingAttr, binder, args, culture, null);
64 [System.Security.SecuritySafeCritical] // auto-generated
65 [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
66 static public Object CreateInstance(Type type,
67 BindingFlags bindingAttr,
71 Object[] activationAttributes)
73 if ((object)type == null)
74 throw new ArgumentNullException("type");
75 Contract.EndContractBlock();
77 if (type is System.Reflection.Emit.TypeBuilder)
78 throw new NotSupportedException(Environment.GetResourceString("NotSupported_CreateInstanceWithTypeBuilder"));
80 // If they didn't specify a lookup, then we will provide the default lookup.
81 if ((bindingAttr & (BindingFlags) LookupMask) == 0)
82 bindingAttr |= Activator.ConstructorDefault;
84 if (activationAttributes != null && activationAttributes.Length > 0){
85 // If type does not derive from MBR
86 // throw notsupportedexception
88 if(type.IsMarshalByRef){
89 // The fix below is preventative.
91 if(!(type.IsContextful)){
92 if(activationAttributes.Length > 1 || !(activationAttributes[0] is UrlAttribute))
93 throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonUrlAttrOnMBR"));
98 throw new NotSupportedException(Environment.GetResourceString("NotSupported_ActivAttrOnNonMBR" ));
101 RuntimeType rt = type.UnderlyingSystemType as RuntimeType;
104 throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"type");
106 StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
107 return rt.CreateInstanceImpl(bindingAttr,binder,args,culture,activationAttributes, ref stackMark);
110 static public Object CreateInstance(Type type, params Object[] args)
112 return CreateInstance(type,
113 Activator.ConstructorDefault,
120 static public Object CreateInstance(Type type,
122 Object[] activationAttributes)
124 return CreateInstance(type,
125 Activator.ConstructorDefault,
129 activationAttributes);
132 static public Object CreateInstance(Type type)
134 return Activator.CreateInstance(type, false);
138 * Create an instance using the name of type and the assembly where it exists. This allows
139 * types to be created remotely without having to load the type locally.
142 [System.Security.SecuritySafeCritical] // auto-generated
143 [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
144 static public ObjectHandle CreateInstance(String assemblyName,
148 if(assemblyName == null)
149 assemblyName = Assembly.GetCallingAssembly ().GetName ().Name;
151 StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
152 return CreateInstance(assemblyName,
155 Activator.ConstructorDefault,
164 [System.Security.SecuritySafeCritical] // auto-generated
165 [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
166 static public ObjectHandle CreateInstance(String assemblyName,
168 Object[] activationAttributes)
172 if(assemblyName == null)
173 assemblyName = Assembly.GetCallingAssembly ().GetName ().Name;
175 StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
176 return CreateInstance(assemblyName,
179 Activator.ConstructorDefault,
183 activationAttributes,
188 [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
189 static public Object CreateInstance(Type type, bool nonPublic)
191 if ((object)type == null)
192 throw new ArgumentNullException("type");
193 Contract.EndContractBlock();
195 RuntimeType rt = type.UnderlyingSystemType as RuntimeType;
198 throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "type");
200 StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
201 return rt.CreateInstanceDefaultCtor(!nonPublic, false, true, ref stackMark);
204 [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
205 static public T CreateInstance<T>()
207 RuntimeType rt = typeof(T) as RuntimeType;
209 // This is a hack to maintain compatibility with V2. Without this we would throw a NotSupportedException for void[].
210 // Array, Ref, and Pointer types don't have default constructors.
211 if (rt.HasElementType)
212 throw new MissingMethodException(Environment.GetResourceString("Arg_NoDefCTor"));
214 StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
216 // Skip the CreateInstanceCheckThis call to avoid perf cost and to maintain compatibility with V2 (throwing the same exceptions).
218 // In SL2/3 CreateInstance<T> doesn't do any security checks. This would mean that Assembly B can create instances of an internal
219 // type in Assembly A upon A's request:
220 // TypeInAssemblyA.DoWork() { AssemblyB.Create<InternalTypeInAssemblyA>();}
221 // TypeInAssemblyB.Create<T>() {return new T();}
222 // This violates type safety but we saw multiple user apps that have put a dependency on it. So for compatability we allow this if
223 // the SL app was built against SL2/3.
224 // Note that in SL2/3 it is possible for app code to instantiate public transparent types with public critical default constructors.
225 // Fortunately we don't have such types in out platform assemblies.
226 if (CompatibilitySwitches.IsAppEarlierThanSilverlight4 ||
227 CompatibilitySwitches.IsAppEarlierThanWindowsPhone8)
228 return (T)rt.CreateInstanceSlow(true /*publicOnly*/, true /*skipCheckThis*/, false /*fillCache*/, ref stackMark);
230 #endif // FEATURE_CORECLR
231 return (T)rt.CreateInstanceDefaultCtor(true /*publicOnly*/, true /*skipCheckThis*/, true /*fillCache*/, ref stackMark);
234 [ResourceExposure(ResourceScope.Machine)]
235 [ResourceConsumption(ResourceScope.Machine)]
236 static public ObjectHandle CreateInstanceFrom(String assemblyFile,
240 return CreateInstanceFrom(assemblyFile, typeName, null);
243 [ResourceExposure(ResourceScope.Machine)]
244 [ResourceConsumption(ResourceScope.Machine)]
245 static public ObjectHandle CreateInstanceFrom(String assemblyFile,
247 Object[] activationAttributes)
250 return CreateInstanceFrom(assemblyFile,
253 Activator.ConstructorDefault,
257 activationAttributes);
260 [System.Security.SecuritySafeCritical] // auto-generated
261 [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
262 [Obsolete("Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of CreateInstance which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
263 static public ObjectHandle CreateInstance(String assemblyName,
266 BindingFlags bindingAttr,
270 Object[] activationAttributes,
271 Evidence securityInfo)
274 if(assemblyName == null)
275 assemblyName = Assembly.GetCallingAssembly ().GetName ().Name;
277 StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
278 return CreateInstance(assemblyName,
285 activationAttributes,
290 [SecuritySafeCritical]
291 [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
292 public static ObjectHandle CreateInstance(string assemblyName,
295 BindingFlags bindingAttr,
299 object[] activationAttributes)
302 if(assemblyName == null)
303 assemblyName = Assembly.GetCallingAssembly ().GetName ().Name;
305 StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
306 return CreateInstance(assemblyName,
313 activationAttributes,
318 [System.Security.SecurityCritical] // auto-generated
319 static internal ObjectHandle CreateInstance(String assemblyString,
322 BindingFlags bindingAttr,
326 Object[] activationAttributes,
327 Evidence securityInfo,
328 ref StackCrawlMark stackMark)
330 #if FEATURE_CAS_POLICY
331 if (securityInfo != null && !AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled)
333 throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit"));
335 #endif // FEATURE_CAS_POLICY
337 Assembly assembly = null;
338 if (assemblyString == null) {
339 assembly = RuntimeAssembly.GetExecutingAssembly(ref stackMark);
341 RuntimeAssembly assemblyFromResolveEvent;
342 AssemblyName assemblyName = RuntimeAssembly.CreateAssemblyName(assemblyString, false /*forIntrospection*/, out assemblyFromResolveEvent);
343 if (assemblyFromResolveEvent != null) {
344 // Assembly was resolved via AssemblyResolve event
345 assembly = assemblyFromResolveEvent;
346 } else if (assemblyName.ContentType == AssemblyContentType.WindowsRuntime) {
347 // WinRT type - we have to use Type.GetType
348 type = Type.GetType(typeName + ", " + assemblyString, true /*throwOnError*/, ignoreCase);
350 // Classic managed type
351 assembly = RuntimeAssembly.InternalLoadAssemblyName(
352 assemblyName, securityInfo, null, ref stackMark,
353 true /*thrownOnFileNotFound*/, false /*forIntrospection*/, false /*suppressSecurityChecks*/);
358 // It's classic managed type (not WinRT type)
359 Log(assembly != null, "CreateInstance:: ", "Loaded " + assembly.FullName, "Failed to Load: " + assemblyString);
360 if(assembly == null) return null;
362 type = assembly.GetType(typeName, true /*throwOnError*/, ignoreCase);
365 Object o = Activator.CreateInstance(type,
370 activationAttributes);
372 Log(o != null, "CreateInstance:: ", "Created Instance of class " + typeName, "Failed to create instance of class " + typeName);
376 ObjectHandle Handle = new ObjectHandle(o);
381 [ResourceExposure(ResourceScope.Machine)]
382 [ResourceConsumption(ResourceScope.Machine)]
383 [Obsolete("Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of CreateInstanceFrom which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
384 static public ObjectHandle CreateInstanceFrom(String assemblyFile,
387 BindingFlags bindingAttr,
391 Object[] activationAttributes,
392 Evidence securityInfo)
395 #if FEATURE_CAS_POLICY
396 if (securityInfo != null && !AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled)
398 throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit"));
400 #endif // FEATURE_CAS_POLICY
402 return CreateInstanceFromInternal(assemblyFile,
409 activationAttributes,
413 [ResourceExposure(ResourceScope.Machine)]
414 [ResourceConsumption(ResourceScope.Machine)]
415 public static ObjectHandle CreateInstanceFrom(string assemblyFile,
418 BindingFlags bindingAttr,
422 object[] activationAttributes)
424 return CreateInstanceFromInternal(assemblyFile,
431 activationAttributes,
435 [ResourceExposure(ResourceScope.Machine)]
436 [ResourceConsumption(ResourceScope.Machine)]
437 private static ObjectHandle CreateInstanceFromInternal(String assemblyFile,
440 BindingFlags bindingAttr,
444 Object[] activationAttributes,
445 Evidence securityInfo)
447 #if FEATURE_CAS_POLICY
448 Contract.Assert(AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled || securityInfo == null);
449 #endif // FEATURE_CAS_POLICY
451 #pragma warning disable 618
452 Assembly assembly = Assembly.LoadFrom(assemblyFile, securityInfo);
453 #pragma warning restore 618
454 Type t = assembly.GetType(typeName, true, ignoreCase);
456 Object o = Activator.CreateInstance(t,
461 activationAttributes);
463 Log(o != null, "CreateInstanceFrom:: ", "Created Instance of class " + typeName, "Failed to create instance of class " + typeName);
467 ObjectHandle Handle = new ObjectHandle(o);
473 // This API is designed to be used when a host needs to execute code in an AppDomain
474 // with restricted security permissions. In that case, we demand in the client domain
475 // and assert in the server domain because the server domain might not be trusted enough
476 // to pass the security checks when activating the type.
479 [System.Security.SecurityCritical] // auto-generated_required
480 public static ObjectHandle CreateInstance (AppDomain domain, string assemblyName, string typeName) {
482 throw new ArgumentNullException("domain");
483 Contract.EndContractBlock();
484 return domain.InternalCreateInstanceWithNoSecurity(assemblyName, typeName);
487 [System.Security.SecurityCritical] // auto-generated_required
488 [Obsolete("Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of CreateInstance which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
489 public static ObjectHandle CreateInstance (AppDomain domain,
493 BindingFlags bindingAttr,
497 Object[] activationAttributes,
498 Evidence securityAttributes) {
500 throw new ArgumentNullException("domain");
501 Contract.EndContractBlock();
503 #if FEATURE_CAS_POLICY
504 if (securityAttributes != null && !AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled)
506 throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit"));
508 #endif // FEATURE_CAS_POLICY
510 return domain.InternalCreateInstanceWithNoSecurity(assemblyName, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes, securityAttributes);
514 public static ObjectHandle CreateInstance(AppDomain domain,
518 BindingFlags bindingAttr,
522 object[] activationAttributes)
525 throw new ArgumentNullException("domain");
526 Contract.EndContractBlock();
528 return domain.InternalCreateInstanceWithNoSecurity(assemblyName,
535 activationAttributes,
540 // This API is designed to be used when a host needs to execute code in an AppDomain
541 // with restricted security permissions. In that case, we demand in the client domain
542 // and assert in the server domain because the server domain might not be trusted enough
543 // to pass the security checks when activating the type.
546 [System.Security.SecurityCritical] // auto-generated_required
547 [ResourceExposure(ResourceScope.Machine)]
548 [ResourceConsumption(ResourceScope.Machine)]
549 public static ObjectHandle CreateInstanceFrom (AppDomain domain, string assemblyFile, string typeName) {
551 throw new ArgumentNullException("domain");
552 Contract.EndContractBlock();
553 return domain.InternalCreateInstanceFromWithNoSecurity(assemblyFile, typeName);
556 [System.Security.SecurityCritical] // auto-generated_required
557 [ResourceExposure(ResourceScope.Machine)]
558 [ResourceConsumption(ResourceScope.Machine)]
559 [Obsolete("Methods which use Evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of CreateInstanceFrom which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
560 public static ObjectHandle CreateInstanceFrom (AppDomain domain,
564 BindingFlags bindingAttr,
568 Object[] activationAttributes,
569 Evidence securityAttributes) {
571 throw new ArgumentNullException("domain");
572 Contract.EndContractBlock();
574 #if FEATURE_CAS_POLICY
575 if (securityAttributes != null && !AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled)
577 throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit"));
579 #endif // FEATURE_CAS_POLICY
581 return domain.InternalCreateInstanceFromWithNoSecurity(assemblyFile, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes, securityAttributes);
585 [ResourceExposure(ResourceScope.Machine)]
586 [ResourceConsumption(ResourceScope.Machine)]
587 public static ObjectHandle CreateInstanceFrom(AppDomain domain,
591 BindingFlags bindingAttr,
595 object[] activationAttributes)
598 throw new ArgumentNullException("domain");
599 Contract.EndContractBlock();
601 return domain.InternalCreateInstanceFromWithNoSecurity(assemblyFile,
608 activationAttributes,
611 #if FEATURE_COMINTEROP || MONO_COM || MOBILE_LEGACY
613 #if FEATURE_CLICKONCE || MOBILE_LEGACY
614 #if FEATURE_CLICKONCE || MONO_FEATURE_MULTIPLE_APPDOMAINS
615 [System.Security.SecuritySafeCritical] // auto-generated
616 public static ObjectHandle CreateInstance (ActivationContext activationContext) {
617 AppDomainManager domainManager = AppDomain.CurrentDomain.DomainManager;
618 if (domainManager == null)
619 domainManager = new AppDomainManager();
621 return domainManager.ApplicationActivator.CreateInstance(activationContext);
624 [System.Security.SecuritySafeCritical] // auto-generated
625 public static ObjectHandle CreateInstance (ActivationContext activationContext, string[] activationCustomData) {
626 AppDomainManager domainManager = AppDomain.CurrentDomain.DomainManager;
627 if (domainManager == null)
628 domainManager = new AppDomainManager();
630 return domainManager.ApplicationActivator.CreateInstance(activationContext, activationCustomData);
633 [Obsolete ("Activator.CreateInstance (ActivationContext) is not supported on this platform.", true)]
634 public static ObjectHandle CreateInstance (ActivationContext activationContext) {
635 throw new PlatformNotSupportedException ("Activator.CreateInstance (ActivationContext) is not supported on this platform.");
638 [Obsolete ("Activator.CreateInstance (ActivationContext, string[]) is not supported on this platform.", true)]
639 public static ObjectHandle CreateInstance (ActivationContext activationContext, string[] activationCustomData) {
640 throw new PlatformNotSupportedException ("Activator.CreateInstance (ActivationContext) is not supported on this platform.");
643 #endif // FEATURE_CLICKONCE
645 [ResourceExposure(ResourceScope.Machine)]
646 [ResourceConsumption(ResourceScope.Machine)]
647 public static ObjectHandle CreateComInstanceFrom(String assemblyName,
650 return CreateComInstanceFrom(assemblyName,
653 AssemblyHashAlgorithm.None);
657 [ResourceExposure(ResourceScope.Machine)]
658 [ResourceConsumption(ResourceScope.Machine)]
659 public static ObjectHandle CreateComInstanceFrom(String assemblyName,
662 AssemblyHashAlgorithm hashAlgorithm)
664 Assembly assembly = Assembly.LoadFrom(assemblyName, hashValue, hashAlgorithm);
666 Type t = assembly.GetType(typeName, true, false);
668 Object[] Attr = t.GetCustomAttributes(typeof(ComVisibleAttribute),false);
671 if (((ComVisibleAttribute)Attr[0]).Value == false)
672 throw new TypeLoadException(Environment.GetResourceString( "Argument_TypeMustBeVisibleFromCom" ));
675 Log(assembly != null, "CreateInstance:: ", "Loaded " + assembly.FullName, "Failed to Load: " + assemblyName);
677 if(assembly == null) return null;
680 Object o = Activator.CreateInstance(t,
681 Activator.ConstructorDefault,
687 Log(o != null, "CreateInstance:: ", "Created Instance of class " + typeName, "Failed to create instance of class " + typeName);
691 ObjectHandle Handle = new ObjectHandle(o);
695 #endif // FEATURE_COMINTEROP
697 #if FEATURE_REMOTING || MOBILE_LEGACY
698 // This method is a helper method and delegates to the remoting
699 // services to do the actual work.
700 [System.Security.SecurityCritical] // auto-generated_required
701 static public Object GetObject(Type type, String url)
703 return GetObject(type, url, null);
706 // This method is a helper method and delegates to the remoting
707 // services to do the actual work.
708 [System.Security.SecurityCritical] // auto-generated_required
709 static public Object GetObject(Type type, String url, Object state)
712 throw new ArgumentNullException("type");
713 Contract.EndContractBlock();
714 return RemotingServices.Connect(type, url, state);
718 [System.Diagnostics.Conditional("_DEBUG")]
719 private static void Log(bool test, string title, string success, string failure)
723 BCLDebug.Trace("REMOTE", "{0}{1}", title, success);
725 BCLDebug.Trace("REMOTE", "{0}{1}", title, failure);
730 void _Activator.GetTypeInfoCount(out uint pcTInfo)
732 throw new NotImplementedException();
735 void _Activator.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
737 throw new NotImplementedException();
740 void _Activator.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
742 throw new NotImplementedException();
745 // If you implement this method, make sure to include _Activator.Invoke in VM\DangerousAPIs.h and
746 // include _Activator in SystemDomain::IsReflectionInvocationMethod in AppDomain.cpp.
747 void _Activator.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
749 throw new NotImplementedException();