Welcome to mirror list, hosted at ThFree Co, Russian Federation.

Xcode.cs « AppleAppBuilder « tasks « src - github.com/dotnet/runtime.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 442eb539af38b2c5ef2a190055b99174dd650c4a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

internal class Xcode
{
    private string RuntimeIdentifier { get; set; }
    private string SysRoot { get; set; }
    private string Target { get; set; }

    public Xcode(string target, string arch)
    {
        Target = target;
        switch (Target)
        {
            case TargetNames.iOS:
                SysRoot = Utils.RunProcess("xcrun", "--sdk iphoneos --show-sdk-path");
                break;
            case TargetNames.iOSsim:
                SysRoot = Utils.RunProcess("xcrun", "--sdk iphonesimulator --show-sdk-path");
                break;
            case TargetNames.tvOS:
                SysRoot = Utils.RunProcess("xcrun", "--sdk appletvos --show-sdk-path");
                break;
            case TargetNames.tvOSsim:
                SysRoot = Utils.RunProcess("xcrun", "--sdk appletvsimulator --show-sdk-path");
                break;
            default:
                SysRoot = Utils.RunProcess("xcrun", "--sdk macosx --show-sdk-path");
                break;
        }

        RuntimeIdentifier = $"{Target}-{arch}";
    }

    public bool EnableRuntimeLogging { get; set; }

    public string GenerateXCode(
        string projectName,
        string entryPointLib,
        IEnumerable<string> asmFiles,
        string workspace,
        string binDir,
        string monoInclude,
        bool preferDylibs,
        bool useConsoleUiTemplate,
        bool forceAOT,
        bool forceInterpreter,
        bool invariantGlobalization,
        bool stripDebugSymbols,
        string? nativeMainSource = null)
    {
        // bundle everything as resources excluding native files
        var excludes = new List<string> { ".dll.o", ".dll.s", ".dwarf", ".m", ".h", ".a", ".bc", "libmonosgen-2.0.dylib" };
        if (stripDebugSymbols)
        {
            excludes.Add(".pdb");
        }

        string[] resources = Directory.GetFiles(workspace)
            .Where(f => !excludes.Any(e => f.EndsWith(e, StringComparison.InvariantCultureIgnoreCase)))
            .Concat(Directory.GetFiles(binDir, "*.aotdata"))
            .ToArray();

        if (string.IsNullOrEmpty(nativeMainSource))
        {
            // use built-in main.m (with default UI) if it's not set
            nativeMainSource = Path.Combine(binDir, "main.m");
            File.WriteAllText(nativeMainSource, Utils.GetEmbeddedResource(useConsoleUiTemplate ? "main-console.m" : "main-simple.m"));
        }
        else
        {
            string newMainPath = Path.Combine(binDir, "main.m");
            if (nativeMainSource != newMainPath)
            {
                File.Copy(nativeMainSource, Path.Combine(binDir, "main.m"), true);
                nativeMainSource = newMainPath;
            }
        }

        var entitlements = new List<KeyValuePair<string, string>>();

        bool hardenedRuntime = false;
        if (Target == TargetNames.MacCatalyst && !(forceInterpreter || forceAOT)) {
            hardenedRuntime = true;

            /* for mmmap MAP_JIT */
            entitlements.Add (KeyValuePair.Create ("com.apple.security.cs.allow-jit", "<true/>"));
            /* for loading unsigned dylibs like libicu from outside the bundle or libSystem.Native.dylib from inside */
            entitlements.Add (KeyValuePair.Create ("com.apple.security.cs.disable-library-validation", "<true/>"));
        }

        string cmakeLists = Utils.GetEmbeddedResource("CMakeLists.txt.template")
            .Replace("%ProjectName%", projectName)
            .Replace("%AppResources%", string.Join(Environment.NewLine, resources.Select(r => "    " + r)))
            .Replace("%MainSource%", nativeMainSource)
            .Replace("%MonoInclude%", monoInclude)
            .Replace("%HardenedRuntime%", hardenedRuntime ? "TRUE" : "FALSE");


        string[] dylibs = Directory.GetFiles(workspace, "*.dylib");
        string toLink = "";
        foreach (string lib in Directory.GetFiles(workspace, "*.a"))
        {
            string libName = Path.GetFileNameWithoutExtension(lib);
            // libmono must always be statically linked, for other librarires we can use dylibs
            bool dylibExists = libName != "libmonosgen-2.0" && dylibs.Any(dylib => Path.GetFileName(dylib) == libName + ".dylib");

            if (forceAOT || !(preferDylibs && dylibExists))
            {
                // these libraries are pinvoked
                // -force_load will be removed once we enable direct-pinvokes for AOT
                toLink += $"    \"-force_load {lib}\"{Environment.NewLine}";
            }
        }

        string aotSources = "";
        foreach (string asm in asmFiles)
        {
            // these libraries are linked via modules.m
            var name = Path.GetFileNameWithoutExtension(asm);
            aotSources += $"add_library({name} OBJECT {asm}){Environment.NewLine}";
            toLink += $"    {name}{Environment.NewLine}";
        }

        string frameworks = "";
        if ((Target == TargetNames.iOS) || (Target == TargetNames.iOSsim) || (Target == TargetNames.MacCatalyst))
        {
            frameworks = "\"-framework GSS\"";
        }

        cmakeLists = cmakeLists.Replace("%FrameworksToLink%", frameworks);
        cmakeLists = cmakeLists.Replace("%NativeLibrariesToLink%", toLink);
        cmakeLists = cmakeLists.Replace("%AotSources%", aotSources);
        cmakeLists = cmakeLists.Replace("%AotModulesSource%", string.IsNullOrEmpty(aotSources) ? "" : "modules.m");

        var defines = new StringBuilder();
        if (forceInterpreter)
        {
            defines.AppendLine("add_definitions(-DFORCE_INTERPRETER=1)");
        }
        else if (forceAOT)
        {
            defines.AppendLine("add_definitions(-DFORCE_AOT=1)");
        }

        if (invariantGlobalization)
        {
            defines.AppendLine("add_definitions(-DINVARIANT_GLOBALIZATION=1)");
        }

        if (EnableRuntimeLogging)
        {
            defines.AppendLine("add_definitions(-DENABLE_RUNTIME_LOGGING=1)");
        }

        cmakeLists = cmakeLists.Replace("%Defines%", defines.ToString());

        string plist = Utils.GetEmbeddedResource("Info.plist.template")
            .Replace("%BundleIdentifier%", projectName);

        File.WriteAllText(Path.Combine(binDir, "Info.plist"), plist);

        var needEntitlements = entitlements.Count != 0;
        cmakeLists = cmakeLists.Replace("%HardenedRuntimeUseEntitlementsFile%",
                                        needEntitlements ? "TRUE" : "FALSE");

        File.WriteAllText(Path.Combine(binDir, "CMakeLists.txt"), cmakeLists);

        if (needEntitlements) {
            var ent = new StringBuilder();
            foreach ((var key, var value) in entitlements) {
                ent.AppendLine ($"<key>{key}</key>");
                ent.AppendLine (value);
            }
            string entitlementsTemplate = Utils.GetEmbeddedResource("app.entitlements.template");
            File.WriteAllText(Path.Combine(binDir, "app.entitlements"), entitlementsTemplate.Replace("%Entitlements%", ent.ToString()));
        }

        string targetName;
        switch (Target)
        {
            case TargetNames.MacCatalyst:
                targetName = "Darwin";
                break;
            case TargetNames.iOS:
            case TargetNames.iOSsim:
                targetName = "iOS";
                break;
            case TargetNames.tvOS:
            case TargetNames.tvOSsim:
                targetName = "tvOS";
                break;
            default:
                targetName = Target.ToString();
                break;
        }
        var deployTarget = (Target == TargetNames.MacCatalyst) ? " -DCMAKE_OSX_ARCHITECTURES=\"x86_64 arm64\"" : " -DCMAKE_OSX_DEPLOYMENT_TARGET=10.1";
        var cmakeArgs = new StringBuilder();
        cmakeArgs
            .Append("-S.")
            .Append(" -B").Append(projectName)
            .Append(" -GXcode")
            .Append(" -DCMAKE_SYSTEM_NAME=" + targetName)
            .Append(deployTarget);

        File.WriteAllText(Path.Combine(binDir, "runtime.h"),
            Utils.GetEmbeddedResource("runtime.h"));

        // forward pinvokes to "__Internal"
        var dllMap = new StringBuilder();
        foreach (string aFile in Directory.GetFiles(workspace, "*.a"))
        {
            string aFileName = Path.GetFileNameWithoutExtension(aFile);
            dllMap.AppendLine($"    mono_dllmap_insert (NULL, \"{aFileName}\", NULL, \"__Internal\", NULL);");

            // also register with or without "lib" prefix
            aFileName = aFileName.StartsWith("lib") ? aFileName.Remove(0, 3) : "lib" + aFileName;
            dllMap.AppendLine($"    mono_dllmap_insert (NULL, \"{aFileName}\", NULL, \"__Internal\", NULL);");
        }

        dllMap.AppendLine($"    mono_dllmap_insert (NULL, \"System.Globalization.Native\", NULL, \"__Internal\", NULL);");

        File.WriteAllText(Path.Combine(binDir, "runtime.m"),
            Utils.GetEmbeddedResource("runtime.m")
                .Replace("//%DllMap%", dllMap.ToString())
                .Replace("//%APPLE_RUNTIME_IDENTIFIER%", RuntimeIdentifier)
                .Replace("%EntryPointLibName%", Path.GetFileName(entryPointLib)));

        Utils.RunProcess("cmake", cmakeArgs.ToString(), workingDir: binDir);

        return Path.Combine(binDir, projectName, projectName + ".xcodeproj");
    }

    public string BuildAppBundle(
        string xcodePrjPath, string architecture, bool optimized, string? devTeamProvisioning = null)
    {
        string sdk = "";
        var args = new StringBuilder();
        args.Append("ONLY_ACTIVE_ARCH=YES");

        if (devTeamProvisioning == "-")
        {
            args.Append(" CODE_SIGN_IDENTITY=\"\"")
                .Append(" CODE_SIGNING_REQUIRED=NO")
                .Append(" CODE_SIGNING_ALLOWED=NO");
        }
        else
        {
            args.Append(" -allowProvisioningUpdates")
                .Append(" DEVELOPMENT_TEAM=").Append(devTeamProvisioning);
        }


        if (architecture == "arm64")
        {
            switch (Target)
            {
                case TargetNames.iOS:
                    sdk = "iphoneos";
                    args.Append(" -arch arm64")
                        .Append(" -sdk " + sdk);
                    break;
                case TargetNames.iOSsim:
                    sdk = "iphonesimulator";
                    args.Append(" -arch arm64")
                        .Append(" -sdk " + sdk);
                    break;
                case TargetNames.tvOS:
                    sdk = "appletvos";
                    args.Append(" -arch arm64")
                        .Append(" -sdk " + sdk);
                    break;
                case TargetNames.tvOSsim:
                    sdk = "appletvsimulator";
                    args.Append(" -arch arm64")
                        .Append(" -sdk " + sdk);
                    break;
                default:
                    sdk = "maccatalyst";
                    args.Append(" -scheme \"" + Path.GetFileNameWithoutExtension(xcodePrjPath) + "\"")
                        .Append(" -destination \"platform=macOS,arch=arm64,variant=Mac Catalyst\"")
                        .Append(" -UseModernBuildSystem=YES")
                        .Append(" IPHONEOS_DEPLOYMENT_TARGET=14.2");
                    break;
            }
        }
        else
        {
            switch (Target)
            {
                case TargetNames.iOSsim:
                    sdk = "iphonesimulator";
                    args.Append(" -arch x86_64")
                        .Append(" -sdk " + sdk);
                    break;
                case TargetNames.tvOSsim:
                    sdk = "appletvsimulator";
                    args.Append(" -arch x86_64")
                        .Append(" -sdk " + sdk);
                    break;
                default:
                    sdk = "maccatalyst";
                    args.Append(" -scheme \"" + Path.GetFileNameWithoutExtension(xcodePrjPath) + "\"")
                        .Append(" -destination \"platform=macOS,arch=x86_64,variant=Mac Catalyst\"")
                        .Append(" -UseModernBuildSystem=YES")
                        .Append(" IPHONEOS_DEPLOYMENT_TARGET=13.5");
                    break;
            }
        }

        string config = optimized ? "Release" : "Debug";
        args.Append(" -configuration ").Append(config);

        Utils.RunProcess("xcodebuild", args.ToString(), workingDir: Path.GetDirectoryName(xcodePrjPath));

        string appPath = Path.Combine(Path.GetDirectoryName(xcodePrjPath)!, config + "-" + sdk,
            Path.GetFileNameWithoutExtension(xcodePrjPath) + ".app");

        long appSize = new DirectoryInfo(appPath)
            .EnumerateFiles("*", SearchOption.AllDirectories)
            .Sum(file => file.Length);

        Utils.LogInfo($"\nAPP size: {(appSize / 1000_000.0):0.#} Mb.\n");

        return appPath;
    }
}