-
Notifications
You must be signed in to change notification settings - Fork 566
Expand file tree
/
Copy pathLinkerTests.cs
More file actions
815 lines (697 loc) · 31.5 KB
/
LinkerTests.cs
File metadata and controls
815 lines (697 loc) · 31.5 KB
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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using Java.Interop.Tools.Cecil;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Linker;
using Mono.Linker.Steps;
using Mono.Tuner;
using MonoDroid.Tuner;
using NUnit.Framework;
using Xamarin.Android.Tasks;
using Xamarin.ProjectTools;
using SR = System.Reflection;
namespace Xamarin.Android.Build.Tests
{
public class LinkerTests : BaseTest
{
void Logger (TraceLevel level, string message) =>
TestContext.WriteLine ($"{level}: {message}");
[Test]
public void FixAbstractMethodsStep_SkipDimMembers ()
{
var path = Path.Combine (Root, "temp", TestName);
var step = new FixAbstractMethodsStep ();
Directory.CreateDirectory (path);
using (var resolver = new DirectoryAssemblyResolver (Logger, false))
using (var context = new LinkContext (resolver)) {
step.Initialize (context, new EmptyMarkContext ());
resolver.SearchDirectories.Add (path);
var myAssemblyPath = Path.Combine (path, "MyAssembly.dll");
using (var android = CreateFauxMonoAndroidAssembly ()) {
android.Write (Path.Combine (path, "Mono.Android.dll"));
CreateAbstractIfaceImplementation (myAssemblyPath, android);
}
using (var assm = context.Resolve ("MyAssembly")) {
step.FixAbstractMethods (assm);
var impl = assm.MainModule.GetType ("MyNamespace.MyClass");
Assert.IsTrue (impl.Methods.Any (m => m.Name == "MyAbstractMethod"), "We should have generated an override for MyAbstractMethod");
Assert.IsFalse (impl.Methods.Any (m => m.Name == "MyDefaultMethod"), "We should not have generated an override for MyDefaultMethod");
}
}
Directory.Delete (path, true);
}
static void CreateAbstractIfaceImplementation (string assemblyPath, AssemblyDefinition android)
{
using (var assm = AssemblyDefinition.CreateAssembly (new AssemblyNameDefinition ("DimTest", new Version ()), "DimTest", ModuleKind.Dll)) {
var void_type = assm.MainModule.ImportReference (typeof (void));
// Create interface
var iface = new TypeDefinition ("MyNamespace", "IMyInterface", TypeAttributes.Interface);
var abstract_method = new MethodDefinition ("MyAbstractMethod", MethodAttributes.Abstract, void_type);
var default_method = new MethodDefinition ("MyDefaultMethod", MethodAttributes.Public, void_type);
iface.Methods.Add (abstract_method);
iface.Methods.Add (default_method);
assm.MainModule.Types.Add (iface);
// Create implementing class
var jlo = assm.MainModule.Import (android.MainModule.GetType ("Java.Lang.Object"));
var impl = new TypeDefinition ("MyNamespace", "MyClass", TypeAttributes.Public, jlo);
impl.Interfaces.Add (new InterfaceImplementation (iface));
assm.MainModule.Types.Add (impl);
assm.Write (assemblyPath);
}
}
[Test]
public void FixAbstractMethodsStep_Explicit ()
{
var path = Path.Combine (Root, "temp", TestName);
var step = new FixAbstractMethodsStep ();
Directory.CreateDirectory (path);
using (var resolver = new DirectoryAssemblyResolver (Logger, false))
using (var context = new LinkContext (resolver)) {
step.Initialize (context, new EmptyMarkContext ());
resolver.SearchDirectories.Add (path);
var myAssemblyPath = Path.Combine (path, "MyAssembly.dll");
using (var android = CreateFauxMonoAndroidAssembly ()) {
android.Write (Path.Combine (path, "Mono.Android.dll"));
CreateExplicitInterface (myAssemblyPath, android);
}
using (var assm = context.Resolve ("MyAssembly")) {
step.FixAbstractMethods (assm);
var impl = assm.MainModule.GetType ("MyNamespace.MyClass");
Assert.AreEqual (2, impl.Methods.Count, "MyClass should contain 2 methods");
var method = impl.Methods.FirstOrDefault (m => m.Name == "MyNamespace.IMyInterface.MyMethod");
Assert.IsNotNull (method, "MyNamespace.IMyInterface.MyMethod should exist");
method = impl.Methods.FirstOrDefault (m => m.Name == "MyMissingMethod");
Assert.IsNotNull (method, "MyMissingMethod should exist");
}
}
Directory.Delete (path, true);
}
static void CreateExplicitInterface (string assemblyPath, AssemblyDefinition android)
{
using (var assm = AssemblyDefinition.CreateAssembly (new AssemblyNameDefinition ("NestedIFaceTest", new Version ()), "NestedIFaceTest", ModuleKind.Dll)) {
var void_type = assm.MainModule.ImportReference (typeof (void));
// Create interface
var iface = new TypeDefinition ("MyNamespace", "IMyInterface", TypeAttributes.Interface);
var iface_method = new MethodDefinition ("MyMethod", MethodAttributes.Abstract, void_type);
iface.Methods.Add (iface_method);
iface.Methods.Add (new MethodDefinition ("MyMissingMethod", MethodAttributes.Abstract, void_type));
assm.MainModule.Types.Add (iface);
// Create implementing class
var jlo = assm.MainModule.Import (android.MainModule.GetType ("Java.Lang.Object"));
var impl = new TypeDefinition ("MyNamespace", "MyClass", TypeAttributes.Public, jlo);
impl.Interfaces.Add (new InterfaceImplementation (iface));
var explicit_method = new MethodDefinition ("MyNamespace.IMyInterface.MyMethod", MethodAttributes.Abstract, void_type);
explicit_method.Overrides.Add (iface_method);
impl.Methods.Add (explicit_method);
assm.MainModule.Types.Add (impl);
assm.Write (assemblyPath);
}
}
static AssemblyDefinition CreateFauxMonoAndroidAssembly ()
{
var assm = AssemblyDefinition.CreateAssembly (new AssemblyNameDefinition ("Mono.Android", new Version ()), "DimTest", ModuleKind.Dll);
var void_type = assm.MainModule.ImportReference (typeof (void));
// Create fake JLO type
var jlo = new TypeDefinition ("Java.Lang", "Object", TypeAttributes.Public);
assm.MainModule.Types.Add (jlo);
// Create fake Java.Lang.AbstractMethodError type
var ame = new TypeDefinition ("Java.Lang", "AbstractMethodError", TypeAttributes.Public);
ame.Methods.Add (new MethodDefinition (".ctor", MethodAttributes.Public, void_type));
assm.MainModule.Types.Add (ame);
return assm;
}
private void PreserveCustomHttpClientHandler (
string handlerType,
string handlerAssembly,
string testProjectName,
string assemblyPath,
TrimMode trimMode,
AndroidRuntime runtime)
{
const bool isRelease = true;
if (IgnoreUnsupportedConfiguration (runtime, release: isRelease)) {
return;
}
testProjectName += trimMode.ToString ();
var class_library = new XamarinAndroidLibraryProject {
IsRelease = isRelease,
ProjectName = "MyClassLibrary",
Sources = {
new BuildItem.Source ("MyCustomHandler.cs") {
TextContent = () => """
class MyCustomHandler : System.Net.Http.HttpMessageHandler
{
protected override Task <HttpResponseMessage> SendAsync (HttpRequestMessage request, CancellationToken cancellationToken) =>
throw new NotImplementedException ();
}
"""
},
new BuildItem.Source ("Bar.cs") {
TextContent = () => "public class Bar { }",
}
}
};
class_library.SetRuntime (runtime);
using (var libBuilder = CreateDllBuilder ($"{testProjectName}/{class_library.ProjectName}")) {
Assert.IsTrue (libBuilder.Build (class_library), $"Build for {class_library.ProjectName} should have succeeded.");
}
var proj = new XamarinAndroidApplicationProject {
ProjectName = "MyApp",
IsRelease = isRelease,
TrimModeRelease = trimMode,
Sources = {
new BuildItem.Source ("Foo.cs") {
TextContent = () => "public class Foo : Bar { }",
}
}
};
proj.SetRuntime (runtime);
proj.AddReference (class_library);
proj.AddReferences ("System.Net.Http");
string handlerTypeFullName = string.IsNullOrEmpty(handlerAssembly) ? handlerType : handlerType + ", " + handlerAssembly;
proj.SetProperty (proj.ActiveConfigurationProperties, "AndroidHttpClientHandlerType", handlerTypeFullName);
proj.MainActivity = proj.DefaultMainActivity.Replace ("base.OnCreate (bundle);", "base.OnCreate (bundle);\nvar client = new System.Net.Http.HttpClient ();");
using (var b = CreateApkBuilder ($"{testProjectName}/{proj.ProjectName}")) {
Assert.IsTrue (b.Build (proj), "Build should have succeeded.");
using (var assembly = AssemblyDefinition.ReadAssembly (Path.Combine (Root, b.ProjectDirectory, proj.IntermediateOutputPath, assemblyPath))) {
Assert.IsTrue (assembly.MainModule.GetType (handlerType) != null, $"'{handlerTypeFullName}' should have been preserved by the linker.");
}
}
}
[Test]
public void PreserveCustomHttpClientHandlers ([Values (TrimMode.Partial, TrimMode.Full)] TrimMode trimMode, [Values] AndroidRuntime runtime)
{
PreserveCustomHttpClientHandler ("Xamarin.Android.Net.AndroidMessageHandler", "",
$"temp/PreserveAndroidMessageHandler{trimMode}{runtime}", "android-arm64/linked/Mono.Android.dll", trimMode, runtime);
PreserveCustomHttpClientHandler ("System.Net.Http.SocketsHttpHandler", "System.Net.Http",
$"temp/PreserveSocketsHttpHandler{trimMode}{runtime}", "android-arm64/linked/System.Net.Http.dll", trimMode, runtime);
PreserveCustomHttpClientHandler ("MyCustomHandler", "MyClassLibrary",
$"temp/MyCustomHandler{trimMode}{runtime}", "android-arm64/linked/MyClassLibrary.dll", trimMode, runtime);
}
[Test]
public void WarnAboutAppDomains ([Values] bool isRelease, [Values] AndroidRuntime runtime)
{
if (IgnoreUnsupportedConfiguration (runtime, release: isRelease)) {
return;
}
if (isRelease) {
// NOTE: trimmer warnings are hidden by default in .NET 7 rc1
Assert.Ignore("https://github.com/dotnet/linker/issues/2982");
}
var path = Path.Combine (Root, "temp", TestName);
var lib = new XamarinAndroidLibraryProject {
IsRelease = isRelease,
ProjectName = "Library",
Sources = {
new BuildItem.Source ("Foo.cs") {
TextContent = () => "class Foo { System.AppDomain Bar => System.AppDomain.CreateDomain (\"myDomain\"); }",
}
}
};
lib.SetRuntime (runtime);
var app = new XamarinAndroidApplicationProject { IsRelease = isRelease };
app.SetRuntime (runtime);
app.SetAndroidSupportedAbis ("arm64-v8a");
app.AddReference (lib);
using var libBuilder = CreateDllBuilder (Path.Combine (path, lib.ProjectName));
Assert.IsTrue (libBuilder.Build (lib), "library build should have succeeded.");
// AppDomain.CreateDomain() is [Obsolete]
Assert.IsTrue (StringAssertEx.ContainsText (libBuilder.LastBuildOutput, "1 Warning(s)"), "MSBuild should count 1 warnings.");
using var appBuilder = CreateApkBuilder (Path.Combine (path, app.ProjectName));
Assert.IsTrue (appBuilder.Build (app), "app build should have succeeded.");
// NOTE: in .NET 6, we only emit IL6200 for Release builds
if (isRelease) {
string code = "IL6200";
Assert.IsTrue (StringAssertEx.ContainsText (appBuilder.LastBuildOutput, "1 Warning(s)"), "MSBuild should count 1 warnings.");
Assert.IsTrue (StringAssertEx.ContainsText (appBuilder.LastBuildOutput, $"warning {code}: Use of AppDomain.CreateDomain()"), $"Should warn {code} about creating AppDomain.");
}
}
[Test]
public void RemoveDesigner ([Values (true, false)] bool useAssemblyStore, [Values (AndroidRuntime.MonoVM, AndroidRuntime.CoreCLR)] AndroidRuntime runtime)
{
if (!useAssemblyStore && runtime == AndroidRuntime.CoreCLR) {
Assert.Ignore ("CoreCLR supports only assembly stores");
return;
}
var proj = new XamarinAndroidApplicationProject {
IsRelease = true,
};
proj.SetRuntime (runtime);
proj.SetProperty ("AndroidEnableAssemblyCompression", "False");
proj.SetProperty ("AndroidLinkResources", "True");
proj.SetProperty ("AndroidUseAssemblyStore", useAssemblyStore.ToString ());
string assemblyName = proj.ProjectName;
using var b = CreateApkBuilder ();
Assert.IsTrue (b.Build (proj), "build should have succeeded.");
var apk = Path.Combine (Root, b.ProjectDirectory, proj.OutputPath, $"{proj.PackageName}-Signed.apk");
FileAssert.Exists (apk);
var helper = new ArchiveAssemblyHelper (apk, useAssemblyStore);
foreach (string abi in proj.GetRuntimeIdentifiersAsAbis ()) {
Assert.IsTrue (helper.Exists ($"assemblies/{abi}/{assemblyName}.dll"), $"{assemblyName}.dll should exist in apk!");
using var stream = helper.ReadEntry ($"assemblies/{assemblyName}.dll");
stream.Position = 0;
using var assembly = AssemblyDefinition.ReadAssembly (stream);
var type = assembly.MainModule.GetType ($"{assemblyName}.Resource");
var intType = typeof(int);
foreach (var nestedType in type.NestedTypes) {
int count = 0;
foreach (var field in nestedType.Fields) {
if (field.FieldType.FullName == intType.FullName)
count++;
}
Assert.AreEqual (0, count, "All Nested Resource Type int fields should be removed.");
}
}
}
[Test]
public void LinkDescription ([Values (true, false)] bool useAssemblyStore, [Values (AndroidRuntime.MonoVM, AndroidRuntime.CoreCLR)] AndroidRuntime runtime)
{
if (!useAssemblyStore && runtime == AndroidRuntime.CoreCLR) {
Assert.Ignore ("CoreCLR doesn't support builds without assembly stores.");
return;
}
string assembly_name = "System.Console";
string linker_xml = "<linker/>";
var proj = new XamarinAndroidApplicationProject {
IsRelease = true,
OtherBuildItems = {
new BuildItem ("LinkDescription", "linker.xml") {
TextContent = () => linker_xml
}
}
};
proj.SetRuntime (runtime);
// So we can use Mono.Cecil to open assemblies directly
proj.SetProperty ("AndroidEnableAssemblyCompression", "False");
proj.SetProperty ("AndroidUseAssemblyStore", useAssemblyStore.ToString ());
using (var b = CreateApkBuilder ()) {
Assert.IsTrue (b.Build (proj), "first build should have succeeded.");
linker_xml =
$@"<linker>
<assembly fullname=""{assembly_name}"">
<type fullname=""System.Console"">
<method name=""Beep"" />
</type>
</assembly>
</linker>";
proj.Touch ("linker.xml");
Assert.IsTrue (b.Build (proj, doNotCleanupOnUpdate: true), "second build should have succeeded.");
var apk = Path.Combine (Root, b.ProjectDirectory, proj.OutputPath, $"{proj.PackageName}-Signed.apk");
FileAssert.Exists (apk);
var helper = new ArchiveAssemblyHelper (apk, useAssemblyStore);
foreach (string abi in proj.GetRuntimeIdentifiersAsAbis ()) {
Assert.IsTrue (helper.Exists ($"assemblies/{abi}/{assembly_name}.dll"), $"{assembly_name}.dll should exist in apk!");
}
using (var stream = helper.ReadEntry ($"assemblies/{assembly_name}.dll")) {
stream.Position = 0;
using (var assembly = AssemblyDefinition.ReadAssembly (stream)) {
var type = assembly.MainModule.GetType ("System.Console");
var method = type.Methods.FirstOrDefault (p => p.Name == "Beep");
Assert.IsNotNull (method, "System.Console.Beep should exist!");
}
}
}
}
[Test]
public void LinkWithNullAttribute ([Values] AndroidRuntime runtime)
{
const bool isRelease = true;
if (IgnoreUnsupportedConfiguration (runtime, release: isRelease)) {
return;
}
var proj = new XamarinAndroidApplicationProject {
IsRelease = isRelease,
OtherBuildItems = {
new BuildItem ("Compile", "NullAttribute.cs") { TextContent = () => @"
using System;
using Android.Content;
using Android.Widget;
namespace UnnamedProject {
public class MyAttribute : Attribute
{
Type[] types;
public Type[] Types {
get { return types; }
}
public MyAttribute (Type[] ta)
{
types = ta;
}
}
[MyAttribute (null)]
public class AttributedButtonStub : Button
{
public AttributedButtonStub (Context context) : base (context)
{
}
}
}"
},
}
};
proj.SetRuntime (runtime);
proj.MainActivity = proj.DefaultMainActivity.Replace ("//${AFTER_ONCREATE}",
$@" var myButton = new AttributedButtonStub (this);
myButton.Text = ""Bug #35710"";
");
using (var b = CreateApkBuilder ()) {
Assert.IsTrue (b.Build (proj), "Building a project with a null attribute value should have succeded.");
}
}
static IEnumerable<object[]> Get_AndroidAddKeepAlivesData ()
{
var ret = new List<object[]> ();
foreach (AndroidRuntime runtime in Enum.GetValues (typeof (AndroidRuntime))) {
// Debug configuration
AddTestData (isRelease: false, setAndroidAddKeepAlivesTrue: false, setLinkModeNone: false, shouldAddKeepAlives: false, runtime);
// Debug configuration, AndroidAddKeepAlives=true
AddTestData (isRelease: false, setAndroidAddKeepAlivesTrue: true, setLinkModeNone: false, shouldAddKeepAlives: true, runtime);
// Release configuration
AddTestData (isRelease: true, setAndroidAddKeepAlivesTrue: false, setLinkModeNone: false, shouldAddKeepAlives: true, runtime);
// Release configuration, AndroidLinkMode=None
AddTestData (isRelease: true, setAndroidAddKeepAlivesTrue: false, setLinkModeNone: true, shouldAddKeepAlives: true, runtime);
}
return ret;
void AddTestData (bool isRelease, bool setAndroidAddKeepAlivesTrue, bool setLinkModeNone, bool shouldAddKeepAlives, AndroidRuntime runtime)
{
ret.Add (new object[] {
isRelease,
setAndroidAddKeepAlivesTrue,
setLinkModeNone,
shouldAddKeepAlives,
runtime
});
}
}
[Test]
[TestCaseSource (nameof (Get_AndroidAddKeepAlivesData))]
public void AndroidAddKeepAlives (bool isRelease, bool setAndroidAddKeepAlivesTrue, bool setLinkModeNone, bool shouldAddKeepAlives, AndroidRuntime runtime)
{
if (IgnoreUnsupportedConfiguration (runtime, release: isRelease)) {
return;
}
var proj = new XamarinAndroidApplicationProject {
IsRelease = isRelease,
OtherBuildItems = {
new BuildItem ("Compile", "Method.cs") { TextContent = () => @"
using System;
using Java.Interop;
namespace UnnamedProject {
public class MyClass : Java.Lang.Object
{
[Android.Runtime.Register(""MyMethod"")]
public unsafe bool MyMethod (Android.OS.IBinder windowToken, [global::Android.Runtime.GeneratedEnum] Android.Views.InputMethods.HideSoftInputFlags flags)
{
const string __id = ""hideSoftInputFromWindow.(Landroid/os/IBinder;I)Z"";
try {
JniArgumentValue* __args = stackalloc JniArgumentValue [1];
__args [0] = new JniArgumentValue ((windowToken == null) ? IntPtr.Zero : ((global::Java.Lang.Object) windowToken).Handle);
__args [1] = new JniArgumentValue ((int) flags);
var __rm = JniPeerMembers.InstanceMethods.InvokeAbstractBooleanMethod (__id, this, __args);
return __rm;
} finally {
}
}
}
}"
},
}
};
proj.SetRuntime (runtime);
proj.SetProperty ("AllowUnsafeBlocks", "True");
// We don't want `[TargetPlatform ("android35")]` to get set because we don't do AddKeepAlives on .NET for Android assemblies
proj.SetProperty ("GenerateAssemblyInfo", "False");
if (setAndroidAddKeepAlivesTrue)
proj.SetProperty ("AndroidAddKeepAlives", "True");
if (setLinkModeNone)
proj.SetProperty (isRelease ? proj.ReleaseProperties : proj.DebugProperties, "AndroidLinkMode", "None");
using (var b = CreateApkBuilder ()) {
Assert.IsTrue (b.Build (proj), "Building a project should have succeded.");
string projectDir = Path.Combine (proj.Root, b.ProjectDirectory);
var assemblyFile = "UnnamedProject.dll";
if (!isRelease || setLinkModeNone) {
foreach (string abi in proj.GetRuntimeIdentifiersAsAbis ()) {
string assemblyDir = runtime switch {
AndroidRuntime.NativeAOT => Path.Combine (MonoAndroidHelper.AbiToRid (abi), "linked"),
_ => Path.Combine ("android", "assets", abi)
};
CheckAssembly (b.Output.GetIntermediaryPath (Path.Combine (assemblyDir, assemblyFile)), projectDir);
}
} else {
CheckAssembly (BuildTest.GetLinkedPath (b, true, assemblyFile), projectDir);
}
}
void CheckAssembly (string assemblyPath, string projectDir)
{
string shortAssemblyPath = Path.GetRelativePath (projectDir, assemblyPath);
Console.WriteLine ($"CheckAssembly for '{shortAssemblyPath}'");
using var assembly = AssemblyDefinition.ReadAssembly (assemblyPath);
Assert.IsTrue (assembly != null, $"Assembly '${shortAssemblyPath}' should have been loaded");
var td = assembly.MainModule.GetType ("UnnamedProject.MyClass");
Assert.IsTrue (td != null, $"`UnnamedProject.MyClass` type definition should have been found in assembly '{shortAssemblyPath}'");
var mr = td.GetMethods ().Where (m => m.Name == "MyMethod").FirstOrDefault ();
Assert.IsTrue (mr != null, $"`MyMethod` method reference should have been found (assembly '{shortAssemblyPath}')");
var md = mr.Resolve ();
Assert.IsTrue (md != null, $"`MyMethod` method reference should have been resolved (assembly '{shortAssemblyPath}')");
bool hasKeepAliveCall = false;
foreach (var i in md.Body.Instructions) {
if (i.OpCode.Code != Mono.Cecil.Cil.Code.Call)
continue;
if (!i.Operand.ToString ().Contains ("System.GC::KeepAlive"))
continue;
hasKeepAliveCall = true;
break;
}
string not = shouldAddKeepAlives ? String.Empty : " not";
Assert.IsTrue (hasKeepAliveCall == shouldAddKeepAlives, $"KeepAlive call should{not} have been found (assembly '{shortAssemblyPath}')");
}
}
[Test]
public void AndroidUseNegotiateAuthentication ([Values (true, false, null)] bool? useNegotiateAuthentication, [Values] AndroidRuntime runtime)
{
bool isRelease = runtime == AndroidRuntime.NativeAOT;
if (IgnoreUnsupportedConfiguration (runtime, release: isRelease)) {
return;
}
var proj = new XamarinAndroidApplicationProject { IsRelease = true };
proj.SetRuntime (runtime);
proj.AddReferences ("System.Net.Http");
proj.MainActivity = proj.DefaultMainActivity.Replace (
"base.OnCreate (bundle);",
"base.OnCreate (bundle);\n" +
"var client = new System.Net.Http.HttpClient (new Xamarin.Android.Net.AndroidMessageHandler ());\n" +
"client.GetAsync (\"https://microsoft.com\").GetAwaiter ().GetResult ();");
if (useNegotiateAuthentication.HasValue)
proj.SetProperty ("AndroidUseNegotiateAuthentication", useNegotiateAuthentication.ToString ());
var shouldBeEnabled = useNegotiateAuthentication.HasValue && useNegotiateAuthentication.Value;
using (var b = CreateApkBuilder ()) {
Assert.IsTrue (b.Build (proj), "Build should have succeeded.");
var assemblyPath = BuildTest.GetLinkedPath (b, true, "Mono.Android.dll");
using (var assembly = AssemblyDefinition.ReadAssembly (assemblyPath)) {
Assert.IsTrue (assembly != null);
var td = assembly.MainModule.GetType ("Xamarin.Android.Net.NegotiateAuthenticationHelper");
if (shouldBeEnabled) {
Assert.IsNotNull (td, "NegotiateAuthenticationHelper shouldn't have been linked out");
} else {
Assert.IsNull (td, "NegotiateAuthenticationHelper should have been linked out");
}
}
}
}
[Test]
public void PreserveIX509TrustManagerSubclasses ([Values] bool hasServerCertificateCustomValidationCallback, [Values] AndroidRuntime runtime)
{
const bool isRelease = true;
if (IgnoreUnsupportedConfiguration (runtime, release: isRelease)) {
return;
}
var proj = new XamarinAndroidApplicationProject { IsRelease = isRelease };
proj.SetRuntime (runtime);
proj.AddReferences ("System.Net.Http");
proj.MainActivity = proj.DefaultMainActivity.Replace (
"base.OnCreate (bundle);",
"base.OnCreate (bundle);\n" +
(hasServerCertificateCustomValidationCallback
? "var handler = new Xamarin.Android.Net.AndroidMessageHandler { ServerCertificateCustomValidationCallback = (message, certificate, chain, errors) => true };\n"
: "var handler = new Xamarin.Android.Net.AndroidMessageHandler();\n") +
"var client = new System.Net.Http.HttpClient (handler);\n" +
"client.GetAsync (\"https://microsoft.com\").GetAwaiter ().GetResult ();");
using (var b = CreateApkBuilder ()) {
Assert.IsTrue (b.Build (proj), "Build should have succeeded.");
var assemblyPath = BuildTest.GetLinkedPath (b, true, "Mono.Android.dll");
using (var assembly = AssemblyDefinition.ReadAssembly (assemblyPath)) {
Assert.IsTrue (assembly != null);
var types = new[] { "Javax.Net.Ssl.X509ExtendedTrustManager", "Javax.Net.Ssl.IX509TrustManagerInvoker" };
foreach (var typeName in types) {
var td = assembly.MainModule.GetType (typeName);
if (hasServerCertificateCustomValidationCallback) {
Assert.IsNotNull (td, $"{typeName} shouldn't have been linked out");
} else {
Assert.IsNull (td, $"{typeName} should have been linked out");
}
}
}
}
}
[Test]
public void PreserveServices ([Values] AndroidRuntime runtime)
{
const bool isRelease = true;
if (IgnoreUnsupportedConfiguration (runtime, release: isRelease)) {
return;
}
var proj = new XamarinAndroidApplicationProject {
IsRelease = isRelease,
TrimModeRelease = TrimMode.Full,
PackageReferences = {
new Package { Id = "Plugin.Firebase.CloudMessaging", Version = "3.0.0" },
}
};
proj.SetRuntime (runtime);
proj.MainActivity = proj.DefaultMainActivity
.Replace ("//${FIELDS}",
"""
protected override void OnNewIntent (Android.Content.Intent? intent)
{
base.OnNewIntent (intent);
Plugin.Firebase.CloudMessaging.FirebaseCloudMessagingImplementation.OnNewIntent (intent);
}
""")
.Replace ("//${AFTER_ONCREATE}", "Plugin.Firebase.Core.Platforms.Android.CrossFirebase.Initialize (this);");
using var b = CreateApkBuilder ();
Assert.IsTrue (b.Build (proj), "Build should have succeeded.");
var assemblyPath = BuildTest.GetLinkedPath (b, isRelease: true, "Plugin.Firebase.CloudMessaging.dll");
FileAssert.Exists (assemblyPath);
using var assembly = AssemblyDefinition.ReadAssembly (assemblyPath);
var types = new [] { "Plugin.Firebase.CloudMessaging.Platforms.Android.MyFirebaseMessagingService" };
foreach (var typeName in types) {
var td = assembly.MainModule.GetType (typeName);
Assert.IsNotNull (td, $"{typeName} should not have been linked out!");
}
}
// TODO: fix for (true, AndroidRuntime.CoreCLR)
[Test]
public void DoNotErrorOnPerArchJavaTypeDuplicates (
[Values(true, false)] bool enableMarshalMethods,
[Values(AndroidRuntime.MonoVM, AndroidRuntime.CoreCLR)] AndroidRuntime runtime)
{
if (enableMarshalMethods == true && runtime == AndroidRuntime.CoreCLR) {
// This currently fails with the following exception:
//
// Xamarin.Android.Common.targets(1603,3): error XARMM7015: System.NotSupportedException: Writing mixed-mode assemblies is not supported
// at Mono.Cecil.ModuleWriter.Write(ModuleDefinition module, Disposable`1 stream, WriterParameters parameters)
// at Mono.Cecil.ModuleWriter.WriteModule(ModuleDefinition module, Disposable`1 stream, WriterParameters parameters)
// at Mono.Cecil.ModuleDefinition.Write(String fileName, WriterParameters parameters)
// at Mono.Cecil.AssemblyDefinition.Write(String fileName, WriterParameters parameters)
// at Xamarin.Android.Tasks.MarshalMethodsAssemblyRewriter.Rewrite(Boolean brokenExceptionTransitions) in src/Xamarin.Android.Build.Tasks/Utilities/MarshalMethodsAssemblyRewriter.cs:line 165
// at Xamarin.Android.Tasks.RewriteMarshalMethods.RewriteMethods(NativeCodeGenState state, Boolean brokenExceptionTransitionsEnabled) in src/Xamarin.Android.Build.Tasks/Tasks/RewriteMarshalMethods.cs:line 160
Assert.Ignore ("Fails with Mono.Cecil exception on CoreCLR");
return;
}
var path = Path.Combine (Root, "temp", TestName);
var lib = new XamarinAndroidLibraryProject { IsRelease = true, ProjectName = "Lib1" };
lib.SetRuntime (runtime);
lib.SetProperty ("IsTrimmable", "true");
lib.Sources.Add (new BuildItem.Source ("Library1.cs") {
TextContent = () => @"
namespace Lib1;
public class Library1 : Com.Example.Androidlib.MyRunner {
private static bool Is64Bits = IntPtr.Size >= 8;
public static bool Is64 () {
return Is64Bits;
}
public override void Run () => Console.WriteLine (Is64Bits);
}",
});
lib.Sources.Add (new BuildItem ("AndroidJavaSource", "MyRunner.java") {
Encoding = new UTF8Encoding (encoderShouldEmitUTF8Identifier: false),
TextContent = () => @"
package com.example.androidlib;
public abstract class MyRunner {
public abstract void run();
}"
});
var proj = new XamarinAndroidApplicationProject { IsRelease = true, ProjectName = "App1" };
proj.SetRuntime (runtime);
if (runtime == AndroidRuntime.MonoVM) {
proj.SetRuntimeIdentifiers(["armeabi-v7a", "arm64-v8a", "x86", "x86_64"]);
}
proj.References.Add(new BuildItem.ProjectReference (Path.Combine ("..", "Lib1", "Lib1.csproj"), "Lib1"));
proj.MainActivity = proj.DefaultMainActivity.Replace (
"base.OnCreate (bundle);",
"base.OnCreate (bundle);\n" +
"if (Lib1.Library1.Is64 ()) Console.WriteLine (\"Hello World!\");");
proj.EnableMarshalMethods = enableMarshalMethods;
using var lb = CreateDllBuilder (Path.Combine (path, "Lib1"));
using var b = CreateApkBuilder (Path.Combine (path, "App1"));
Assert.IsTrue (lb.Build (lib), "build should have succeeded.");
Assert.IsTrue (b.Build (proj), "build should have succeeded.");
var intermediate = Path.Combine (Root, b.ProjectDirectory, proj.IntermediateOutputPath);
var dll = $"{lib.ProjectName}.dll";
if (runtime == AndroidRuntime.MonoVM) {
Assert64Bit ("android-arm", expected64: false);
Assert64Bit ("android-x86", expected64: false);
}
Assert64Bit ("android-arm64", expected64: true);
Assert64Bit ("android-x64", expected64: true);
void Assert64Bit(string rid, bool expected64)
{
string libDir = Path.Combine (intermediate, rid, "linked");
if (runtime == AndroidRuntime.MonoVM) {
libDir = Path.Combine (libDir, "shrunk");
}
var assembly = AssemblyDefinition.ReadAssembly (Path.Combine (libDir, dll));
var type = assembly.MainModule.FindType ("Lib1.Library1");
Assert.NotNull (type, "Should find Lib1.Library1!");
var cctor = type.GetTypeConstructor ();
Assert.NotNull (type, "Should find Lib1.Library1.cctor!");
Assert.AreNotEqual (0, cctor.Body.Instructions.Count);
/*
* IL snippet
* .method private hidebysig specialname rtspecialname static
* void .cctor () cil managed
* {
* // Is64Bits = 4 >= 8;
* IL_0000: ldc.i4 4
* IL_0005: ldc.i4.8
* ...
*/
var instruction = cctor.Body.Instructions [0];
Assert.AreEqual (OpCodes.Ldc_I4, instruction.OpCode);
if (expected64) {
Assert.AreEqual (8, instruction.Operand, $"Expected 64-bit: {expected64}");
} else {
Assert.AreEqual (4, instruction.Operand, $"Expected 64-bit: {expected64}");
}
}
}
[Test]
public void WarnWithReferenceToPreserveAttribute ([Values] AndroidRuntime runtime)
{
const bool isRelease = true;
if (IgnoreUnsupportedConfiguration (runtime, release: isRelease)) {
return;
}
var proj = new XamarinAndroidApplicationProject { IsRelease = isRelease };
proj.SetRuntime (runtime);
proj.AddReferences ("System.Net.Http");
proj.MainActivity = proj.DefaultMainActivity.Replace (
"protected override void OnCreate",
"[Android.Runtime.PreserveAttribute]\n\t\tprotected override void OnCreate"
);
using (var b = CreateApkBuilder ()) {
var bo = proj.CreateBuildOutput (b);
Assert.IsTrue (b.Build (proj), "Build should have succeeded.");
// Verify the trimmer logged our custom warning from WarnOnPreserveAttribute
var output = b.LastBuildOutput;
Assert.IsTrue (StringAssertEx.ContainsText (output, "obsolete attribute 'Android.Runtime.PreserveAttribute'"), "Should warn about obsolete PreserveAttribute usage");
Assert.IsTrue (StringAssertEx.ContainsText (output, "warning IL6001"), "Should include IL6001 warning code");
}
}
}
}