public SetPublicKey ( byte publicKey ) : void | ||
publicKey | byte | |
return | void |
public EmittedAssembly(string name, string rootNamespace, Version version, CultureInfo culture , byte[] publicKey, byte[] publicKeyToken) { Contracts.Require.IsNotNull("name", name); Contracts.Require.IsNotEmpty("name", name); Contracts.Require.IsNotNull("rootNamespace", rootNamespace); Contracts.Require.IsNotEmpty("rootNamespace", name); Contracts.Require.IsNotNull("version", version); Contracts.Require.IsNotNull("culture", culture); this._classes = new Dictionary<string, EmittedClass>(); this.RootNamespace = rootNamespace ?? name; _assemName = new AssemblyName(name); _assemName.Version = version; _assemName.CultureInfo = culture; _assemName.SetPublicKey(publicKey); _assemName.SetPublicKeyToken(publicKeyToken); #if DEBUG this._assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(_assemName, AssemblyBuilderAccess.RunAndSave); this._module = this._assembly.DefineDynamicModule(name, name + ".dll", false); #else this._assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(_assemName, AssemblyBuilderAccess.Run); this._module = this._assembly.DefineDynamicModule(name, name + ".dll", false); #endif }
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod internal Assembly?InternalGetSatelliteAssembly(CultureInfo culture, Version?version, bool throwOnFileNotFound) { var an = new AssemblyName(); an.SetPublicKey(GetPublicKey()); an.Flags = GetFlags() | AssemblyNameFlags.PublicKey; an.Version = version ?? GetVersion(); an.CultureInfo = culture; an.Name = GetSimpleName() + ".resources"; // This stack crawl mark is never used because the requesting assembly is explicitly specified, // so the value could be anything. StackCrawlMark unused = default; RuntimeAssembly?retAssembly = InternalLoad(an, ref unused, requestingAssembly: this, throwOnFileNotFound: throwOnFileNotFound); if (retAssembly == this) { retAssembly = null; } if (retAssembly == null && throwOnFileNotFound) { throw new FileNotFoundException(SR.Format(culture, SR.IO_FileNotFound_FileName, an.Name)); } return(retAssembly); }
// If the assembly is copied before it is loaded, the codebase will be set to the // actual file loaded if copiedName is true. If it is false, then the original code base // is returned. public override AssemblyName GetName(bool copiedName) { var an = new AssemblyName(); an.Name = GetSimpleName(); an.Version = GetVersion(); an.CultureInfo = GetLocale(); an.SetPublicKey(GetPublicKey()); an.RawFlags = GetFlags() | AssemblyNameFlags.PublicKey; #pragma warning disable IL3000 // System.Reflection.AssemblyName.CodeBase' always returns an empty string for assemblies embedded in a single-file app. an.CodeBase = GetCodeBase(); #pragma warning restore IL3000 #pragma warning disable SYSLIB0037 // AssemblyName.HashAlgorithm is obsolete an.HashAlgorithm = GetHashAlgorithm(); #pragma warning restore SYSLIB0037 Module manifestModule = ManifestModule; if (manifestModule.MDStreamVersion > 0x10000) { manifestModule.GetPEKind(out PortableExecutableKinds pek, out ImageFileMachine ifm); an.SetProcArchIndex(pek, ifm); } return(an); }
private static ModuleBuilder CreateProxyModule() { AssemblyName name = new AssemblyName("AutoMapper.Proxies"); name.SetPublicKey(privateKey); name.SetPublicKeyToken(privateKeyToken); //AssemblyBuilder builder = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run); AssemblyBuilder builder = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run); return builder.DefineDynamicModule("AutoMapper.Proxies.emit"); }
public void Case5_SetPublicKey() { AssemblyName n = new AssemblyName(); byte[] barray = new byte[16]; n.SetPublicKey(barray); byte[] barray_returned = n.GetPublicKey(); Assert.NotNull(barray_returned); Assert.True(isEqual(barray, barray_returned)); }
//See: https://stackoverflow.com/a/33277079 //This resolver method will ignore version, cultures and keys to make loading more reasonable. private static System.Reflection.Assembly GGDBFAssemblyResolver(System.Reflection.AssemblyName assemblyName) { assemblyName.Version = null; assemblyName.SetPublicKey(null); assemblyName.SetPublicKeyToken(null); assemblyName.CultureInfo = null; assemblyName.CultureName = null; return System.Reflection.Assembly.Load(assemblyName); }
public void Case6_SetPublicKey() { AssemblyName n = new AssemblyName(); byte[] barray = new byte[16]; for (int i = 0; i < barray.Length; i++) barray[i] = (byte)'\0'; n.SetPublicKey(barray); byte[] barray_returned = n.GetPublicKey(); Assert.NotNull(barray_returned); Assert.True(isEqual(barray, barray_returned)); }
internal AssemblyLoader(TypeProvider typeProvider, string filePath) { this.isLocalAssembly = false; this.typeProvider = typeProvider; if (!File.Exists(filePath)) { throw new FileNotFoundException(); } System.Reflection.AssemblyName assemblyName = System.Reflection.AssemblyName.GetAssemblyName(filePath); if (assemblyName != null) { ITypeResolutionService service = (ITypeResolutionService)typeProvider.GetService(typeof(ITypeResolutionService)); if (service != null) { try { this.assembly = service.GetAssembly(assemblyName); if ((((this.assembly == null) && (assemblyName.GetPublicKeyToken() != null)) && ((assemblyName.GetPublicKeyToken().GetLength(0) == 0) && (assemblyName.GetPublicKey() != null))) && (assemblyName.GetPublicKey().GetLength(0) == 0)) { System.Reflection.AssemblyName name = (System.Reflection.AssemblyName)assemblyName.Clone(); name.SetPublicKey(null); name.SetPublicKeyToken(null); this.assembly = service.GetAssembly(name); } } catch { } } if (this.assembly == null) { try { if (MultiTargetingInfo.MultiTargetingUtilities.IsFrameworkReferenceAssembly(filePath)) { this.assembly = System.Reflection.Assembly.Load(assemblyName.FullName); } else { this.assembly = System.Reflection.Assembly.Load(assemblyName); } } catch { } } } if (this.assembly == null) { this.assembly = System.Reflection.Assembly.LoadFrom(filePath); } }
internal RuntimeAssembly InternalGetSatelliteAssembly(String name, CultureInfo culture, Version version, bool throwOnFileNotFound, ref StackCrawlMark stackMark) { AssemblyName an = new AssemblyName(); an.SetPublicKey(GetPublicKey()); an.Flags = GetFlags() | AssemblyNameFlags.PublicKey; if (version == null) { an.Version = GetVersion(); } else { an.Version = version; } an.CultureInfo = culture; an.Name = name; Assembly assembly; try { assembly = AppDomain.CurrentDomain.LoadSatellite(an, false); if (assembly != null) { return((RuntimeAssembly)assembly); } } catch (FileNotFoundException) { assembly = null; // ignore } if (String.IsNullOrEmpty(Location)) { return(null); } // Try the assembly directory string location = Path.GetDirectoryName(Location); string fullName = Path.Combine(location, Path.Combine(culture.Name, an.Name + ".dll")); try { return((RuntimeAssembly)LoadFrom(fullName)); } catch { if (!throwOnFileNotFound && !File.Exists(fullName)) { return(null); } throw; } }
// Returns cached copy of the name. Caller has to create a clone before mutating the name. public AssemblyName GetName() { if (_assemblyName == null) { MetadataReader metadataReader = this.MetadataReader; AssemblyName an = new AssemblyName(); an.Name = metadataReader.GetString(_assemblyDefinition.Name); an.Version = _assemblyDefinition.Version; an.SetPublicKey(metadataReader.GetBlobBytes(_assemblyDefinition.PublicKey)); an.CultureName = metadataReader.GetString(_assemblyDefinition.Culture); an.ContentType = GetContentTypeFromAssemblyFlags(_assemblyDefinition.Flags); _assemblyName = an; } return _assemblyName; }
public static BuildManager Build(IBuildManager buildManager) { // Locate the MVC assembly var mvcAssembly = Assembly.GetAssembly(typeof(Controller)); // Locate the InternalsVisibleTo attribute and create a public key token that matches the one specified. var internalsVisisbleTo = mvcAssembly.GetCustomAttributes(typeof(InternalsVisibleToAttribute), true).Cast<InternalsVisibleToAttribute>().First(); var internalsVisisbleToAssemblyName = internalsVisisbleTo.AssemblyName.Split(",".ToCharArray())[0]; var internalsVisisbleToPublicKeyString = internalsVisisbleTo.AssemblyName.Split("=".ToCharArray())[1]; var internalsVisisbleToPublicKey = ToBytes(internalsVisisbleToPublicKeyString); // Get the domain of our current thread to host the new fake assembly var domain = Thread.GetDomain(); // Create a fake assembly name with the appropriate assembly name and public key token set var assemblyName = new AssemblyName(internalsVisisbleToAssemblyName); assemblyName.SetPublicKey(internalsVisisbleToPublicKey); // Define and host the assembly in the domain var assemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave); var moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName.Name, string.Format("{0}.dll", assemblyName.Name)); // Create a new type that inherits from our BuildManager class and implements the MVC IBuildManager interface var buildManagerInterface = mvcAssembly.GetType("System.Web.Mvc.IBuildManager", true); var buildManagerTypeBuilder = moduleBuilder.DefineType(Guid.NewGuid().ToString(), TypeAttributes.NotPublic | TypeAttributes.Class, typeof(BuildManager), new[] { buildManagerInterface }); var buildManagerTypeCtorBuilder = buildManagerTypeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.ExplicitThis | CallingConventions.HasThis, new[] { typeof(IBuildManager) }); buildManagerTypeCtorBuilder.DefineParameter(1, ParameterAttributes.None, "buildManager"); // Call the base constructor with the mocked IBuildManager interface var buildManagerTypeCtorEmitter = buildManagerTypeCtorBuilder.GetILGenerator(); buildManagerTypeCtorEmitter.Emit(OpCodes.Nop); buildManagerTypeCtorEmitter.Emit(OpCodes.Ldarg_0); buildManagerTypeCtorEmitter.Emit(OpCodes.Ldarg_1); buildManagerTypeCtorEmitter.Emit(OpCodes.Call, typeof(BuildManager).GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance).Single()); buildManagerTypeCtorEmitter.Emit(OpCodes.Ret); var buildManagerMockType = buildManagerTypeBuilder.CreateType(); // Magic! var buildManagerMock = Activator.CreateInstance(buildManagerMockType, new object[] { buildManager }) as BuildManager; return buildManagerMock; }
// CultureInfo is not portable. /// <summary> /// Converts this identity to <see cref="AssemblyName"/>. /// </summary> /// <returns>A new instance of <see cref="AssemblyName"/>.</returns> /// <exception cref="System.Globalization.CultureNotFoundException">The culture specified in <see cref="AssemblyIdentity.CultureName"/> is not available on the current platform.</exception> public static AssemblyName ToAssemblyName(this AssemblyIdentity identity) { var result = new AssemblyName(); result.Name = identity.Name; result.Version = identity.Version; result.Flags = identity.Flags; result.ContentType = identity.ContentType; result.CultureInfo = CultureInfo.GetCultureInfo(identity.CultureName); if (identity.PublicKey.Length > 0) { result.SetPublicKey(identity.PublicKey.ToArray()); } if (!identity.PublicKeyToken.IsDefault) { result.SetPublicKeyToken(identity.PublicKeyToken.ToArray()); } return result; }
private static AssemblyName CreateAssemblyName(MetadataName name, MetadataName culture, Version version, AssemblyNameFlags flags, byte[] publicKeyOrToken) { var result = new AssemblyName(); result.Name = name.ToString(); if (!culture.IsEmpty) { result.CultureInfo = new CultureInfo(culture.ToString()); } result.Version = version; result.Flags = flags; if (publicKeyOrToken.Length != 0) { if ((result.Flags & AssemblyNameFlags.PublicKey) != 0) { result.SetPublicKey(publicKeyOrToken); } else { result.SetPublicKeyToken(publicKeyOrToken); } } return result; }
private static RuntimeAssembly LoadWithPartialNameHack(string partialName, bool cropPublicKey) { StackCrawlMark lookForMyCaller = StackCrawlMark.LookForMyCaller; RuntimeAssembly assembly = null; AssemblyName name = new AssemblyName(partialName); if (!IsSimplyNamed(name)) { if (cropPublicKey) { name.SetPublicKey(null); name.SetPublicKeyToken(null); } AssemblyName assemblyRef = EnumerateCache(name); if (assemblyRef != null) { assembly = InternalLoadAssemblyName(assemblyRef, null, ref lookForMyCaller, false, false); } } return(assembly); }
private AssemblyName ConstructAssemblyName(IntPtr asmMetaPtr, char[] asmNameBuf, uint asmNameLength, IntPtr pubKeyPtr, uint pubKeyBytes, uint flags) { ASSEMBLYMETADATA assemblymetadata = (ASSEMBLYMETADATA) Marshal.PtrToStructure(asmMetaPtr, typeof(ASSEMBLYMETADATA)); AssemblyName name = new AssemblyName { Name = new string(asmNameBuf, 0, ((int) asmNameLength) - 1), Version = new Version(assemblymetadata.usMajorVersion, assemblymetadata.usMinorVersion, assemblymetadata.usBuildNumber, assemblymetadata.usRevisionNumber) }; string str = Marshal.PtrToStringUni(assemblymetadata.rpLocale); name.CultureInfo = new CultureInfo(str); if (pubKeyBytes > 0) { byte[] destination = new byte[pubKeyBytes]; Marshal.Copy(pubKeyPtr, destination, 0, (int) pubKeyBytes); if ((flags & 1) != 0) { name.SetPublicKey(destination); return name; } name.SetPublicKeyToken(destination); } return name; }
// // Copies a RuntimeAssemblyName into a freshly allocated AssemblyName with no data aliasing to any other object. // public void CopyToAssemblyName(AssemblyName blank) { blank.Name = this.Name; if (this.Version != null) { blank.Version = this.Version; } if (this.CultureName != null) { blank.CultureName = this.CultureName; } // Our "Flags" contain both the classic flags and the ProcessorArchitecture + ContentType bits. The public AssemblyName has separate properties for // these. The setters for these properties quietly mask out any bits intended for the other one, so we needn't do that ourselves.. blank.Flags = this.Flags.ExtractAssemblyNameFlags(); blank.ContentType = this.Flags.ExtractAssemblyContentType(); #pragma warning disable SYSLIB0037 // AssemblyName.ProcessorArchitecture is obsolete blank.ProcessorArchitecture = this.Flags.ExtractProcessorArchitecture(); #pragma warning restore SYSLIB0037 if (this.PublicKeyOrToken != null) { // We must not hand out our own copy of the PKT to AssemblyName as AssemblyName is amazingly trusting and gives untrusted callers // full freedom to scribble on its PKT array. (As do we but we only have trusted callers!) byte[] pkCopy = new byte[this.PublicKeyOrToken.Length]; ((ICollection <byte>)(this.PublicKeyOrToken)).CopyTo(pkCopy, 0); if (0 != (this.Flags & AssemblyNameFlags.PublicKey)) { blank.SetPublicKey(pkCopy); } else { blank.SetPublicKeyToken(pkCopy); } } return; }
/// <summary> /// Converts <see cref="IAssemblyName"/> to <see cref="AssemblyName"/> with possibly missing name components. /// </summary> /// <returns> /// An <see cref="AssemblyName"/> whose fields are be null if not present in <paramref name="nameObject"/>. /// </returns> internal static AssemblyName ToAssemblyName(FusionAssemblyIdentity.IAssemblyName nameObject) { var result = new AssemblyName(); result.Name = FusionAssemblyIdentity.GetName(nameObject); result.Version = FusionAssemblyIdentity.GetVersion(nameObject); var cultureName = FusionAssemblyIdentity.GetCulture(nameObject); result.CultureInfo = (cultureName != null) ? new CultureInfo(cultureName) : null; byte[] publicKey = FusionAssemblyIdentity.GetPublicKey(nameObject); if (publicKey != null && publicKey.Length != 0) { result.SetPublicKey(publicKey); } else { result.SetPublicKeyToken(FusionAssemblyIdentity.GetPublicKeyToken(nameObject)); } result.Flags = FusionAssemblyIdentity.GetFlags(nameObject); result.ContentType = FusionAssemblyIdentity.GetContentType(nameObject); return result; }
internal RuntimeAssembly InternalGetSatelliteAssembly(string name, CultureInfo culture, Version version, bool throwOnFileNotFound, ref StackCrawlMark stackMark) { AssemblyName fileName = new AssemblyName(); fileName.SetPublicKey(this.GetPublicKey()); fileName.Flags = this.GetFlags() | AssemblyNameFlags.PublicKey; if (version == null) { fileName.Version = this.GetVersion(); } else { fileName.Version = version; } fileName.CultureInfo = culture; fileName.Name = name; RuntimeAssembly assembly = nLoad(fileName, null, null, this, ref stackMark, throwOnFileNotFound, false, false); if (assembly == this) { throw new FileNotFoundException(string.Format(culture, Environment.GetResourceString("IO.FileNotFound_FileName"), new object[] { fileName.Name })); } return(assembly); }
internal RuntimeAssembly InternalGetSatelliteAssembly (String name, CultureInfo culture, Version version, bool throwOnFileNotFound, ref StackCrawlMark stackMark) { AssemblyName an = new AssemblyName (); an.SetPublicKey (GetPublicKey ()); an.Flags = GetFlags () | AssemblyNameFlags.PublicKey; if (version == null) an.Version = GetVersion (); else an.Version = version; an.CultureInfo = culture; an.Name = name; Assembly assembly; try { assembly = AppDomain.CurrentDomain.LoadSatellite (an, false); if (assembly != null) return (RuntimeAssembly)assembly; } catch (FileNotFoundException) { assembly = null; // ignore } if (String.IsNullOrEmpty (Location)) return null; // Try the assembly directory string location = Path.GetDirectoryName (Location); string fullName = Path.Combine (location, Path.Combine (culture.Name, an.Name + ".dll")); try { return (RuntimeAssembly)LoadFrom (fullName); } catch { if (!throwOnFileNotFound && !File.Exists (fullName)) return null; throw; } }
[System.Security.SecurityCritical] // auto-generated 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("name"); if (access != AssemblyBuilderAccess.Run #if !FEATURE_CORECLR && access != AssemblyBuilderAccess.Save && access != AssemblyBuilderAccess.RunAndSave #endif // !FEATURE_CORECLR #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), "access"); } if (securityContextSource < SecurityContextSource.CurrentAppDomain || securityContextSource > SecurityContextSource.CurrentAssembly) { throw new ArgumentOutOfRangeException("securityContextSource"); } // Clone the name in case the caller modifies it underneath us. name = (AssemblyName)name.Clone(); #if !FEATURE_CORECLR // Set the public key from the key pair if one has been provided. // (Overwite any public key in the Assembly name, since it's no // longer valid to have a disparity). if (name.KeyPair != null) name.SetPublicKey(name.KeyPair.PublicKey); #endif // 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 #if FEATURE_COLLECTIBLE_TYPES && !FEATURE_CORECLR // Collectible assemblies require FullTrust. This demand may be removed if we deem the // feature robust enough to be used directly by untrusted API consumers. if (access == AssemblyBuilderAccess.RunAndCollect) new PermissionSet(PermissionState.Unrestricted).Demand(); #endif // FEATURE_COLLECTIBLE_TYPES && !FEATURE_CORECLR // 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)) { #if !FEATURE_CORECLR SecurityCriticalScope scope = SecurityCriticalScope.Everything; if (attribute.m_constructorArgs != null && attribute.m_constructorArgs.Length == 1 && attribute.m_constructorArgs[0] is SecurityCriticalScope) { scope = (SecurityCriticalScope)attribute.m_constructorArgs[0]; } assemblyFlags |= DynamicAssemblyFlags.Critical; if (scope == SecurityCriticalScope.Everything) #endif // !FEATURE_CORECLR { assemblyFlags |= DynamicAssemblyFlags.AllCritical; } } #if !FEATURE_CORECLR else if (attribute.m_con.DeclaringType == typeof(SecurityRulesAttribute)) { securityRulesBlob = new byte[attribute.m_blob.Length]; Buffer.BlockCopy(attribute.m_blob, 0, securityRulesBlob, 0, securityRulesBlob.Length); } else if (attribute.m_con.DeclaringType == typeof(SecurityTreatAsSafeAttribute)) { assemblyFlags |= DynamicAssemblyFlags.TreatAsSafe; } #endif // !FEATURE_CORECLR #if FEATURE_APTCA else if (attribute.m_con.DeclaringType == typeof(AllowPartiallyTrustedCallersAttribute)) { assemblyFlags |= DynamicAssemblyFlags.Aptca; aptcaBlob = new byte[attribute.m_blob.Length]; Buffer.BlockCopy(attribute.m_blob, 0, aptcaBlob, 0, aptcaBlob.Length); } #endif // FEATURE_APTCA } #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); } }
internal AssemblyBuilder InternalDefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access, string dir, System.Security.Policy.Evidence evidence, PermissionSet requiredPermissions, PermissionSet optionalPermissions, PermissionSet refusedPermissions, ref StackCrawlMark stackMark, IEnumerable<CustomAttributeBuilder> unsafeAssemblyAttributes) { lock (typeof(AssemblyBuilderLock)) { AssemblyBuilder builder2; if (name == null) { throw new ArgumentNullException("name"); } if (((access != AssemblyBuilderAccess.Run) && (access != AssemblyBuilderAccess.Save)) && ((access != AssemblyBuilderAccess.RunAndSave) && (access != AssemblyBuilderAccess.ReflectionOnly))) { throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", new object[] { (int) access }), "access"); } if (name.KeyPair != null) { name.SetPublicKey(name.KeyPair.PublicKey); } if (evidence != null) { new SecurityPermission(SecurityPermissionFlag.ControlEvidence).Demand(); } List<CustomAttributeBuilder> list = null; DynamicAssemblyFlags none = DynamicAssemblyFlags.None; if (unsafeAssemblyAttributes != null) { list = new List<CustomAttributeBuilder>(unsafeAssemblyAttributes); foreach (CustomAttributeBuilder builder in list) { if (builder.m_con.DeclaringType == typeof(SecurityTransparentAttribute)) { none |= DynamicAssemblyFlags.Transparent; } } } builder2 = new AssemblyBuilder((AssemblyBuilder) this.nCreateDynamicAssembly(name, evidence, ref stackMark, requiredPermissions, optionalPermissions, refusedPermissions, access, none)) { m_assemblyData = new AssemblyBuilderData(builder2, name.Name, access, dir) }; builder2.m_assemblyData.AddPermissionRequests(requiredPermissions, optionalPermissions, refusedPermissions); if (list != null) { foreach (CustomAttributeBuilder builder3 in list) { builder2.SetCustomAttribute(builder3); } } builder2.m_assemblyData.GetInMemoryAssemblyModule(); return builder2; } }
// // Initializes the code generator // public bool Create (AppDomain domain, AssemblyBuilderAccess access) { ResolveAssemblySecurityAttributes (); var an = new AssemblyName (name); if (public_key != null && RootContext.Target != Target.Module) { if (delay_sign) { an.SetPublicKey (public_key); } else { if (public_key.Length == 16) { Report.Error (1606, "Could not sign the assembly. ECMA key can only be used to delay-sign assemblies"); } else if (private_key == null) { Error_AssemblySigning ("The specified key file does not have a private key"); } else { an.KeyPair = private_key; } } } try { Builder = file_name == null ? domain.DefineDynamicAssembly (an, access) : domain.DefineDynamicAssembly (an, access, Dirname (file_name)); } catch (ArgumentException) { // specified key may not be exportable outside it's container if (RootContext.StrongNameKeyContainer != null) { Report.Error (1548, "Could not access the key inside the container `" + RootContext.StrongNameKeyContainer + "'."); } throw; } builder_extra = new AssemblyBuilderExtension (Builder, Compiler); return true; }
internal RuntimeAssembly InternalGetSatelliteAssembly(string name, CultureInfo culture, Version version, bool throwOnFileNotFound, ref StackCrawlMark stackMark) { AssemblyName fileName = new AssemblyName(); fileName.SetPublicKey(this.GetPublicKey()); fileName.Flags = this.GetFlags() | AssemblyNameFlags.PublicKey; if (version == null) { fileName.Version = this.GetVersion(); } else { fileName.Version = version; } fileName.CultureInfo = culture; fileName.Name = name; RuntimeAssembly assembly = nLoad(fileName, null, null, this, ref stackMark, throwOnFileNotFound, false, false); if (assembly == this) { throw new FileNotFoundException(string.Format(culture, Environment.GetResourceString("IO.FileNotFound_FileName"), new object[] { fileName.Name })); } return assembly; }
private Assembly ProbeForPlatformSpecificAssembly() { AssemblyName assemblyName = new AssemblyName(GetType().GetTypeInfo().Assembly.FullName); assemblyName.Name = "MetroLog.Platform" ; Assembly assm = null; try { assm = _assemblyLoader(assemblyName); } catch (Exception) { // Try again without the SN for WP8 // HACK...no real strong name support here assemblyName.SetPublicKey(null); assemblyName.SetPublicKeyToken(null); try { assm = _assemblyLoader(assemblyName); } catch (Exception) { } } return assm; }
private static RuntimeAssembly LoadWithPartialNameHack(string partialName, bool cropPublicKey) { StackCrawlMark lookForMyCaller = StackCrawlMark.LookForMyCaller; RuntimeAssembly assembly = null; AssemblyName name = new AssemblyName(partialName); if (!IsSimplyNamed(name)) { if (cropPublicKey) { name.SetPublicKey(null); name.SetPublicKeyToken(null); } AssemblyName assemblyRef = EnumerateCache(name); if (assemblyRef != null) { assembly = InternalLoadAssemblyName(assemblyRef, null, ref lookForMyCaller, false, false); } } return assembly; }
// fix bug #56621 private void SetPublicKey (AssemblyName an, byte[] strongNameBlob) { try { // check for possible ECMA key if (strongNameBlob.Length == 16) { // will be rejected if not "the" ECMA key an.SetPublicKey (strongNameBlob); } else { // take it, with or without, a private key RSA rsa = CryptoConvert.FromCapiKeyBlob (strongNameBlob); // and make sure we only feed the public part to Sys.Ref byte[] publickey = CryptoConvert.ToCapiPublicKeyBlob (rsa); // AssemblyName.SetPublicKey requires an additional header byte[] publicKeyHeader = new byte [12] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x94, 0x00, 0x00, 0x00 }; byte[] encodedPublicKey = new byte [12 + publickey.Length]; Buffer.BlockCopy (publicKeyHeader, 0, encodedPublicKey, 0, 12); Buffer.BlockCopy (publickey, 0, encodedPublicKey, 12, publickey.Length); an.SetPublicKey (encodedPublicKey); } } catch (Exception) { Error_AssemblySigning ("The specified file `" + RootContext.StrongNameKeyFile + "' is incorrectly encoded"); Environment.Exit (1); } }
AssemblyName CreateAssemblyName(string outputFile) { var assemblyName = new AssemblyName(); assemblyName.Name = GetAssemblySimpleName(outputFile); assemblyName.Version = GetAssemblyVersion(); if (Parameters.DelaySign) assemblyName.SetPublicKey(GetAssemblyKeyPair(outputFile).PublicKey); else assemblyName.KeyPair = GetAssemblyKeyPair(outputFile); return assemblyName; }
internal Assembly InternalGetSatelliteAssembly(CultureInfo culture, Version version, bool throwOnFileNotFound) { if (culture == null) throw new ArgumentNullException("culture"); AssemblyName an = new AssemblyName(); an.SetPublicKey(nGetPublicKey()); an.Flags = nGetFlags() | AssemblyNameFlags.PublicKey; if (version == null) an.Version = GetVersion(); else an.Version = version; an.CultureInfo = culture; an.Name = nGetSimpleName() + ".resources"; StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; Assembly a = nLoad(an, null, false, null, throwOnFileNotFound, this, ref stackMark); if (a == this) { if (throwOnFileNotFound) throw new FileNotFoundException(String.Format(Environment.GetResourceString("IO.FileNotFound_FileName"), an.Name)); return null; } return a; }
public AssemblyBuilder DoProcess( Object typeLib, string asmFilename, TypeLibImporterFlags flags, ITypeLibImporterNotifySink notifySink, byte[] publicKey, StrongNameKeyPair keyPair, string asmNamespace, Version asmVersion, bool isVersion2, bool isPreserveSig, string ruleSetFileName) { m_resolver = notifySink; TypeLib tlb = new TypeLib((TypeLibTypes.Interop.ITypeLib)typeLib); if (asmNamespace == null) { asmNamespace = tlb.GetDocumentation(); string fileName = System.IO.Path.GetFileNameWithoutExtension(asmFilename); if (fileName != asmNamespace) asmNamespace = fileName; // // Support for GUID_ManagedName (for namespace) // string customManagedNamespace = tlb.GetCustData(CustomAttributeGuids.GUID_ManagedName) as string; if (customManagedNamespace != null) { customManagedNamespace = customManagedNamespace.Trim(); if (customManagedNamespace.ToUpper().EndsWith(".DLL")) customManagedNamespace = customManagedNamespace.Substring(0, customManagedNamespace.Length - 4); else if (customManagedNamespace.ToUpper().EndsWith(".EXE")) customManagedNamespace = customManagedNamespace.Substring(0, customManagedNamespace.Length - 4); asmNamespace = customManagedNamespace; } } // // Check for GUID_ExportedFromComPlus // object value = tlb.GetCustData(CustomAttributeGuids.GUID_ExportedFromComPlus); if (value != null) { // Make this a critical failure, instead of returning null which will be ignored. throw new TlbImpGeneralException(Resource.FormatString("Err_CircularImport", asmNamespace), ErrorCode.Err_CircularImport); } string strModuleName = asmFilename; if (asmFilename.Contains("\\")) { int nIndex; for (nIndex = strModuleName.Length; strModuleName[nIndex - 1] != '\\'; --nIndex) ; strModuleName = strModuleName.Substring(nIndex); } // If the version information was not specified, then retrieve it from the typelib. if (asmVersion == null) { using (TypeLibAttr attr = tlb.GetLibAttr()) { asmVersion = new Version(attr.wMajorVerNum, attr.wMinorVerNum, 0, 0); } } // Assembly name should not have .DLL // while module name must contain the .DLL string strAsmName = String.Copy(strModuleName); if (strAsmName.EndsWith(".DLL", StringComparison.InvariantCultureIgnoreCase)) strAsmName = strAsmName.Substring(0, strAsmName.Length - 4); AssemblyName assemblyName = new AssemblyName(); assemblyName.Name = strAsmName; assemblyName.SetPublicKey(publicKey); assemblyName.Version = asmVersion; assemblyName.KeyPair = keyPair; m_assemblyBuilder = CreateAssemblyBuilder(assemblyName, tlb, flags); m_moduleBuilder = CreateModuleBuilder(m_assemblyBuilder, strModuleName); // Add a listener for the reflection load only resolve events. AppDomain currentDomain = Thread.GetDomain(); ResolveEventHandler asmResolveHandler = ReflectionOnlyResolveAsmEvent; currentDomain.ReflectionOnlyAssemblyResolve += asmResolveHandler; ConverterSettings settings; settings.m_isGenerateClassInterfaces = true; settings.m_namespace = asmNamespace; settings.m_flags = flags; settings.m_isVersion2 = isVersion2; settings.m_isPreserveSig = isPreserveSig; RuleEngine.InitRuleEngine(new TlbImpActionManager(), new TlbImpCategoryManager(), new TlbImpConditionManager(), new TlbImpOperatorManager()); if (ruleSetFileName != null) { try { RuleFileParser parser = new RuleFileParser(ruleSetFileName); settings.m_ruleSet = parser.Parse(); } catch (Exception ex) { Output.WriteWarning(Resource.FormatString("Wrn_LoadRuleFileFailed", ruleSetFileName, ex.Message), WarningCode.Wrn_LoadRuleFileFailed); settings.m_ruleSet = null; } } else { settings.m_ruleSet = null; } m_converterInfo = new ConverterInfo(m_moduleBuilder, tlb, m_resolver, settings); // // Generate class interfaces // NOTE: // We have to create class interface ahead of time because of the need to convert default interfaces to // class interfafces. However, this creates another problem that the event interface is always named first // before the other interfaces, because we need to create the type builder for the event interface first // so that we can create a class interface that implement it. But in the previous version of TlbImp, // it doesn't have to do that because it can directly create a typeref with the class interface name, // without actually creating anything like the TypeBuilder. The result is that the name would be different // with interop assemblies generated by old tlbimp in this case. // Given the nature of reflection API, this cannot be easily workarounded unless we switch to metadata APIs. // I believe this is acceptable because this only happens when: // 1. People decide to migrate newer .NET framework // 2. The event interface name conflicts with a normal interface // // In this case the problem can be easily fixed with a global refactoring, so I wouldn't worry about that // if (m_converterInfo.GenerateClassInterfaces) { CreateClassInterfaces(); } // // Generate the remaining types except coclass // Because during creating coclass, we require every type, including all the referenced type to be created // This is a restriction of reflection API that when you override a method in parent interface, the method info // is needed so the type must be already created and loaded // var coclassList = new List<TypeInfo>(); int nCount = tlb.GetTypeInfoCount(); for (int n = 0; n < nCount; ++n) { try { TypeInfo type = tlb.GetTypeInfo(n); string strType = type.GetDocumentation(); using (TypeAttr attr = type.GetTypeAttr()) { TypeLibTypes.Interop.TYPEKIND kind = attr.typekind; TypeInfo typeToProcess; TypeAttr attrToProcess; if (kind == TypeLibTypes.Interop.TYPEKIND.TKIND_ALIAS) { ConvCommon.ResolveAlias(type, attr.tdescAlias, out typeToProcess, out attrToProcess); if (attrToProcess.typekind == TypeLibTypes.Interop.TYPEKIND.TKIND_ALIAS) { continue; } else { // We need to duplicate the definition of the user defined type in the name of the alias kind = attrToProcess.typekind; typeToProcess = type; attrToProcess = attr; } } else { typeToProcess = type; attrToProcess = attr; } switch (kind) { // Process coclass later because of reflection API requirements case TypeLibTypes.Interop.TYPEKIND.TKIND_COCLASS: coclassList.Add(typeToProcess); break; case TypeLibTypes.Interop.TYPEKIND.TKIND_ENUM: m_converterInfo.GetEnum(typeToProcess, attrToProcess); break; case TypeLibTypes.Interop.TYPEKIND.TKIND_DISPATCH: case TypeLibTypes.Interop.TYPEKIND.TKIND_INTERFACE: m_converterInfo.GetInterface(typeToProcess, attrToProcess); break; case TypeLibTypes.Interop.TYPEKIND.TKIND_MODULE: m_converterInfo.GetModule(typeToProcess, attrToProcess); break; case TypeLibTypes.Interop.TYPEKIND.TKIND_RECORD: m_converterInfo.GetStruct(typeToProcess, attrToProcess); break; case TypeLibTypes.Interop.TYPEKIND.TKIND_UNION: m_converterInfo.GetUnion(typeToProcess, attrToProcess); break; } m_converterInfo.ReportEvent( MessageCode.Msg_TypeInfoImported, Resource.FormatString("Msg_TypeInfoImported", typeToProcess.GetDocumentation())); } } catch (ReflectionTypeLoadException) { throw; // Fatal failure. Throw } catch (TlbImpResolveRefFailWrapperException) { throw; // Fatal failure. Throw } catch (TlbImpGeneralException) { throw; // Fatal failure. Throw } catch (TypeLoadException) { throw; // TypeLoadException is critical. Throw. } catch (Exception) { } } // Process coclass after processing all the other types foreach (TypeInfo type in coclassList) { using (TypeAttr attr = type.GetTypeAttr()) { try { m_converterInfo.GetCoClass(type, attr); } catch (ReflectionTypeLoadException) { throw; // Fatal failure. Throw } catch (TlbImpResolveRefFailWrapperException) { throw; // Fatal failure. Throw } catch (TlbImpGeneralException) { throw; // Fatal failure. Throw } catch (TypeLoadException) { throw; // TypeLoadException is critical. Throw. } catch (Exception) { } } } // // Build an array of EventItfInfo & generate event provider / event sink helpers // var eventAdapterGenerator = new Event.TCEAdapterGenerator(); var eventItfList = new List<Event.EventItfInfo>(); foreach (IConvBase symbol in m_converterInfo.GetAllConvBase) { var convInterface = symbol as IConvInterface; if (convInterface != null) { if (convInterface.EventInterface != null) { Debug.Assert(convInterface.EventInterface is ConvEventInterfaceLocal); var local = convInterface.EventInterface as ConvEventInterfaceLocal; Type eventInterfaceType = convInterface.EventInterface.ManagedType; // Build EventItfInfo and add to the list Type sourceInterfaceType = convInterface.ManagedType; string sourceInterfaceName = sourceInterfaceType.FullName; Event.EventItfInfo eventItfInfo = new Event.EventItfInfo( eventInterfaceType.FullName, sourceInterfaceName, local.EventProviderName, eventInterfaceType, convInterface.ManagedType); eventItfList.Add(eventItfInfo); } } } eventAdapterGenerator.Process(m_moduleBuilder, eventItfList); return m_assemblyBuilder; }
private int LoadAssemblyInternal (LuaState luaState) { try { string assemblyName = LuaLib.LuaToString (luaState, 1).ToString (); Assembly assembly = null; Exception exception = null; try { assembly = Assembly.Load (assemblyName); } catch (BadImageFormatException) { // The assemblyName was invalid. It is most likely a path. } catch (FileNotFoundException e) { exception = e; } #if !SILVERLIGHT if (assembly == null) { try { assembly = Assembly.Load (AssemblyName.GetAssemblyName (assemblyName)); } catch (FileNotFoundException e) { exception = e; } if (assembly == null) { AssemblyName mscor = assemblies [0].GetName (); AssemblyName name = new AssemblyName (); name.Name = assemblyName; name.CultureInfo = mscor.CultureInfo; name.Version = mscor.Version; name.SetPublicKeyToken (mscor.GetPublicKeyToken ()); name.SetPublicKey (mscor.GetPublicKey ()); assembly = Assembly.Load (name); if (assembly != null) exception = null; } if (exception != null) ThrowError (luaState, exception); } #endif if (assembly != null && !assemblies.Contains (assembly)) assemblies.Add (assembly); } catch (Exception e) { ThrowError (luaState, e); } return 0; }
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable private static unsafe RuntimeAssembly LoadWithPartialNameHack(String partialName, bool cropPublicKey) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; AssemblyName an = new AssemblyName(partialName); if (!IsSimplyNamed(an)) { if (cropPublicKey) { an.SetPublicKey(null); an.SetPublicKeyToken(null); } if(IsFrameworkAssembly(an) || !AppDomain.IsAppXModel()) { AssemblyName GACAssembly = EnumerateCache(an); if(GACAssembly != null) return InternalLoadAssemblyName(GACAssembly, null, null,ref stackMark, true /*thrownOnFileNotFound*/, false, false); else return null; } } if (AppDomain.IsAppXModel()) { // also try versionless bind from the package an.Version = null; return nLoad(an, null, null, null, ref stackMark, #if FEATURE_HOSTED_BINDER IntPtr.Zero, #endif false, false, false); } return null; }
// copied from /mcs/mcs/codegen.cs private void SetPublicKey (AssemblyName an, byte[] strongNameBlob) { // check for possible ECMA key if (strongNameBlob.Length == 16) { // will be rejected if not "the" ECMA key an.SetPublicKey (strongNameBlob); } else { // take it, with or without, a private key RSA rsa = CryptoConvert.FromCapiKeyBlob (strongNameBlob); // and make sure we only feed the public part to Sys.Ref byte[] publickey = CryptoConvert.ToCapiPublicKeyBlob (rsa); // AssemblyName.SetPublicKey requires an additional header byte[] publicKeyHeader = new byte [12] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x94, 0x00, 0x00, 0x00 }; byte[] encodedPublicKey = new byte [12 + publickey.Length]; Buffer.BlockCopy (publicKeyHeader, 0, encodedPublicKey, 0, 12); Buffer.BlockCopy (publickey, 0, encodedPublicKey, 12, publickey.Length); an.SetPublicKey (encodedPublicKey); } }
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable internal RuntimeAssembly InternalGetSatelliteAssembly(String name, CultureInfo culture, Version version, bool throwOnFileNotFound, ref StackCrawlMark stackMark) { AssemblyName an = new AssemblyName(); an.SetPublicKey(GetPublicKey()); an.Flags = GetFlags() | AssemblyNameFlags.PublicKey; if (version == null) an.Version = GetVersion(); else an.Version = version; an.CultureInfo = culture; an.Name = name; RuntimeAssembly retAssembly = null; #if !FEATURE_CORECLR bool bIsAppXDevMode = AppDomain.IsAppXDesignMode(); bool useRelativeBind = false; if (CodeAccessSecurityEngine.QuickCheckForAllDemands()) { if (IsFrameworkAssembly()) useRelativeBind = true; else useRelativeBind = UseRelativeBindForSatellites(); } if (bIsAppXDevMode || useRelativeBind) { if (GlobalAssemblyCache) { // lookup in GAC ArrayList a = new ArrayList(); bool bTryLoadAnyway = false; try { Fusion.ReadCache(a, an.FullName, ASM_CACHE.GAC); } catch(Exception e) { if (e.IsTransient) throw; // We also catch any other exception types we haven't come across yet, // not just UnauthorizedAccessException. // We do not want this by itself to cause us to fail to load resources. // On Classic, try the old unoptimized way, for full compatibility with 4.0. // i.e. fall back to using nLoad. if (!AppDomain.IsAppXModel()) bTryLoadAnyway = true; // On AppX: // Do not try nLoad since that would effectively allow Framework // resource satellite assemblies to be placed in AppX packages. // Instead, leave retAssembly == null. If we were called by the // ResourceManager, this will usually result in falling back to // the next culture in the resource fallback chain, possibly the // neutral culture. // Note: if throwOnFileNotFound is true, arbitrary // exceptions will be absorbed here and // FileNotFoundException will be thrown in their place. // (See below: "throw new FileNotFoundException"). } if (a.Count > 0 || bTryLoadAnyway) { // present in the GAC, load it from there retAssembly = nLoad(an, null, null, this, ref stackMark, #if FEATURE_HOSTED_BINDER IntPtr.Zero, #endif throwOnFileNotFound, false, false); } } else { String codeBase = CodeBase; if ((codeBase != null) && (String.Compare(codeBase, 0, s_localFilePrefix, 0, 5, StringComparison.OrdinalIgnoreCase) == 0)) { retAssembly = InternalProbeForSatelliteAssemblyNextToParentAssembly(an, name, codeBase, culture, throwOnFileNotFound, bIsAppXDevMode /* useLoadFile */, // if bIsAppXDevMode is false, then useRelativeBind is true. ref stackMark); if (retAssembly != null && !IsSimplyNamed(an)) { AssemblyName defName = retAssembly.GetName(); if (!AssemblyName.ReferenceMatchesDefinitionInternal(an,defName,false)) retAssembly = null; } } else if (!bIsAppXDevMode) { retAssembly = nLoad(an, null, null, this, ref stackMark, #if FEATURE_HOSTED_BINDER IntPtr.Zero, #endif throwOnFileNotFound, false, false); } } } else #endif // !FEATURE_CORECLR { retAssembly = nLoad(an, null, null, this, ref stackMark, #if FEATURE_HOSTED_BINDER IntPtr.Zero, #endif throwOnFileNotFound, false, false); } if (retAssembly == this || (retAssembly == null && throwOnFileNotFound)) { #if FEATURE_LEGACYNETCF if (CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) { if (retAssembly == this) { if (throwOnFileNotFound) throw new FileNotFoundException(); return null; } } #endif throw new FileNotFoundException(String.Format(culture, Environment.GetResourceString("IO.FileNotFound_FileName"), an.Name)); } return retAssembly; }
public void FromAssemblyDefinition() { var name = new AssemblyName("foo"); name.Flags = AssemblyNameFlags.Retargetable | AssemblyNameFlags.PublicKey | AssemblyNameFlags.EnableJITcompileOptimizer | AssemblyNameFlags.EnableJITcompileTracking; name.CultureInfo = new CultureInfo("en-US"); name.ContentType = AssemblyContentType.Default; name.Version = new Version(1, 2, 3, 4); name.ProcessorArchitecture = ProcessorArchitecture.X86; var id = AssemblyIdentity.FromAssemblyDefinition(name); Assert.Equal("foo", id.Name); Assert.True(id.IsRetargetable); Assert.Equal(new Version(1, 2, 3, 4), id.Version); Assert.Equal(AssemblyContentType.Default, id.ContentType); Assert.False(id.HasPublicKey); Assert.False(id.IsStrongName); name = new AssemblyName("foo"); name.SetPublicKey(PublicKey1); name.Version = new Version(1, 2, 3, 4); id = AssemblyIdentity.FromAssemblyDefinition(name); Assert.Equal("foo", id.Name); Assert.Equal(new Version(1, 2, 3, 4), id.Version); Assert.True(id.HasPublicKey); Assert.True(id.IsStrongName); AssertEx.Equal(id.PublicKey, PublicKey1); name = new AssemblyName("foo"); name.ContentType = AssemblyContentType.WindowsRuntime; id = AssemblyIdentity.FromAssemblyDefinition(name); Assert.Equal("foo", id.Name); Assert.Equal(AssemblyContentType.WindowsRuntime, id.ContentType); }
public void Case4_SetPublicKey() { AssemblyName n = new AssemblyName(); n.SetPublicKey(null); Assert.Null(n.GetPublicKey()); }
internal CompilerGlobals(VsaEngine engine, string assemName, string assemblyFileName, PEFileKinds PEFileKind, bool save, bool run, bool debugOn, bool isCLSCompliant, Version version, Globals globals) { string fileName = null; string dir = null; if (assemblyFileName != null) { try { dir = Path.GetDirectoryName(Path.GetFullPath(assemblyFileName)); } catch (Exception exception) { throw new JSVsaException(JSVsaError.AssemblyNameInvalid, assemblyFileName, exception); } fileName = Path.GetFileName(assemblyFileName); if ((assemName == null) || (string.Empty == assemName)) { assemName = Path.GetFileName(assemblyFileName); if (Path.HasExtension(assemName)) { assemName = assemName.Substring(0, assemName.Length - Path.GetExtension(assemName).Length); } } } if ((assemName == null) || (assemName == string.Empty)) { assemName = "JScriptAssembly"; } if (fileName == null) { if (PEFileKind == PEFileKinds.Dll) { fileName = "JScriptModule.dll"; } else { fileName = "JScriptModule.exe"; } } AssemblyName name = new AssemblyName { CodeBase = assemblyFileName }; if (globals.assemblyCulture != null) { name.CultureInfo = globals.assemblyCulture; } name.Flags = AssemblyNameFlags.None; if ((globals.assemblyFlags & AssemblyFlags.PublicKey) != AssemblyFlags.SideBySideCompatible) { name.Flags = AssemblyNameFlags.PublicKey; } AssemblyFlags flags = globals.assemblyFlags & AssemblyFlags.CompatibilityMask; if (flags == AssemblyFlags.NonSideBySideAppDomain) { name.VersionCompatibility = AssemblyVersionCompatibility.SameDomain; } else if (flags == AssemblyFlags.NonSideBySideProcess) { name.VersionCompatibility = AssemblyVersionCompatibility.SameProcess; } else if (flags == AssemblyFlags.NonSideBySideMachine) { name.VersionCompatibility = AssemblyVersionCompatibility.SameMachine; } else { name.VersionCompatibility = (AssemblyVersionCompatibility) 0; } name.HashAlgorithm = globals.assemblyHashAlgorithm; if (globals.assemblyKeyFileName != null) { try { using (FileStream stream = new FileStream(globals.assemblyKeyFileName, FileMode.Open, FileAccess.Read)) { StrongNameKeyPair pair = new StrongNameKeyPair(stream); if (globals.assemblyDelaySign) { if (stream.Length == 160L) { byte[] buffer = new byte[160]; stream.Seek(0L, SeekOrigin.Begin); stream.Read(buffer, 0, 160); name.SetPublicKey(buffer); } else { name.SetPublicKey(pair.PublicKey); } } else { byte[] publicKey = pair.PublicKey; name.KeyPair = pair; } } goto Label_024E; } catch { globals.assemblyKeyFileNameContext.HandleError(JSError.InvalidAssemblyKeyFile, globals.assemblyKeyFileName); goto Label_024E; } } if (globals.assemblyKeyName != null) { try { StrongNameKeyPair pair2 = new StrongNameKeyPair(globals.assemblyKeyName); byte[] buffer2 = pair2.PublicKey; name.KeyPair = pair2; } catch { globals.assemblyKeyNameContext.HandleError(JSError.InvalidAssemblyKeyFile, globals.assemblyKeyName); } } Label_024E: name.Name = assemName; if (version != null) { name.Version = version; } else if (globals.assemblyVersion != null) { name.Version = globals.assemblyVersion; } AssemblyBuilderAccess reflectionOnly = save ? (run ? AssemblyBuilderAccess.RunAndSave : AssemblyBuilderAccess.Save) : AssemblyBuilderAccess.Run; if (engine.ReferenceLoaderAPI == LoaderAPI.ReflectionOnlyLoadFrom) { reflectionOnly = AssemblyBuilderAccess.ReflectionOnly; } if (globals.engine.genStartupClass) { this.assemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(name, reflectionOnly, dir, globals.engine.Evidence); } else { this.assemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(name, reflectionOnly, dir); } if (save) { this.module = this.assemblyBuilder.DefineDynamicModule("JScript Module", fileName, debugOn); } else { this.module = this.assemblyBuilder.DefineDynamicModule("JScript Module", debugOn); } if (isCLSCompliant) { this.module.SetCustomAttribute(new CustomAttributeBuilder(clsCompliantAttributeCtor, new object[] { isCLSCompliant })); } if (debugOn) { ConstructorInfo constructor = Typeob.DebuggableAttribute.GetConstructor(new Type[] { Typeob.Boolean, Typeob.Boolean }); this.assemblyBuilder.SetCustomAttribute(new CustomAttributeBuilder(constructor, new object[] { (globals.assemblyFlags & AssemblyFlags.EnableJITcompileTracking) != AssemblyFlags.SideBySideCompatible, (globals.assemblyFlags & AssemblyFlags.DisableJITcompileOptimizer) != AssemblyFlags.SideBySideCompatible })); } this.compilationEvidence = globals.engine.Evidence; this.classwriter = null; }
public void Keys() { var an = new AssemblyName(); an.Name = "Foo"; an.Version = new Version(1, 0, 0, 0); an.SetPublicKey(PublicKey1); var anPkt = an.GetPublicKeyToken(); var aiPkt = AssemblyIdentity.CalculatePublicKeyToken(RoPublicKey1); AssertEx.Equal(PublicKeyToken1, anPkt); AssertEx.Equal(PublicKeyToken1, aiPkt); }
internal CompilerGlobals(VsaEngine engine, String assemName, String assemblyFileName, PEFileKinds PEFileKind, bool save, bool run, bool debugOn, bool isCLSCompliant, Version version, Globals globals) { String moduleFileName = null; String directory = null; //Default has assembly stored in current directory if (assemblyFileName != null){ //The directory is an absolute path where the assembly is written try{ directory = Path.GetDirectoryName(Path.GetFullPath(assemblyFileName)); }catch(Exception e){ throw new VsaException(VsaError.AssemblyNameInvalid, assemblyFileName, e); }catch{ throw new JScriptException(JSError.NonClsException); } //For a single file assembly module filename is set to assembly filename moduleFileName = Path.GetFileName(assemblyFileName); //If simple name is not specified, get it by extracting the basename from assembly name if (null == assemName || String.Empty == assemName){ assemName = Path.GetFileName(assemblyFileName); if (Path.HasExtension(assemName)) assemName = assemName.Substring(0, assemName.Length - Path.GetExtension(assemName).Length); } } //Setup default simple assembly name and module name for the case where no assemblyFileName is specified. if (assemName == null || assemName == String.Empty) assemName = "JScriptAssembly"; if (moduleFileName == null) { if (PEFileKind == PEFileKinds.Dll) moduleFileName = "JScriptModule.dll"; else moduleFileName = "JScriptModule.exe"; } AssemblyName assemblyName = new AssemblyName(); assemblyName.CodeBase = assemblyFileName; if (globals.assemblyCulture != null) assemblyName.CultureInfo = globals.assemblyCulture; assemblyName.Flags = AssemblyNameFlags.None; if ((globals.assemblyFlags & AssemblyFlags.PublicKey) != 0) assemblyName.Flags = AssemblyNameFlags.PublicKey; switch ((AssemblyFlags)(globals.assemblyFlags & AssemblyFlags.CompatibilityMask)){ case AssemblyFlags.NonSideBySideAppDomain: assemblyName.VersionCompatibility = AssemblyVersionCompatibility.SameDomain; break; case AssemblyFlags.NonSideBySideMachine: assemblyName.VersionCompatibility = AssemblyVersionCompatibility.SameMachine; break; case AssemblyFlags.NonSideBySideProcess: assemblyName.VersionCompatibility = AssemblyVersionCompatibility.SameProcess; break; default: assemblyName.VersionCompatibility = (AssemblyVersionCompatibility)0; break; } assemblyName.HashAlgorithm = globals.assemblyHashAlgorithm; if (globals.assemblyKeyFileName != null){ try { using (FileStream fs = new FileStream(globals.assemblyKeyFileName, FileMode.Open, FileAccess.Read)) { StrongNameKeyPair keyPair = new StrongNameKeyPair(fs); if (globals.assemblyDelaySign) if (fs.Length == 160) { Byte[] pkey = new Byte[160]; fs.Seek(0, SeekOrigin.Begin); int len = fs.Read(pkey, 0, 160); assemblyName.SetPublicKey(pkey); } else assemblyName.SetPublicKey(keyPair.PublicKey); else { // Fetch to force reflection to try and process the key file data and throw an exception byte[] publicKey = keyPair.PublicKey; assemblyName.KeyPair = keyPair; } } } catch { globals.assemblyKeyFileNameContext.HandleError(JSError.InvalidAssemblyKeyFile, globals.assemblyKeyFileName); } }else if (globals.assemblyKeyName != null){ try{ StrongNameKeyPair keyPair = new StrongNameKeyPair(globals.assemblyKeyName); byte[] publicKey = keyPair.PublicKey; // Force validation assemblyName.KeyPair = keyPair; }catch{ globals.assemblyKeyNameContext.HandleError(JSError.InvalidAssemblyKeyFile, globals.assemblyKeyName); } } assemblyName.Name = assemName; if (version != null) assemblyName.Version = version; else if (globals.assemblyVersion != null) assemblyName.Version = globals.assemblyVersion; AssemblyBuilderAccess access = save ? (run ? AssemblyBuilderAccess.RunAndSave : AssemblyBuilderAccess.Save) : AssemblyBuilderAccess.Run; if (engine.ReferenceLoaderAPI == LoaderAPI.ReflectionOnlyLoadFrom) access = AssemblyBuilderAccess.ReflectionOnly; // Supply the evidence to assemblies built for VSA if (globals.engine.genStartupClass) this.assemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(assemblyName, access, directory, globals.engine.Evidence); else this.assemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(assemblyName, access, directory); if (save) this.module = this.assemblyBuilder.DefineDynamicModule("JScript Module", moduleFileName, debugOn); else this.module = this.assemblyBuilder.DefineDynamicModule("JScript Module", debugOn); if (isCLSCompliant) this.module.SetCustomAttribute(new CustomAttributeBuilder(CompilerGlobals.clsCompliantAttributeCtor, new Object[]{isCLSCompliant})); if (debugOn){ ConstructorInfo debuggableAttr = Typeob.DebuggableAttribute.GetConstructor(new Type[] {Typeob.Boolean, Typeob.Boolean}); assemblyBuilder.SetCustomAttribute(new CustomAttributeBuilder(debuggableAttr, new Object[] {(globals.assemblyFlags & AssemblyFlags.EnableJITcompileTracking) != 0, (globals.assemblyFlags & AssemblyFlags.DisableJITcompileOptimizer) != 0})); } this.compilationEvidence = globals.engine.Evidence; this.classwriter = null; }