Exemplo n.º 1
0
        protected AssemblyDefinition ResolveOriginalsAssembly(string assemblyName)
        {
            var cleanAssemblyName = assemblyName;

            if (assemblyName.EndsWith(".exe") || assemblyName.EndsWith(".dll"))
            {
                cleanAssemblyName = Path.GetFileNameWithoutExtension(assemblyName);
            }
            return(_originalsResolver.Resolve(new AssemblyNameReference(cleanAssemblyName, null), _originalReaderParameters));
        }
Exemplo n.º 2
0
        AssemblyDefinition ResolveLinkedAssembly(string assemblyName)
        {
            var cleanAssemblyName = assemblyName;

            if (assemblyName.EndsWith(".exe") || assemblyName.EndsWith(".dll"))
            {
                cleanAssemblyName = System.IO.Path.GetFileNameWithoutExtension(assemblyName);
            }
            return(_linkedResolver.Resolve(new AssemblyNameReference(cleanAssemblyName, null), _readerParameters));
        }
Exemplo n.º 3
0
 private static void TryAddReference(BaseAssemblyResolver assemblyResolver, HashSet <string> assemblyLocations, List <MetadataReference> metadataReferences, string referenceName)
 {
     if (assemblyLocations.Add(referenceName))
     {
         try
         {
             metadataReferences.Add(CreateMetadataReference(assemblyResolver, assemblyResolver.Resolve(referenceName)));
         }
         catch (AssemblyResolutionException)
         {
         }
     }
 }
Exemplo n.º 4
0
        /// <summary>
        /// Generates the Mono.Cecil TypeReference from its .NET <see cref="Type"/> counterpart.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <param name="assemblyResolver">The assembly resolver.</param>
        /// <returns></returns>
        public static TypeReference GenerateTypeCecil(this Type type, BaseAssemblyResolver assemblyResolver)
        {
            var           assemblyDefinition = assemblyResolver.Resolve(type.Assembly.FullName);
            TypeReference typeReference;

            if (type.IsNested)
            {
                var declaringType = GenerateTypeCecil(type.DeclaringType, assemblyResolver);
                typeReference = declaringType.Resolve().NestedTypes.FirstOrDefault(x => x.Name == type.Name);
            }
            else if (type.IsArray)
            {
                var elementType = GenerateTypeCecil(type.GetElementType(), assemblyResolver);
                typeReference = new ArrayType(elementType, type.GetArrayRank());
            }
            else
            {
                typeReference = assemblyDefinition.MainModule.GetTypeResolved(type.IsGenericType ? type.GetGenericTypeDefinition().FullName : type.FullName);
            }

            if (typeReference == null)
            {
                throw new InvalidOperationException("Could not resolve cecil type.");
            }

            if (type.IsGenericType)
            {
                var genericInstanceType = new GenericInstanceType(typeReference);
                foreach (var argType in type.GetGenericArguments())
                {
                    TypeReference argTypeReference;
                    if (argType.IsGenericParameter)
                    {
                        argTypeReference = new GenericParameter(argType.Name, typeReference);
                    }
                    else
                    {
                        argTypeReference = GenerateTypeCecil(argType, assemblyResolver);
                    }
                    genericInstanceType.GenericArguments.Add(argTypeReference);
                }

                typeReference = genericInstanceType;
            }

            return(typeReference);
        }
        public static string GenerateBlackList(string librariesFolder, RuntimeClassRegistry usedClasses, string[] allAssemblies)
        {
            string text = "tmplink.xml";

            usedClasses.SynchronizeClasses();
            using (TextWriter textWriter = new StreamWriter(Path.Combine(librariesFolder, text)))
            {
                textWriter.WriteLine("<linker>");
                textWriter.WriteLine("<assembly fullname=\"UnityEngine\">");
                foreach (string current in usedClasses.GetAllManagedClassesAsString())
                {
                    textWriter.WriteLine(string.Format("<type fullname=\"UnityEngine.{0}\" preserve=\"{1}\"/>", current, usedClasses.GetRetentionLevel(current)));
                }
                textWriter.WriteLine("</assembly>");
                DefaultAssemblyResolver defaultAssemblyResolver = new DefaultAssemblyResolver();
                defaultAssemblyResolver.AddSearchDirectory(librariesFolder);
                for (int i = 0; i < allAssemblies.Length; i++)
                {
                    string path = allAssemblies[i];
                    BaseAssemblyResolver arg_CB_0     = defaultAssemblyResolver;
                    string           arg_CB_1         = Path.GetFileNameWithoutExtension(path);
                    ReaderParameters readerParameters = new ReaderParameters();
                    readerParameters.set_AssemblyResolver(defaultAssemblyResolver);
                    AssemblyDefinition assemblyDefinition = arg_CB_0.Resolve(arg_CB_1, readerParameters);
                    textWriter.WriteLine("<assembly fullname=\"{0}\">", assemblyDefinition.get_Name().get_Name());
                    if (assemblyDefinition.get_Name().get_Name().StartsWith("UnityEngine."))
                    {
                        foreach (string current2 in usedClasses.GetAllManagedClassesAsString())
                        {
                            textWriter.WriteLine(string.Format("<type fullname=\"UnityEngine.{0}\" preserve=\"{1}\"/>", current2, usedClasses.GetRetentionLevel(current2)));
                        }
                    }
                    MonoAssemblyStripping.GenerateBlackListTypeXML(textWriter, assemblyDefinition.get_MainModule().get_Types(), usedClasses.GetAllManagedBaseClassesAsString());
                    textWriter.WriteLine("</assembly>");
                }
                textWriter.WriteLine("</linker>");
            }
            return(text);
        }
        public static string GenerateLinkXmlToPreserveDerivedTypes(string stagingArea, string librariesFolder, RuntimeClassRegistry usedClasses)
        {
            string fullPath = Path.GetFullPath(Path.Combine(stagingArea, "preserved_derived_types.xml"));
            DefaultAssemblyResolver resolver = new DefaultAssemblyResolver();

            resolver.AddSearchDirectory(librariesFolder);
            using (TextWriter textWriter = new StreamWriter(fullPath))
            {
                textWriter.WriteLine("<linker>");
                foreach (AssemblyDefinition current in MonoAssemblyStripping.CollectAssembliesRecursive((from s in usedClasses.GetUserAssemblies()
                                                                                                         where usedClasses.IsDLLUsed(s)
                                                                                                         select s).Select(delegate(string file)
                {
                    BaseAssemblyResolver arg_1F_0 = resolver;
                    string arg_1F_1 = Path.GetFileNameWithoutExtension(file);
                    ReaderParameters readerParameters = new ReaderParameters();
                    readerParameters.set_AssemblyResolver(resolver);
                    return(arg_1F_0.Resolve(arg_1F_1, readerParameters));
                })))
                {
                    if (!(current.get_Name().get_Name() == "UnityEngine"))
                    {
                        HashSet <TypeDefinition> hashSet = new HashSet <TypeDefinition>();
                        MonoAssemblyStripping.CollectBlackListTypes(hashSet, current.get_MainModule().get_Types(), usedClasses.GetAllManagedBaseClassesAsString());
                        if (hashSet.Count != 0)
                        {
                            textWriter.WriteLine("<assembly fullname=\"{0}\">", current.get_Name().get_Name());
                            foreach (TypeDefinition current2 in hashSet)
                            {
                                textWriter.WriteLine("<type fullname=\"{0}\" preserve=\"all\"/>", current2.get_FullName());
                            }
                            textWriter.WriteLine("</assembly>");
                        }
                    }
                }
                textWriter.WriteLine("</linker>");
            }
            return(fullPath);
        }
Exemplo n.º 7
0
        public static AssemblyDefinition GenerateSerializationAssembly(PlatformType platformType, BaseAssemblyResolver assemblyResolver, AssemblyDefinition assembly, string serializationAssemblyLocation, string signKeyFile, List <string> serializatonProjectReferencePaths)
        {
            // Make sure all assemblies in serializatonProjectReferencePaths are referenced (sometimes they might be optimized out if no direct references)
            foreach (var serializatonProjectReferencePath in serializatonProjectReferencePaths)
            {
                var shortAssemblyName = Path.GetFileNameWithoutExtension(serializatonProjectReferencePath);

                // Still in references (not optimized)
                if (assembly.MainModule.AssemblyReferences.Any(x => x.Name == shortAssemblyName))
                {
                    continue;
                }

                // For now, use AssemblyDefinition.ReadAssembly to compute full name -- maybe not very efficient but it shouldn't happen often anyway)
                var referencedAssembly = AssemblyDefinition.ReadAssembly(serializatonProjectReferencePath);

                assembly.MainModule.AssemblyReferences.Add(AssemblyNameReference.Parse(referencedAssembly.FullName));
            }

            // Create the serializer code generator
            var serializerGenerator = new ComplexSerializerCodeGenerator(assemblyResolver, assembly);

            // Register default serialization profile (to help AOT generic instantiation of serializers)
            RegisterDefaultSerializationProfile(assemblyResolver, assembly, serializerGenerator);

            // Generate serializer code
            var serializerGeneratedCode = serializerGenerator.TransformText();

            var syntaxTree = CSharpSyntaxTree.ParseText(serializerGeneratedCode);

            // Add reference from source assembly
            // Use a hash set because it seems including twice mscorlib (2.0 and 4.0) seems to be a problem.
            var skipWindows = "Windows, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null";

            var compilerOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, allowUnsafe: true);

            // Sign the serialization assembly the same way the source was signed
            // TODO: Transmit over command line
            if (assembly.Name.HasPublicKey)
            {
                // TODO: If delay signed, we could actually extract the public key and apply it ourself maybe?
                if (signKeyFile == null)
                {
                    throw new InvalidOperationException("Generating serialization code for signed assembly, but no key was specified.");
                }

                compilerOptions = compilerOptions.WithCryptoKeyFile(signKeyFile).WithStrongNameProvider(new DesktopStrongNameProvider());
                if ((assembly.MainModule.Attributes & ModuleAttributes.StrongNameSigned) != ModuleAttributes.StrongNameSigned)
                {
                    // Delay signed
                    compilerOptions = compilerOptions.WithDelaySign(true);
                }
            }

            var metadataReferences = new List <MetadataReference>();
            var assemblyLocations  = new HashSet <string>();

            foreach (var referencedAssemblyName in assembly.MainModule.AssemblyReferences)
            {
                // We skip both Windows, and current assembly (AssemblyProcessor.Common, which might be added with an alias)
                if (referencedAssemblyName.FullName != skipWindows && referencedAssemblyName.FullName != typeof(ComplexSerializerGenerator).Assembly.FullName && referencedAssemblyName.FullName != "SiliconStudio.AssemblyProcessor")
                {
                    if (assemblyLocations.Add(referencedAssemblyName.Name))
                    {
                        //Console.WriteLine("Resolve Assembly for serialization [{0}]", referencedAssemblyName.FullName);
                        metadataReferences.Add(CreateMetadataReference(assemblyResolver, assemblyResolver.Resolve(referencedAssemblyName)));
                    }
                }
            }

            // typeof(Dictionary<,>)
            // Special case for 4.5: Because Dictionary<,> is forwarded, we need to add a reference to the actual assembly
            var mscorlibAssembly = CecilExtensions.FindCorlibAssembly(assembly);

            metadataReferences.Add(CreateMetadataReference(assemblyResolver, mscorlibAssembly));
            var collectionType = mscorlibAssembly.MainModule.GetTypeResolved(typeof(Dictionary <,>).FullName);

            metadataReferences.Add(CreateMetadataReference(assemblyResolver, collectionType.Module.Assembly));

            // Make sure System and System.Reflection are added
            // TODO: Maybe we should do that for .NETCore and PCL too? (instead of WinRT only)
            if (platformType == PlatformType.WindowsStore || platformType == PlatformType.WindowsPhone)
            {
                if (assemblyLocations.Add("System"))
                {
                    metadataReferences.Add(CreateMetadataReference(assemblyResolver, assemblyResolver.Resolve("System")));
                }
                if (assemblyLocations.Add("System.Reflection"))
                {
                    metadataReferences.Add(CreateMetadataReference(assemblyResolver, assemblyResolver.Resolve("System.Reflection")));
                }
            }

            metadataReferences.Add(CreateMetadataReference(assemblyResolver, assembly));
            assemblyLocations.Add(assembly.Name.Name);

            // In case Paradox.Framework.Serialization was not referenced, let's add it.
            if (!assemblyLocations.Contains("SiliconStudio.Core"))
            {
                metadataReferences.Add(CreateMetadataReference(assemblyResolver, assemblyResolver.Resolve("SiliconStudio.Core")));
                assemblyLocations.Add("SiliconStudio.Core");
            }

            // Create roslyn compilation object
            var assemblyName = Path.GetFileNameWithoutExtension(serializationAssemblyLocation);
            var compilation  = CSharpCompilation.Create(assemblyName, new[] { syntaxTree }, metadataReferences, compilerOptions);

            // Do the actual compilation, and check errors
            using (var peStream = new FileStream(serializationAssemblyLocation, FileMode.Create, FileAccess.Write))
            {
                var compilationResult = compilation.Emit(peStream);

                if (!compilationResult.Success)
                {
                    var errors = new StringBuilder();
                    errors.AppendLine(string.Format("Serialization assembly compilation: {0} error(s)", compilationResult.Diagnostics.Count(x => x.Severity >= DiagnosticSeverity.Error)));
                    foreach (var error in compilationResult.Diagnostics)
                    {
                        if (error.Severity >= DiagnosticSeverity.Warning)
                        {
                            errors.AppendLine(error.ToString());
                        }
                    }
                    throw new InvalidOperationException(errors.ToString());
                }
            }

            // Run ILMerge
            var merge = new ILRepacking.ILRepack()
            {
                OutputFile     = assembly.MainModule.FullyQualifiedName,
                DebugInfo      = true,
                CopyAttributes = true,
                AllowMultipleAssemblyLevelAttributes = true,
                XmlDocumentation          = false,
                NoRepackRes               = true,
                PrimaryAssemblyDefinition = assembly,
                WriteToDisk               = false,
                //KeepFirstOfMultipleAssemblyLevelAttributes = true,
                //Log = true,
                //LogFile = "ilmerge.log",
            };

            merge.SetInputAssemblies(new string[] { serializationAssemblyLocation });

            // Force to use the correct framework
            //merge.SetTargetPlatform("v4", frameworkFolder);
            merge.SetSearchDirectories(assemblyResolver.GetSearchDirectories());
            merge.Merge();

            // Copy name
            merge.TargetAssemblyDefinition.Name.Name    = assembly.Name.Name;
            merge.TargetAssemblyDefinition.Name.Version = assembly.Name.Version;

            // Add assembly signing info
            if (assembly.Name.HasPublicKey)
            {
                merge.TargetAssemblyDefinition.Name.PublicKey      = assembly.Name.PublicKey;
                merge.TargetAssemblyDefinition.Name.PublicKeyToken = assembly.Name.PublicKeyToken;
                merge.TargetAssemblyDefinition.Name.Attributes    |= AssemblyAttributes.PublicKey;
                if ((assembly.MainModule.Attributes & ModuleAttributes.StrongNameSigned) == ModuleAttributes.StrongNameSigned)
                {
                    merge.TargetAssemblyMainModule.Attributes |= ModuleAttributes.StrongNameSigned;
                }
            }

            try
            {
                // Delete serializer dll
                File.Delete(serializationAssemblyLocation);

                var serializationAssemblyPdbFilePath = Path.ChangeExtension(serializationAssemblyLocation, "pdb");
                if (File.Exists(serializationAssemblyPdbFilePath))
                {
                    File.Delete(serializationAssemblyPdbFilePath);
                }
            }
            catch (IOException)
            {
                // Mute IOException
            }

            return(merge.TargetAssemblyDefinition);
        }
Exemplo n.º 8
0
        public static AssemblyDefinition GenerateRoslynAssembly(BaseAssemblyResolver assemblyResolver, AssemblyDefinition assembly, string serializationAssemblyLocation, string signKeyFile, List <string> references, List <AssemblyDefinition> memoryReferences, ILogger log, IEnumerable <string> sourceCodes)
        {
            var syntaxTrees = sourceCodes.Select(x => CSharpSyntaxTree.ParseText(x));

            var compilerOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, allowUnsafe: true, assemblyIdentityComparer: DesktopAssemblyIdentityComparer.Default);

            // Sign the serialization assembly the same way the source was signed
            // TODO: Transmit over command line
            if (assembly.Name.HasPublicKey)
            {
                // TODO: If delay signed, we could actually extract the public key and apply it ourself maybe?
                if (signKeyFile == null)
                {
                    throw new InvalidOperationException("Generating serialization code for signed assembly, but no key was specified.");
                }

                compilerOptions = compilerOptions.WithCryptoKeyFile(signKeyFile).WithStrongNameProvider(new DesktopStrongNameProvider());
                if ((assembly.MainModule.Attributes & ModuleAttributes.StrongNameSigned) != ModuleAttributes.StrongNameSigned)
                {
                    // Delay signed
                    compilerOptions = compilerOptions.WithDelaySign(true);
                }
            }

            // Add references (files and in-memory PE data)
            var metadataReferences = new List <MetadataReference>();

            foreach (var reference in references)
            {
                metadataReferences.Add(MetadataReference.CreateFromFile(reference));
            }

            foreach (var reference in memoryReferences)
            {
                metadataReferences.Add(CreateMetadataReference(assemblyResolver, reference));
            }

            // typeof(Dictionary<,>)
            // Special case for 4.5: Because Dictionary<,> is forwarded, we need to add a reference to the actual assembly
            var mscorlibAssembly = CecilExtensions.FindCorlibAssembly(assembly);

            metadataReferences.Add(CreateMetadataReference(assemblyResolver, mscorlibAssembly));
            var collectionAssembly = CecilExtensions.FindCollectionsAssembly(assembly);

            metadataReferences.Add(CreateMetadataReference(assemblyResolver, collectionAssembly));
            metadataReferences.Add(CreateMetadataReference(assemblyResolver, assembly));

            // In case SiliconStudio.Core was not referenced, let's add it.
            if (assembly.Name.Name != "SiliconStudio.Core" && !references.Any(x => string.Compare(Path.GetFileNameWithoutExtension(x), "SiliconStudio.Core", StringComparison.OrdinalIgnoreCase) == 0))
            {
                metadataReferences.Add(CreateMetadataReference(assemblyResolver, assemblyResolver.Resolve("SiliconStudio.Core")));
            }

            // Create roslyn compilation object
            var assemblyName = assembly.Name.Name + ".Serializers";
            var compilation  = CSharpCompilation.Create(assemblyName, syntaxTrees, metadataReferences, compilerOptions);

            // Do the actual compilation, and check errors
            using (var peStream = new FileStream(serializationAssemblyLocation, FileMode.Create, FileAccess.Write))
            {
                var compilationResult = compilation.Emit(peStream);

                if (!compilationResult.Success)
                {
                    var errors = new StringBuilder();
                    errors.AppendLine(string.Format("Serialization assembly compilation: {0} error(s)", compilationResult.Diagnostics.Count(x => x.Severity >= DiagnosticSeverity.Error)));
                    foreach (var error in compilationResult.Diagnostics)
                    {
                        if (error.Severity >= DiagnosticSeverity.Warning)
                        {
                            errors.AppendLine(error.ToString());
                        }
                    }
                    throw new InvalidOperationException(errors.ToString());
                }
            }

            var repackOptions = new ILRepacking.RepackOptions(new string[0])
            {
                OutputFile     = assembly.MainModule.FullyQualifiedName,
                DebugInfo      = true,
                CopyAttributes = true,
                AllowMultipleAssemblyLevelAttributes = true,
                XmlDocumentation  = false,
                NoRepackRes       = true,
                InputAssemblies   = new[] { serializationAssemblyLocation },
                SearchDirectories = assemblyResolver.GetSearchDirectories(),
                SearchAssemblies  = references,
            };

            // Run ILMerge
            var merge = new ILRepacking.ILRepack(repackOptions)
            {
                PrimaryAssemblyDefinition = assembly,
                MemoryOnly = true,
                //KeepFirstOfMultipleAssemblyLevelAttributes = true,
                //Log = true,
                //LogFile = "ilmerge.log",
            };

            try
            {
                var consoleWriter = Console.Out;
                Console.SetOut(TextWriter.Null);

                try
                {
                    merge.Repack();
                }
                finally
                {
                    Console.SetOut(consoleWriter);
                }
            }
            catch (Exception)
            {
                log.Log(new LogMessage("ILRepack", LogMessageType.Error, string.Format("Error while ILRepacking {0}", assembly.Name.Name)));
                throw;
            }

            // Copy name
            merge.TargetAssemblyDefinition.Name.Name    = assembly.Name.Name;
            merge.TargetAssemblyDefinition.Name.Version = assembly.Name.Version;

            // Copy assembly characterics. This is necessary especially when targeting a windows app
            merge.TargetAssemblyMainModule.Characteristics = assembly.MainModule.Characteristics;

            // Add assembly signing info
            if (assembly.Name.HasPublicKey)
            {
                merge.TargetAssemblyDefinition.Name.PublicKey      = assembly.Name.PublicKey;
                merge.TargetAssemblyDefinition.Name.PublicKeyToken = assembly.Name.PublicKeyToken;
                merge.TargetAssemblyDefinition.Name.Attributes    |= AssemblyAttributes.PublicKey;
                if ((assembly.MainModule.Attributes & ModuleAttributes.StrongNameSigned) == ModuleAttributes.StrongNameSigned)
                {
                    merge.TargetAssemblyMainModule.Attributes |= ModuleAttributes.StrongNameSigned;
                }
            }

            try
            {
                // Delete serializer dll
                File.Delete(serializationAssemblyLocation);

                var serializationAssemblyPdbFilePath = Path.ChangeExtension(serializationAssemblyLocation, "pdb");
                if (File.Exists(serializationAssemblyPdbFilePath))
                {
                    File.Delete(serializationAssemblyPdbFilePath);
                }
            }
            catch (IOException)
            {
                // Mute IOException
            }

            return(merge.TargetAssemblyDefinition);
        }
Exemplo n.º 9
0
        public static AssemblyDefinition GenerateSerializationAssembly(PlatformType platformType, BaseAssemblyResolver assemblyResolver, AssemblyDefinition assembly, string serializationAssemblyLocation, string signKeyFile = null)
        {
            // Create the serializer code generator
            var serializerGenerator = new ComplexSerializerCodeGenerator(assemblyResolver, assembly);

            // Register default serialization profile (to help AOT generic instantiation of serializers)
            RegisterDefaultSerializationProfile(assemblyResolver, assembly, serializerGenerator);

            // Generate serializer code
            var serializerGeneratedCode = serializerGenerator.TransformText();

            var compilerParameters = new CompilerParameters();

            compilerParameters.IncludeDebugInformation = false;
            compilerParameters.GenerateInMemory        = false;
            compilerParameters.CompilerOptions         = "/nostdlib";
            compilerParameters.TreatWarningsAsErrors   = false;
            compilerParameters.TempFiles.KeepFiles     = false;
            //Console.WriteLine("Generating {0}", serializationAssemblyLocation);

            // Add reference from source assembly
            // Use a hash set because it seems including twice mscorlib (2.0 and 4.0) seems to be a problem.
            var skipWindows = "Windows, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null";

            // Sign the serialization assembly the same way the source was signed
            // TODO: Transmit over command line
            if (assembly.Name.HasPublicKey)
            {
                // TODO: If delay signed, we could actually extract the public key and apply it ourself maybe?
                if (signKeyFile == null)
                {
                    throw new InvalidOperationException("Generating serialization code for signed assembly, but no key was specified.");
                }

                var assemblyPath = Path.GetDirectoryName(assembly.MainModule.FullyQualifiedName);
                if ((assembly.MainModule.Attributes & ModuleAttributes.StrongNameSigned) == ModuleAttributes.StrongNameSigned)
                {
                    // Strongly signed
                    compilerParameters.CompilerOptions += string.Format(" /keyfile:\"{0}\"", signKeyFile);
                }
                else
                {
                    // Delay signed
                    compilerParameters.CompilerOptions += string.Format(" /delaysign+ /keyfile:\"{0}\"", signKeyFile);
                }
            }

            var assemblyLocations = new HashSet <string>();

            foreach (var referencedAssemblyName in assembly.MainModule.AssemblyReferences)
            {
                if (referencedAssemblyName.FullName != skipWindows)
                {
                    if (assemblyLocations.Add(referencedAssemblyName.Name))
                    {
                        //Console.WriteLine("Resolve Assembly for serialization [{0}]", referencedAssemblyName.FullName);
                        compilerParameters.ReferencedAssemblies.Add(assemblyResolver.Resolve(referencedAssemblyName).MainModule.FullyQualifiedName);
                    }
                }
            }

            // typeof(Dictionary<,>)
            // Special case for 4.5: Because Dictionary<,> is forwarded, we need to add a reference to the actual assembly
            var mscorlibAssembly = CecilExtensions.FindCorlibAssembly(assembly);

            compilerParameters.ReferencedAssemblies.Add(mscorlibAssembly.MainModule.FullyQualifiedName);
            var collectionType = mscorlibAssembly.MainModule.GetTypeResolved(typeof(Dictionary <,>).FullName);

            compilerParameters.ReferencedAssemblies.Add(collectionType.Module.FullyQualifiedName);

            // Make sure System and System.Reflection are added
            // TODO: Maybe we should do that for .NETCore and PCL too? (instead of WinRT only)
            if (platformType == PlatformType.WindowsStore || platformType == PlatformType.WindowsPhone)
            {
                if (assemblyLocations.Add("System"))
                {
                    compilerParameters.ReferencedAssemblies.Add(assemblyResolver.Resolve("System").MainModule.FullyQualifiedName);
                }
                if (assemblyLocations.Add("System.Reflection"))
                {
                    compilerParameters.ReferencedAssemblies.Add(assemblyResolver.Resolve("System.Reflection").MainModule.FullyQualifiedName);
                }
            }

            compilerParameters.ReferencedAssemblies.Add(assembly.MainModule.FullyQualifiedName);
            assemblyLocations.Add(assembly.Name.Name);

            // In case Paradox.Framework.Serialization was not referenced, let's add it.
            if (!assemblyLocations.Contains("SiliconStudio.Core"))
            {
                compilerParameters.ReferencedAssemblies.Add(assemblyResolver.Resolve("SiliconStudio.Core").MainModule.FullyQualifiedName);
            }

            compilerParameters.OutputAssembly = serializationAssemblyLocation;
            var compilerResults = codeDomProvider.CompileAssemblyFromSource(compilerParameters, serializerGeneratedCode);

            if (compilerResults.Errors.HasErrors)
            {
                var errors = new StringBuilder();
                errors.AppendLine(string.Format("Serialization assembly compilation: {0} error(s)", compilerResults.Errors.Count));
                foreach (var error in compilerResults.Errors)
                {
                    errors.AppendLine(error.ToString());
                }
                throw new InvalidOperationException(errors.ToString());
            }

            // Run ILMerge
            var merge = new ILRepacking.ILRepack()
            {
                OutputFile     = assembly.MainModule.FullyQualifiedName,
                DebugInfo      = true,
                CopyAttributes = true,
                AllowMultipleAssemblyLevelAttributes = true,
                XmlDocumentation          = false,
                NoRepackRes               = true,
                PrimaryAssemblyDefinition = assembly,
                WriteToDisk               = false,
                //KeepFirstOfMultipleAssemblyLevelAttributes = true,
                //Log = true,
                //LogFile = "ilmerge.log",
            };

            merge.SetInputAssemblies(new string[] { serializationAssemblyLocation });

            // Force to use the correct framework
            //merge.SetTargetPlatform("v4", frameworkFolder);
            merge.SetSearchDirectories(assemblyResolver.GetSearchDirectories());
            merge.Merge();

            // Add assembly signing info
            if (assembly.Name.HasPublicKey)
            {
                merge.TargetAssemblyDefinition.Name.PublicKey      = assembly.Name.PublicKey;
                merge.TargetAssemblyDefinition.Name.PublicKeyToken = assembly.Name.PublicKeyToken;
                merge.TargetAssemblyDefinition.Name.Attributes    |= AssemblyAttributes.PublicKey;
                if ((assembly.MainModule.Attributes & ModuleAttributes.StrongNameSigned) == ModuleAttributes.StrongNameSigned)
                {
                    merge.TargetAssemblyMainModule.Attributes |= ModuleAttributes.StrongNameSigned;
                }
            }

            try
            {
                // Delete serializer dll
                File.Delete(serializationAssemblyLocation);

                var serializationAssemblyPdbFilePath = Path.ChangeExtension(serializationAssemblyLocation, "pdb");
                if (File.Exists(serializationAssemblyPdbFilePath))
                {
                    File.Delete(serializationAssemblyPdbFilePath);
                }
            }
            catch (IOException)
            {
                // Mute IOException
            }

            return(merge.TargetAssemblyDefinition);
        }
Exemplo n.º 10
0
        static IEnumerable <AssemblyDefinition> FindDependendAssemblies(List <string> assemblyFullNames)
        {
            List <string> dependencies = new List <string>();

            foreach (var fullName in assemblyFullNames)
            {
                Debug("Loading {0} for dependency searching.", fullName);
                var assemblyDefinition = assemblyResolver.Resolve(fullName);
                var fileName           = assemblyDefinition.MainModule.FullyQualifiedName;
                dependencies.Add(assemblyDefinition.FullName);
                yield return(assemblyDefinition);
            }

            bool retry = false;

            do
            {
                retry = false;
                foreach (var searchDirectory in assemblyResolver.GetSearchDirectories())
                {
                    if (!Directory.Exists(searchDirectory))
                    {
                        continue;
                    }
                    foreach (var fileName in Directory.GetFiles(searchDirectory))
                    {
                        if ((!fileName.ToLower().EndsWith(".dll") &&
                             !fileName.ToLower().EndsWith(".exe")))
                        {
                            continue;
                        }
                        AssemblyDefinition assemblyDefinition = null;
                        try
                        {
                            assemblyDefinition = LoadAssemblyDefinition(fileName);
                        }
                        catch (BadImageFormatException exception)
                        {
                            Debug("Unable to load {0}: {1}", fileName, exception.Message);
                            continue;
                        }
                        catch (Exception exception)
                        {
                            Error("Unknown error while loading {0}: {1}", fileName, exception.ToString());
                            continue;
                        }
                        if (dependencies.Contains(assemblyDefinition.FullName))
                        {
                            continue;
                        }
                        foreach (var r in assemblyDefinition.MainModule.AssemblyReferences)
                        {
                            if (!dependencies.Contains(r.FullName))
                            {
                                continue;
                            }
                            retry = true;
                            dependencies.Add(assemblyDefinition.FullName);
                            yield return(assemblyDefinition);

                            break;
                        }
                    }
                }
            } while (retry);
        }