public static void GenerateDependencies(string strippedAssemblyDir, string icallsListFile, RuntimeClassRegistry rcr, out HashSet<string> nativeClasses, out HashSet<string> nativeModules)
 {
   string[] userAssemblies = CodeStrippingUtils.GetUserAssemblies(strippedAssemblyDir);
   nativeClasses = !PlayerSettings.stripEngineCode ? (HashSet<string>) null : CodeStrippingUtils.GenerateNativeClassList(rcr, strippedAssemblyDir, userAssemblies);
   if (nativeClasses != null)
     CodeStrippingUtils.ExcludeModuleManagers(ref nativeClasses);
   nativeModules = CodeStrippingUtils.GetNativeModulesToRegister(nativeClasses);
   if (nativeClasses != null && icallsListFile != null)
   {
     HashSet<string> modulesFromIcalls = CodeStrippingUtils.GetModulesFromICalls(icallsListFile);
     int classId = BaseObjectTools.StringToClassID("GlobalGameManager");
     using (HashSet<string>.Enumerator enumerator = modulesFromIcalls.GetEnumerator())
     {
       while (enumerator.MoveNext())
       {
         foreach (int moduleClass in ModuleMetadata.GetModuleClasses(enumerator.Current))
         {
           if (BaseObjectTools.IsDerivedFromClassID(moduleClass, classId))
             nativeClasses.Add(BaseObjectTools.ClassIDToString(moduleClass));
         }
       }
     }
     nativeModules.UnionWith((IEnumerable<string>) modulesFromIcalls);
   }
   new AssemblyReferenceChecker().CollectReferencesFromRoots(strippedAssemblyDir, (IEnumerable<string>) userAssemblies, true, 0.0f, true);
 }
        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];
                    AssemblyDefinition assemblyDefinition = defaultAssemblyResolver.Resolve(Path.GetFileNameWithoutExtension(path), new ReaderParameters
                    {
                        AssemblyResolver = defaultAssemblyResolver
                    });
                    textWriter.WriteLine("<assembly fullname=\"{0}\">", assemblyDefinition.Name.Name);
                    MonoAssemblyStripping.GenerateBlackListTypeXML(textWriter, assemblyDefinition.MainModule.Types, usedClasses.GetAllManagedBaseClassesAsString());
                    textWriter.WriteLine("</assembly>");
                }
                textWriter.WriteLine("</linker>");
            }
            return(text);
        }
Esempio n. 3
0
        private static HashSet <string> GenerateNativeClassList(RuntimeClassRegistry rcr, string directory, string[] rootAssemblies)
        {
            HashSet <string> set = CollectNativeClassListFromRoots(directory, rootAssemblies);

            foreach (string str in NativeClassBlackList)
            {
                set.Add(str);
            }
            foreach (string str2 in rcr.GetAllNativeClassesIncludingManagersAsString())
            {
                int iD = BaseObjectTools.StringToClassID(str2);
                if ((iD != -1) && !BaseObjectTools.IsBaseObject(iD))
                {
                    set.Add(str2);
                }
            }
            HashSet <string> set2 = new HashSet <string>();

            foreach (string str3 in set)
            {
                for (int i = BaseObjectTools.StringToClassID(str3); !BaseObjectTools.IsBaseObject(i); i = BaseObjectTools.GetSuperClassID(i))
                {
                    set2.Add(BaseObjectTools.ClassIDToString(i));
                }
            }
            return(set2);
        }
        public static void GenerateRegisterModules(RuntimeClassRegistry allClasses, TextWriter output, bool strippingEnabled)
        {
            allClasses.SynchronizeClasses();
            HashSet <string> modulesToRegister = CodeStrippingUtils.GetNativeModulesToRegister(!strippingEnabled ? (HashSet <string>)null : new HashSet <string>((IEnumerable <string>)allClasses.GetAllNativeClassesAsString()));

            modulesToRegister.Add("IMGUI");
            using (HashSet <string> .Enumerator enumerator = modulesToRegister.GetEnumerator())
            {
                while (enumerator.MoveNext())
                {
                    string current = enumerator.Current;
                    output.WriteLine("\textern \"C\" void RegisterModule_" + current + "();");
                }
            }
            output.WriteLine("void RegisterStaticallyLinkedModules()");
            output.WriteLine("{");
            using (HashSet <string> .Enumerator enumerator = modulesToRegister.GetEnumerator())
            {
                while (enumerator.MoveNext())
                {
                    string current = enumerator.Current;
                    output.WriteLine("\tRegisterModule_" + current + "();");
                }
            }
            output.WriteLine("}");
        }
 public static void WriteModuleAndClassRegistrationFile(string strippedAssemblyDir, string icallsListFile, string outputDir, RuntimeClassRegistry rcr, IEnumerable<string> classesToSkip)
 {
   HashSet<string> nativeClasses;
   HashSet<string> nativeModules;
   CodeStrippingUtils.GenerateDependencies(strippedAssemblyDir, icallsListFile, rcr, out nativeClasses, out nativeModules);
   CodeStrippingUtils.WriteModuleAndClassRegistrationFile(Path.Combine(outputDir, "UnityClassRegistration.cpp"), nativeModules, nativeClasses, new HashSet<string>(classesToSkip));
 }
		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];
					AssemblyDefinition assemblyDefinition = defaultAssemblyResolver.Resolve(Path.GetFileNameWithoutExtension(path), new ReaderParameters
					{
						AssemblyResolver = defaultAssemblyResolver
					});
					textWriter.WriteLine("<assembly fullname=\"{0}\">", assemblyDefinition.Name.Name);
					MonoAssemblyStripping.GenerateBlackListTypeXML(textWriter, assemblyDefinition.MainModule.Types, usedClasses.GetAllManagedBaseClassesAsString());
					textWriter.WriteLine("</assembly>");
				}
				textWriter.WriteLine("</linker>");
			}
			return text;
		}
Esempio n. 7
0
		public IL2CPPBuilder(string tempFolder, string stagingAreaData, IIl2CppPlatformProvider platformProvider, Action<string> modifyOutputBeforeCompile, RuntimeClassRegistry runtimeClassRegistry)
		{
			this.m_TempFolder = tempFolder;
			this.m_StagingAreaData = stagingAreaData;
			this.m_PlatformProvider = platformProvider;
			this.m_ModifyOutputBeforeCompile = modifyOutputBeforeCompile;
			this.m_RuntimeClassRegistry = runtimeClassRegistry;
		}
Esempio n. 8
0
        private static HashSet <string> GenerateNativeClassList(RuntimeClassRegistry rcr, string directory, string[] rootAssemblies, StrippingInfo strippingInfo)
        {
            HashSet <string> hashSet = CodeStrippingUtils.CollectNativeClassListFromRoots(directory, rootAssemblies, strippingInfo);

            string[] nativeClassBlackList = CodeStrippingUtils.NativeClassBlackList;
            for (int i = 0; i < nativeClassBlackList.Length; i++)
            {
                string text = nativeClassBlackList[i];
                hashSet.Add(text);
                if (strippingInfo != null)
                {
                    strippingInfo.RegisterDependency(text, "Blacklisted");
                }
            }
            foreach (string current in CodeStrippingUtils.NativeClassDependencyBlackList.Keys)
            {
                if (hashSet.Contains(current))
                {
                    string text2 = CodeStrippingUtils.NativeClassDependencyBlackList[current];
                    hashSet.Add(text2);
                    if (strippingInfo != null)
                    {
                        strippingInfo.RegisterDependency(text2, string.Format("Blacklisted due to dependent class '{0}'", current));
                    }
                }
            }
            foreach (string current2 in rcr.GetAllNativeClassesIncludingManagersAsString())
            {
                int num = BaseObjectTools.StringToClassID(current2);
                if (num != -1 && !BaseObjectTools.IsBaseObject(num))
                {
                    hashSet.Add(current2);
                    if (strippingInfo != null && !BaseObjectTools.IsDerivedFromClassID(num, CodeStrippingUtils.gameManagerClassId))
                    {
                        strippingInfo.RegisterDependency(current2, "Used in Scenes");
                    }
                }
            }
            HashSet <string> hashSet2 = new HashSet <string>();

            foreach (string current3 in hashSet)
            {
                int iD = BaseObjectTools.StringToClassID(current3);
                while (!BaseObjectTools.IsBaseObject(iD))
                {
                    hashSet2.Add(BaseObjectTools.ClassIDToString(iD));
                    int superClassID = BaseObjectTools.GetSuperClassID(iD);
                    if (strippingInfo != null)
                    {
                        strippingInfo.RegisterDependency(BaseObjectTools.ClassIDToString(superClassID), BaseObjectTools.ClassIDToString(iD));
                    }
                    iD = BaseObjectTools.GetSuperClassID(iD);
                }
            }
            return(hashSet2);
        }
Esempio n. 9
0
        private static HashSet <UnityType> GenerateNativeClassList(RuntimeClassRegistry rcr, string directory, string[] rootAssemblies, StrippingInfo strippingInfo)
        {
            if (AssemblyStripper.UseUnityLinkerEngineModuleStripping)
            {
                throw new NotSupportedException("Don't want to rely on this method when UnityLinker EMS is used");
            }

            HashSet <UnityType> nativeClasses = CollectNativeClassListFromRoots(directory, rootAssemblies, strippingInfo);

            // List native classes found in scenes
            foreach (string klassName in rcr.GetAllNativeClassesIncludingManagersAsString())
            {
                UnityType klass = UnityType.FindTypeByName(klassName);
                if (klass != null && klass.baseClass != null)
                {
                    nativeClasses.Add(klass);
                    if (strippingInfo != null)
                    {
                        if (!klass.IsDerivedFrom(GameManagerTypeInfo))
                        {
                            var scenes = rcr.GetScenesForClass(klass.persistentTypeID);
                            if (scenes != null)
                            {
                                foreach (var scene in scenes)
                                {
                                    strippingInfo.RegisterDependency(klassName, scene);
                                    if (scene.EndsWith(".unity"))
                                    {
                                        strippingInfo.SetIcon(scene, "class/SceneAsset");
                                    }
                                    else
                                    {
                                        strippingInfo.SetIcon(scene, "class/AssetBundle");
                                    }
                                }
                            }
                        }
                    }
                }
            }

            // Always include base classes of derived native classes.
            HashSet <UnityType> nativeClassesAndBaseClasses = new HashSet <UnityType>();

            foreach (var klass in nativeClasses)
            {
                var current = klass;
                while (current.baseClass != null)
                {
                    nativeClassesAndBaseClasses.Add(current);
                    current = current.baseClass;
                }
            }

            return(nativeClassesAndBaseClasses);
        }
Esempio n. 10
0
 public static void GenerateRegisterClassesForStripping(RuntimeClassRegistry allClasses, TextWriter output)
 {
     output.Write("void RegisterAllClasses() \n{\n");
     allClasses.SynchronizeClasses();
     foreach (string str in allClasses.GetAllNativeClassesAsString())
     {
         output.WriteLine(string.Format("extern int RegisterClass_{0}();\nRegisterClass_{0}();", str));
     }
     output.Write("\n}\n");
 }
        static public void Postprocess(BuildTargetGroup targetGroup, BuildTarget target, int subtarget, string installPath, string companyName, string productName,
                                       int width, int height, BuildOptions options,
                                       RuntimeClassRegistry usedClassRegistry, BuildReport report)
        {
            string stagingArea            = "Temp/StagingArea";
            string stagingAreaData        = "Temp/StagingArea/Data";
            string stagingAreaDataManaged = "Temp/StagingArea/Data/Managed";
            string playerPackage          = BuildPipeline.GetPlaybackEngineDirectory(target, options);

            // Disallow providing an empty string as the installPath
            bool willInstallInBuildFolder = (options & BuildOptions.InstallInBuildFolder) != 0 && SupportsInstallInBuildFolder(targetGroup, target);

            if (installPath == String.Empty && !willInstallInBuildFolder)
            {
                throw new Exception(installPath + " must not be an empty string");
            }

            IBuildPostprocessor postprocessor = ModuleManager.GetBuildPostProcessor(targetGroup, target);

            if (postprocessor != null)
            {
                BuildPostProcessArgs args;
                args.target                 = target;
                args.subtarget              = subtarget;
                args.stagingAreaData        = stagingAreaData;
                args.stagingArea            = stagingArea;
                args.stagingAreaDataManaged = stagingAreaDataManaged;
                args.playerPackage          = playerPackage;
                args.installPath            = installPath;
                args.companyName            = companyName;
                args.productName            = productName;
                args.productGUID            = PlayerSettings.productGUID;
                args.options                = options;
                args.usedClassRegistry      = usedClassRegistry;
                args.report                 = report;

                BuildProperties props;
                try
                {
                    postprocessor.PostProcess(args, out props);
                }
                catch (System.Exception e)
                {
                    // Rethrow exceptions during build postprocessing as BuildFailedException, so we don't pretend the build was fine.
                    throw new UnityEditor.Build.BuildFailedException(e);
                }
                report.AddAppendix(props);

                return;
            }

            // If postprocessor is not provided, build target is not supported
            throw new UnityException(string.Format("Build target '{0}' not supported", target));
        }
		public static void WriteModuleAndClassRegistrationFile(string strippedAssemblyDir, string outputDir, RuntimeClassRegistry rcr)
		{
			HashSet<string> hashSet = (PlayerSettings.strippingLevel != StrippingLevel.Disabled) ? CodeStrippingUtils.GenerateNativeClassList(rcr, strippedAssemblyDir, CodeStrippingUtils.GetUserAssemblies(strippedAssemblyDir)) : null;
			if (hashSet != null)
			{
				CodeStrippingUtils.ExcludeModuleManagers(ref hashSet);
			}
			HashSet<string> nativeModules = (hashSet != null) ? CodeStrippingUtils.GetRequiredStrippableModules(hashSet) : CodeStrippingUtils.GetAllStrippableModules();
			string file = Path.Combine(outputDir, "UnityClassRegistration.cpp");
			CodeStrippingUtils.WriteModuleAndClassRegistrationFile(file, nativeModules, hashSet);
		}
 public static void GenerateRegisterClassesForStripping(RuntimeClassRegistry allClasses, TextWriter output)
 {
     output.Write("void RegisterAllClasses() \n{\n");
     allClasses.SynchronizeClasses();
     using (List <string> .Enumerator enumerator = allClasses.GetAllNativeClassesAsString().GetEnumerator())
     {
         while (enumerator.MoveNext())
         {
             string current = enumerator.Current;
             output.WriteLine(string.Format("extern int RegisterClass_{0}();\nRegisterClass_{0}();", (object)current));
         }
     }
     output.Write("\n}\n");
 }
        public static string GenerateBlackList(string librariesFolder, RuntimeClassRegistry usedClasses, string[] allAssemblies)
        {
            string path2 = "tmplink.xml";

            usedClasses.SynchronizeClasses();
            using (TextWriter w = (TextWriter) new StreamWriter(Path.Combine(librariesFolder, path2)))
            {
                w.WriteLine("<linker>");
                w.WriteLine("<assembly fullname=\"UnityEngine\">");
                using (List <string> .Enumerator enumerator = usedClasses.GetAllManagedClassesAsString().GetEnumerator())
                {
                    while (enumerator.MoveNext())
                    {
                        string current = enumerator.Current;
                        w.WriteLine(string.Format("<type fullname=\"UnityEngine.{0}\" preserve=\"{1}\"/>", (object)current, (object)usedClasses.GetRetentionLevel(current)));
                    }
                }
                w.WriteLine("</assembly>");
                DefaultAssemblyResolver assemblyResolver1 = new DefaultAssemblyResolver();
                ((BaseAssemblyResolver)assemblyResolver1).AddSearchDirectory(librariesFolder);
                foreach (string allAssembly in allAssemblies)
                {
                    DefaultAssemblyResolver assemblyResolver2 = assemblyResolver1;
                    string           withoutExtension         = Path.GetFileNameWithoutExtension(allAssembly);
                    ReaderParameters readerParameters1        = new ReaderParameters();
                    readerParameters1.set_AssemblyResolver((IAssemblyResolver)assemblyResolver1);
                    ReaderParameters   readerParameters2  = readerParameters1;
                    AssemblyDefinition assemblyDefinition = ((BaseAssemblyResolver)assemblyResolver2).Resolve(withoutExtension, readerParameters2);
                    w.WriteLine("<assembly fullname=\"{0}\">", (object)((AssemblyNameReference)assemblyDefinition.get_Name()).get_Name());
                    if (((AssemblyNameReference)assemblyDefinition.get_Name()).get_Name().StartsWith("UnityEngine."))
                    {
                        using (List <string> .Enumerator enumerator = usedClasses.GetAllManagedClassesAsString().GetEnumerator())
                        {
                            while (enumerator.MoveNext())
                            {
                                string current = enumerator.Current;
                                w.WriteLine(string.Format("<type fullname=\"UnityEngine.{0}\" preserve=\"{1}\"/>", (object)current, (object)usedClasses.GetRetentionLevel(current)));
                            }
                        }
                    }
                    MonoAssemblyStripping.GenerateBlackListTypeXML(w, (IList <TypeDefinition>)assemblyDefinition.get_MainModule().get_Types(), usedClasses.GetAllManagedBaseClassesAsString());
                    w.WriteLine("</assembly>");
                }
                w.WriteLine("</linker>");
            }
            return(path2);
        }
Esempio n. 15
0
        public static void GenerateDependencies(string strippedAssemblyDir, RuntimeClassRegistry rcr, out HashSet <string> nativeClasses, out HashSet <string> nativeModules)
        {
            string[] userAssemblies = GetUserAssemblies(strippedAssemblyDir);
            nativeClasses = !PlayerSettings.stripEngineCode ? null : GenerateNativeClassList(rcr, strippedAssemblyDir, userAssemblies);
            if (nativeClasses != null)
            {
                ExcludeModuleManagers(ref nativeClasses);
            }
            nativeModules = GetNativeModulesToRegister(nativeClasses);
            AssemblyReferenceChecker checker = new AssemblyReferenceChecker();

            checker.CollectReferencesFromRoots(strippedAssemblyDir, userAssemblies, true, 0f, true);
            if (checker.HasDefinedMethod("OnGUI"))
            {
                nativeModules.Add("IMGUI");
            }
        }
Esempio n. 16
0
        private static HashSet <string> GenerateNativeClassList(RuntimeClassRegistry rcr, string directory, string[] rootAssemblies)
        {
            HashSet <string> stringSet1 = CodeStrippingUtils.CollectNativeClassListFromRoots(directory, rootAssemblies);

            foreach (string nativeClassBlack in CodeStrippingUtils.NativeClassBlackList)
            {
                stringSet1.Add(nativeClassBlack);
            }
            using (Dictionary <string, string> .KeyCollection.Enumerator enumerator = CodeStrippingUtils.NativeClassDependencyBlackList.Keys.GetEnumerator())
            {
                while (enumerator.MoveNext())
                {
                    string current = enumerator.Current;
                    if (stringSet1.Contains(current))
                    {
                        string classDependencyBlack = CodeStrippingUtils.NativeClassDependencyBlackList[current];
                        stringSet1.Add(classDependencyBlack);
                    }
                }
            }
            using (List <string> .Enumerator enumerator = rcr.GetAllNativeClassesIncludingManagersAsString().GetEnumerator())
            {
                while (enumerator.MoveNext())
                {
                    string current = enumerator.Current;
                    int    classId = BaseObjectTools.StringToClassID(current);
                    if (classId != -1 && !BaseObjectTools.IsBaseObject(classId))
                    {
                        stringSet1.Add(current);
                    }
                }
            }
            HashSet <string> stringSet2 = new HashSet <string>();

            using (HashSet <string> .Enumerator enumerator = stringSet1.GetEnumerator())
            {
                while (enumerator.MoveNext())
                {
                    for (int ID = BaseObjectTools.StringToClassID(enumerator.Current); !BaseObjectTools.IsBaseObject(ID); ID = BaseObjectTools.GetSuperClassID(ID))
                    {
                        stringSet2.Add(BaseObjectTools.ClassIDToString(ID));
                    }
                }
            }
            return(stringSet2);
        }
Esempio n. 17
0
        public static void GenerateRegisterModules(RuntimeClassRegistry allClasses, TextWriter output, bool strippingEnabled)
        {
            allClasses.SynchronizeClasses();
            HashSet <string> nativeClasses           = !strippingEnabled ? null : new HashSet <string>(allClasses.GetAllNativeClassesAsString());
            HashSet <string> nativeModulesToRegister = CodeStrippingUtils.GetNativeModulesToRegister(nativeClasses);

            nativeModulesToRegister.Add("IMGUI");
            foreach (string str in nativeModulesToRegister)
            {
                output.WriteLine("\textern \"C\" void RegisterModule_" + str + "();");
            }
            output.WriteLine("void RegisterStaticallyLinkedModules()");
            output.WriteLine("{");
            foreach (string str2 in nativeModulesToRegister)
            {
                output.WriteLine("\tRegisterModule_" + str2 + "();");
            }
            output.WriteLine("}");
        }
Esempio n. 18
0
        private static HashSet <string> GenerateNativeClassList(RuntimeClassRegistry rcr, string directory, string[] rootAssemblies)
        {
            HashSet <string> hashSet = CodeStrippingUtils.CollectNativeClassListFromRoots(directory, rootAssemblies);

            string[] nativeClassBlackList = CodeStrippingUtils.NativeClassBlackList;
            for (int i = 0; i < nativeClassBlackList.Length; i++)
            {
                string item = nativeClassBlackList[i];
                hashSet.Add(item);
            }
            foreach (string current in rcr.GetAllNativeClassesIncludingManagersAsString())
            {
                int num = BaseObjectTools.StringToClassID(current);
                if (num != -1 && !BaseObjectTools.IsBaseObject(num))
                {
                    hashSet.Add(current);
                }
            }
            return(hashSet);
        }
Esempio n. 19
0
        private static HashSet <string> GenerateNativeClassList(RuntimeClassRegistry rcr, string directory, string[] rootAssemblies)
        {
            HashSet <string> hashSet = CodeStrippingUtils.CollectNativeClassListFromRoots(directory, rootAssemblies);

            string[] nativeClassBlackList = CodeStrippingUtils.NativeClassBlackList;
            for (int i = 0; i < nativeClassBlackList.Length; i++)
            {
                string item = nativeClassBlackList[i];
                hashSet.Add(item);
            }
            foreach (string current in CodeStrippingUtils.NativeClassDependencyBlackList.Keys)
            {
                if (hashSet.Contains(current))
                {
                    string item2 = CodeStrippingUtils.NativeClassDependencyBlackList[current];
                    hashSet.Add(item2);
                }
            }
            foreach (string current2 in rcr.GetAllNativeClassesIncludingManagersAsString())
            {
                int num = BaseObjectTools.StringToClassID(current2);
                if (num != -1 && !BaseObjectTools.IsBaseObject(num))
                {
                    hashSet.Add(current2);
                }
            }
            HashSet <string> hashSet2 = new HashSet <string>();

            foreach (string current3 in hashSet)
            {
                int iD = BaseObjectTools.StringToClassID(current3);
                while (!BaseObjectTools.IsBaseObject(iD))
                {
                    hashSet2.Add(BaseObjectTools.ClassIDToString(iD));
                    iD = BaseObjectTools.GetSuperClassID(iD);
                }
            }
            return(hashSet2);
        }
        public static string GenerateBlackList(string librariesFolder, RuntimeClassRegistry usedClasses, string[] allAssemblies)
        {
            string str = "tmplink.xml";

            usedClasses.SynchronizeClasses();
            using (TextWriter writer = new StreamWriter(Path.Combine(librariesFolder, str)))
            {
                writer.WriteLine("<linker>");
                writer.WriteLine("<assembly fullname=\"UnityEngine\">");
                foreach (string str2 in usedClasses.GetAllManagedClassesAsString())
                {
                    writer.WriteLine(string.Format("<type fullname=\"UnityEngine.{0}\" preserve=\"{1}\"/>", str2, usedClasses.GetRetentionLevel(str2)));
                }
                writer.WriteLine("</assembly>");
                DefaultAssemblyResolver resolver = new DefaultAssemblyResolver();
                resolver.AddSearchDirectory(librariesFolder);
                foreach (string str3 in allAssemblies)
                {
                    ReaderParameters parameters = new ReaderParameters {
                        AssemblyResolver = resolver
                    };
                    AssemblyDefinition definition = resolver.Resolve(Path.GetFileNameWithoutExtension(str3), parameters);
                    writer.WriteLine("<assembly fullname=\"{0}\">", definition.Name.Name);
                    if (definition.Name.Name.StartsWith("UnityEngine."))
                    {
                        foreach (string str4 in usedClasses.GetAllManagedClassesAsString())
                        {
                            writer.WriteLine(string.Format("<type fullname=\"UnityEngine.{0}\" preserve=\"{1}\"/>", str4, usedClasses.GetRetentionLevel(str4)));
                        }
                    }
                    GenerateBlackListTypeXML(writer, definition.MainModule.Types, usedClasses.GetAllManagedBaseClassesAsString());
                    writer.WriteLine("</assembly>");
                }
                writer.WriteLine("</linker>");
            }
            return(str);
        }
Esempio n. 21
0
 public static string GenerateBlackList(string librariesFolder, RuntimeClassRegistry usedClasses, string[] allAssemblies)
 {
     string str = "tmplink.xml";
     usedClasses.SynchronizeClasses();
     using (TextWriter writer = new StreamWriter(Path.Combine(librariesFolder, str)))
     {
         writer.WriteLine("<linker>");
         writer.WriteLine("<assembly fullname=\"UnityEngine\">");
         foreach (string str2 in usedClasses.GetAllManagedClassesAsString())
         {
             writer.WriteLine(string.Format("<type fullname=\"UnityEngine.{0}\" preserve=\"{1}\"/>", str2, usedClasses.GetRetentionLevel(str2)));
         }
         writer.WriteLine("</assembly>");
         DefaultAssemblyResolver resolver = new DefaultAssemblyResolver();
         resolver.AddSearchDirectory(librariesFolder);
         foreach (string str3 in allAssemblies)
         {
             ReaderParameters parameters = new ReaderParameters {
                 AssemblyResolver = resolver
             };
             AssemblyDefinition definition = resolver.Resolve(Path.GetFileNameWithoutExtension(str3), parameters);
             writer.WriteLine("<assembly fullname=\"{0}\">", definition.Name.Name);
             if (definition.Name.Name.StartsWith("UnityEngine."))
             {
                 foreach (string str4 in usedClasses.GetAllManagedClassesAsString())
                 {
                     writer.WriteLine(string.Format("<type fullname=\"UnityEngine.{0}\" preserve=\"{1}\"/>", str4, usedClasses.GetRetentionLevel(str4)));
                 }
             }
             GenerateBlackListTypeXML(writer, definition.MainModule.Types, usedClasses.GetAllManagedBaseClassesAsString());
             writer.WriteLine("</assembly>");
         }
         writer.WriteLine("</linker>");
     }
     return str;
 }
 public static void ResolveDefinedNativeClassesFromMono(AssemblyDefinition[] assemblies, RuntimeClassRegistry res)
 {
     if (res == null)
     {
         return;
     }
     foreach (AssemblyDefinition assembly in assemblies)
     {
         using (Collection <TypeDefinition> .Enumerator enumerator = assembly.get_MainModule().get_Types().GetEnumerator())
         {
             // ISSUE: explicit reference operation
             while (((Collection <TypeDefinition> .Enumerator)@enumerator).MoveNext())
             {
                 // ISSUE: explicit reference operation
                 TypeDefinition current = ((Collection <TypeDefinition> .Enumerator)@enumerator).get_Current();
                 if (current.get_Fields().get_Count() > 0 || current.get_Methods().get_Count() > 0 || current.get_Properties().get_Count() > 0)
                 {
                     string name = ((TypeReference)current).get_Name();
                     res.AddMonoClass(name);
                 }
             }
         }
     }
 }
Esempio n. 23
0
 private static HashSet<string> GenerateNativeClassList(RuntimeClassRegistry rcr, string directory, string[] rootAssemblies)
 {
     HashSet<string> set = CollectNativeClassListFromRoots(directory, rootAssemblies);
     foreach (string str in NativeClassBlackList)
     {
         set.Add(str);
     }
     foreach (string str2 in rcr.GetAllNativeClassesIncludingManagersAsString())
     {
         int iD = BaseObjectTools.StringToClassID(str2);
         if ((iD != -1) && !BaseObjectTools.IsBaseObject(iD))
         {
             set.Add(str2);
         }
     }
     HashSet<string> set2 = new HashSet<string>();
     foreach (string str3 in set)
     {
         for (int i = BaseObjectTools.StringToClassID(str3); !BaseObjectTools.IsBaseObject(i); i = BaseObjectTools.GetSuperClassID(i))
         {
             set2.Add(BaseObjectTools.ClassIDToString(i));
         }
     }
     return set2;
 }
Esempio n. 24
0
        internal static BuildReport BuildPlayerData(BuildPlayerDataOptions buildPlayerDataOptions, out RuntimeClassRegistry usedClasses)
        {
            var result = BuildPlayerData(buildPlayerDataOptions);

            usedClasses = result.usedClasses;
            return(result.report);
        }
Esempio n. 25
0
        public static void Postprocess(BuildTarget target, string installPath, string companyName, string productName, int width, int height, string downloadWebplayerUrl, string manualDownloadWebplayerUrl, BuildOptions options, RuntimeClassRegistry usedClassRegistry)
        {
            string str1 = "Temp/StagingArea";
            string str2 = "Temp/StagingArea/Data";
            string str3 = "Temp/StagingArea/Data/Managed";
            string playbackEngineDirectory = BuildPipeline.GetPlaybackEngineDirectory(target, options);
            bool   flag = (options & BuildOptions.InstallInBuildFolder) != BuildOptions.None && PostprocessBuildPlayer.SupportsInstallInBuildFolder(target);

            if (installPath == string.Empty && !flag)
            {
                throw new Exception(installPath + " must not be an empty string");
            }
            IBuildPostprocessor buildPostProcessor = ModuleManager.GetBuildPostProcessor(target);

            if (buildPostProcessor != null)
            {
                BuildPostProcessArgs args;
                args.target                 = target;
                args.stagingAreaData        = str2;
                args.stagingArea            = str1;
                args.stagingAreaDataManaged = str3;
                args.playerPackage          = playbackEngineDirectory;
                args.installPath            = installPath;
                args.companyName            = companyName;
                args.productName            = productName;
                args.productGUID            = PlayerSettings.productGUID;
                args.options                = options;
                args.usedClassRegistry      = usedClassRegistry;
                buildPostProcessor.PostProcess(args);
            }
            else
            {
                switch (target)
                {
                case BuildTarget.WebPlayer:
                case BuildTarget.WebPlayerStreamed:
                    PostProcessWebPlayer.PostProcess(options, installPath, downloadWebplayerUrl, width, height);
                    break;

                default:
                    throw new UnityException(string.Format("Build target '{0}' not supported", (object)target));
                }
            }
        }
Esempio n. 26
0
        public static void WriteModuleAndClassRegistrationFile(string strippedAssemblyDir, string icallsListFile, string outputDir, RuntimeClassRegistry rcr, IEnumerable <string> classesToSkip)
        {
            HashSet <string> nativeClasses;
            HashSet <string> nativeModules;

            CodeStrippingUtils.GenerateDependencies(strippedAssemblyDir, icallsListFile, rcr, out nativeClasses, out nativeModules);
            CodeStrippingUtils.WriteModuleAndClassRegistrationFile(Path.Combine(outputDir, "UnityClassRegistration.cpp"), nativeModules, nativeClasses, new HashSet <string>(classesToSkip));
        }
 public static void ResolveDefinedNativeClassesFromMono(AssemblyDefinition[] assemblies, RuntimeClassRegistry res)
 {
   if (res == null)
     return;
   foreach (AssemblyDefinition assembly in assemblies)
   {
     using (Collection<TypeDefinition>.Enumerator enumerator = assembly.get_MainModule().get_Types().GetEnumerator())
     {
       // ISSUE: explicit reference operation
       while (((Collection<TypeDefinition>.Enumerator) @enumerator).MoveNext())
       {
         // ISSUE: explicit reference operation
         TypeDefinition current = ((Collection<TypeDefinition>.Enumerator) @enumerator).get_Current();
         if (current.get_Fields().get_Count() > 0 || current.get_Methods().get_Count() > 0 || current.get_Properties().get_Count() > 0)
         {
           string name = ((TypeReference) current).get_Name();
           res.AddMonoClass(name);
         }
       }
     }
   }
 }
		public static void MonoLink(BuildTarget buildTarget, string managedLibrariesDirectory, string[] input, string[] allAssemblies, RuntimeClassRegistry usedClasses)
		{
			Process process = MonoProcessUtility.PrepareMonoProcess(buildTarget, managedLibrariesDirectory);
			string buildToolsDirectory = BuildPipeline.GetBuildToolsDirectory(buildTarget);
			string text = null;
			string frameWorksFolder = MonoInstallationFinder.GetFrameWorksFolder();
			string text2 = Path.Combine(frameWorksFolder, MonoAssemblyStripping.StripperExe());
			string text3 = Path.Combine(Path.GetDirectoryName(text2), "link.xml");
			string text4 = Path.Combine(managedLibrariesDirectory, "output");
			Directory.CreateDirectory(text4);
			process.StartInfo.Arguments = "\"" + text2 + "\" -l none -c link";
			for (int i = 0; i < input.Length; i++)
			{
				string str = input[i];
				ProcessStartInfo expr_80 = process.StartInfo;
				expr_80.Arguments = expr_80.Arguments + " -a \"" + str + "\"";
			}
			ProcessStartInfo expr_B3 = process.StartInfo;
			string arguments = expr_B3.Arguments;
			expr_B3.Arguments = string.Concat(new string[]
			{
				arguments,
				" -out output -x \"",
				text3,
				"\" -d \"",
				managedLibrariesDirectory,
				"\""
			});
			string text5 = Path.Combine(buildToolsDirectory, "link.xml");
			if (File.Exists(text5))
			{
				ProcessStartInfo expr_110 = process.StartInfo;
				expr_110.Arguments = expr_110.Arguments + " -x \"" + text5 + "\"";
			}
			string text6 = Path.Combine(Path.GetDirectoryName(text2), "native_link.xml");
			if (File.Exists(text6))
			{
				ProcessStartInfo expr_151 = process.StartInfo;
				expr_151.Arguments = expr_151.Arguments + " -x \"" + text6 + "\"";
			}
			string[] files = Directory.GetFiles(Path.Combine(Directory.GetCurrentDirectory(), "Assets"), "link.xml", SearchOption.AllDirectories);
			string[] array = files;
			for (int j = 0; j < array.Length; j++)
			{
				string str2 = array[j];
				ProcessStartInfo expr_1A2 = process.StartInfo;
				expr_1A2.Arguments = expr_1A2.Arguments + " -x \"" + str2 + "\"";
			}
			if (usedClasses != null)
			{
				text = MonoAssemblyStripping.GenerateBlackList(managedLibrariesDirectory, usedClasses, allAssemblies);
				ProcessStartInfo expr_1E6 = process.StartInfo;
				expr_1E6.Arguments = expr_1E6.Arguments + " -x \"" + text + "\"";
			}
			MonoProcessUtility.RunMonoProcess(process, "assemblies stripper", Path.Combine(text4, "mscorlib.dll"));
			MonoAssemblyStripping.DeleteAllDllsFrom(managedLibrariesDirectory);
			MonoAssemblyStripping.CopyAllDlls(managedLibrariesDirectory, text4);
			string[] files2 = Directory.GetFiles(managedLibrariesDirectory);
			for (int k = 0; k < files2.Length; k++)
			{
				string text7 = files2[k];
				if (text7.Contains(".mdb"))
				{
					string path = text7.Replace(".mdb", string.Empty);
					if (!File.Exists(path))
					{
						FileUtil.DeleteFileOrDirectory(text7);
					}
				}
			}
			if (text != null)
			{
				FileUtil.DeleteFileOrDirectory(Path.Combine(managedLibrariesDirectory, text));
			}
			FileUtil.DeleteFileOrDirectory(text4);
		}
 public static void GenerateRegisterClassesForStripping(RuntimeClassRegistry allClasses, TextWriter output)
 {
   output.Write("void RegisterAllClasses() \n{\n");
   allClasses.SynchronizeClasses();
   using (List<string>.Enumerator enumerator = allClasses.GetAllNativeClassesAsString().GetEnumerator())
   {
     while (enumerator.MoveNext())
     {
       string current = enumerator.Current;
       output.WriteLine(string.Format("extern int RegisterClass_{0}();\nRegisterClass_{0}();", (object) current));
     }
   }
   output.Write("\n}\n");
 }
 private static List<string> GetUserAssemblies(RuntimeClassRegistry rcr, string managedDir)
 {
   // ISSUE: object of a compiler-generated type is created
   // ISSUE: variable of a compiler-generated type
   AssemblyStripper.\u003CGetUserAssemblies\u003Ec__AnonStorey66 assembliesCAnonStorey66 = new AssemblyStripper.\u003CGetUserAssemblies\u003Ec__AnonStorey66();
   // ISSUE: reference to a compiler-generated field
   assembliesCAnonStorey66.rcr = rcr;
   // ISSUE: reference to a compiler-generated field
   assembliesCAnonStorey66.managedDir = managedDir;
   // ISSUE: reference to a compiler-generated field
   // ISSUE: reference to a compiler-generated method
   // ISSUE: reference to a compiler-generated method
   return ((IEnumerable<string>) assembliesCAnonStorey66.rcr.GetUserAssemblies()).Where<string>(new Func<string, bool>(assembliesCAnonStorey66.\u003C\u003Em__D9)).Select<string, string>(new Func<string, string>(assembliesCAnonStorey66.\u003C\u003Em__DA)).ToList<string>();
 }
 internal static void StripAssemblies(string stagingAreaData, IIl2CppPlatformProvider platformProvider, RuntimeClassRegistry rcr, bool developmentBuild)
 {
   string fullPath = Path.GetFullPath(Path.Combine(stagingAreaData, "Managed"));
   List<string> userAssemblies = AssemblyStripper.GetUserAssemblies(rcr, fullPath);
   string[] array = userAssemblies.ToArray();
   string[] searchDirs = new string[1]{ fullPath };
   AssemblyStripper.RunAssemblyStripper(stagingAreaData, (IEnumerable) userAssemblies, fullPath, array, searchDirs, AssemblyStripper.MonoLinker2Path, platformProvider, rcr, developmentBuild);
 }
Esempio n. 32
0
		internal static IL2CPPBuilder RunIl2Cpp(string stagingAreaData, IIl2CppPlatformProvider platformProvider, Action<string> modifyOutputBeforeCompile, RuntimeClassRegistry runtimeClassRegistry)
		{
			IL2CPPBuilder iL2CPPBuilder = new IL2CPPBuilder(stagingAreaData, stagingAreaData, platformProvider, modifyOutputBeforeCompile, runtimeClassRegistry);
			iL2CPPBuilder.Run();
			return iL2CPPBuilder;
		}
 public static void WriteCPlusPlusFileForStaticAOTModuleRegistration(BuildTarget buildTarget, string file, CrossCompileOptions crossCompileOptions, bool advancedLic, string targetDevice, bool stripping, RuntimeClassRegistry usedClassRegistry, AssemblyReferenceChecker checker)
 {
   using (TextWriter output = (TextWriter) new StreamWriter(file))
   {
     string[] assemblyFileNames = checker.GetAssemblyFileNames();
     AssemblyDefinition[] assemblyDefinitions = checker.GetAssemblyDefinitions();
     bool flag = (crossCompileOptions & CrossCompileOptions.FastICall) != CrossCompileOptions.Dynamic;
     ArrayList arrayList = MonoAOTRegistration.BuildNativeMethodList(assemblyDefinitions);
     if (buildTarget == BuildTarget.iOS)
     {
       output.WriteLine("#include \"RegisterMonoModules.h\"");
       output.WriteLine("#include <stdio.h>");
     }
     output.WriteLine(string.Empty);
     output.WriteLine("#if defined(TARGET_IPHONE_SIMULATOR) && TARGET_IPHONE_SIMULATOR");
     output.WriteLine("    #define DECL_USER_FUNC(f) void f() __attribute__((weak_import))");
     output.WriteLine("    #define REGISTER_USER_FUNC(f)\\");
     output.WriteLine("        do {\\");
     output.WriteLine("        if(f != NULL)\\");
     output.WriteLine("            mono_dl_register_symbol(#f, (void*)f);\\");
     output.WriteLine("        else\\");
     output.WriteLine("            ::printf_console(\"Symbol '%s' not found. Maybe missing implementation for Simulator?\\n\", #f);\\");
     output.WriteLine("        }while(0)");
     output.WriteLine("#else");
     output.WriteLine("    #define DECL_USER_FUNC(f) void f() ");
     output.WriteLine("    #if !defined(__arm64__)");
     output.WriteLine("    #define REGISTER_USER_FUNC(f) mono_dl_register_symbol(#f, (void*)&f)");
     output.WriteLine("    #else");
     output.WriteLine("        #define REGISTER_USER_FUNC(f)");
     output.WriteLine("    #endif");
     output.WriteLine("#endif");
     output.WriteLine("extern \"C\"\n{");
     output.WriteLine("    typedef void* gpointer;");
     output.WriteLine("    typedef int gboolean;");
     if (buildTarget == BuildTarget.iOS)
     {
       output.WriteLine("    const char*         UnityIPhoneRuntimeVersion = \"{0}\";", (object) Application.unityVersion);
       output.WriteLine("    void                mono_dl_register_symbol (const char* name, void *addr);");
       output.WriteLine("#if !defined(__arm64__)");
       output.WriteLine("    extern int          mono_ficall_flag;");
       output.WriteLine("#endif");
     }
     output.WriteLine("    void                mono_aot_register_module(gpointer *aot_info);");
     output.WriteLine("#if __ORBIS__ || SN_TARGET_PSP2");
     output.WriteLine("#define DLL_EXPORT __declspec(dllexport)");
     output.WriteLine("#else");
     output.WriteLine("#define DLL_EXPORT");
     output.WriteLine("#endif");
     output.WriteLine("#if !(TARGET_IPHONE_SIMULATOR)");
     output.WriteLine("    extern gboolean     mono_aot_only;");
     for (int index = 0; index < assemblyFileNames.Length; ++index)
     {
       string str1 = assemblyFileNames[index];
       string str2 = ((AssemblyNameReference) assemblyDefinitions[index].get_Name()).get_Name().Replace(".", "_").Replace("-", "_").Replace(" ", "_");
       output.WriteLine("    extern gpointer*    mono_aot_module_{0}_info; // {1}", (object) str2, (object) str1);
     }
     output.WriteLine("#endif // !(TARGET_IPHONE_SIMULATOR)");
     foreach (string str in arrayList)
       output.WriteLine("    DECL_USER_FUNC({0});", (object) str);
     output.WriteLine("}");
     output.WriteLine("DLL_EXPORT void RegisterMonoModules()");
     output.WriteLine("{");
     output.WriteLine("#if !(TARGET_IPHONE_SIMULATOR) && !defined(__arm64__)");
     output.WriteLine("    mono_aot_only = true;");
     if (buildTarget == BuildTarget.iOS)
       output.WriteLine("    mono_ficall_flag = {0};", !flag ? (object) "false" : (object) "true");
     foreach (AssemblyDefinition assemblyDefinition in assemblyDefinitions)
     {
       string str = ((AssemblyNameReference) assemblyDefinition.get_Name()).get_Name().Replace(".", "_").Replace("-", "_").Replace(" ", "_");
       output.WriteLine("    mono_aot_register_module(mono_aot_module_{0}_info);", (object) str);
     }
     output.WriteLine("#endif // !(TARGET_IPHONE_SIMULATOR) && !defined(__arm64__)");
     output.WriteLine(string.Empty);
     if (buildTarget == BuildTarget.iOS)
     {
       foreach (string str in arrayList)
         output.WriteLine("    REGISTER_USER_FUNC({0});", (object) str);
     }
     output.WriteLine("}");
     output.WriteLine(string.Empty);
     AssemblyDefinition unityEngine = (AssemblyDefinition) null;
     for (int index = 0; index < assemblyFileNames.Length; ++index)
     {
       if (assemblyFileNames[index] == "UnityEngine.dll")
         unityEngine = assemblyDefinitions[index];
     }
     if (buildTarget == BuildTarget.iOS)
     {
       AssemblyDefinition[] assemblies = new AssemblyDefinition[1]{ unityEngine };
       MonoAOTRegistration.GenerateRegisterInternalCalls(assemblies, output);
       MonoAOTRegistration.ResolveDefinedNativeClassesFromMono(assemblies, usedClassRegistry);
       MonoAOTRegistration.ResolveReferencedUnityEngineClassesFromMono(assemblyDefinitions, unityEngine, usedClassRegistry);
       MonoAOTRegistration.GenerateRegisterModules(usedClassRegistry, output, stripping);
       if (stripping && usedClassRegistry != null)
         MonoAOTRegistration.GenerateRegisterClassesForStripping(usedClassRegistry, output);
       else
         MonoAOTRegistration.GenerateRegisterClasses(usedClassRegistry, output);
     }
     output.Close();
   }
 }
 public static void GenerateRegisterClasses(RuntimeClassRegistry allClasses, TextWriter output)
 {
   output.Write("void RegisterAllClasses() \n{\n");
   output.Write("void RegisterAllClassesIPhone();\nRegisterAllClassesIPhone();\n");
   output.Write("\n}\n");
 }
 public static void ResolveReferencedUnityEngineClassesFromMono(AssemblyDefinition[] assemblies, AssemblyDefinition unityEngine, RuntimeClassRegistry res)
 {
   if (res == null)
     return;
   foreach (AssemblyDefinition assembly in assemblies)
   {
     if (assembly != unityEngine)
     {
       using (IEnumerator<TypeReference> enumerator = assembly.get_MainModule().GetTypeReferences().GetEnumerator())
       {
         while (((IEnumerator) enumerator).MoveNext())
         {
           TypeReference current = enumerator.Current;
           if (current.get_Namespace().StartsWith("UnityEngine"))
           {
             string name = current.get_Name();
             res.AddMonoClass(name);
           }
         }
       }
     }
   }
 }
Esempio n. 36
0
 internal static IL2CPPBuilder RunIl2Cpp(string stagingAreaData, IIl2CppPlatformProvider platformProvider, System.Action<string> modifyOutputBeforeCompile, RuntimeClassRegistry runtimeClassRegistry, bool developmentBuild)
 {
   IL2CPPBuilder il2CppBuilder = new IL2CPPBuilder(stagingAreaData, stagingAreaData, platformProvider, modifyOutputBeforeCompile, runtimeClassRegistry, developmentBuild);
   il2CppBuilder.Run();
   return il2CppBuilder;
 }
 private static void RunAssemblyStripper(string stagingAreaData, IEnumerable assemblies, string managedAssemblyFolderPath, string[] assembliesToStrip, string[] searchDirs, string monoLinkerPath, IIl2CppPlatformProvider platformProvider, RuntimeClassRegistry rcr, bool developmentBuild)
 {
   bool flag1 = rcr != null && PlayerSettings.stripEngineCode && platformProvider.supportsEngineStripping;
   IEnumerable<string> blacklists = (IEnumerable<string>) AssemblyStripper.Il2CppBlacklistPaths;
   if (rcr != null)
     blacklists = blacklists.Concat<string>((IEnumerable<string>) new string[2]
     {
       AssemblyStripper.WriteMethodsToPreserveBlackList(stagingAreaData, rcr),
       MonoAssemblyStripping.GenerateLinkXmlToPreserveDerivedTypes(stagingAreaData, managedAssemblyFolderPath, rcr)
     });
   if (!flag1)
   {
     foreach (string file in Directory.GetFiles(platformProvider.moduleStrippingInformationFolder, "*.xml"))
       blacklists = blacklists.Concat<string>((IEnumerable<string>) new string[1]{ file });
   }
   string fullPath1 = Path.GetFullPath(Path.Combine(managedAssemblyFolderPath, "tempStrip"));
   bool flag2;
   do
   {
     flag2 = false;
     if (EditorUtility.DisplayCancelableProgressBar("Building Player", "Stripping assemblies", 0.0f))
       throw new OperationCanceledException();
     string output;
     string error;
     if (!AssemblyStripper.StripAssembliesTo(assembliesToStrip, searchDirs, fullPath1, managedAssemblyFolderPath, out output, out error, monoLinkerPath, platformProvider, blacklists, developmentBuild))
       throw new Exception("Error in stripping assemblies: " + (object) assemblies + ", " + error);
     string icallsListFile = Path.Combine(managedAssemblyFolderPath, "ICallSummary.txt");
     Runner.RunManagedProgram(Path.Combine(MonoInstallationFinder.GetFrameWorksFolder(), "Tools/InternalCallRegistrationWriter/InternalCallRegistrationWriter.exe"), string.Format("-assembly=\"{0}\" -output=\"{1}\" -summary=\"{2}\"", (object) Path.Combine(fullPath1, "UnityEngine.dll"), (object) Path.Combine(managedAssemblyFolderPath, "UnityICallRegistration.cpp"), (object) icallsListFile));
     if (flag1)
     {
       HashSet<string> nativeClasses;
       HashSet<string> nativeModules;
       CodeStrippingUtils.GenerateDependencies(fullPath1, icallsListFile, rcr, out nativeClasses, out nativeModules);
       flag2 = AssemblyStripper.AddWhiteListsForModules((IEnumerable<string>) nativeModules, ref blacklists, platformProvider.moduleStrippingInformationFolder);
     }
   }
   while (flag2);
   string fullPath2 = Path.GetFullPath(Path.Combine(managedAssemblyFolderPath, "tempUnstripped"));
   Directory.CreateDirectory(fullPath2);
   foreach (string file in Directory.GetFiles(managedAssemblyFolderPath))
   {
     string extension = Path.GetExtension(file);
     if (string.Equals(extension, ".dll", StringComparison.InvariantCultureIgnoreCase) || string.Equals(extension, ".mdb", StringComparison.InvariantCultureIgnoreCase))
       File.Move(file, Path.Combine(fullPath2, Path.GetFileName(file)));
   }
   foreach (string file in Directory.GetFiles(fullPath1))
     File.Move(file, Path.Combine(managedAssemblyFolderPath, Path.GetFileName(file)));
   Directory.Delete(fullPath1);
 }
 public static void GenerateRegisterModules(RuntimeClassRegistry allClasses, TextWriter output, bool strippingEnabled)
 {
   allClasses.SynchronizeClasses();
   HashSet<string> modulesToRegister = CodeStrippingUtils.GetNativeModulesToRegister(!strippingEnabled ? (HashSet<string>) null : new HashSet<string>((IEnumerable<string>) allClasses.GetAllNativeClassesAsString()));
   modulesToRegister.Add("IMGUI");
   using (HashSet<string>.Enumerator enumerator = modulesToRegister.GetEnumerator())
   {
     while (enumerator.MoveNext())
     {
       string current = enumerator.Current;
       output.WriteLine("\textern \"C\" void RegisterModule_" + current + "();");
     }
   }
   output.WriteLine("void RegisterStaticallyLinkedModules()");
   output.WriteLine("{");
   using (HashSet<string>.Enumerator enumerator = modulesToRegister.GetEnumerator())
   {
     while (enumerator.MoveNext())
     {
       string current = enumerator.Current;
       output.WriteLine("\tRegisterModule_" + current + "();");
     }
   }
   output.WriteLine("}");
 }
 private static string WriteMethodsToPreserveBlackList(string stagingAreaData, RuntimeClassRegistry rcr)
 {
   string path = (!Path.IsPathRooted(stagingAreaData) ? Directory.GetCurrentDirectory() + "/" : string.Empty) + stagingAreaData + "/methods_pointedto_by_uievents.xml";
   File.WriteAllText(path, AssemblyStripper.GetMethodPreserveBlacklistContents(rcr));
   return path;
 }
 public static void ResolveReferencedUnityEngineClassesFromMono(AssemblyDefinition[] assemblies, AssemblyDefinition unityEngine, RuntimeClassRegistry res)
 {
     if (res != null)
     {
         foreach (AssemblyDefinition definition in assemblies)
         {
             if (definition != unityEngine)
             {
                 foreach (TypeReference reference in definition.MainModule.GetTypeReferences())
                 {
                     if (reference.Namespace.StartsWith("UnityEngine"))
                     {
                         string name = reference.Name;
                         res.AddMonoClass(name);
                     }
                 }
             }
         }
     }
 }
Esempio n. 41
0
 public static void GenerateDependencies(string strippedAssemblyDir, string icallsListFile, RuntimeClassRegistry rcr, out HashSet <string> nativeClasses, out HashSet <string> nativeModules)
 {
     string[] userAssemblies = CodeStrippingUtils.GetUserAssemblies(strippedAssemblyDir);
     nativeClasses = !PlayerSettings.stripEngineCode ? (HashSet <string>)null : CodeStrippingUtils.GenerateNativeClassList(rcr, strippedAssemblyDir, userAssemblies);
     if (nativeClasses != null)
     {
         CodeStrippingUtils.ExcludeModuleManagers(ref nativeClasses);
     }
     nativeModules = CodeStrippingUtils.GetNativeModulesToRegister(nativeClasses);
     if (nativeClasses != null && icallsListFile != null)
     {
         HashSet <string> modulesFromIcalls = CodeStrippingUtils.GetModulesFromICalls(icallsListFile);
         int classId = BaseObjectTools.StringToClassID("GlobalGameManager");
         using (HashSet <string> .Enumerator enumerator = modulesFromIcalls.GetEnumerator())
         {
             while (enumerator.MoveNext())
             {
                 foreach (int moduleClass in ModuleMetadata.GetModuleClasses(enumerator.Current))
                 {
                     if (BaseObjectTools.IsDerivedFromClassID(moduleClass, classId))
                     {
                         nativeClasses.Add(BaseObjectTools.ClassIDToString(moduleClass));
                     }
                 }
             }
         }
         nativeModules.UnionWith((IEnumerable <string>)modulesFromIcalls);
     }
     new AssemblyReferenceChecker().CollectReferencesFromRoots(strippedAssemblyDir, (IEnumerable <string>)userAssemblies, true, 0.0f, true);
 }
 public static void Postprocess(BuildTarget target, string installPath, string companyName, string productName, int width, int height, string downloadWebplayerUrl, string manualDownloadWebplayerUrl, BuildOptions options, RuntimeClassRegistry usedClassRegistry)
 {
   string str1 = "Temp/StagingArea";
   string str2 = "Temp/StagingArea/Data";
   string str3 = "Temp/StagingArea/Data/Managed";
   string playbackEngineDirectory = BuildPipeline.GetPlaybackEngineDirectory(target, options);
   bool flag = (options & BuildOptions.InstallInBuildFolder) != BuildOptions.None && PostprocessBuildPlayer.SupportsInstallInBuildFolder(target);
   if (installPath == string.Empty && !flag)
     throw new Exception(installPath + " must not be an empty string");
   IBuildPostprocessor buildPostProcessor = ModuleManager.GetBuildPostProcessor(target);
   if (buildPostProcessor != null)
   {
     BuildPostProcessArgs args;
     args.target = target;
     args.stagingAreaData = str2;
     args.stagingArea = str1;
     args.stagingAreaDataManaged = str3;
     args.playerPackage = playbackEngineDirectory;
     args.installPath = installPath;
     args.companyName = companyName;
     args.productName = productName;
     args.productGUID = PlayerSettings.productGUID;
     args.options = options;
     args.usedClassRegistry = usedClassRegistry;
     buildPostProcessor.PostProcess(args);
   }
   else
   {
     switch (target)
     {
       case BuildTarget.WebPlayer:
       case BuildTarget.WebPlayerStreamed:
         PostProcessWebPlayer.PostProcess(options, installPath, downloadWebplayerUrl, width, height);
         break;
       default:
         throw new UnityException(string.Format("Build target '{0}' not supported", (object) target));
     }
   }
 }
        public static void Postprocess(BuildTarget target, string installPath, string companyName, string productName, int width, int height, string downloadWebplayerUrl, string manualDownloadWebplayerUrl, BuildOptions options, RuntimeClassRegistry usedClassRegistry, BuildReport report)
        {
            BuildPostProcessArgs args;
            string str  = "Temp/StagingArea";
            string str2 = "Temp/StagingArea/Data";
            string str3 = "Temp/StagingArea/Data/Managed";
            string playbackEngineDirectory = BuildPipeline.GetPlaybackEngineDirectory(target, options);
            bool   flag = ((options & BuildOptions.InstallInBuildFolder) != BuildOptions.CompressTextures) && SupportsInstallInBuildFolder(target);

            if ((installPath == string.Empty) && !flag)
            {
                throw new Exception(installPath + " must not be an empty string");
            }
            IBuildPostprocessor buildPostProcessor = ModuleManager.GetBuildPostProcessor(target);

            if (buildPostProcessor == null)
            {
                throw new UnityException($"Build target '{target}' not supported");
            }
            args.target                 = target;
            args.stagingAreaData        = str2;
            args.stagingArea            = str;
            args.stagingAreaDataManaged = str3;
            args.playerPackage          = playbackEngineDirectory;
            args.installPath            = installPath;
            args.companyName            = companyName;
            args.productName            = productName;
            args.productGUID            = PlayerSettings.productGUID;
            args.options                = options;
            args.usedClassRegistry      = usedClassRegistry;
            args.report                 = report;
            buildPostProcessor.PostProcess(args);
        }
 public static void Postprocess(BuildTarget target, string installPath, string companyName, string productName, int width, int height, string downloadWebplayerUrl, string manualDownloadWebplayerUrl, BuildOptions options, RuntimeClassRegistry usedClassRegistry, BuildReport report)
 {
     BuildPostProcessArgs args;
     string str = "Temp/StagingArea";
     string str2 = "Temp/StagingArea/Data";
     string str3 = "Temp/StagingArea/Data/Managed";
     string playbackEngineDirectory = BuildPipeline.GetPlaybackEngineDirectory(target, options);
     bool flag = ((options & BuildOptions.InstallInBuildFolder) != BuildOptions.CompressTextures) && SupportsInstallInBuildFolder(target);
     if ((installPath == string.Empty) && !flag)
     {
         throw new Exception(installPath + " must not be an empty string");
     }
     IBuildPostprocessor buildPostProcessor = ModuleManager.GetBuildPostProcessor(target);
     if (buildPostProcessor == null)
     {
         throw new UnityException(string.Format("Build target '{0}' not supported", target));
     }
     args.target = target;
     args.stagingAreaData = str2;
     args.stagingArea = str;
     args.stagingAreaDataManaged = str3;
     args.playerPackage = playbackEngineDirectory;
     args.installPath = installPath;
     args.companyName = companyName;
     args.productName = productName;
     args.productGUID = PlayerSettings.productGUID;
     args.options = options;
     args.usedClassRegistry = usedClassRegistry;
     args.report = report;
     buildPostProcessor.PostProcess(args);
 }
        private static HashSet <UnityType> GenerateNativeClassList(RuntimeClassRegistry rcr, string directory, string[] rootAssemblies, StrippingInfo strippingInfo)
        {
            HashSet <UnityType> nativeClasses = CollectNativeClassListFromRoots(directory, rootAssemblies, strippingInfo);

            // Inject blacklisted native types
            foreach (var klass in BlackListNativeClasses)
            {
                nativeClasses.Add(klass);
            }

            foreach (var dependent in BlackListNativeClassesDependency.Keys)
            {
                if (nativeClasses.Contains(dependent))
                {
                    var provider = BlackListNativeClassesDependency[dependent];
                    nativeClasses.Add(provider);
                }
            }

            // List native classes found in scenes
            foreach (string klassName in rcr.GetAllNativeClassesIncludingManagersAsString())
            {
                UnityType klass = UnityType.FindTypeByName(klassName);
                if (klass != null && klass.baseClass != null)
                {
                    nativeClasses.Add(klass);
                    if (strippingInfo != null)
                    {
                        if (!klass.IsDerivedFrom(GameManagerTypeInfo))
                        {
                            var scenes = rcr.GetScenesForClass(klass.persistentTypeID);
                            if (scenes != null)
                            {
                                foreach (var scene in scenes)
                                {
                                    strippingInfo.RegisterDependency(klassName, scene);
                                    if (scene.EndsWith(".unity"))
                                    {
                                        strippingInfo.SetIcon(scene, "class/SceneAsset");
                                    }
                                    else
                                    {
                                        strippingInfo.SetIcon(scene, "class/AssetBundle");
                                    }
                                }
                            }
                        }
                    }
                }
            }

            // Always include base classes of derived native classes.
            HashSet <UnityType> nativeClassesAndBaseClasses = new HashSet <UnityType>();

            foreach (var klass in nativeClasses)
            {
                var current = klass;
                while (current.baseClass != null)
                {
                    nativeClassesAndBaseClasses.Add(current);
                    current = current.baseClass;
                }
            }

            return(nativeClassesAndBaseClasses);
        }
 public static void ResolveDefinedNativeClassesFromMono(AssemblyDefinition[] assemblies, RuntimeClassRegistry res)
 {
     if (res != null)
     {
         foreach (AssemblyDefinition definition in assemblies)
         {
             foreach (TypeDefinition definition2 in definition.MainModule.Types)
             {
                 if (((definition2.Fields.Count > 0) || (definition2.Methods.Count > 0)) || (definition2.Properties.Count > 0))
                 {
                     string name = definition2.Name;
                     res.AddMonoClass(name);
                 }
             }
         }
     }
 }
Esempio n. 47
0
        public static void WriteModuleAndClassRegistrationFile(string strippedAssemblyDir, string icallsListFile, string outputDir, RuntimeClassRegistry rcr, IEnumerable <UnityType> classesToSkip, IIl2CppPlatformProvider platformProvider)
        {
            HashSet <UnityType> nativeClasses;
            HashSet <string>    nativeModules;
            // by default, we only care about il2cpp
            bool doStripping = PlayerSettings.stripEngineCode;

            GenerateDependencies(strippedAssemblyDir, icallsListFile, rcr, doStripping, out nativeClasses, out nativeModules, platformProvider);

            var outputClassRegistration = Path.Combine(outputDir, "UnityClassRegistration.cpp");

            WriteModuleAndClassRegistrationFile(outputClassRegistration, nativeModules, nativeClasses, new HashSet <UnityType>(classesToSkip));
        }
 public static void WriteCPlusPlusFileForStaticAOTModuleRegistration(BuildTarget buildTarget, string file, CrossCompileOptions crossCompileOptions, bool advancedLic, string targetDevice, bool stripping, RuntimeClassRegistry usedClassRegistry, AssemblyReferenceChecker checker)
 {
     using (TextWriter output = (TextWriter) new StreamWriter(file))
     {
         string[]             assemblyFileNames   = checker.GetAssemblyFileNames();
         AssemblyDefinition[] assemblyDefinitions = checker.GetAssemblyDefinitions();
         bool      flag      = (crossCompileOptions & CrossCompileOptions.FastICall) != CrossCompileOptions.Dynamic;
         ArrayList arrayList = MonoAOTRegistration.BuildNativeMethodList(assemblyDefinitions);
         if (buildTarget == BuildTarget.iOS)
         {
             output.WriteLine("#include \"RegisterMonoModules.h\"");
             output.WriteLine("#include <stdio.h>");
         }
         output.WriteLine(string.Empty);
         output.WriteLine("#if defined(TARGET_IPHONE_SIMULATOR) && TARGET_IPHONE_SIMULATOR");
         output.WriteLine("    #define DECL_USER_FUNC(f) void f() __attribute__((weak_import))");
         output.WriteLine("    #define REGISTER_USER_FUNC(f)\\");
         output.WriteLine("        do {\\");
         output.WriteLine("        if(f != NULL)\\");
         output.WriteLine("            mono_dl_register_symbol(#f, (void*)f);\\");
         output.WriteLine("        else\\");
         output.WriteLine("            ::printf_console(\"Symbol '%s' not found. Maybe missing implementation for Simulator?\\n\", #f);\\");
         output.WriteLine("        }while(0)");
         output.WriteLine("#else");
         output.WriteLine("    #define DECL_USER_FUNC(f) void f() ");
         output.WriteLine("    #if !defined(__arm64__)");
         output.WriteLine("    #define REGISTER_USER_FUNC(f) mono_dl_register_symbol(#f, (void*)&f)");
         output.WriteLine("    #else");
         output.WriteLine("        #define REGISTER_USER_FUNC(f)");
         output.WriteLine("    #endif");
         output.WriteLine("#endif");
         output.WriteLine("extern \"C\"\n{");
         output.WriteLine("    typedef void* gpointer;");
         output.WriteLine("    typedef int gboolean;");
         if (buildTarget == BuildTarget.iOS)
         {
             output.WriteLine("    const char*         UnityIPhoneRuntimeVersion = \"{0}\";", (object)Application.unityVersion);
             output.WriteLine("    void                mono_dl_register_symbol (const char* name, void *addr);");
             output.WriteLine("#if !defined(__arm64__)");
             output.WriteLine("    extern int          mono_ficall_flag;");
             output.WriteLine("#endif");
         }
         output.WriteLine("    void                mono_aot_register_module(gpointer *aot_info);");
         output.WriteLine("#if __ORBIS__ || SN_TARGET_PSP2");
         output.WriteLine("#define DLL_EXPORT __declspec(dllexport)");
         output.WriteLine("#else");
         output.WriteLine("#define DLL_EXPORT");
         output.WriteLine("#endif");
         output.WriteLine("#if !(TARGET_IPHONE_SIMULATOR)");
         output.WriteLine("    extern gboolean     mono_aot_only;");
         for (int index = 0; index < assemblyFileNames.Length; ++index)
         {
             string str1 = assemblyFileNames[index];
             string str2 = ((AssemblyNameReference)assemblyDefinitions[index].get_Name()).get_Name().Replace(".", "_").Replace("-", "_").Replace(" ", "_");
             output.WriteLine("    extern gpointer*    mono_aot_module_{0}_info; // {1}", (object)str2, (object)str1);
         }
         output.WriteLine("#endif // !(TARGET_IPHONE_SIMULATOR)");
         foreach (string str in arrayList)
         {
             output.WriteLine("    DECL_USER_FUNC({0});", (object)str);
         }
         output.WriteLine("}");
         output.WriteLine("DLL_EXPORT void RegisterMonoModules()");
         output.WriteLine("{");
         output.WriteLine("#if !(TARGET_IPHONE_SIMULATOR) && !defined(__arm64__)");
         output.WriteLine("    mono_aot_only = true;");
         if (buildTarget == BuildTarget.iOS)
         {
             output.WriteLine("    mono_ficall_flag = {0};", !flag ? (object)"false" : (object)"true");
         }
         foreach (AssemblyDefinition assemblyDefinition in assemblyDefinitions)
         {
             string str = ((AssemblyNameReference)assemblyDefinition.get_Name()).get_Name().Replace(".", "_").Replace("-", "_").Replace(" ", "_");
             output.WriteLine("    mono_aot_register_module(mono_aot_module_{0}_info);", (object)str);
         }
         output.WriteLine("#endif // !(TARGET_IPHONE_SIMULATOR) && !defined(__arm64__)");
         output.WriteLine(string.Empty);
         if (buildTarget == BuildTarget.iOS)
         {
             foreach (string str in arrayList)
             {
                 output.WriteLine("    REGISTER_USER_FUNC({0});", (object)str);
             }
         }
         output.WriteLine("}");
         output.WriteLine(string.Empty);
         AssemblyDefinition unityEngine = (AssemblyDefinition)null;
         for (int index = 0; index < assemblyFileNames.Length; ++index)
         {
             if (assemblyFileNames[index] == "UnityEngine.dll")
             {
                 unityEngine = assemblyDefinitions[index];
             }
         }
         if (buildTarget == BuildTarget.iOS)
         {
             AssemblyDefinition[] assemblies = new AssemblyDefinition[1] {
                 unityEngine
             };
             MonoAOTRegistration.GenerateRegisterInternalCalls(assemblies, output);
             MonoAOTRegistration.ResolveDefinedNativeClassesFromMono(assemblies, usedClassRegistry);
             MonoAOTRegistration.ResolveReferencedUnityEngineClassesFromMono(assemblyDefinitions, unityEngine, usedClassRegistry);
             MonoAOTRegistration.GenerateRegisterModules(usedClassRegistry, output, stripping);
             if (stripping && usedClassRegistry != null)
             {
                 MonoAOTRegistration.GenerateRegisterClassesForStripping(usedClassRegistry, output);
             }
             else
             {
                 MonoAOTRegistration.GenerateRegisterClasses(usedClassRegistry, output);
             }
         }
         output.Close();
     }
 }
 public static void ResolveReferencedUnityEngineClassesFromMono(AssemblyDefinition[] assemblies, AssemblyDefinition unityEngine, RuntimeClassRegistry res)
 {
     if (res == null)
     {
         return;
     }
     foreach (AssemblyDefinition assembly in assemblies)
     {
         if (assembly != unityEngine)
         {
             using (IEnumerator <TypeReference> enumerator = assembly.get_MainModule().GetTypeReferences().GetEnumerator())
             {
                 while (((IEnumerator)enumerator).MoveNext())
                 {
                     TypeReference current = enumerator.Current;
                     if (current.get_Namespace().StartsWith("UnityEngine"))
                     {
                         string name = current.get_Name();
                         res.AddMonoClass(name);
                     }
                 }
             }
         }
     }
 }
Esempio n. 50
0
        // this logic produces similar list of assemblies that IL2CPP will convert (it differs in the way it collects winmd files)
        public static IEnumerable <AssemblyDefinition> CollectAllAssemblies(string librariesFolder, RuntimeClassRegistry usedClasses)
        {
            var resolver = new DefaultAssemblyResolver();

            resolver.RemoveSearchDirectory(".");
            resolver.RemoveSearchDirectory("bin");
            resolver.AddSearchDirectory(librariesFolder);

            var usedDlls = usedClasses.GetUserAssemblies().Where(s => usedClasses.IsDLLUsed(s)).Select(file => AssemblyNameReference.Parse(Path.GetFileNameWithoutExtension(file)));

            return(CollectAssembliesRecursive(usedDlls.Select(dll => ResolveAssemblyReference(resolver, dll)).Where(a => a != null)));
        }
Esempio n. 51
0
 public static void WriteModuleAndClassRegistrationFile(string strippedAssemblyDir, string outputDir, RuntimeClassRegistry rcr, IEnumerable<string> classesToSkip)
 {
     HashSet<string> set;
     HashSet<string> set2;
     GenerateDependencies(strippedAssemblyDir, rcr, out set, out set2);
     WriteModuleAndClassRegistrationFile(Path.Combine(outputDir, "UnityClassRegistration.cpp"), set2, set, new HashSet<string>(classesToSkip));
 }
Esempio n. 52
0
        public static void WriteModuleAndClassRegistrationFile(string strippedAssemblyDir, string icallsListFile, string outputDir, RuntimeClassRegistry rcr, IEnumerable <UnityType> classesToSkip, IIl2CppPlatformProvider platformProvider, bool writeModuleRegistration = true, bool writeClassRegistration = true)
        {
            HashSet <UnityType> nativeClasses;
            HashSet <string>    nativeModules;
            // by default, we only care about il2cpp
            bool doStripping = PlayerSettings.stripEngineCode;

            GenerateDependencies(strippedAssemblyDir, icallsListFile, rcr, doStripping, out nativeClasses, out nativeModules, platformProvider);

            var outputClassRegistration = Path.Combine(outputDir, "UnityClassRegistration.cpp");

            using (TextWriter w = new StreamWriter(outputClassRegistration))
            {
                if (writeModuleRegistration)
                {
                    WriteFunctionRegisterStaticallyLinkedModulesGranular(w, nativeModules);
                }
                if (writeClassRegistration)
                {
                    WriteStaticallyLinkedModuleClassRegistration(w, nativeClasses, new HashSet <UnityType>(classesToSkip));
                }
                w.Close();
            }
        }
 public static void GenerateRegisterClasses(RuntimeClassRegistry allClasses, TextWriter output)
 {
     output.Write("void RegisterAllClasses() \n{\n");
     output.Write("void RegisterAllClassesIPhone();\nRegisterAllClassesIPhone();\n");
     output.Write("\n}\n");
 }
 public static void WriteCPlusPlusFileForStaticAOTModuleRegistration(BuildTarget buildTarget, string file, CrossCompileOptions crossCompileOptions, bool advancedLic, string targetDevice, bool stripping, RuntimeClassRegistry usedClassRegistry, AssemblyReferenceChecker checker, string stagingAreaDataManaged)
 {
     HashSet<UnityType> set;
     HashSet<string> set2;
     string str = Path.Combine(stagingAreaDataManaged, "ICallSummary.txt");
     string exe = Path.Combine(MonoInstallationFinder.GetFrameWorksFolder(), "Tools/InternalCallRegistrationWriter/InternalCallRegistrationWriter.exe");
     string args = string.Format("-assembly=\"{0}\" -summary=\"{1}\"", Path.Combine(stagingAreaDataManaged, "UnityEngine.dll"), str);
     Runner.RunManagedProgram(exe, args);
     CodeStrippingUtils.GenerateDependencies(Path.GetDirectoryName(stagingAreaDataManaged), str, usedClassRegistry, stripping, out set, out set2, null);
     using (TextWriter writer = new StreamWriter(file))
     {
         string[] assemblyFileNames = checker.GetAssemblyFileNames();
         AssemblyDefinition[] assemblyDefinitions = checker.GetAssemblyDefinitions();
         bool flag = (crossCompileOptions & CrossCompileOptions.FastICall) != CrossCompileOptions.Dynamic;
         ArrayList list = BuildNativeMethodList(assemblyDefinitions);
         if (buildTarget == BuildTarget.iOS)
         {
             writer.WriteLine("#include \"RegisterMonoModules.h\"");
             writer.WriteLine("#include <stdio.h>");
         }
         writer.WriteLine("");
         writer.WriteLine("#if defined(TARGET_IPHONE_SIMULATOR) && TARGET_IPHONE_SIMULATOR");
         writer.WriteLine("    #define DECL_USER_FUNC(f) void f() __attribute__((weak_import))");
         writer.WriteLine(@"    #define REGISTER_USER_FUNC(f)\");
         writer.WriteLine(@"        do {\");
         writer.WriteLine(@"        if(f != NULL)\");
         writer.WriteLine(@"            mono_dl_register_symbol(#f, (void*)f);\");
         writer.WriteLine(@"        else\");
         writer.WriteLine("            ::printf_console(\"Symbol '%s' not found. Maybe missing implementation for Simulator?\\n\", #f);\\");
         writer.WriteLine("        }while(0)");
         writer.WriteLine("#else");
         writer.WriteLine("    #define DECL_USER_FUNC(f) void f() ");
         writer.WriteLine("    #if !defined(__arm64__)");
         writer.WriteLine("    #define REGISTER_USER_FUNC(f) mono_dl_register_symbol(#f, (void*)&f)");
         writer.WriteLine("    #else");
         writer.WriteLine("        #define REGISTER_USER_FUNC(f)");
         writer.WriteLine("    #endif");
         writer.WriteLine("#endif");
         writer.WriteLine("extern \"C\"\n{");
         writer.WriteLine("    typedef void* gpointer;");
         writer.WriteLine("    typedef int gboolean;");
         if (buildTarget == BuildTarget.iOS)
         {
             writer.WriteLine("    const char*         UnityIPhoneRuntimeVersion = \"{0}\";", Application.unityVersion);
             writer.WriteLine("    void                mono_dl_register_symbol (const char* name, void *addr);");
             writer.WriteLine("#if !defined(__arm64__)");
             writer.WriteLine("    extern int          mono_ficall_flag;");
             writer.WriteLine("#endif");
         }
         writer.WriteLine("    void                mono_aot_register_module(gpointer *aot_info);");
         writer.WriteLine("#if __ORBIS__ || SN_TARGET_PSP2");
         writer.WriteLine("#define DLL_EXPORT __declspec(dllexport)");
         writer.WriteLine("#else");
         writer.WriteLine("#define DLL_EXPORT");
         writer.WriteLine("#endif");
         writer.WriteLine("#if !(TARGET_IPHONE_SIMULATOR)");
         writer.WriteLine("    extern gboolean     mono_aot_only;");
         for (int i = 0; i < assemblyFileNames.Length; i++)
         {
             string str4 = assemblyFileNames[i];
             string str5 = assemblyDefinitions[i].Name.Name.Replace(".", "_").Replace("-", "_").Replace(" ", "_");
             writer.WriteLine("    extern gpointer*    mono_aot_module_{0}_info; // {1}", str5, str4);
         }
         writer.WriteLine("#endif // !(TARGET_IPHONE_SIMULATOR)");
         IEnumerator enumerator = list.GetEnumerator();
         try
         {
             while (enumerator.MoveNext())
             {
                 string current = (string) enumerator.Current;
                 writer.WriteLine("    DECL_USER_FUNC({0});", current);
             }
         }
         finally
         {
             IDisposable disposable = enumerator as IDisposable;
             if (disposable != null)
             {
                 disposable.Dispose();
             }
         }
         writer.WriteLine("}");
         writer.WriteLine("DLL_EXPORT void RegisterMonoModules()");
         writer.WriteLine("{");
         writer.WriteLine("#if !(TARGET_IPHONE_SIMULATOR) && !defined(__arm64__)");
         writer.WriteLine("    mono_aot_only = true;");
         if (buildTarget == BuildTarget.iOS)
         {
             writer.WriteLine("    mono_ficall_flag = {0};", !flag ? "false" : "true");
         }
         foreach (AssemblyDefinition definition in assemblyDefinitions)
         {
             string str7 = definition.Name.Name.Replace(".", "_").Replace("-", "_").Replace(" ", "_");
             writer.WriteLine("    mono_aot_register_module(mono_aot_module_{0}_info);", str7);
         }
         writer.WriteLine("#endif // !(TARGET_IPHONE_SIMULATOR) && !defined(__arm64__)");
         writer.WriteLine("");
         if (buildTarget == BuildTarget.iOS)
         {
             IEnumerator enumerator2 = list.GetEnumerator();
             try
             {
                 while (enumerator2.MoveNext())
                 {
                     string str8 = (string) enumerator2.Current;
                     writer.WriteLine("    REGISTER_USER_FUNC({0});", str8);
                 }
             }
             finally
             {
                 IDisposable disposable2 = enumerator2 as IDisposable;
                 if (disposable2 != null)
                 {
                     disposable2.Dispose();
                 }
             }
         }
         writer.WriteLine("}");
         writer.WriteLine("");
         AssemblyDefinition unityEngine = null;
         for (int j = 0; j < assemblyFileNames.Length; j++)
         {
             if (assemblyFileNames[j] == "UnityEngine.dll")
             {
                 unityEngine = assemblyDefinitions[j];
             }
         }
         if (buildTarget == BuildTarget.iOS)
         {
             AssemblyDefinition[] assemblies = new AssemblyDefinition[] { unityEngine };
             GenerateRegisterInternalCalls(assemblies, writer);
             ResolveDefinedNativeClassesFromMono(assemblies, usedClassRegistry);
             ResolveReferencedUnityEngineClassesFromMono(assemblyDefinitions, unityEngine, usedClassRegistry);
             GenerateRegisterModules(set, set2, writer, stripping);
             if (stripping && (usedClassRegistry != null))
             {
                 GenerateRegisterClassesForStripping(set, writer);
             }
             else
             {
                 GenerateRegisterClasses(set, writer);
             }
         }
         writer.Close();
     }
 }
Esempio n. 55
0
        public static string GenerateLinkXmlToPreserveDerivedTypes(string librariesFolder, RuntimeClassRegistry usedClasses)
        {
            string path = Path.GetTempFileName();

            using (TextWriter w = new StreamWriter(path))
            {
                w.WriteLine("<linker>");
                foreach (var assembly in CollectAllAssemblies(librariesFolder, usedClasses))
                {
                    if (AssemblyHelper.IsUnityEngineModule(assembly))
                    {
                        continue;
                    }

                    var typesToPreserve = new HashSet <TypeDefinition>();
                    CollectBlackListTypes(typesToPreserve, assembly.MainModule.Types, usedClasses.GetAllManagedBaseClassesAsString());

                    // don't write out xml file for assemblies with no types since link.xml files on disk have special meaning to IL2CPP stripping
                    if (typesToPreserve.Count == 0)
                    {
                        continue;
                    }

                    w.WriteLine("<assembly fullname=\"{0}\">", assembly.Name.Name);
                    foreach (var typeToPreserve in typesToPreserve)
                    {
                        w.WriteLine("<type fullname=\"{0}\" preserve=\"all\"/>", typeToPreserve.FullName);
                    }
                    w.WriteLine("</assembly>");
                }
                w.WriteLine("</linker>");
            }

            return(path);
        }
		private static HashSet<string> GenerateNativeClassList(RuntimeClassRegistry rcr, string directory, string[] rootAssemblies)
		{
			HashSet<string> hashSet = CodeStrippingUtils.CollectNativeClassListFromRoots(directory, rootAssemblies);
			string[] nativeClassBlackList = CodeStrippingUtils.NativeClassBlackList;
			for (int i = 0; i < nativeClassBlackList.Length; i++)
			{
				string item = nativeClassBlackList[i];
				hashSet.Add(item);
			}
			foreach (string current in rcr.GetAllNativeClassesIncludingManagersAsString())
			{
				int num = BaseObjectTools.StringToClassID(current);
				if (num != -1 && !BaseObjectTools.IsBaseObject(num))
				{
					hashSet.Add(current);
				}
			}
			return hashSet;
		}
Esempio n. 57
0
        public static void GenerateDependencies(string strippedAssemblyDir, string icallsListFile, RuntimeClassRegistry rcr, bool doStripping, out HashSet <UnityType> nativeClasses, out HashSet <string> nativeModules, IIl2CppPlatformProvider platformProvider)
        {
            if (AssemblyStripper.UseUnityLinkerEngineModuleStripping)
            {
                GenerateDependencies2(strippedAssemblyDir, doStripping, out nativeClasses, out nativeModules);
                return;
            }

            var strippingInfo  = platformProvider == null ? null : StrippingInfo.GetBuildReportData(platformProvider.buildReport);
            var userAssemblies = GetUserAssemblies(strippedAssemblyDir);

            // [1] Extract native classes from scene and scripts
            nativeClasses = doStripping ? GenerateNativeClassList(rcr, strippedAssemblyDir, userAssemblies, strippingInfo) : null;

            // Exclude module managers (GlobalGameManager) if no dependent classes are used.
            if (nativeClasses != null)
            {
                ExcludeModuleManagers(ref nativeClasses);
            }

            // [2] Prepare a list of modules to register
            nativeModules = GetNativeModulesToRegister(nativeClasses, strippingInfo);

            if (nativeClasses != null && icallsListFile != null)
            {
                // Get required modules from icall list file
                var icallModules = GetModulesFromICalls(icallsListFile);

                // Add GameManager classes for modules
                foreach (var module in icallModules)
                {
                    if (!nativeModules.Contains(module))
                    {
                        if (strippingInfo != null)
                        {
                            strippingInfo.RegisterDependency(StrippingInfo.ModuleName(module), StrippingInfo.RequiredByScripts);
                        }
                    }

                    var moduleClasses = ModuleMetadata.GetModuleTypes(module);
                    foreach (var klass in moduleClasses)
                    {
                        if (klass.IsDerivedFrom(GameManagerTypeInfo))
                        {
                            nativeClasses.Add(klass);
                        }
                    }
                }

                nativeModules.UnionWith(icallModules);
            }

            ApplyManualStrippingOverrides(nativeClasses, nativeModules, strippingInfo);

            bool didAdd = true;

            if (platformProvider != null)
            {
                while (didAdd)
                {
                    didAdd = false;
                    foreach (var module in nativeModules.ToList())
                    {
                        var dependecies = ModuleMetadata.GetModuleDependencies(module);
                        foreach (var dependentModule in dependecies)
                        {
                            if (!nativeModules.Contains(dependentModule))
                            {
                                nativeModules.Add(dependentModule);
                                didAdd = true;
                            }
                            if (strippingInfo != null)
                            {
                                var moduleName = StrippingInfo.ModuleName(module);
                                strippingInfo.RegisterDependency(StrippingInfo.ModuleName(dependentModule), "Required by " + moduleName);
                                strippingInfo.SetIcon("Required by " + moduleName, $"package/com.unity.modules.{module.ToLower()}");
                            }
                        }
                    }
                }
            }

            if (nativeClasses != null)
            {
                RemoveClassesFromRemovedModules(nativeClasses, nativeModules);
            }

            AssemblyReferenceChecker checker = new AssemblyReferenceChecker();

            checker.CollectReferencesFromRoots(strippedAssemblyDir, userAssemblies, true, 0.0f, true);

            if (strippingInfo != null)
            {
                foreach (var module in nativeModules)
                {
                    strippingInfo.AddModule(module);
                }
                strippingInfo.AddModule("Core");
            }

            if (nativeClasses != null && strippingInfo != null && platformProvider != null)
            {
                InjectCustomDependencies(platformProvider.target, strippingInfo, nativeClasses, nativeModules);
            }
        }
 private static HashSet<string> GenerateNativeClassList(RuntimeClassRegistry rcr, string directory, string[] rootAssemblies)
 {
   HashSet<string> stringSet1 = CodeStrippingUtils.CollectNativeClassListFromRoots(directory, rootAssemblies);
   foreach (string nativeClassBlack in CodeStrippingUtils.NativeClassBlackList)
     stringSet1.Add(nativeClassBlack);
   using (Dictionary<string, string>.KeyCollection.Enumerator enumerator = CodeStrippingUtils.NativeClassDependencyBlackList.Keys.GetEnumerator())
   {
     while (enumerator.MoveNext())
     {
       string current = enumerator.Current;
       if (stringSet1.Contains(current))
       {
         string classDependencyBlack = CodeStrippingUtils.NativeClassDependencyBlackList[current];
         stringSet1.Add(classDependencyBlack);
       }
     }
   }
   using (List<string>.Enumerator enumerator = rcr.GetAllNativeClassesIncludingManagersAsString().GetEnumerator())
   {
     while (enumerator.MoveNext())
     {
       string current = enumerator.Current;
       int classId = BaseObjectTools.StringToClassID(current);
       if (classId != -1 && !BaseObjectTools.IsBaseObject(classId))
         stringSet1.Add(current);
     }
   }
   HashSet<string> stringSet2 = new HashSet<string>();
   using (HashSet<string>.Enumerator enumerator = stringSet1.GetEnumerator())
   {
     while (enumerator.MoveNext())
     {
       for (int ID = BaseObjectTools.StringToClassID(enumerator.Current); !BaseObjectTools.IsBaseObject(ID); ID = BaseObjectTools.GetSuperClassID(ID))
         stringSet2.Add(BaseObjectTools.ClassIDToString(ID));
     }
   }
   return stringSet2;
 }
 private static string GetMethodPreserveBlacklistContents(RuntimeClassRegistry rcr)
 {
   StringBuilder stringBuilder = new StringBuilder();
   stringBuilder.AppendLine("<linker>");
   foreach (IGrouping<string, RuntimeClassRegistry.MethodDescription> source in rcr.GetMethodsToPreserve().GroupBy<RuntimeClassRegistry.MethodDescription, string>((Func<RuntimeClassRegistry.MethodDescription, string>) (m => m.assembly)))
   {
     stringBuilder.AppendLine(string.Format("\t<assembly fullname=\"{0}\">", (object) source.Key));
     foreach (IGrouping<string, RuntimeClassRegistry.MethodDescription> grouping in source.GroupBy<RuntimeClassRegistry.MethodDescription, string>((Func<RuntimeClassRegistry.MethodDescription, string>) (m => m.fullTypeName)))
     {
       stringBuilder.AppendLine(string.Format("\t\t<type fullname=\"{0}\">", (object) grouping.Key));
       foreach (RuntimeClassRegistry.MethodDescription methodDescription in (IEnumerable<RuntimeClassRegistry.MethodDescription>) grouping)
         stringBuilder.AppendLine(string.Format("\t\t\t<method name=\"{0}\"/>", (object) methodDescription.methodName));
       stringBuilder.AppendLine("\t\t</type>");
     }
     stringBuilder.AppendLine("\t</assembly>");
   }
   stringBuilder.AppendLine("</linker>");
   return stringBuilder.ToString();
 }
Esempio n. 60
0
 public static void MonoLink(BuildTarget buildTarget, string managedLibrariesDirectory, string[] input, string[] allAssemblies, RuntimeClassRegistry usedClasses)
 {
     Process process = MonoProcessUtility.PrepareMonoProcess(buildTarget, managedLibrariesDirectory);
     string buildToolsDirectory = BuildPipeline.GetBuildToolsDirectory(buildTarget);
     string str2 = null;
     string path = Path.Combine(MonoInstallationFinder.GetFrameWorksFolder(), StripperExe());
     string str5 = Path.Combine(Path.GetDirectoryName(path), "link.xml");
     string str6 = Path.Combine(managedLibrariesDirectory, "output");
     Directory.CreateDirectory(str6);
     process.StartInfo.Arguments = "\"" + path + "\" -l none -c link";
     foreach (string str7 in input)
     {
         ProcessStartInfo info1 = process.StartInfo;
         info1.Arguments = info1.Arguments + " -a \"" + str7 + "\"";
     }
     ProcessStartInfo startInfo = process.StartInfo;
     string arguments = startInfo.Arguments;
     string[] textArray1 = new string[] { arguments, " -out output -x \"", str5, "\" -d \"", managedLibrariesDirectory, "\"" };
     startInfo.Arguments = string.Concat(textArray1);
     string str8 = Path.Combine(buildToolsDirectory, "link.xml");
     if (File.Exists(str8))
     {
         ProcessStartInfo info3 = process.StartInfo;
         info3.Arguments = info3.Arguments + " -x \"" + str8 + "\"";
     }
     string str9 = Path.Combine(Path.GetDirectoryName(path), "native_link.xml");
     if (File.Exists(str9))
     {
         ProcessStartInfo info4 = process.StartInfo;
         info4.Arguments = info4.Arguments + " -x \"" + str9 + "\"";
     }
     foreach (string str10 in Directory.GetFiles(Path.Combine(Directory.GetCurrentDirectory(), "Assets"), "link.xml", SearchOption.AllDirectories))
     {
         ProcessStartInfo info5 = process.StartInfo;
         info5.Arguments = info5.Arguments + " -x \"" + str10 + "\"";
     }
     if (usedClasses != null)
     {
         str2 = GenerateBlackList(managedLibrariesDirectory, usedClasses, allAssemblies);
         ProcessStartInfo info6 = process.StartInfo;
         info6.Arguments = info6.Arguments + " -x \"" + str2 + "\"";
     }
     MonoProcessUtility.RunMonoProcess(process, "assemblies stripper", Path.Combine(str6, "mscorlib.dll"));
     DeleteAllDllsFrom(managedLibrariesDirectory);
     CopyAllDlls(managedLibrariesDirectory, str6);
     foreach (string str11 in Directory.GetFiles(managedLibrariesDirectory))
     {
         if (str11.Contains(".mdb") && !File.Exists(str11.Replace(".mdb", string.Empty)))
         {
             FileUtil.DeleteFileOrDirectory(str11);
         }
     }
     if (str2 != null)
     {
         FileUtil.DeleteFileOrDirectory(Path.Combine(managedLibrariesDirectory, str2));
     }
     FileUtil.DeleteFileOrDirectory(str6);
 }