baxi 3 недель назад
Родитель
Сommit
c56017c8c5

+ 2 - 0
CHANGELOG.md

@@ -2,6 +2,8 @@
 
 ## 1.0.0
 
+- Normalize iOS native plugin exports to standard Frameworks/Libraries paths without package wrapper directories, preserving Xcode references, compiler flags and build phases.
+- Initialize writable GUPS project directories and settings before SDK access to prevent first-build metadata write errors after UPM installation; validate iOS export with obfuscation enabled.
 - Extract AppRuntimes into the standalone `come.app.runtimes` UPM package, displayed as AppRuntimes.
 - Bundle existing SDK distributions while preserving platform code, binaries and asset GUIDs.
 - Remove DOTween and its UniTask adapter; declare seven required registry dependencies and make Input System/Addressables integrations optional.

+ 176 - 0
Editor/XcodePluginLayout.cs

@@ -0,0 +1,176 @@
+#if UNITY_EDITOR && UNITY_IOS
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Text.RegularExpressions;
+using UnityEditor.Build;
+using UnityEditor.iOS.Xcode;
+
+internal static class XcodePluginLayout
+{
+    private const string PackageName = "come.app.runtimes";
+    private static readonly string[] ExportRoots = { "Frameworks", "Libraries" };
+    private static readonly string[] PackageFolders = { "Runtime", "ThirdParty" };
+
+    internal static void Normalize(string buildPath)
+    {
+        string projectPath = PBXProject.GetPBXProjectPath(buildPath);
+        var project = new PBXProject();
+        project.ReadFromFile(projectPath);
+
+        // Work on Unity's canonical serialization. Keep all file/build GUIDs, target
+        // memberships, embed settings and per-file compiler flags intact.
+        string projectText = FlattenGroups(project.WriteToString());
+        var moves = new List<KeyValuePair<string, string>>();
+        foreach (string root in ExportRoots)
+        {
+            string packagePrefix = root + "/" + PackageName + "/";
+            foreach (string folder in PackageFolders)
+                projectText = projectText.Replace(packagePrefix + folder + "/", root + "/");
+            projectText = projectText.Replace(packagePrefix, root + "/");
+
+            string source = Path.Combine(buildPath, root, PackageName);
+            if (!Directory.Exists(source)) continue;
+            foreach (string file in Directory.GetFiles(source, "*", SearchOption.AllDirectories))
+            {
+                string relative = file.Substring(source.Length + 1).Replace('\\', '/');
+                foreach (string folder in PackageFolders)
+                    if (relative.StartsWith(folder + "/", StringComparison.Ordinal))
+                    {
+                        relative = relative.Substring(folder.Length + 1);
+                        break;
+                    }
+                moves.Add(new KeyValuePair<string, string>(file, Path.Combine(buildPath, root, relative)));
+            }
+        }
+
+        // Check every collision before changing the export. Identical files from
+        // an append export are safe; different files require a clean export folder.
+        var destinations = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
+        foreach (var move in moves)
+        {
+            if (!destinations.Add(move.Value) || Directory.Exists(move.Value)
+                || (File.Exists(move.Value) && !FilesEqual(move.Key, move.Value)))
+                throw new BuildFailedException("AppRuntimes iOS export path conflict: " + move.Value
+                    + ". Export to an empty folder or remove the conflicting plugin.");
+        }
+
+        // Validate the rewritten project before moving any files.
+        project.ReadFromString(projectText);
+        foreach (var move in moves)
+        {
+            Directory.CreateDirectory(Path.GetDirectoryName(move.Value));
+            if (File.Exists(move.Value)) File.Delete(move.Key); // Identical, checked above.
+            else File.Move(move.Key, move.Value);
+        }
+        foreach (string root in ExportRoots)
+            RemoveEmptyDirectories(Path.Combine(buildPath, root, PackageName));
+        project.WriteToFile(projectPath);
+    }
+
+    private static string FlattenGroups(string text)
+    {
+        const string begin = "/* Begin PBXGroup section */";
+        const string end = "/* End PBXGroup section */";
+        int start = text.IndexOf(begin, StringComparison.Ordinal);
+        int finish = text.IndexOf(end, StringComparison.Ordinal);
+        if (start < 0 || finish < start)
+            throw new BuildFailedException("AppRuntimes could not find Xcode project groups.");
+
+        string section = text.Substring(start, finish - start);
+        var groups = Regex.Matches(section,
+            @"(?ms)^\t\t(?<id>[A-Fa-f0-9]{24}) /\* .*? \*/ = \{\r?\n.*?^\t\t\};\r?\n")
+            .Cast<Match>().ToDictionary(m => m.Groups["id"].Value);
+        var removed = new HashSet<string>();
+        var replacements = new Dictionary<string, string>();
+
+        foreach (var entry in groups)
+        {
+            string root = GroupPath(entry.Value.Value);
+            if (!ExportRoots.Contains(root)) continue;
+            string children = Children(entry.Value.Value).Groups["items"].Value;
+            foreach (Match child in ChildReferences(children))
+            {
+                string id = child.Groups["id"].Value;
+                if (!groups.TryGetValue(id, out Match package) || GroupPath(package.Value) != PackageName)
+                    continue;
+
+                string promoted = Children(package.Value).Groups["items"].Value;
+                foreach (Match nested in ChildReferences(promoted))
+                {
+                    string nestedId = nested.Groups["id"].Value;
+                    if (groups.TryGetValue(nestedId, out Match wrapper)
+                        && PackageFolders.Contains(GroupPath(wrapper.Value)))
+                    {
+                        promoted = promoted.Replace(nested.Value, Children(wrapper.Value).Groups["items"].Value);
+                        removed.Add(nestedId);
+                    }
+                }
+                children = children.Replace(child.Value, promoted);
+                removed.Add(id);
+            }
+            Match original = Children(entry.Value.Value);
+            Group items = original.Groups["items"];
+            replacements[entry.Key] = entry.Value.Value.Remove(items.Index, items.Length).Insert(items.Index, children);
+        }
+
+        foreach (var entry in groups)
+        {
+            if (removed.Contains(entry.Key)) section = section.Replace(entry.Value.Value, "");
+            else if (replacements.TryGetValue(entry.Key, out string replacement))
+                section = section.Replace(entry.Value.Value, replacement);
+        }
+        if (Regex.IsMatch(section, @"\bpath = ""?" + Regex.Escape(PackageName) + @"""?;"))
+            throw new BuildFailedException("AppRuntimes could not normalize the package's Xcode groups.");
+        return text.Substring(0, start) + section + text.Substring(finish);
+    }
+
+    private static string GroupPath(string group) =>
+        Regex.Match(group, @"(?m)^\s*path = ""?(?<path>[^"";\r\n]+)""?;").Groups["path"].Value;
+
+    private static Match Children(string group) =>
+        Regex.Match(group, @"(?s)children = \(\r?\n(?<items>.*?)\t\t\t\);");
+
+    private static MatchCollection ChildReferences(string children) =>
+        Regex.Matches(children, @"(?m)^\t\t\t\t(?<id>[A-Fa-f0-9]{24}) /\* .*? \*/,\r?\n");
+
+    private static bool FilesEqual(string first, string second)
+    {
+        // Unity's Mono FileStream needs the extended prefix for deep XCFramework paths on Windows.
+        if (Path.DirectorySeparatorChar == '\\')
+        {
+            first = @"\\?\" + Path.GetFullPath(first);
+            second = @"\\?\" + Path.GetFullPath(second);
+        }
+        if (new FileInfo(first).Length != new FileInfo(second).Length) return false;
+        using (var a = File.OpenRead(first))
+        using (var b = File.OpenRead(second))
+        {
+            var left = new byte[81920];
+            var right = new byte[left.Length];
+            int count;
+            while ((count = a.Read(left, 0, left.Length)) > 0)
+            {
+                int read = 0;
+                while (read < count)
+                {
+                    int chunk = b.Read(right, read, count - read);
+                    if (chunk == 0) return false;
+                    read += chunk;
+                }
+                for (int i = 0; i < count; i++)
+                    if (left[i] != right[i]) return false;
+            }
+            return true;
+        }
+    }
+
+    private static void RemoveEmptyDirectories(string directory)
+    {
+        if (!Directory.Exists(directory)) return;
+        foreach (string child in Directory.GetDirectories(directory)) RemoveEmptyDirectories(child);
+        Directory.Delete(directory, false);
+    }
+}
+#endif

+ 2 - 0
Editor/XcodePluginLayout.cs.meta

@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 2ca8aa7de31a46739e98e21d4c0db4da

+ 2 - 1
Editor/XcodePostprocessor.cs

@@ -14,6 +14,7 @@ public static class XcodePostprocessor
 
         UpdateInfoPlist(buildPath);
         UpdateXcodeBuildSettings(buildPath);
+        XcodePluginLayout.Normalize(buildPath);
     }
 
     private static void UpdateInfoPlist(string buildPath)
@@ -56,4 +57,4 @@ public static class XcodePostprocessor
         project.WriteToFile(projectPath);
     }
 }
-#endif
+#endif

+ 4 - 0
README.md

@@ -48,6 +48,10 @@ UI/IMGUI 模块由 UGUI 间接引入。Input System 和 Addressables 按接入
 
 Android 的 Facebook Maven 依赖由保留的 EDM4U/Gradle 解析;AndroidManifest、Gradle 模板属于接入工程。iOS 使用随包提供的 Facebook XCFramework,不再通过 CocoaPods 重复下载。UniWebView 原有平台限制仍适用,例如 Windows Editor 使用占位实现。
 
+iOS 导出后会自动移除 `Frameworks` 和 `Libraries` 中的 `come.app.runtimes` 包目录及 `Runtime` / `ThirdParty` 中间层,采用普通 Assets 插件的布局:`Frameworks/FacebookSDK`、`Frameworks/UniWebView`、`Libraries/FacebookSDK`、`Libraries/IAPiOS` 和 `Libraries/Plugins/iOS`。同时更新 Xcode 分组、文件引用和搜索路径,保留文件 GUID、编译标记及链接/嵌入配置。其他 UPM 包的目录不受影响。首次切换或插件内容更新后建议导出到空目录;目标路径已有不同内容时构建会报冲突,不会覆盖已有插件。
+
+GUPS 的 DLL 使用宿主 `Assets/GUPS/Obfuscator` 作为可写目录。Package 会在编辑器启动及构建开始前创建 Settings、Cache、Log、Temp 目录和对应元数据;缺少 `Settings/Obfuscator_Settings.json` 时复制包内默认配置,已有配置及 GUID 保持不变。SDK 代码继续由 Package 管理,构建过程中不会写入包目录。包内默认配置启用混淆,空工程验证也会实际运行混淆流程。
+
 ## 配置与使用
 
 包内 `Editor/DefaultSettings` 保存来自 `unity_ab_framework` 当前配置的三份默认模板。Unity 编辑器启动、安装包或脚本重编译后,会在资源导入完成时检查并补齐缺失配置:

+ 1 - 1
Runtime/Scripts/AppRuntimes.cs

@@ -49,7 +49,7 @@ public static class AppRuntimes
 
     public static string AppAddress { get; private set; } = Settings.AppAddress;
 
-    public static string PrivacyUrl { get; set; } = Settings.PrivacyUrl;
+    public static string PrivacyUrl { get; set; } = Settings.PrivacyUrl.Trim();
 
     public static string AppChannel { get; private set; } = Settings.AppChannel;
 

+ 67 - 0
Tests~/Editor/AppRuntimesGupsValidation.cs

@@ -0,0 +1,67 @@
+using System;
+using System.IO;
+using System.Linq;
+using GUPS.Obfuscator;
+using Newtonsoft.Json.Linq;
+using UnityEditor;
+using UnityEngine;
+
+public static class AppRuntimesGupsValidation
+{
+    private static byte[] templateBytes;
+    private static string template;
+
+    public static void BeforeBuild()
+    {
+        var package = UnityEditor.PackageManager.PackageInfo.FindForAssembly(typeof(GupsProjectSettings).Assembly);
+        template = Path.Combine(package.resolvedPath, "ThirdParty/GUPS/Obfuscator/Settings/Obfuscator_Settings.json");
+        templateBytes = File.ReadAllBytes(template);
+        Require(File.Exists(GupsProjectSettings.SettingsPath), "GUPS settings initialized on Editor startup");
+        foreach (string folder in new[] { "", "/Obfuscator", "/Obfuscator/Settings", "/Obfuscator/Cache", "/Obfuscator/Log", "/Obfuscator/Temp" })
+            Require(AssetDatabase.IsValidFolder("Assets/GUPS" + folder) && File.Exists("Assets/GUPS" + folder + ".meta"),
+                "GUPS folder and metadata exist before build: " + folder);
+
+        var before = File.ReadAllBytes(GupsProjectSettings.SettingsPath);
+        string guid = AssetDatabase.AssetPathToGUID(GupsProjectSettings.SettingsPath);
+        GupsProjectSettings.EnsureInitialized();
+        Require(before.SequenceEqual(File.ReadAllBytes(GupsProjectSettings.SettingsPath))
+            && guid == AssetDatabase.AssetPathToGUID(GupsProjectSettings.SettingsPath), "Existing GUPS settings and GUID preserved");
+
+        if (!Environment.GetCommandLineArgs().Contains("-appRuntimesPackageOnly")) return;
+        Require(templateBytes.SequenceEqual(before), "Fresh project uses bundled GUPS defaults");
+        Require(Enabled(), "Obfuscation enabled for clean-project regression build");
+
+        // Verify custom project values survive initialization before restoring the test defaults.
+        var custom = JObject.Parse(File.ReadAllText(GupsProjectSettings.SettingsPath));
+        custom["SettingElement_Array"].Single(item => (string)item["Key"] == "Global_Enable_Obfuscation")["Value"] = "False";
+        File.WriteAllText(GupsProjectSettings.SettingsPath, custom.ToString());
+        GupsProjectSettings.EnsureInitialized();
+        Require(!Enabled() && guid == AssetDatabase.AssetPathToGUID(GupsProjectSettings.SettingsPath), "Customized GUPS settings are not overwritten");
+        File.WriteAllBytes(GupsProjectSettings.SettingsPath, before);
+
+        // Reproduce a first build with no legacy GUPS folders; the early build callback must repair it.
+        Require(AssetDatabase.DeleteAsset("Assets/GUPS"), "Remove GUPS workspace in isolated test project");
+        Require(!Directory.Exists("Assets/GUPS"), "No GUPS parent directory before build callbacks");
+    }
+
+    public static void AfterBuild()
+    {
+        Require(File.Exists(GupsProjectSettings.SettingsPath + ".meta"), "GUPS settings metadata restored before SDK write");
+        Require(File.ReadAllBytes(template).SequenceEqual(templateBytes), "Package GUPS template unchanged by build");
+        if (Environment.GetCommandLineArgs().Contains("-appRuntimesPackageOnly"))
+        {
+            Require(Enabled(), "GUPS obfuscation remains enabled after build");
+            Require(Directory.GetFiles("Assets/GUPS/Obfuscator/Log", "*", SearchOption.AllDirectories)
+                .Any(path => !path.EndsWith(".meta", StringComparison.OrdinalIgnoreCase)), "GUPS produced a build report");
+        }
+    }
+
+    private static bool Enabled() => string.Equals((string)JObject.Parse(File.ReadAllText(GupsProjectSettings.SettingsPath))
+        ["SettingElement_Array"].Single(item => (string)item["Key"] == "Global_Enable_Obfuscation")["Value"], "True", StringComparison.OrdinalIgnoreCase);
+
+    private static void Require(bool condition, string check)
+    {
+        if (!condition) throw new Exception("AppRuntimes GUPS validation failed: " + check);
+        Debug.Log("APP_RUNTIMES_GUPS_CHECK_PASS " + check);
+    }
+}

+ 22 - 4
Tests~/Editor/AppRuntimesPackageValidation.cs

@@ -61,14 +61,32 @@ public static class AppRuntimesPackageValidation
         new GameObject("IAP validation").AddComponent<IAPWrapper>();
         const string scenePath = "Assets/AppRuntimesValidation.unity";
         EditorSceneManager.SaveScene(scene, scenePath);
+        // GUPS discovers scene references through EditorBuildSettings, including explicit BuildPlayer scenes.
+        EditorBuildSettings.scenes = new[] { new EditorBuildSettingsScene(scenePath, true) };
         PlayerSettings.SetApplicationIdentifier(NamedBuildTarget.iOS, "come.app.runtimes.validation");
         PlayerSettings.SetScriptingBackend(NamedBuildTarget.iOS, ScriptingImplementation.IL2CPP);
         PlayerSettings.SetManagedStrippingLevel(NamedBuildTarget.iOS, ManagedStrippingLevel.High);
-        var report = BuildPipeline.BuildPlayer(new BuildPlayerOptions {
-            scenes = new[] { scenePath }, target = BuildTarget.iOS,
-            locationPathName = "Build/iOS", options = BuildOptions.None
-        });
+        AppRuntimesGupsValidation.BeforeBuild();
+        bool obfuscationSkipped = false;
+        Application.LogCallback checkObfuscation = (message, stack, type) => {
+            if (message.Contains("Obfuscation is deactivated")) obfuscationSkipped = true;
+        };
+        BuildReport report;
+        Application.logMessageReceived += checkObfuscation;
+        try
+        {
+            report = BuildPipeline.BuildPlayer(new BuildPlayerOptions {
+                scenes = new[] { scenePath }, target = BuildTarget.iOS,
+                locationPathName = "Build/iOS", options = BuildOptions.None
+            });
+        }
+        finally { Application.logMessageReceived -= checkObfuscation; }
         Require(report != null && report.summary.result == BuildResult.Succeeded, "iOS build export");
+        Require(report.summary.totalErrors == 0, "iOS build has no reported errors");
+        if (Environment.GetCommandLineArgs().Contains("-appRuntimesPackageOnly"))
+            Require(!obfuscationSkipped, "GUPS obfuscation was not skipped");
+        AppRuntimesGupsValidation.AfterBuild();
+        AppRuntimesXcodeLayoutValidation.Verify("Build/iOS");
         var project = new UnityEditor.iOS.Xcode.PBXProject();
         project.ReadFromFile("Build/iOS/Unity-iPhone.xcodeproj/project.pbxproj");
         var bridge = project.GetRealPathsOfAllFiles(UnityEditor.iOS.Xcode.PBXSourceTree.Source)

+ 129 - 0
Tests~/Editor/AppRuntimesXcodeLayoutValidation.cs

@@ -0,0 +1,129 @@
+#if UNITY_IOS
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Reflection;
+using System.Security.Cryptography;
+using System.Text.RegularExpressions;
+using UnityEditor;
+using UnityEditor.Callbacks;
+using UnityEditor.iOS.Xcode;
+
+public static class AppRuntimesXcodeLayoutValidation
+{
+    private static string originalProject;
+    private static Dictionary<string, string> hashes;
+
+    [PostProcessBuild(999)]
+    public static void Capture(BuildTarget target, string buildPath)
+    {
+        if (target != BuildTarget.iOS) return;
+        var project = new PBXProject();
+        project.ReadFromFile(PBXProject.GetPBXProjectPath(buildPath));
+        originalProject = project.WriteToString();
+        hashes = new Dictionary<string, string>();
+        foreach (string root in new[] { "Frameworks", "Libraries" })
+        {
+            string directory = Path.Combine(buildPath, root, "come.app.runtimes");
+            foreach (string file in Directory.GetFiles(directory, "*", SearchOption.AllDirectories))
+                hashes.Add(Map(file.Substring(buildPath.Length + 1).Replace('\\', '/')), Hash(file));
+        }
+    }
+
+    public static void Verify(string buildPath)
+    {
+        Require(hashes != null && hashes.Count > 0, "Captured package native files before normalization");
+        string projectPath = PBXProject.GetPBXProjectPath(buildPath);
+        var before = new PBXProject();
+        before.ReadFromString(originalProject);
+        var after = new PBXProject();
+        after.ReadFromFile(projectPath);
+        string text = after.WriteToString();
+        foreach (string root in new[] { "Frameworks", "Libraries" })
+        {
+            Require(!Directory.Exists(Path.Combine(buildPath, root, "come.app.runtimes")), "Removed package directory: " + root);
+            Require(!text.Contains(root + "/come.app.runtimes/"), "No stale package paths: " + root);
+        }
+        Require(!text.Contains("/* come.app.runtimes */"), "Removed package groups from Xcode navigator");
+        foreach (var file in hashes)
+            Require(File.Exists(Path.Combine(buildPath, file.Key)) && Hash(Path.Combine(buildPath, file.Key)) == file.Value,
+                "Native file preserved: " + file.Key);
+
+        foreach (string path in before.GetRealPathsOfAllFiles(PBXSourceTree.Source))
+        {
+            string guid = before.FindFileGuidByRealPath(path, PBXSourceTree.Source);
+            Require(after.FindFileGuidByRealPath(Map(path), PBXSourceTree.Source) == guid, "File GUID preserved: " + path);
+            if (path.StartsWith("Frameworks/come.app.runtimes/") || path.StartsWith("Libraries/come.app.runtimes/"))
+                Require(after.FindFileGuidByProjectPath(Map(path)) == guid, "Navigator group path matches native file: " + path);
+            foreach (string target in new[] { before.GetUnityMainTargetGuid(), before.GetUnityFrameworkTargetGuid() })
+            {
+                var flagsBefore = before.GetCompileFlagsForFile(target, guid);
+                var flagsAfter = after.GetCompileFlagsForFile(target, guid);
+                // Facebook credentials gains ARC in the existing callback at order 1000.
+                if (Path.GetFileName(path) == "FacebookDynamicCredentials.m") continue;
+                Require((flagsBefore ?? new List<string>()).SequenceEqual(flagsAfter ?? new List<string>()),
+                    "Compiler flags preserved: " + path);
+            }
+        }
+        foreach (string section in new[] { "PBXSourcesBuildPhase", "PBXFrameworksBuildPhase", "PBXCopyFilesBuildPhase" })
+        {
+            // LocalFacebookSdk adds system frameworks; all original memberships must survive.
+            string oldSection = Section(originalProject, section);
+            string newSection = Section(text, section);
+            foreach (Match guid in Regex.Matches(oldSection, @"\b[A-Fa-f0-9]{24}\b"))
+                Require(newSection.Contains(guid.Value), "Build phase membership preserved: " + section);
+        }
+        Require(Directory.Exists(Path.Combine(buildPath, "Frameworks/FacebookSDK/Plugins/iOS/XCFrameworks")), "Standard Facebook framework layout");
+        Require(Directory.Exists(Path.Combine(buildPath, "Frameworks/UniWebView/Plugins/iOS/UniWebView.xcframework")), "Standard UniWebView framework layout");
+        Require(File.Exists(Path.Combine(buildPath, "Libraries/Plugins/iOS/AppRuntimesNative.mm")), "Standard native plugin layout");
+
+        Normalize(buildPath);
+        Require(File.ReadAllText(projectPath) == text, "Normalization is idempotent");
+
+        // Exercise append exports and collision protection without touching the real export.
+        string fixture = Path.GetFullPath("Library/XcodeLayoutFixture-" + Guid.NewGuid().ToString("N"));
+        string fixtureProject = PBXProject.GetPBXProjectPath(fixture);
+        Directory.CreateDirectory(Path.GetDirectoryName(fixtureProject));
+        const string sourcePath = "Libraries/come.app.runtimes/Runtime/Plugins/iOS/DeviceTimeZone.mm";
+        string source = Path.Combine(fixture, sourcePath);
+        string destination = Path.Combine(fixture, Map(sourcePath));
+        Directory.CreateDirectory(Path.GetDirectoryName(source));
+        Directory.CreateDirectory(Path.GetDirectoryName(destination));
+        File.WriteAllText(fixtureProject, originalProject);
+        File.WriteAllText(source, "new plugin");
+        File.WriteAllText(destination, "host plugin");
+        bool rejected = false;
+        try { Normalize(fixture); }
+        catch (TargetInvocationException exception) when (exception.InnerException is UnityEditor.Build.BuildFailedException) { rejected = true; }
+        Require(rejected && File.ReadAllText(source) == "new plugin" && File.ReadAllText(destination) == "host plugin"
+            && File.ReadAllText(fixtureProject) == originalProject, "Conflicts fail before changing export");
+        File.WriteAllText(destination, "new plugin");
+        Normalize(fixture);
+        Require(!File.Exists(source) && File.ReadAllText(destination) == "new plugin", "Identical append-export files supported");
+        UnityEngine.Debug.Log("APP_RUNTIMES_XCODE_LAYOUT_VALIDATION_PASS");
+    }
+
+    private static void Normalize(string path) => typeof(XcodePostprocessor).Assembly
+        .GetType("XcodePluginLayout").GetMethod("Normalize", BindingFlags.Static | BindingFlags.NonPublic)
+        .Invoke(null, new object[] { path });
+
+    private static string Map(string path) => Regex.Replace(path,
+        @"^(Frameworks|Libraries)/come\.app\.runtimes/(?:(?:Runtime|ThirdParty)/)?", "$1/");
+
+    private static string Hash(string path)
+    {
+        if (Path.DirectorySeparatorChar == '\\') path = @"\\?\" + Path.GetFullPath(path);
+        using (var sha = SHA256.Create())
+        using (var stream = File.OpenRead(path)) return Convert.ToBase64String(sha.ComputeHash(stream));
+    }
+
+    private static string Section(string text, string name) => Regex.Match(text,
+        @"(?s)/\* Begin " + name + @" section \*/.*?/\* End " + name + @" section \*/").Value;
+
+    private static void Require(bool condition, string message)
+    {
+        if (!condition) throw new Exception("Xcode layout validation failed: " + message);
+    }
+}
+#endif

+ 4 - 1
ThirdParty/GUPS/Obfuscator/Editor/BuildPostProcessor.cs

@@ -61,6 +61,9 @@ namespace GUPS.Obfuscator
 
         public void OnPreprocessBuild(BuildReport _Report)
         {
+            // Also guard direct invocations that bypass Unity's earlier build callbacks.
+            GupsProjectSettings.EnsureInitialized();
+
             // Settings
             GUPS.Obfuscator.Editor.Settings.Unity.Editor.EditorSettings var_EditorSettings = PrepareEditorSettings();
             GUPS.Obfuscator.Editor.Settings.Unity.Build.BuildSettings var_BuildSettings = PrepareBuildSettings(_Report);
@@ -170,4 +173,4 @@ namespace GUPS.Obfuscator
         }
     }
 }
-#endif
+#endif

+ 67 - 0
ThirdParty/GUPS/Obfuscator/Editor/GupsProjectSettings.cs

@@ -0,0 +1,67 @@
+using System.IO;
+using UnityEditor;
+using UnityEditor.Build;
+using UnityEditor.Build.Reporting;
+using PackageInfo = UnityEditor.PackageManager.PackageInfo;
+
+namespace GUPS.Obfuscator
+{
+    // The vendor DLL uses fixed project paths for writable settings and build data.
+    public static class GupsProjectSettings
+    {
+        public const string SettingsPath = "Assets/GUPS/Obfuscator/Settings/Obfuscator_Settings.json";
+        private const string TemplatePath = "ThirdParty/GUPS/Obfuscator/Settings/Obfuscator_Settings.json";
+
+        public static void EnsureInitialized()
+        {
+            foreach (string folder in new[] { "Settings", "Cache", "Log", "Temp" })
+                EnsureFolder("Assets/GUPS/Obfuscator/" + folder);
+
+            // Preserve project-specific changes, including the obfuscation enable flag.
+            if (File.Exists(SettingsPath))
+            {
+                if (!File.Exists(SettingsPath + ".meta"))
+                    AssetDatabase.ImportAsset(SettingsPath, ImportAssetOptions.ForceSynchronousImport);
+                return;
+            }
+
+            var package = PackageInfo.FindForAssembly(typeof(GupsProjectSettings).Assembly);
+            string template = package?.assetPath + "/" + TemplatePath;
+            if (package == null || AssetDatabase.LoadAssetAtPath<UnityEngine.TextAsset>(template) == null)
+                throw new BuildFailedException("AppRuntimes GUPS default settings could not be loaded: " + template);
+            if (!AssetDatabase.CopyAsset(template, SettingsPath))
+                throw new BuildFailedException("Could not initialize GUPS project settings: " + SettingsPath);
+        }
+
+        private static void EnsureFolder(string path)
+        {
+            if (path == "Assets") return;
+            EnsureFolder(Path.GetDirectoryName(path).Replace('\\', '/'));
+            if (AssetDatabase.IsValidFolder(path) && File.Exists(path + ".meta")) return;
+
+            // A previous failed build may have left a directory without its metadata.
+            if (Directory.Exists(path))
+                AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceSynchronousImport);
+            else
+                AssetDatabase.CreateFolder(Path.GetDirectoryName(path).Replace('\\', '/'), Path.GetFileName(path));
+
+            if (!AssetDatabase.IsValidFolder(path) || !File.Exists(path + ".meta"))
+                throw new BuildFailedException("Could not initialize GUPS project folder and metadata: " + path);
+        }
+    }
+
+    internal sealed class GupsSettingsInitializer : AssetPostprocessor
+    {
+        private static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets,
+            string[] movedAssets, string[] movedFromAssetPaths, bool didDomainReload)
+        {
+            if (didDomainReload) GupsProjectSettings.EnsureInitialized();
+        }
+    }
+
+    internal sealed class GupsSettingsBuildPreparation : IPreprocessBuildWithReport
+    {
+        public int callbackOrder => int.MinValue;
+        public void OnPreprocessBuild(BuildReport report) => GupsProjectSettings.EnsureInitialized();
+    }
+}

+ 11 - 0
ThirdParty/GUPS/Obfuscator/Editor/GupsProjectSettings.cs.meta

@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 4137e19016cd4d8e8f8a3d7aada82754
+MonoImporter:
+  externalObjects: {}
+  serializedVersion: 2
+  defaultReferences: []
+  executionOrder: 0
+  icon: {instanceID: 0}
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 5 - 0
Tools~/Validate-iOS.ps1

@@ -38,6 +38,8 @@ if ($SourceProject) {
 [IO.File]::WriteAllText($taskManifestPath, ($taskManifest | ConvertTo-Json -Depth 20))
 Copy-Item -LiteralPath (Join-Path $taskPackage 'Tests~/Editor/AppRuntimesPackageValidation.cs') -Destination (Join-Path $taskProject 'Assets/Editor/AppRuntimesPackageValidation.cs')
 Copy-Item -LiteralPath (Join-Path $taskPackage 'Tests~/Editor/AppRuntimesSettingsValidation.cs') -Destination (Join-Path $taskProject 'Assets/Editor/AppRuntimesSettingsValidation.cs')
+Copy-Item -LiteralPath (Join-Path $taskPackage 'Tests~/Editor/AppRuntimesGupsValidation.cs') -Destination (Join-Path $taskProject 'Assets/Editor/AppRuntimesGupsValidation.cs')
+Copy-Item -LiteralPath (Join-Path $taskPackage 'Tests~/Editor/AppRuntimesXcodeLayoutValidation.cs') -Destination (Join-Path $taskProject 'Assets/Editor/AppRuntimesXcodeLayoutValidation.cs')
 Copy-Item -LiteralPath (Join-Path $taskPackage 'Tests~/Runtime/AppRuntimesValidationStartup.cs') -Destination (Join-Path $taskProject 'Assets/AppRuntimesValidationStartup.cs')
 $taskBaseline = @()
 foreach ($taskAsset in (Get-ChildItem -LiteralPath (Join-Path $taskProject 'Assets') -Recurse -File)) {
@@ -61,5 +63,8 @@ $taskProcess = Start-Process -FilePath $UnityPath -ArgumentList $taskArguments -
 if ($taskProcess.ExitCode -ne 0 -or -not (Select-String -LiteralPath $taskLog -Pattern $taskMarker -Quiet)) {
     throw "Validation failed (exit $($taskProcess.ExitCode)). Inspect $taskLog"
 }
+if (Select-String -LiteralPath $taskLog -Pattern 'Failed to write meta file|Cannot open file.*Settings.meta|\[OPS\] Error:' -Quiet) {
+    throw "Validation logged an asset-write or obfuscator error. Inspect $taskLog"
+}
 if ($SettingsOnly) { Write-Output "PASS: settings startup, defaults and preservation. Project: $taskProject" }
 else { Write-Output "PASS: iOS. Xcode project: $taskProject/Build/iOS" }