-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
MonoAOTCompiler.cs
1341 lines (1144 loc) · 51.6 KB
/
MonoAOTCompiler.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
// 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.Collections.Concurrent;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Reflection.Metadata;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using System.Reflection.PortableExecutable;
using JoinedString;
public class MonoAOTCompiler : Microsoft.Build.Utilities.Task
{
/// <summary>
/// Path to AOT cross-compiler binary (mono-aot-cross)
/// </summary>
[Required]
public string CompilerBinaryPath { get; set; } = ""!;
/// <summary>
/// Assemblies to be AOTd. They need to be in a self-contained directory.
///
/// Metadata:
/// - AotArguments: semicolon-separated list of options that will be passed to --aot=
/// - ProcessArguments: semicolon-separated list of options that will be passed to the AOT compiler itself
/// </summary>
[Required]
public ITaskItem[] Assemblies { get; set; } = Array.Empty<ITaskItem>();
/// <summary>
/// Paths to be passed as MONO_PATH environment variable, when running mono-cross-aot.
/// These are in addition to the directory containing the assembly being precompiled.
///
/// MONO_PATH=${dir_containing_assembly}:${AdditionalAssemblySearchPaths}
///
/// </summary>
public string[]? AdditionalAssemblySearchPaths { get; set; }
/// <summary>
/// Directory where the AOT'ed files will be emitted
/// </summary>
[NotNull]
[Required]
public string? OutputDir { get; set; }
/// <summary>
/// Target triple passed to the AOT compiler.
/// </summary>
public string? Triple { get; set; }
/// <summary>
/// Assemblies which were AOT compiled.
///
/// Successful AOT compilation will set the following metadata on the items:
/// - AssemblerFile (when using OutputType=AsmOnly)
/// - ObjectFile (when using OutputType=Normal)
/// - LibraryFile (when using OutputType=Library)
/// - AotDataFile (when using UseAotDataFile=true)
/// - LlvmObjectFile (if using LLVM)
/// - LlvmBitcodeFile (if using LLVM-only)
/// - ExportsFile (used in LibraryMode only)
/// - MethodTokenFile (when using CollectTrimmingEligibleMethods=true)
/// </summary>
[Output]
public ITaskItem[]? CompiledAssemblies { get; set; }
/// <summary>
/// Disable parallel AOT compilation
/// </summary>
public bool DisableParallelAot { get; set; }
/// <summary>
/// Use LLVM for AOT compilation.
/// The cross-compiler must be built with LLVM support
/// </summary>
public bool UseLLVM { get; set; }
/// <summary>
/// This instructs the AOT code generator to output certain data constructs into a separate file. This can reduce the executable images some five to twenty percent.
/// Developers need to then ship the resulting aotdata as a resource and register a hook to load the data on demand by using the mono_install_load_aot_data_hook() method.
/// Defaults to true.
/// </summary>
public bool UseAotDataFile { get; set; } = true;
/// <summary>
/// Create an ELF object file (.o) or .s file which can be statically linked into an executable when embedding the mono runtime.
/// Only valid if OutputType is ObjectFile or AsmOnly.
/// </summary>
public bool UseStaticLinking { get; set; }
/// <summary>
/// When this option is specified, icalls (internal calls made from the standard library into the mono runtime code) are invoked directly instead of going through the operating system symbol lookup operation.
/// This requires UseStaticLinking=true.
/// </summary>
public bool UseDirectIcalls { get; set; }
/// <summary>
/// When this option is specified, P/Invoke methods are invoked directly instead of going through the operating system symbol lookup operation
/// This requires UseStaticLinking=true.
/// </summary>
public bool UseDirectPInvoke { get; set; }
/// <summary>
/// When this option is specified, the mono aot compiler will generate direct calls for only specified direct pinvokes.
/// Specified direct pinvokes can be in the format of 'module' to generate direct calls for all entrypoints in the module,
/// or 'module!entrypoint' to generate direct calls for individual entrypoints in a module. 'module' will trump 'module!entrypoint'.
/// For a direct call to be generated, the managed code must call the native function through a direct pinvoke, e.g.
///
/// [DllImport("module", EntryPoint="entrypoint")]
/// public static extern <ret> ManagedName (arg)
///
/// or
///
/// [DllImport("module")]
/// public static extern <ret> entrypoint (arg)
///
/// The native sources must be supplied in the direct pinvoke sources parammeter in the LibraryBuilder to generate a shared library.
/// If not using the LibraryBuilder, the native sources must be linked manually in the final executable or library.
/// This requires UseStaticLinking=true, can be used in conjunction with DirectPInvokeLists, but is incompatible with UseDirectPInvoke.
/// </summary>
public ITaskItem[] DirectPInvokes { get; set; } = Array.Empty<ITaskItem>();
/// <summary>
/// When this option is specified, the mono aot compiler will generate direct calls for only specified direct pinvokes in the provided files.
/// Specified direct pinvokes can be in the format of 'module' to generate direct calls for all entrypoints in the module,
/// or 'module!entrypoint' to generate direct calls for individual entrypoints in a module. 'module' will trump 'module!entrypoint'.
/// For a direct call to be generated, the managed code must call the native function through a direct pinvoke, e.g.
///
/// [DllImport("module", EntryPoint="entrypoint")]
/// public static extern <ret> ManagedName (arg)
///
/// or
///
/// [DllImport("module")]
/// public static extern <ret> entrypoint (arg)
///
/// The native sources must be supplied in the direct pinvoke sources parammeter in the LibraryBuilder to generate a shared library.
/// If not using the LibraryBuilder, the native sources must be linked manually in the final executable or library.
/// This requires UseStaticLinking=true, can be used in conjunction with DirectPInvokes, but is incompatible with UseDirectPInvoke.
/// </summary>
public ITaskItem[] DirectPInvokeLists { get; set; } = Array.Empty<ITaskItem>();
/// <summary>
/// Instructs the AOT compiler to emit DWARF debugging information.
/// </summary>
public bool UseDwarfDebug { get; set; }
/// <summary>
/// Instructs the AOT compiler to print the list of aot compiled methods
/// </summary>
public bool CollectTrimmingEligibleMethods { get; set; }
/// <summary>
/// Directory to store the aot output when using switch trimming-eligible-methods-outfile
/// </summary>
public string? TrimmingEligibleMethodsOutputDirectory { get; set; }
/// <summary>
/// File to use for profile-guided optimization, *only* the methods described in the file will be AOT compiled.
/// </summary>
public string[]? AotProfilePath { get; set; }
/// <summary>
/// Mibc file to use for profile-guided optimization, *only* the methods described in the file will be AOT compiled.
/// </summary>
public string[] MibcProfilePath { get; set; } = Array.Empty<string>();
/// <summary>
/// List of profilers to use.
/// </summary>
public string[]? Profilers { get; set; }
/// <summary>
/// Generate a file containing mono_aot_register_module() calls for each AOT module which can be compiled into the app embedding mono.
/// If set, this implies UseStaticLinking=true.
/// </summary>
public string? AotModulesTablePath { get; set; }
/// <summary>
/// Source code language of the AOT modules table. Supports "C" or "ObjC".
/// Defaults to "C".
/// </summary>
public string? AotModulesTableLanguage { get; set; } = nameof(MonoAotModulesTableLanguage.C);
/// <summary>
/// Choose between 'Normal', 'JustInterp', 'Full', 'FullInterp', 'Hybrid', 'LLVMOnly', 'LLVMOnlyInterp'.
/// LLVMOnly means to use only LLVM for FullAOT, AOT result will be a LLVM Bitcode file (the cross-compiler must be built with LLVM support)
/// The "interp" options ('LLVMOnlyInterp' and 'FullInterp') mean generate necessary support to fall back to interpreter if AOT code is not possible for some methods.
/// The difference between 'JustInterp' and 'FullInterp' is that 'FullInterp' will AOT all the methods in the given assemblies, while 'JustInterp' will only AOT the wrappers and trampolines necessary for the runtime to execute the managed methods using the interpreter and to interoperate with P/Invokes and unmanaged callbacks.
/// </summary>
public string Mode { get; set; } = nameof(MonoAotMode.Normal);
/// <summary>
/// Choose between 'ObjectFile', 'AsmOnly', 'Library'
/// ObjectFile means the AOT compiler will produce an .o object file, AsmOnly will produce .s assembly code and Library will produce a .so/.dylib/.dll shared library.
/// </summary>
public string OutputType { get; set; } = nameof(MonoAotOutputType.ObjectFile);
/// <summary>
/// Choose between 'Dll', 'Dylib', 'So'. Only valid if OutputType is Library.
/// Dll means the AOT compiler will produce a Windows PE .dll file, Dylib means an Apple Mach-O .dylib and So means a Linux/Android ELF .so file.
/// </summary>
public string? LibraryFormat { get; set; }
/// <summary>
/// Prefix that will be added to the library file name, e.g. to add 'lib' prefix required by some platforms. Only valid if OutputType is Library.
/// </summary>
public string LibraryFilePrefix { get; set; } = "";
/// <summary>
/// Enables exporting symbols of methods decorated with UnmanagedCallersOnly Attribute containing a specified EntryPoint
/// </summary>
public bool EnableUnmanagedCallersOnlyMethodsExport { get; set; }
/// <summary>
/// Path to the directory where LLVM binaries (opt and llc) are found.
/// It's required if UseLLVM is set
/// </summary>
public string? LLVMPath { get; set; }
/// <summary>
/// Prepends a prefix to the name of tools ran by the AOT compiler, i.e. 'as'/'ld'.
/// </summary>
public string? ToolPrefix { get; set; }
/// <summary>
/// Prepends a prefix to the name of the assembler (as) tool ran by the AOT compiler.
/// </summary>
public string? AsPrefix { get; set; }
/// <summary>
/// Path to the directory where msym artifacts are stored.
/// </summary>
public string? MsymPath { get; set; }
/// <summary>
/// The assembly whose AOT image will contained dedup-ed generic instances
/// </summary>
public string? DedupAssembly { get; set; }
/// <summary>
/// Debug option in llvm aot mode
/// defaults to "nodebug" since some targes can't generate debug info
/// </summary>
public string? LLVMDebug { get; set; } = "nodebug";
/// <summary>
/// File used to track hashes of assemblies, to act as a cache
/// Output files don't get written, if they haven't changed
/// </summary>
public string? CacheFilePath { get; set; }
/// <summary>
/// Passes additional, custom arguments to --aot
/// </summary>
public string? AotArguments { get; set; }
/// <summary>
/// Passes temp-path to the AOT compiler
/// </summary>
public string? TempPath { get; set; }
/// <summary>
/// Passes ld-name to the AOT compiler, for use with UseLLVM=true
/// </summary>
public string? LdName { get; set; }
/// <summary>
/// Passes ld-flags to the AOT compiler, for use with UseLLVM=true
/// </summary>
public string? LdFlags { get; set; }
/// <summary>
/// Specify WorkingDirectory for the AOT compiler
/// </summary>
public string? WorkingDirectory { get; set; }
[Required]
public string IntermediateOutputPath { get; set; } = string.Empty;
[Output]
public string[]? FileWrites { get; private set; }
private static readonly Encoding s_utf8Encoding = new UTF8Encoding(false);
private const string s_originalFullPathMetadataName = "__OriginalFullPath";
private List<string> _fileWrites = new();
private List<ITaskItem>? _assembliesToCompile;
private ConcurrentDictionary<string, ITaskItem> compiledAssemblies = new();
private BuildPropertiesTable? _propertiesTable;
private MonoAotMode parsedAotMode;
private MonoAotOutputType parsedOutputType;
private MonoAotLibraryFormat parsedLibraryFormat;
private MonoAotModulesTableLanguage parsedAotModulesTableLanguage;
private FileCache? _cache;
private int _numCompiled;
private int _totalNumAssemblies;
private readonly Dictionary<string, string> _symbolNameFixups = new();
private static readonly char[] s_semicolon = new char[]{ ';' };
private bool ProcessAndValidateArguments()
{
if (!File.Exists(CompilerBinaryPath))
{
Log.LogError($"{nameof(CompilerBinaryPath)}='{CompilerBinaryPath}' doesn't exist.");
return false;
}
if (Assemblies.Length == 0)
{
Log.LogError($"'{nameof(Assemblies)}' is required.");
return false;
}
// A relative path might be used along with WorkingDirectory,
// only call Path.GetFullPath() if WorkingDirectory is blank.
if (string.IsNullOrEmpty(WorkingDirectory) && !Path.IsPathRooted(OutputDir))
OutputDir = Path.GetFullPath(OutputDir);
if (!Directory.Exists(OutputDir))
{
Log.LogError($"OutputDir={OutputDir} doesn't exist");
return false;
}
if (!Directory.Exists(IntermediateOutputPath))
Directory.CreateDirectory(IntermediateOutputPath);
if (AotProfilePath != null)
{
foreach (var path in AotProfilePath)
{
if (!File.Exists(path))
{
Log.LogError($"AotProfilePath '{path}' doesn't exist.");
return false;
}
}
}
foreach (var path in MibcProfilePath)
{
if (!File.Exists(path))
{
Log.LogError($"MibcProfilePath '{path}' doesn't exist.");
return false;
}
}
if (UseLLVM)
{
if (string.IsNullOrEmpty(LLVMPath))
// prevent using some random llc/opt from PATH (installed with clang)
throw new LogAsErrorException($"'{nameof(LLVMPath)}' is required when '{nameof(UseLLVM)}' is true.");
if (!Directory.Exists(LLVMPath))
{
Log.LogError($"Could not find LLVMPath=${LLVMPath}");
return false;
}
}
if (!Enum.TryParse(Mode, true, out parsedAotMode))
{
Log.LogError($"Unknown Mode value: {Mode}. '{nameof(Mode)}' must be one of: {string.Join(",", Enum.GetNames(typeof(MonoAotMode)))}");
return false;
}
switch (OutputType)
{
case "ObjectFile": parsedOutputType = MonoAotOutputType.ObjectFile; break;
case "AsmOnly": parsedOutputType = MonoAotOutputType.AsmOnly; break;
case "Library": parsedOutputType = MonoAotOutputType.Library; break;
case "Normal":
Log.LogWarning($"'{nameof(OutputType)}=Normal' is deprecated, use 'ObjectFile' instead.");
parsedOutputType = MonoAotOutputType.ObjectFile; break;
default:
throw new LogAsErrorException($"'{nameof(OutputType)}' must be one of: '{nameof(MonoAotOutputType.ObjectFile)}', '{nameof(MonoAotOutputType.AsmOnly)}', '{nameof(MonoAotOutputType.Library)}'. Received: '{OutputType}'.");
}
switch (LibraryFormat)
{
case "Dll": parsedLibraryFormat = MonoAotLibraryFormat.Dll; break;
case "Dylib": parsedLibraryFormat = MonoAotLibraryFormat.Dylib; break;
case "So": parsedLibraryFormat = MonoAotLibraryFormat.So; break;
default:
if (parsedOutputType == MonoAotOutputType.Library)
throw new LogAsErrorException($"'{nameof(LibraryFormat)}' must be one of: '{nameof(MonoAotLibraryFormat.Dll)}', '{nameof(MonoAotLibraryFormat.Dylib)}', '{nameof(MonoAotLibraryFormat.So)}'. Received: '{LibraryFormat}'.");
break;
}
if (parsedAotMode == MonoAotMode.LLVMOnly && !UseLLVM)
{
throw new LogAsErrorException($"'{nameof(UseLLVM)}' must be true when '{nameof(Mode)}' is {nameof(MonoAotMode.LLVMOnly)}.");
}
switch (AotModulesTableLanguage)
{
case "C": parsedAotModulesTableLanguage = MonoAotModulesTableLanguage.C; break;
case "ObjC": parsedAotModulesTableLanguage = MonoAotModulesTableLanguage.ObjC; break;
default:
throw new LogAsErrorException($"'{nameof(AotModulesTableLanguage)}' must be one of: '{nameof(MonoAotModulesTableLanguage.C)}', '{nameof(MonoAotModulesTableLanguage.ObjC)}'. Received: '{AotModulesTableLanguage}'.");
}
if (!string.IsNullOrEmpty(AotModulesTablePath) || parsedOutputType == MonoAotOutputType.ObjectFile)
{
// AOT modules for static linking, needs the aot modules table
UseStaticLinking = true;
}
if (UseDirectIcalls && !UseStaticLinking)
{
throw new LogAsErrorException($"'{nameof(UseDirectIcalls)}' can only be used with '{nameof(UseStaticLinking)}=true'.");
}
if (UseDirectPInvoke && (DirectPInvokes.Length > 0 || DirectPInvokeLists.Length > 0))
{
throw new LogAsErrorException($"'{nameof(UseDirectPInvoke)}' flag trumps specified '{nameof(DirectPInvokes)}' and '{nameof(DirectPInvokeLists)}' arguments. Unset either the flag or the specific direct pinvoke arguments.");
}
if (UseDirectPInvoke || DirectPInvokes.Length > 0 || DirectPInvokeLists.Length > 0)
{
if (!UseStaticLinking)
throw new LogAsErrorException($"'{nameof(UseDirectPInvoke)}', '{nameof(DirectPInvokes)}', and '{nameof(DirectPInvokeLists)}' can only be used with '{nameof(UseStaticLinking)}=true'.");
foreach (var directPInvokeList in DirectPInvokeLists)
{
if (!File.Exists(directPInvokeList.GetMetadata("FullPath")))
throw new LogAsErrorException($"Could not find file '{directPInvokeList}'.");
}
}
if (UseStaticLinking && (parsedOutputType == MonoAotOutputType.Library))
{
throw new LogAsErrorException($"'{nameof(OutputType)}=Library' can not be used with '{nameof(UseStaticLinking)}=true'.");
}
foreach (var asmItem in Assemblies)
{
string? fullPath = asmItem.GetMetadata("FullPath");
if (!File.Exists(fullPath))
throw new LogAsErrorException($"Could not find {fullPath} to AOT");
}
if (CollectTrimmingEligibleMethods)
{
if (string.IsNullOrEmpty(TrimmingEligibleMethodsOutputDirectory))
throw new LogAsErrorException($"{nameof(TrimmingEligibleMethodsOutputDirectory)} is empty. When {nameof(CollectTrimmingEligibleMethods)} is set to true, the user needs to provide a directory for {nameof(TrimmingEligibleMethodsOutputDirectory)}.");
if (!Directory.Exists(TrimmingEligibleMethodsOutputDirectory))
{
Directory.CreateDirectory(TrimmingEligibleMethodsOutputDirectory);
}
}
return !Log.HasLoggedErrors;
}
public override bool Execute()
{
try
{
return ExecuteInternal();
}
catch (LogAsErrorException laee)
{
Log.LogError(laee.Message);
return false;
}
finally
{
if (_cache != null && _cache.Save(CacheFilePath!))
_fileWrites.Add(CacheFilePath!);
FileWrites = _fileWrites.ToArray();
}
}
private bool ExecuteInternal()
{
if (!ProcessAndValidateArguments())
return false;
string propertiesTableFilePath = Path.Combine(IntermediateOutputPath, "monoAotPropertyValues.txt");
_propertiesTable = new BuildPropertiesTable(propertiesTableFilePath);
IEnumerable<ITaskItem> managedAssemblies = FilterOutUnmanagedAssemblies(Assemblies);
managedAssemblies = EnsureAllAssembliesInTheSameDir(managedAssemblies);
_assembliesToCompile = managedAssemblies.Where(f => !ShouldSkipForAOT(f)).ToList();
if (!string.IsNullOrEmpty(AotModulesTablePath) && !GenerateAotModulesTable(_assembliesToCompile, Profilers, AotModulesTablePath))
return false;
string? monoPaths = null;
if (AdditionalAssemblySearchPaths != null)
monoPaths = string.Join(Path.PathSeparator.ToString(), AdditionalAssemblySearchPaths);
_cache = new FileCache(CacheFilePath, Log);
List<PrecompileArguments> argsList = new();
foreach (var assemblyItem in _assembliesToCompile)
argsList.Add(GetPrecompileArgumentsFor(assemblyItem, monoPaths));
_totalNumAssemblies = _assembliesToCompile.Count;
if (CheckAllUpToDate(argsList))
{
Log.LogMessage(MessageImportance.High, "Everything is up-to-date, nothing to precompile");
_fileWrites.AddRange(argsList.SelectMany(args => args.ProxyFiles).Select(pf => pf.TargetFile));
foreach (var args in argsList)
compiledAssemblies.GetOrAdd(args.AOTAssembly.ItemSpec, args.AOTAssembly);
}
else
{
int allowedParallelism = DisableParallelAot ? 1 : Math.Min(_assembliesToCompile.Count, Environment.ProcessorCount);
IBuildEngine9? be9 = BuildEngine as IBuildEngine9;
if (be9 is not null)
allowedParallelism = be9.RequestCores(allowedParallelism);
/*
From: https://github.com/dotnet/runtime/issues/46146#issuecomment-754021690
Stephen Toub:
"As such, by default ForEach works on a scheme whereby each
thread takes one item each time it goes back to the enumerator,
and then after a few times of this upgrades to taking two items
each time it goes back to the enumerator, and then four, and
then eight, and so on. This amortizes the cost of taking and
releasing the lock across multiple items, while still enabling
parallelization for enumerables containing just a few items. It
does, however, mean that if you've got a case where the body
takes a really long time and the work for every item is
heterogeneous, you can end up with an imbalance."
The time taken by individual compile jobs here can vary a
lot, depending on various factors like file size. This can
create an imbalance, like mentioned above, and we can end up
in a situation where one of the partitions has a job that
takes very long to execute, by which time other partitions
have completed, so some cores are idle. But the idle
ones won't get any of the remaining jobs, because they are
all assigned to that one partition.
Instead, we want to use work-stealing so jobs can be run by any partition.
*/
try
{
ParallelLoopResult result = Parallel.ForEach(
Partitioner.Create(argsList, EnumerablePartitionerOptions.NoBuffering),
new ParallelOptions { MaxDegreeOfParallelism = allowedParallelism },
PrecompileLibraryParallel);
if (result.IsCompleted)
{
int numUnchanged = _totalNumAssemblies - _numCompiled;
if (numUnchanged > 0 && numUnchanged != _totalNumAssemblies)
Log.LogMessage(MessageImportance.High, $"[{numUnchanged}/{_totalNumAssemblies}] skipped unchanged assemblies.");
}
else if (!Log.HasLoggedErrors)
{
Log.LogError($"Precompiling failed due to unknown reasons. Check log for more info");
}
}
finally
{
be9?.ReleaseCores(allowedParallelism);
}
}
CheckExportSymbolsFile(_assembliesToCompile);
_propertiesTable.Table[nameof(CollectTrimmingEligibleMethods)] = CollectTrimmingEligibleMethods.ToString();
_propertiesTable.Save(propertiesTableFilePath, Log);
CompiledAssemblies = ConvertAssembliesDictToOrderedList(compiledAssemblies, _assembliesToCompile).ToArray();
return !Log.HasLoggedErrors;
}
private static bool CheckAllUpToDate(IList<PrecompileArguments> argsList)
{
foreach (var args in argsList)
{
// compare original assembly vs it's outputs.. all it's outputs!
string assemblyPath = args.AOTAssembly.GetMetadata("FullPath");
if (args.ProxyFiles.Any(pf => Utils.IsNewerThan(assemblyPath, pf.TargetFile)))
return false;
}
return true;
}
private List<ITaskItem> FilterOutUnmanagedAssemblies(IEnumerable<ITaskItem> assemblies)
{
List<ITaskItem> filteredAssemblies = new();
foreach (var asmItem in assemblies)
{
if (ShouldSkipForAOT(asmItem))
{
if (parsedAotMode == MonoAotMode.LLVMOnly)
throw new LogAsErrorException($"Building in AOTMode=LLVMonly is not compatible with excluding any assemblies for AOT. Excluded assembly: {asmItem.ItemSpec}");
Log.LogMessage(MessageImportance.Low, $"Skipping {asmItem.ItemSpec} because it has %(AOT_InternalForceToInterpret)=true");
}
else
{
string assemblyPath = asmItem.GetMetadata("FullPath");
using var assemblyFile = File.OpenRead(assemblyPath);
using PEReader reader = new(assemblyFile, PEStreamOptions.Default);
if (!reader.HasMetadata)
{
Log.LogMessage(MessageImportance.Low, $"Skipping unmanaged {assemblyPath} for AOT");
continue;
}
}
filteredAssemblies.Add(asmItem);
}
return filteredAssemblies;
}
private static bool ShouldSkipForAOT(ITaskItem asmItem)
=> bool.TryParse(asmItem.GetMetadata("AOT_InternalForceToInterpret"), out bool skip) && skip;
private IEnumerable<ITaskItem> EnsureAllAssembliesInTheSameDir(IEnumerable<ITaskItem> assemblies)
{
string firstAsmDir = Path.GetDirectoryName(assemblies.First().GetMetadata("FullPath")) ?? string.Empty;
bool allInSameDir = assemblies.All(asm => Path.GetDirectoryName(asm.GetMetadata("FullPath")) == firstAsmDir);
if (allInSameDir)
return assemblies;
// Copy to aot-in
string aotInPath = Path.Combine(IntermediateOutputPath, "aot-in");
Directory.CreateDirectory(aotInPath);
List<ITaskItem> newAssemblies = new();
foreach (var asmItem in assemblies)
{
string asmPath = asmItem.GetMetadata("FullPath");
string newPath = Path.Combine(aotInPath, Path.GetFileName(asmPath));
// FIXME: delete files not in originalAssemblies though
// FIXME: or .. just delete the whole dir?
if (Utils.CopyIfDifferent(asmPath, newPath, useHash: true))
Log.LogMessage(MessageImportance.Low, $"Copying {asmPath} to {newPath}");
_fileWrites.Add(newPath);
var newAsm = new TaskItem(newPath);
asmItem.CopyMetadataTo(newAsm);
newAsm.SetMetadata(s_originalFullPathMetadataName, asmPath);
newAssemblies.Add(newAsm);
}
return newAssemblies;
}
private PrecompileArguments GetPrecompileArgumentsFor(ITaskItem assemblyItem, string? monoPaths)
{
string assembly = assemblyItem.GetMetadata("FullPath");
string assemblyDir = Path.GetDirectoryName(assembly)!;
var aotAssembly = new TaskItem(assembly, assemblyItem.CloneCustomMetadata());
var aotArgs = new List<string>();
var processArgs = new List<string>();
bool isDedup = Path.GetFileName(assembly) == Path.GetFileName(DedupAssembly);
List<ProxyFile> proxyFiles = new(capacity: 5);
var a = assemblyItem.GetMetadata("AotArguments");
if (a != null)
{
aotArgs.AddRange(a.Split(s_semicolon, StringSplitOptions.RemoveEmptyEntries));
}
var p = assemblyItem.GetMetadata("ProcessArguments");
if (p != null)
{
processArgs.AddRange(p.Split(s_semicolon, StringSplitOptions.RemoveEmptyEntries));
}
processArgs.Add("--debug");
// add LLVM options
if (UseLLVM)
{
processArgs.Add("--llvm");
if (!string.IsNullOrEmpty(LLVMDebug))
aotArgs.Add(LLVMDebug);
aotArgs.Add($"llvm-path={LLVMPath}");
}
else
{
processArgs.Add("--nollvm");
}
if (UseStaticLinking)
{
aotArgs.Add($"static");
}
if (UseDirectPInvoke)
{
aotArgs.Add($"direct-pinvoke");
}
if (DirectPInvokes.Length > 0)
{
aotArgs.Add($$"""direct-pinvokes={{DirectPInvokes.Join("", d => $"{d.ItemSpec};")}}""");
}
if (DirectPInvokeLists.Length > 0)
{
aotArgs.Add($$"""direct-pinvoke-lists={{DirectPInvokeLists.Join("", d => $"{d.GetMetadata("FullPath")};")}}""");
}
if (UseDwarfDebug)
{
aotArgs.Add($"dwarfdebug");
}
if (!string.IsNullOrEmpty(Triple))
{
aotArgs.Add($"mtriple={Triple}");
}
if (!string.IsNullOrEmpty(ToolPrefix))
{
aotArgs.Add($"tool-prefix={ToolPrefix}");
}
if (!string.IsNullOrEmpty(AsPrefix))
{
aotArgs.Add($"as-prefix={AsPrefix}");
}
string assemblyFilename = Path.GetFileName(assembly);
if (isDedup)
{
aotArgs.Add($"dedup-include={assemblyFilename}");
}
else if (!string.IsNullOrEmpty (DedupAssembly))
{
aotArgs.Add("dedup-skip");
}
if (CollectTrimmingEligibleMethods)
{
string assemblyName = FixupSymbolName(assemblyFilename);
string outputFileName = assemblyName + "_compiled_methods.txt";
string outputFilePath;
if (string.IsNullOrEmpty(TrimmingEligibleMethodsOutputDirectory))
{
outputFilePath = outputFileName;
}
else
{
outputFilePath = Path.Combine(TrimmingEligibleMethodsOutputDirectory, outputFileName);
}
aotArgs.Add($"trimming-eligible-methods-outfile={outputFilePath}");
aotAssembly.SetMetadata("MethodTokenFile", outputFilePath);
}
// compute output mode and file names
if (parsedAotMode == MonoAotMode.LLVMOnly || parsedAotMode == MonoAotMode.LLVMOnlyInterp)
{
aotArgs.Add("llvmonly");
string llvmBitcodeFile = Path.Combine(OutputDir, Path.ChangeExtension(assemblyFilename, ".dll.bc"));
ProxyFile proxyFile = _cache!.NewFile(llvmBitcodeFile);
proxyFiles.Add(proxyFile);
aotAssembly.SetMetadata("LlvmBitcodeFile", proxyFile.TargetFile);
if (parsedAotMode == MonoAotMode.LLVMOnlyInterp)
{
aotArgs.Add("interp");
}
if (parsedOutputType == MonoAotOutputType.AsmOnly)
{
aotArgs.Add("asmonly");
aotArgs.Add($"llvm-outfile={proxyFile.TempFile}");
}
else
{
aotArgs.Add($"outfile={proxyFile.TempFile}");
}
}
else
{
if (parsedAotMode == MonoAotMode.Full || parsedAotMode == MonoAotMode.FullInterp)
{
aotArgs.Add("full");
}
if (parsedAotMode == MonoAotMode.Hybrid)
{
aotArgs.Add("hybrid");
}
if (parsedAotMode == MonoAotMode.FullInterp || parsedAotMode == MonoAotMode.JustInterp)
{
aotArgs.Add("interp");
}
switch (parsedOutputType)
{
case MonoAotOutputType.ObjectFile:
{
string objectFile = Path.Combine(OutputDir, Path.ChangeExtension(assemblyFilename, ".dll.o"));
ProxyFile proxyFile = _cache!.NewFile(objectFile);
proxyFiles.Add((proxyFile));
aotArgs.Add($"outfile={proxyFile.TempFile}");
aotAssembly.SetMetadata("ObjectFile", proxyFile.TargetFile);
}
break;
case MonoAotOutputType.AsmOnly:
{
aotArgs.Add("asmonly");
string assemblerFile = Path.Combine(OutputDir, Path.ChangeExtension(assemblyFilename, ".dll.s"));
ProxyFile proxyFile = _cache!.NewFile(assemblerFile);
proxyFiles.Add(proxyFile);
aotArgs.Add($"outfile={proxyFile.TempFile}");
aotAssembly.SetMetadata("AssemblerFile", proxyFile.TargetFile);
}
break;
case MonoAotOutputType.Library:
{
string extension = parsedLibraryFormat switch {
MonoAotLibraryFormat.Dll => ".dll",
MonoAotLibraryFormat.Dylib => ".dylib",
MonoAotLibraryFormat.So => ".so",
_ => throw new ArgumentOutOfRangeException()
};
string libraryFileName = $"{LibraryFilePrefix}{assemblyFilename}{extension}";
string libraryFilePath = Path.Combine(OutputDir, libraryFileName);
ProxyFile proxyFile = _cache!.NewFile(libraryFilePath);
proxyFiles.Add(proxyFile);
aotArgs.Add($"outfile={proxyFile.TempFile}");
aotAssembly.SetMetadata("LibraryFile", proxyFile.TargetFile);
}
break;
default:
throw new Exception($"Bug: Unhandled MonoAotOutputType: {parsedAotMode}");
}
if (UseLLVM)
{
string llvmObjectFile = Path.Combine(OutputDir, Path.ChangeExtension(assemblyFilename, ".dll-llvm.o"));
ProxyFile proxyFile = _cache.NewFile(llvmObjectFile);
proxyFiles.Add(proxyFile);
aotArgs.Add($"llvm-outfile={proxyFile.TempFile}");
if (UseStaticLinking)
{
aotAssembly.SetMetadata("LlvmObjectFile", proxyFile.TargetFile);
}
}
}
if (!string.IsNullOrEmpty(TempPath))
{
aotArgs.Add($"temp-path={TempPath}");
}
else if (!string.IsNullOrEmpty(IntermediateOutputPath))
{
string aotTmpPath = Path.Combine(IntermediateOutputPath, assemblyFilename + ".tmp");
if (!Directory.Exists(aotTmpPath))
{
Directory.CreateDirectory(aotTmpPath);
}
aotArgs.Add($"temp-path={aotTmpPath}");
}
if (EnableUnmanagedCallersOnlyMethodsExport)
{
string exportSymbolsFile = Path.Combine(OutputDir, Path.ChangeExtension(assemblyFilename, ".exportsymbols"));
ProxyFile proxyFile = _cache.NewFile(exportSymbolsFile);
proxyFiles.Add(proxyFile);
aotArgs.Add($"export-symbols-outfile={proxyFile.TempFile}");
aotAssembly.SetMetadata("ExportSymbolsFile", proxyFile.TargetFile);
}
// pass msym-dir if specified
if (MsymPath != null)
{
aotArgs.Add($"msym-dir={MsymPath}");
}
if (UseAotDataFile)
{
string aotDataFile = Path.ChangeExtension(assembly, ".aotdata");
ProxyFile proxyFile = _cache.NewFile(aotDataFile);
proxyFiles.Add(proxyFile);
aotArgs.Add($"data-outfile={proxyFile.TempFile}");
aotAssembly.SetMetadata("AotDataFile", proxyFile.TargetFile);
}
if (Profilers?.Length > 0)
{
foreach (var profiler in Profilers)
{
processArgs.Add($"\"--profile={profiler}\"");
}
}
if (AotProfilePath?.Length > 0)
{
aotArgs.Add("profile-only");
foreach (var path in AotProfilePath)
{
aotArgs.Add($"profile={path}");
}
}
if (MibcProfilePath.Length > 0)
{
aotArgs.Add("profile-only");
foreach (var path in MibcProfilePath)
{
aotArgs.Add($"mibc-profile={path}");
}
}
if (!string.IsNullOrEmpty(AotArguments))
{
aotArgs.Add(AotArguments);
}
if (!string.IsNullOrEmpty(LdName))
{
aotArgs.Add($"ld-name={LdName}");
}
if (!string.IsNullOrEmpty(LdFlags))
{
aotArgs.Add($"ld-flags={LdFlags}");
}
// we need to quote the entire --aot arguments here to make sure it is parsed
// on Windows as one argument. Otherwise it will be split up into multiple
// values, which wont work.
processArgs.Add($"\"--aot={string.Join(",", aotArgs)}\"");
if (isDedup)
{
foreach (var aItem in _assembliesToCompile!)
processArgs.Add($"\"{aItem.ItemSpec}\"");
}
else
{
if (string.IsNullOrEmpty(WorkingDirectory))
{
processArgs.Add('"' + assemblyFilename + '"');
}
else
{
// If WorkingDirectory is supplied, the caller could be passing in a relative path
// Use the original ItemSpec that was passed in.
processArgs.Add('"' + assemblyItem.ItemSpec + '"');
}
}
monoPaths = $"{assemblyDir}{Path.PathSeparator}{monoPaths}";
var envVariables = new Dictionary<string, string>
{
{"MONO_PATH", monoPaths },
{"MONO_ENV_OPTIONS", string.Empty} // we do not want options to be provided out of band to the cross compilers
};
var responseFileContent = string.Join(" ", processArgs);
var responseFilePath = Path.GetTempFileName();
using (var sw = new StreamWriter(responseFilePath, append: false, encoding: s_utf8Encoding))
{
sw.WriteLine(responseFileContent);
}
return new PrecompileArguments(ResponseFilePath: responseFilePath,
EnvironmentVariables: envVariables,
WorkingDir: string.IsNullOrEmpty(WorkingDirectory) ? assemblyDir : WorkingDirectory,
AOTAssembly: aotAssembly,
ProxyFiles: proxyFiles);
}