-
Notifications
You must be signed in to change notification settings - Fork 512
/
Target.mtouch.cs
1721 lines (1493 loc) · 63.4 KB
/
Target.mtouch.cs
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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2013--2014 Xamarin Inc. All rights reserved.
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using MonoTouch.Tuner;
using Mono.Cecil;
using Mono.Tuner;
using Mono.Linker;
using Xamarin.Linker;
using Xamarin.Utils;
using Registrar;
namespace Xamarin.Bundler
{
public class BundleFileInfo
{
public HashSet<string> Sources = new HashSet<string> ();
public bool DylibToFramework;
}
public partial class Target {
public string TargetDirectory;
public string AppTargetDirectory;
public MonoTouchManifestResolver ManifestResolver = new MonoTouchManifestResolver ();
public AssemblyDefinition ProductAssembly;
// directories used during the build process
public string ArchDirectory;
public string PreBuildDirectory;
public string BuildDirectory;
public string LinkDirectory;
public Dictionary<string, BundleFileInfo> BundleFiles = new Dictionary<string, BundleFileInfo> ();
Dictionary<Abi, CompileTask> pinvoke_tasks = new Dictionary<Abi, CompileTask> ();
List<CompileTask> link_with_task_output = new List<CompileTask> ();
List<AOTTask> aot_dependencies = new List<AOTTask> ();
List<LinkTask> embeddinator_tasks = new List<LinkTask> ();
Dictionary<Abi, CompilerFlags> linker_flags_by_abi = new Dictionary<Abi, CompilerFlags> ();
Dictionary<Abi, NativeLinkTask> link_tasks = new Dictionary<Abi, NativeLinkTask> ();
// If the assemblies were symlinked.
public bool Symlinked;
// This is a list of all the architectures we need to build, which may include any architectures
// in any extensions (but not the main app).
List<Abi> all_architectures;
public List<Abi> AllArchitectures {
get {
if (all_architectures == null) {
all_architectures = new List<Abi> ();
var mask = Is32Build ? Abi.Arch32Mask : Abi.Arch64Mask;
foreach (var abi in App.AllArchitectures) {
var a = abi & mask;
if (a != 0)
all_architectures.Add (abi);
}
}
return all_architectures;
}
}
List<Abi> GetArchitectures (AssemblyBuildTarget build_target)
{
switch (build_target) {
case AssemblyBuildTarget.StaticObject:
case AssemblyBuildTarget.DynamicLibrary:
return Abis;
case AssemblyBuildTarget.Framework:
return AllArchitectures;
default:
throw ErrorHelper.CreateError (100, Errors.MT0100, build_target);
}
}
public void AddToBundle (string source, string bundle_path = null, bool dylib_to_framework_conversion = false)
{
BundleFileInfo info;
if (bundle_path == null)
bundle_path = Path.GetFileName (source);
if (!BundleFiles.TryGetValue (bundle_path, out info))
BundleFiles [bundle_path] = info = new BundleFileInfo () { DylibToFramework = dylib_to_framework_conversion };
if (info.DylibToFramework != dylib_to_framework_conversion)
throw ErrorHelper.CreateError (99, Errors.MX0099, "'invalid value for framework conversion'");
info.Sources.Add (source);
}
void LinkWithBuildTarget (AssemblyBuildTarget build_target, string name, CompileTask link_task, IEnumerable<Assembly> assemblies)
{
switch (build_target) {
case AssemblyBuildTarget.StaticObject:
LinkWithTaskOutput (link_task);
break;
case AssemblyBuildTarget.DynamicLibrary:
if (!(!App.HasFrameworksDirectory && assemblies.Any ((asm) => asm.IsCodeShared)))
AddToBundle (link_task.OutputFile);
LinkWithTaskOutput (link_task);
break;
case AssemblyBuildTarget.Framework:
if (!(!App.HasFrameworksDirectory && assemblies.Any ((asm) => asm.IsCodeShared)))
AddToBundle (link_task.OutputFile, $"Frameworks/{name}.framework/{name}", dylib_to_framework_conversion: true);
LinkWithTaskOutput (link_task);
break;
default:
throw ErrorHelper.CreateError (100, Errors.MT0100, build_target);
}
}
public void LinkWithTaskOutput (CompileTask task)
{
if (task.SharedLibrary) {
LinkWithDynamicLibrary (task.Abi, task.OutputFile);
} else {
LinkWithStaticLibrary (task.Abi, task.OutputFile);
}
link_with_task_output.Add (task);
}
public void LinkWithTaskOutput (IEnumerable<CompileTask> tasks)
{
foreach (var t in tasks)
LinkWithTaskOutput (t);
}
public void LinkWithStaticLibrary (Abi abi, string path)
{
linker_flags_by_abi [abi & Abi.ArchMask].AddLinkWith (path);
}
public void LinkWithStaticLibrary (Abi abi, IEnumerable<string> paths)
{
linker_flags_by_abi [abi & Abi.ArchMask].AddLinkWith (paths);
}
public void LinkWithFramework (Abi abi, string path)
{
linker_flags_by_abi [abi & Abi.ArchMask].AddFramework (path);
}
public void LinkWithDynamicLibrary (Abi abi, string path)
{
linker_flags_by_abi [abi & Abi.ArchMask].AddLinkWith (path);
}
PInvokeWrapperGenerator pinvoke_state;
PInvokeWrapperGenerator MarshalNativeExceptionsState {
get {
if (!App.RequiresPInvokeWrappers)
return null;
if (pinvoke_state == null) {
pinvoke_state = new PInvokeWrapperGenerator ()
{
App = App,
SourcePath = Path.Combine (ArchDirectory, "pinvokes.m"),
HeaderPath = Path.Combine (ArchDirectory, "pinvokes.h"),
Registrar = (StaticRegistrar) StaticRegistrar,
};
}
return pinvoke_state;
}
}
Dictionary<Abi, string> executables;
public IDictionary<Abi, string> Executables {
get {
if (executables == null) {
executables = new Dictionary<Abi, string> ();
if (App.IsSimulatorBuild && App.ArchSpecificExecutable) {
// When using simlauncher, we copy the executable directly to the target directory.
// When not using the simlauncher, but still building for the simulator, we write the executable to a arch-specific app directory (if building for both 32-bit and 64-bit), or just the app directory (if building for a single architecture)
if (Abis.Count != 1)
throw ErrorHelper.CreateError (99, Errors.MX0099, $"expected exactly one abi for a simulator architecture, found: {string.Join(", ", Abis.Select((v) => v.ToString()))}");
executables.Add (Abis [0], Path.Combine (TargetDirectory, App.ExecutableName));
} else {
foreach (var abi in Abis)
executables.Add (abi, Path.Combine (Path.Combine (App.Cache.Location, abi.AsArchString (), App.ExecutableName)));
}
}
return executables;
}
}
public void Initialize (bool show_warnings)
{
// we want to load our own mscorlib[-runtime].dll, not something else we're being feeded
// (e.g. bug #6612) since it might not match the libmono[-sgen].a library we'll link with,
// so load the corlib we want first.
var corlib_path = Path.Combine (Resolver.FrameworkDirectory, "mscorlib.dll");
var corlib = ManifestResolver.Load (corlib_path);
if (corlib == null)
throw new ProductException (2006, true, Errors.MT2006, corlib_path);
var roots = new List<AssemblyDefinition> ();
foreach (var root_assembly in App.RootAssemblies) {
var root = ManifestResolver.Load (root_assembly);
if (root == null) {
// We check elsewhere that the path exists, so I'm not sure how we can get into this.
throw ErrorHelper.CreateError (2019, Errors.MT2019, root_assembly);
}
roots.Add (root);
}
foreach (var reference in App.References) {
var ad = ManifestResolver.Load (reference);
if (ad == null)
throw new ProductException (2002, true, Errors.MT2002, reference);
var root_assembly = roots.FirstOrDefault ((v) => v.MainModule.FileName == ad.MainModule.FileName);
if (root_assembly != null) {
// If we asked the manifest resolver for assembly X and got back a root assembly, it means the requested assembly has the same identity as the root assembly, which is not allowed.
throw ErrorHelper.CreateError (23, Errors.MT0023, root_assembly.MainModule.FileName, reference);
}
if (ad.MainModule.Runtime > TargetRuntime.Net_4_0)
ErrorHelper.Show (new ProductException (11, false, Errors.MT0011, Path.GetFileName (reference), ad.MainModule.Runtime));
// Figure out if we're referencing Xamarin.iOS or monotouch.dll
var filename = ad.MainModule.FileName;
if (Path.GetFileNameWithoutExtension (filename) == Driver.GetProductAssembly (App))
ProductAssembly = ad;
// repl / interpreter is a special case where some assemblies can switch location
if (ManifestResolver.EnableRepl) {
// in that case just tweak it before testing for mixed paths - since it's not a problem and should no warning should be in the logs
if (filename.StartsWith (Path.Combine (Resolver.FrameworkDirectory, "repl"), StringComparison.Ordinal))
filename = Path.Combine (Resolver.FrameworkDirectory, Path.GetFileName (filename));
}
if (ad != ProductAssembly && GetRealPath (filename) != GetRealPath (reference) && !filename.EndsWith (".resources.dll", StringComparison.Ordinal))
ErrorHelper.Show (ErrorHelper.CreateWarning (109, Errors.MT0109, Path.GetFileName (reference), reference, filename));
}
ComputeListOfAssemblies ();
if (App.LinkMode == LinkMode.None && App.I18n != I18nAssemblies.None)
AddI18nAssemblies ();
if (!App.Embeddinator) {
if (!Assemblies.Any ((v) => v.AssemblyDefinition.Name.Name == Driver.GetProductAssembly (App)))
throw ErrorHelper.CreateError (123, Errors.MT0123, App.RootAssemblies [0], Driver.GetProductAssembly (App));
}
foreach (var abi in Abis)
linker_flags_by_abi [abi & Abi.ArchMask] = new CompilerFlags (this);
// Verify that there are no entries in our list of intepreted assemblies that doesn't match
// any of the assemblies we know about.
if (App.InterpretedAssemblies.Count > 0) {
var exceptions = new List<Exception> ();
foreach (var entry in App.InterpretedAssemblies) {
var assembly = entry;
if (string.IsNullOrEmpty (assembly))
continue;
if (assembly [0] == '-')
assembly = assembly.Substring (1);
if (assembly == "all")
continue;
if (Assemblies.ContainsKey (assembly))
continue;
exceptions.Add (ErrorHelper.CreateWarning (142, Errors.MT0142, assembly));
}
ErrorHelper.ThrowIfErrors (exceptions);
}
}
IEnumerable<AssemblyDefinition> GetAssemblies ()
{
if (App.LinkMode == LinkMode.None)
return ManifestResolver.GetAssemblies ();
List<AssemblyDefinition> assemblies = new List<AssemblyDefinition> ();
if (LinkContext == null) {
// use data from cache
foreach (var assembly in Assemblies)
assemblies.Add (assembly.AssemblyDefinition);
} else {
foreach (var assembly in LinkContext.GetAssemblies ()) {
if (LinkContext.Annotations.GetAction (assembly) == AssemblyAction.Delete)
continue;
assemblies.Add (assembly);
}
}
return assemblies;
}
//
// Gets a flattened list of all the assemblies pulled by the root assembly
//
public void ComputeListOfAssemblies ()
{
var exceptions = new List<Exception> ();
var assemblies = new HashSet<string> ();
var cache_file = Path.Combine (this.ArchDirectory, "assembly-references.txt");
if (File.Exists (cache_file)) {
assemblies.UnionWith (File.ReadAllLines (cache_file));
// Check if any of the referenced assemblies changed after we cached the complete set of references
if (Application.IsUptodate (assemblies, new string [] { cache_file })) {
// Load all the assemblies in the cached list of assemblies
foreach (var assembly in assemblies) {
var ad = ManifestResolver.Load (assembly);
var asm = AddAssembly (ad);
asm.ComputeSatellites ();
}
return;
}
// We must manually find all the references.
assemblies.Clear ();
}
try {
foreach (var root in App.RootAssemblies) {
var assembly = ManifestResolver.Load (root);
ComputeListOfAssemblies (assemblies, assembly, exceptions);
}
} catch (ProductException mte) {
exceptions.Add (mte);
} catch (Exception e) {
exceptions.Add (new ProductException (9, true, e, Errors.MX0009, e.Message));
}
if (App.LinkMode == LinkMode.None)
exceptions.AddRange (ManifestResolver.list);
if (exceptions.Count > 0)
throw new AggregateException (exceptions);
// Cache all the assemblies we found.
Directory.CreateDirectory (Path.GetDirectoryName (cache_file));
File.WriteAllLines (cache_file, assemblies);
}
void ComputeListOfAssemblies (HashSet<string> assemblies, AssemblyDefinition assembly, List<Exception> exceptions)
{
if (assembly == null)
return;
var fqname = assembly.MainModule.FileName;
if (assemblies.Contains (fqname))
return;
PrintAssemblyReferences (assembly);
assemblies.Add (fqname);
var asm = AddAssembly (assembly);
asm.ComputeSatellites ();
var main = assembly.MainModule;
foreach (AssemblyNameReference reference in main.AssemblyReferences) {
// Verify that none of the references references an incorrect platform assembly.
switch (reference.Name) {
case "Xamarin.iOS":
case "Xamarin.TVOS":
case "Xamarin.WatchOS":
case "Xamarin.MacCatalyst":
if (reference.Name != Driver.GetProductAssembly (App)) {
if (App.Platform == ApplePlatform.MacCatalyst && reference.Name == "Xamarin.iOS") {
// This is allowed, because it's a facade
break;
}
exceptions.Add (ErrorHelper.CreateError (34, Errors.MT0034, reference.Name, Driver.TargetFramework.Identifier, assembly.FullName));
}
break;
}
var reference_assembly = ManifestResolver.Resolve (reference);
if (reference_assembly == null) {
ErrorHelper.Warning (136, Errors.MT0136, reference.FullName, main.FileName);
continue;
}
ComputeListOfAssemblies (assemblies, reference_assembly, exceptions);
}
if (Profile.IsSdkAssembly (assembly) || Profile.IsProductAssembly (assembly))
return; // We know there are no new assembly references from attributes in assemblies we ship
// Custom Attribute metadata can include references to other assemblies, e.g. [X (typeof (Y)],
// but it is not reflected in AssemblyReferences :-( ref: #37611
// so we must scan every custom attribute to look for System.Type
GetCustomAttributeReferences (main, main, assemblies, exceptions);
foreach (var ca in main.GetCustomAttributes ())
GetCustomAttributeReferences (main, ca, assemblies, exceptions);
}
void GetCustomAttributeReferences (ModuleDefinition main, ICustomAttributeProvider cap, HashSet<string> assemblies, List<Exception> exceptions)
{
if (!cap.HasCustomAttributes)
return;
foreach (var ca in cap.CustomAttributes)
GetCustomAttributeReferences (main, ca, assemblies, exceptions);
}
void GetCustomAttributeReferences (ModuleDefinition main, CustomAttribute ca, HashSet<string> assemblies, List<Exception> exceptions)
{
if (ca.HasConstructorArguments) {
foreach (var arg in ca.ConstructorArguments)
GetCustomAttributeArgumentReference (main, ca, arg, assemblies, exceptions);
}
if (ca.HasFields) {
foreach (var arg in ca.Fields)
GetCustomAttributeArgumentReference (main, ca, arg.Argument, assemblies, exceptions);
}
if (ca.HasProperties) {
foreach (var arg in ca.Properties)
GetCustomAttributeArgumentReference (main, ca, arg.Argument, assemblies, exceptions);
}
}
void GetCustomAttributeArgumentReference (ModuleDefinition main, CustomAttribute ca, CustomAttributeArgument arg, HashSet<string> assemblies, List<Exception> exceptions)
{
if (!arg.Type.Is ("System", "Type"))
return;
var ar = (arg.Value as TypeReference)?.Scope as AssemblyNameReference;
if (ar == null)
return;
var reference_assembly = ManifestResolver.Resolve (ar);
if (reference_assembly == null) {
ErrorHelper.Warning (137, Errors.MT0137, ar.FullName, main.Name, ca.AttributeType.FullName);
return;
}
ComputeListOfAssemblies (assemblies, reference_assembly, exceptions);
}
bool IncludeI18nAssembly (Mono.Linker.I18nAssemblies assembly)
{
return (App.I18n & assembly) != 0;
}
public void AddI18nAssemblies ()
{
Assemblies.Add (LoadI18nAssembly ("I18N"));
if (IncludeI18nAssembly (Mono.Linker.I18nAssemblies.CJK))
Assemblies.Add (LoadI18nAssembly ("I18N.CJK"));
if (IncludeI18nAssembly (Mono.Linker.I18nAssemblies.MidEast))
Assemblies.Add (LoadI18nAssembly ("I18N.MidEast"));
if (IncludeI18nAssembly (Mono.Linker.I18nAssemblies.Other))
Assemblies.Add (LoadI18nAssembly ("I18N.Other"));
if (IncludeI18nAssembly (Mono.Linker.I18nAssemblies.Rare))
Assemblies.Add (LoadI18nAssembly ("I18N.Rare"));
if (IncludeI18nAssembly (Mono.Linker.I18nAssemblies.West))
Assemblies.Add (LoadI18nAssembly ("I18N.West"));
}
Assembly LoadI18nAssembly (string name)
{
var assembly = ManifestResolver.Resolve (AssemblyNameReference.Parse (name));
return new Assembly (this, assembly);
}
public void LinkAssemblies (out List<AssemblyDefinition> assemblies, string output_dir, IEnumerable<Target> sharedCodeTargets)
{
var cache = (Dictionary<string, AssemblyDefinition>) Resolver.ResolverCache;
var resolver = new AssemblyResolver (cache);
resolver.AddSearchDirectory (Resolver.RootDirectory);
resolver.AddSearchDirectory (Resolver.FrameworkDirectory);
var main_assemblies = new List<AssemblyDefinition> ();
foreach (var root in App.RootAssemblies)
main_assemblies.Add (Resolver.Load (root));
foreach (var appex in sharedCodeTargets) {
foreach (var root in appex.App.RootAssemblies)
main_assemblies.Add (Resolver.Load (root));
}
if (Driver.Verbosity > 0)
Console.WriteLine ("Linking {0} into {1} using mode '{2}'", string.Join (", ", main_assemblies.Select ((v) => v.MainModule.FileName)), output_dir, App.LinkMode);
LinkerOptions = new LinkerOptions {
MainAssemblies = main_assemblies,
OutputDirectory = output_dir,
LinkMode = App.LinkMode,
Resolver = resolver,
SkippedAssemblies = App.LinkSkipped,
I18nAssemblies = App.I18n,
LinkSymbols = true,
LinkAway = App.LinkAway,
ExtraDefinitions = App.Definitions,
Device = App.IsDeviceBuild,
DebugBuild = App.EnableDebug,
DumpDependencies = App.LinkerDumpDependencies,
RuntimeOptions = App.RuntimeOptions,
MarshalNativeExceptionsState = MarshalNativeExceptionsState,
WarnOnTypeRef = App.WarnOnTypeRef,
Target = this,
};
MonoTouch.Tuner.Linker.Process (LinkerOptions, out LinkContext, out assemblies);
var state = MarshalNativeExceptionsState;
if (state?.Started == true) {
// The generator is 'started' by the linker, which means it may not
// be started if the linker was not executed due to re-using cached results.
state.End ();
}
ErrorHelper.Show (LinkContext.Exceptions);
Driver.Watch ("Link Assemblies", 1);
}
bool linked;
public void ManagedLink ()
{
if (linked)
return;
var cache_path = Path.Combine (ArchDirectory, "linked-assemblies.txt");
// Get all the Target instances we're sharing code with. Make sure to only select targets with matching pointer size.
var sharingTargets = App.SharedCodeApps.SelectMany ((v) => v.Targets).Where ((v) => v.Is32Build == Is32Build).ToList ();
var allTargets = new List<Target> ();
allTargets.Add (this); // We want ourselves first in this list.
allTargets.AddRange (sharingTargets);
// Include any assemblies from appex's we're sharing code with.
foreach (var target in sharingTargets) {
var targetAssemblies = target.Assemblies.ToList (); // We need to clone the list of assemblies, since we'll be modifying the original
foreach (var asm in targetAssemblies) {
Assembly main_asm;
if (!Assemblies.TryGetValue (asm.Identity, out main_asm)) {
// The appex has an assembly that's not present in the main app.
// Re-load it into the main app.
main_asm = new Assembly (this, asm.FullPath);
main_asm.LoadAssembly (main_asm.FullPath);
Assemblies.Add (main_asm);
Driver.Log (1, "Added '{0}' from {1} to the set of assemblies to be linked.", main_asm.Identity, Path.GetFileNameWithoutExtension (target.App.AppDirectory));
} else {
asm.IsCodeShared = true;
}
// Use the same AOT information between both Assembly instances.
target.Assemblies [main_asm.Identity].AotInfos = main_asm.AotInfos;
main_asm.IsCodeShared = true;
}
}
foreach (var a in Assemblies)
a.CopyToDirectory (LinkDirectory, false, check_case: true);
// Check if we can use a previous link result.
var cached_output = new Dictionary<string, List<string>> ();
if (!Driver.Force) {
if (File.Exists (cache_path)) {
using (var reader = new StreamReader (cache_path)) {
string line = null;
while ((line = reader.ReadLine ()) != null) {
var colon = line.IndexOf (':');
if (colon == -1)
continue;
var key = line.Substring (0, colon);
var value = line.Substring (colon + 1);
switch (key) {
case "RemoveDynamicRegistrar":
switch (value) {
case "true":
App.Optimizations.RemoveDynamicRegistrar = true;
break;
case "false":
App.Optimizations.RemoveDynamicRegistrar = false;
break;
default:
App.Optimizations.RemoveDynamicRegistrar = null;
break;
}
foreach (var t in sharingTargets)
t.App.Optimizations.RemoveDynamicRegistrar = App.Optimizations.RemoveDynamicRegistrar;
Driver.Log (1, $"Optimization dynamic registrar removal loaded from cached results: {(App.Optimizations.RemoveDynamicRegistrar.HasValue ? (App.Optimizations.RemoveUIThreadChecks.Value ? "enabled" : "disabled") : "not set")}");
break;
default:
// key: app(ex)
// value: assembly
List<string> asms;
if (!cached_output.TryGetValue (key, out asms))
cached_output [key] = asms = new List<string> ();
asms.Add (value);
break;
}
}
}
var cache_valid = true;
foreach (var target in allTargets) {
List<string> cached_files;
if (!cached_output.TryGetValue (target.App.AppDirectory, out cached_files)) {
cache_valid = false;
Driver.Log (2, $"The cached assemblies are not valid because there are no cached assemblies for {target.App.Name}.");
break;
}
var outputs = new List<string> ();
var inputs = new List<string> (cached_files);
foreach (var input in inputs.ToArray ()) {
var output = Path.Combine (PreBuildDirectory, Path.GetFileName (input));
outputs.Add (output);
if (File.Exists (input + ".mdb")) {
// Debug files can change without the assemblies themselves changing
// This should also invalidate the cached linker results, since the non-linked mdbs can't be copied.
inputs.Add (input + ".mdb");
outputs.Add (output + ".mdb");
}
var pdb = Path.ChangeExtension (input, "pdb");
if (File.Exists (pdb)) {
inputs.Add (pdb);
outputs.Add (Path.ChangeExtension (output, "pdb"));
}
if (File.Exists (input + ".config")) {
// If a config file changes, then the AOT-compiled output can be different,
// so make sure to take config files into account as well.
inputs.Add (input + ".config");
outputs.Add (output + ".config");
}
}
if (!cache_valid)
break;
if (!Application.IsUptodate (inputs, outputs)) {
Driver.Log (2, $"The cached assemblies are not valid because some of the assemblies in {target.App.Name} are out-of-date.");
cache_valid = false;
break;
}
}
cached_link = cache_valid;
}
}
List<AssemblyDefinition> output_assemblies;
if (cached_link) {
Driver.Log (2, $"Reloading cached assemblies.");
output_assemblies = new List<AssemblyDefinition> ();
foreach (var file in cached_output.Values.SelectMany ((v) => v).Select ((v) => Path.GetFileName (v)).Distinct ())
output_assemblies.Add (Resolver.Load (Path.Combine (PreBuildDirectory, file)));
Driver.Watch ("Cached assemblies reloaded", 1);
Driver.Log ("Cached assemblies reloaded.");
} else {
// Load the assemblies into memory.
foreach (var a in Assemblies)
a.LoadAssembly (a.FullPath);
// Link!
Driver.Watch ("Managed Link Preparation", 1);
LinkAssemblies (out output_assemblies, PreBuildDirectory, sharingTargets);
}
// Verify that we don't get multiple identical assemblies from the linker.
foreach (var group in output_assemblies.GroupBy ((v) => v.Name.Name)) {
if (group.Count () != 1)
throw ErrorHelper.CreateError (99, Errors.MX0099, $"The linker output contains more than one assemblies named '{group.Key}':\n\t{string.Join("\n\t", group.Select((v) => v.MainModule.FileName).ToArray())}");
}
// Update (add/remove) list of assemblies in each app, since the linker may have both added and removed assemblies.
// The logic for updating assemblies when doing code-sharing is not equivalent to when we're not code sharing
// (in particular code sharing is not supported when there are xml linker definitions), so we need
// to maintain two paths here.
if (sharingTargets.Count == 0) {
Assemblies.Update (this, output_assemblies);
} else {
// For added assemblies we have to determine exactly which apps need which assemblies.
// Code sharing is only allowed if there are no linker xml definitions, nor any I18N values, which means that
// we can limit ourselves to iterate over assembly references to create the updated list of assemblies.
foreach (var t in allTargets) {
// Find the root assembly
// Here we assume that 'AssemblyReference.Name' == 'Assembly.Identity'.
var rootAssemblies = new List<Assembly> ();
foreach (var root in t.App.RootAssemblies)
rootAssemblies.Add (t.Assemblies [Assembly.GetIdentity (root)]);
var queue = new Queue<string> ();
var collectedNames = new HashSet<string> ();
// First collect the set of all assemblies in the app by walking the assembly references.
foreach (var root in rootAssemblies)
queue.Enqueue (root.Identity);
do {
var next = queue.Dequeue ();
collectedNames.Add (next);
var ad = output_assemblies.SingleOrDefault ((AssemblyDefinition v) => v.Name.Name == next);
if (ad == null)
throw ErrorHelper.CreateError (99, Errors.MX0099, $"The assembly {next} was referenced by another assembly, but at the same time linked out by the linker");
if (ad.MainModule.HasAssemblyReferences) {
foreach (var ar in ad.MainModule.AssemblyReferences) {
if (!collectedNames.Contains (ar.Name) && !queue.Contains (ar.Name))
queue.Enqueue (ar.Name);
}
}
} while (queue.Count > 0);
// Now update the assembly collection
var appexAssemblies = collectedNames.Select ((v) => output_assemblies.Single ((v2) => v2.Name.Name == v));
t.Assemblies.Update (t, appexAssemblies);
// And make sure every Target's assembly resolver knows about all the assemblies.
foreach (var asm in t.Assemblies)
t.Resolver.Add (asm.AssemblyDefinition);
}
// Find assemblies that are in more than 1 appex, but not in the container app.
// These assemblies will be bundled once into the container .app instead of in each appex.
var grouped = sharingTargets.SelectMany ((v) => v.Assemblies).
GroupBy ((v) => Assembly.GetIdentity (v.AssemblyDefinition)).
Where ((v) => !Assemblies.ContainsKey (v.Key)).
Where ((v) => v.Count () > 1);
foreach (var gr in grouped) {
var asm = gr.First ();
Assemblies.Add (asm);
Resolver.Add (asm.AssemblyDefinition);
gr.All ((v) => v.BundleInContainerApp = true);
}
// If any of the appex'es build to a grouped SDK framework, then we must ensure that all SDK assemblies
// in that appex are also in the container app.
foreach (var st in sharingTargets) {
if (!st.App.ContainsGroupedSdkAssemblyBuildTargets)
continue;
foreach (var asm in st.Assemblies.Where ((v) => Profile.IsSdkAssembly (v.AssemblyDefinition) || Profile.IsProductAssembly (v.AssemblyDefinition))) {
if (!Assemblies.ContainsKey (asm.Identity)) {
Driver.Log (2, $"The SDK assembly {asm.Identity} will be included in the app because it's referenced by the extension {st.App.Name}");
Assemblies.Add (asm);
}
}
}
}
// Write the input files to the cache
using (var writer = new StreamWriter (cache_path, false)) {
var opt = App.Optimizations.RemoveDynamicRegistrar;
writer.WriteLine ($"RemoveDynamicRegistrar:{(opt.HasValue ? (opt.Value ? "true" : "false") : string.Empty)}");
foreach (var target in allTargets) {
foreach (var asm in target.Assemblies) {
writer.WriteLine ($"{target.App.AppDirectory}:{asm.FullPath}");
}
}
}
// Now the assemblies are in PreBuildDirectory, and they need to be in the BuildDirectory for the AOT compiler.
foreach (var t in allTargets) {
foreach (var a in t.Assemblies) {
// All these assemblies are in the main app's PreBuildDirectory.
a.FullPath = Path.Combine (PreBuildDirectory, a.FileName);
// The linker can copy files (and not update timestamps), and then we run into this sequence:
// * We run the linker, nothing changes, so the linker copies
// all files to the PreBuild directory, with timestamps intact.
// * This means that for instance SDK assemblies will have the original
// timestamp from their installed location, and the exe will have the
// timestamp of when it was built.
// * mtouch is executed again for some reason, and none of the input assemblies changed.
// We'll still re-execute the linker, because at least one of the input assemblies
// (the .exe) has a newer timestamp than some of the assemblies in the PreBuild directory.
// So here we manually touch all the assemblies we have, to make sure their timestamps
// change (this is us saying 'we know these files are up-to-date at this point in time').
if (!cached_link) {
Driver.Touch (a.FullPath);
if (File.Exists (a.FullPath + ".mdb"))
Driver.Touch (a.FullPath + ".mdb");
var pdb = Path.ChangeExtension (a.FullPath, "pdb");
if (File.Exists (pdb))
Driver.Touch (pdb);
var config = a.FullPath + ".config";
if (File.Exists (config))
Driver.Touch (config);
}
// Now copy to the build directory
var target = Path.Combine (BuildDirectory, a.FileName);
if (!a.CopyAssembly (a.FullPath, target))
Driver.Log (3, "Target '{0}' is up-to-date.", target);
a.FullPath = target;
}
}
// Set the 'linked' flag for the targets sharing code, so that this method can be called
// again, and it won't do anything for the appex's sharing code with the main app (but
// will still work for any appex's not sharing code).
allTargets.ForEach ((v) => v.linked = true);
}
public void ProcessAssemblies ()
{
//
// * Linking
// Copy assemblies to LinkDirectory
// Link and save to PreBuildDirectory
// If marshalling native exceptions:
// * Generate/calculate P/Invoke wrappers and save to PreBuildDirectory
// [AOT assemblies in BuildDirectory]
// Strip managed code save to TargetDirectory (or just copy the file if stripping is disabled).
//
// * No linking
// If marshalling native exceptions:
// Generate/calculate P/Invoke wrappers and save to PreBuildDirectory.
// If not marshalling native exceptions:
// Copy assemblies to PreBuildDirectory
// Copy unmodified assemblies to BuildDirectory
// [AOT assemblies in BuildDirectory]
// Strip managed code save to TargetDirectory (or just copy the file if stripping is disabled).
//
// Note that we end up copying assemblies around quite much,
// this is because we we're comparing contents instead of
// filestamps, so we need the previous file around to be
// able to do the actual comparison. For instance: in the
// 'No linking' case above, we copy the assembly to PreBuild
// before removing the resources and saving that result to Build.
// The copy in PreBuild is required for the next build iteration,
// to see if the original assembly has been modified or not (the
// file in the Build directory might be different due to resource
// removal even if the original assembly didn't change).
//
// This can probably be improved by storing digests/hashes instead
// of the entire files, but this turned out a bit messy when
// trying to make it work with the linker, so I decided to go for
// simple file copying for now.
//
//
// Other notes:
//
// * We need all assemblies in the same directory when doing AOT-compilation.
// * We cannot overwrite in-place, because it will mess up dependency tracking
// and besides if we overwrite in place we might not be able to ignore
// insignificant changes (such as only a GUID change - the code is identical,
// but we still need the original assembly since the AOT-ed image also stores
// the GUID, and we fail at runtime if the GUIDs in the assembly and the AOT-ed
// image don't match - if we overwrite in-place we lose the original assembly and
// its GUID).
//
LinkDirectory = Path.Combine (ArchDirectory, "1-Link");
if (!Directory.Exists (LinkDirectory))
Directory.CreateDirectory (LinkDirectory);
PreBuildDirectory = Path.Combine (ArchDirectory, "2-PreBuild");
if (!Directory.Exists (PreBuildDirectory))
Directory.CreateDirectory (PreBuildDirectory);
BuildDirectory = Path.Combine (ArchDirectory, "3-Build");
if (!Directory.Exists (BuildDirectory))
Directory.CreateDirectory (BuildDirectory);
if (!Directory.Exists (TargetDirectory))
Directory.CreateDirectory (TargetDirectory);
ValidateAssembliesBeforeLink ();
ManagedLink ();
GatherFrameworks ();
}
public void CompilePInvokeWrappers ()
{
if (!App.RequiresPInvokeWrappers)
return;
if (!App.HasFrameworksDirectory && App.IsCodeShared)
return;
// Write P/Invokes
var state = MarshalNativeExceptionsState;
var ifile = state.SourcePath;
var mode = App.LibPInvokesLinkMode;
foreach (var abi in GetArchitectures (mode)) {
var arch = abi.AsArchString ();
string ofile;
switch (mode) {
case AssemblyBuildTarget.StaticObject:
ofile = Path.Combine (App.Cache.Location, arch, "libpinvokes.a");
break;
case AssemblyBuildTarget.DynamicLibrary:
ofile = Path.Combine (App.Cache.Location, arch, "libpinvokes.dylib");
break;
case AssemblyBuildTarget.Framework:
ofile = Path.Combine (App.Cache.Location, arch, "Xamarin.PInvokes.framework", "Xamarin.PInvokes");
var plist_path = Path.Combine (Path.GetDirectoryName (ofile), "Info.plist");
var fw_name = Path.GetFileNameWithoutExtension (ofile);
App.CreateFrameworkInfoPList (plist_path, fw_name, App.BundleId + ".frameworks." + fw_name, fw_name);
break;
default:
throw ErrorHelper.CreateError (100, Errors.MT0100, mode);
}
var pinvoke_task = new PinvokesTask
{
Target = this,
Abi = abi,
InputFile = ifile,
OutputFile = ofile,
SharedLibrary = mode != AssemblyBuildTarget.StaticObject,
Language = "objective-c++",
};
pinvoke_task.CompilerFlags.AddStandardCppLibrary ();
if (pinvoke_task.SharedLibrary) {
if (mode == AssemblyBuildTarget.Framework) {
var name = Path.GetFileNameWithoutExtension (ifile);
pinvoke_task.InstallName = $"@rpath/{name}.framework/{name}";
AddToBundle (pinvoke_task.OutputFile, $"Frameworks/{name}.framework/{name}", dylib_to_framework_conversion: true);
} else {
pinvoke_task.InstallName = $"@rpath/{Path.GetFileName (ofile)}";
AddToBundle (pinvoke_task.OutputFile);
}
pinvoke_task.CompilerFlags.AddFramework ("Foundation");
pinvoke_task.CompilerFlags.LinkWithXamarin ();
}
pinvoke_tasks.Add (abi, pinvoke_task);
LinkWithTaskOutput (pinvoke_task);
}
}
void AOTCompile ()
{
if (App.IsSimulatorBuild)
return;
if (App.Platform == ApplePlatform.MacCatalyst)
return;
// Here we create the tasks to run the AOT compiler.
foreach (var a in Assemblies) {
if (!a.IsAOTCompiled)
continue;
foreach (var abi in GetArchitectures (a.BuildTarget)) {
a.CreateAOTTask (abi);
}
}
// Group the assemblies according to their target name, and link everything together accordingly.
var grouped = Assemblies.GroupBy ((arg) => arg.BuildTargetName);
foreach (var @group in grouped) {
var name = @group.Key;
var assemblies = @group.AsEnumerable ().ToArray ();
if (assemblies.Length <= 0)
continue;
// We ensure elsewhere that all assemblies in a group have the same build target.
var build_target = assemblies [0].BuildTarget;
foreach (var abi in GetArchitectures (build_target)) {
Driver.Log (2, "Building {0} from {1}", name, string.Join (", ", assemblies.Select ((arg1) => Path.GetFileName (arg1.FileName))));
string install_name;
string compiler_output;
var compiler_flags = new CompilerFlags (this);
var link_dependencies = new List<CompileTask> ();
var infos = assemblies.Where ((asm) => asm.AotInfos.ContainsKey (abi)).Select ((asm) => asm.AotInfos [abi]).ToList ();
var aottasks = infos.Select ((info) => info.Task);
if (aottasks == null)
continue;
var existingLinkTask = infos.Where ((v) => v.LinkTask != null).Select ((v) => v.LinkTask).ToList ();
if (existingLinkTask.Count > 0) {
if (existingLinkTask.Count != infos.Count)
throw ErrorHelper.CreateError (99, Errors.MX0099, $"Not all assemblies for {name} have link tasks");
if (!existingLinkTask.All ((v) => v == existingLinkTask [0]))
throw ErrorHelper.CreateError (99, Errors.MX0099, $"Link tasks for {name} aren't all the same");
LinkWithBuildTarget (build_target, name, existingLinkTask [0], assemblies);
continue;
}
// We have to compile any source files to object files before we can link.
var sources = infos.SelectMany ((info) => info.AsmFiles);
if (sources.Count () > 0) {
foreach (var src in sources) {
// We might have to convert .s to bitcode assembly (.ll) first
var assembly = src;