/
ShellTask.cs
2277 lines (1824 loc) · 74 KB
/
ShellTask.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 � 2015-2018 nventive inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ******************************************************************
//
// This file is based on the work from https://github.com/praeclarum/Ooui
//
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Net.Http.Headers;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Transactions;
using Microsoft.Build.Framework;
using Microsoft.Win32.SafeHandles;
using Mono.Cecil;
using Mono.CompilerServices.SymbolWriter;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Uno.Wasm.Bootstrap.Extensions;
namespace Uno.Wasm.Bootstrap
{
public partial class ShellTask_v0 : Microsoft.Build.Utilities.Task
{
private const string WasmScriptsFolder = "WasmScripts";
private const string ServiceWorkerFileName = "service-worker.js";
private const string DeployMetadataName = "UnoDeploy";
private static readonly string _wwwwroot = "wwwroot" + Path.DirectorySeparatorChar;
private string _distPath = "";
private string _workDistPath = "";
private string _workDistRootPath = "";
private string _managedPath = "";
private string _bclPath = "";
private string[]? _bitcodeFilesCache;
private List<string> _referencedAssemblies = new List<string>();
private Dictionary<string, string>? _bclAssemblies;
private readonly List<string> _dependencies = new List<string>();
private string[]? _additionalStyles;
private List<AssemblyDefinition>? _resourceSearchList;
private RuntimeExecutionMode _runtimeExecutionMode;
private ShellMode _shellMode;
private CompressionLayoutMode _compressionLayoutMode;
private string _linkerBinPath = "";
private string _finalPackagePath = "";
private string _remoteBasePackagePath = "";
private string[]? _contentExtensionsToExclude;
private static readonly SHA384Managed _sha384 = new SHA384Managed();
private UTF8Encoding _utf8Encoding = new UTF8Encoding(false);
private byte[] _obfuscationKey = Array.Empty<byte>();
private FileNameObfuscationMode _assembliesFileNameObfuscationMode
= FileNameObfuscationMode.Original;
[Microsoft.Build.Framework.Required]
public string CurrentProjectPath { get; set; } = "";
[Microsoft.Build.Framework.Required]
public string BuildTaskBasePath { get; set; } = "";
[Microsoft.Build.Framework.Required]
public string Assembly { get; set; } = "";
[Microsoft.Build.Framework.Required]
public string DistPath { get; set; } = "";
[Microsoft.Build.Framework.Required]
public string IntermediateOutputPath { get; set; } = "";
[Microsoft.Build.Framework.Required]
public string BaseIntermediateOutputPath { get; set; } = "";
[Microsoft.Build.Framework.Required]
public string MonoWasmSDKPath { get; set; } = "";
public string? PackagerBinPath { get; set; }
public bool UseFileIntegrity { get; set; } = true;
/// <remarks>
/// Disabled until browsers get smarted about fetch vs. prefetch invocations.
/// e.g. Chrome downloads files twice.
/// </remarks>
public bool GeneratePrefetchHeaders { get; set; } = false;
public Microsoft.Build.Framework.ITaskItem[]? ReferencePath { get; set; }
public Microsoft.Build.Framework.ITaskItem[]? MonoEnvironment { get; set; }
public Microsoft.Build.Framework.ITaskItem[]? RuntimeCopyExclude { get; set; }
[Microsoft.Build.Framework.Required]
public string TargetFrameworkIdentifier { get; set; } = "";
public string TargetFramework { get; set; } = "";
public string TargetFrameworkVersion { get; set; } = "0.0";
[Microsoft.Build.Framework.Required]
public string IndexHtmlPath { get; set; } = "";
public string WebAppBasePath { get; set; } = "./";
[Required]
public string WasmShellMode { get; set; } = "";
[Microsoft.Build.Framework.Required]
public string MonoRuntimeExecutionMode { get; set; } = "";
[Microsoft.Build.Framework.Required]
public bool MonoILLinker { get; set; }
public bool InvariantGlobalization { get; set; } = false;
public bool EmccLinkOptimization { get; set; }
public string? EmccLinkOptimizationLevel { get; set; }
public bool EnableLogProfiler { get; set; }
public string LogProfilerOptions { get; set; } = "log:alloc,output=output.mlpd";
public string AssembliesFileExtension { get; set; } = ".clr";
public string AssembliesFileNameObfuscationMode { get; set; } = nameof(FileNameObfuscationMode.Original);
public bool ObfuscateAssemblies { get; set; } = false;
public Microsoft.Build.Framework.ITaskItem[]? Assets { get; set; }
public string? ContentExtensionsToExclude { get; set; }
public Microsoft.Build.Framework.ITaskItem[]? AotProfile { get; set; }
public Microsoft.Build.Framework.ITaskItem[]? LinkerDescriptors { get; set; }
public Microsoft.Build.Framework.ITaskItem[]? MixedModeExcludedAssembly { get; set; }
public string AOTProfileExcludedMethods { get; set; } = "";
public bool GenerateAOTProfileDebugList { get; set; } = false;
public Microsoft.Build.Framework.ITaskItem[]? CompressedExtensions { get; set; }
public Microsoft.Build.Framework.ITaskItem[]? ExtraEmccFlags { get; set; }
public Microsoft.Build.Framework.ITaskItem[]? RuntimeHostConfigurationOption { get; set; }
public Microsoft.Build.Framework.ITaskItem[]? AdditionalPInvokeLibraries { get; set; }
public Microsoft.Build.Framework.ITaskItem[]? NativeCompile { get; set; }
public Microsoft.Build.Framework.ITaskItem[]? EmccExportedRuntimeMethods { get; set; }
public bool GenerateCompressedFiles { get; set; }
public string? DistCompressionLayoutMode { get; set; }
public bool ForceUseWSL { get; set; }
public bool EnableEmscriptenWindows { get; set; } = true;
public bool ForceDisableWSL { get; set; }
public bool SkipPowershellExecutionPolicyValidation { get; set; } = false;
[Microsoft.Build.Framework.Required]
public string RuntimeConfiguration { get; set; } = "";
[Microsoft.Build.Framework.Required]
public bool EnableThreads { get; set; }
public int PThreadsPoolSize { get; set; } = 4;
[Microsoft.Build.Framework.Required]
public bool EnableSimd { get; set; }
[Microsoft.Build.Framework.Required]
public bool RuntimeDebuggerEnabled { get; set; }
public int BrotliCompressionQuality { get; set; } = 7;
public string? CustomDebuggerPath { get; set; }
public string? CustomLinkerPath { get; set; }
public string? WasmTunerBinPath { get; set; }
public string? PWAManifestFile { get; set; }
public bool EnableLongPathSupport { get; set; } = true;
public bool EnableEmccProfiling { get; set; } = false;
public bool EnableNetCoreICU { get; set; } = true;
public bool EnableAOTDeduplication { get; set; } = true;
public bool EnableAotGSharedVT { get; set; } = false;
public string? AotCompilerOptions { get; set; }
public bool GenerateAOTProfile { get; set; } = false;
public string? NinjaAdditionalParameters { get; set; }
[Output]
public string? OutputPackagePath { get; private set; }
[Output]
public string? OutputDistPath { get; private set; }
private Version ActualTargetFrameworkVersion
=> Version.TryParse(TargetFrameworkVersion.Substring(1), out var v) ? v : new Version("0.0");
public override bool Execute()
{
try
{
if (string.IsNullOrEmpty(TargetFramework))
{
throw new InvalidOperationException($"The TargetFramework task parameter must be defined.");
}
if(TargetFrameworkIdentifier == ".NETCoreApp" && ActualTargetFrameworkVersion < new Version("5.0"))
{
throw new InvalidOperationException($"The TargetFramework version must be above 5.0 (found {TargetFrameworkVersion})");
}
// Debugger.Launch();
PreloadAssemblies();
ValidateEmscriptenWindowsAvailability();
TryGenerateObfuscationKey();
TryEnableLongPathAware();
ParseProperties();
GetBcl();
CreateDist();
CopyContent();
CopyRuntime();
RunPackager();
TryDeployDebuggerProxy();
GenerateServerAppFeaturesInfo();
ExtractAdditionalJS();
ExtractAdditionalCSS();
CleanupDist();
PrepareFinalDist();
TouchServiceWorker();
GenerateConfig();
MergeConfig();
GenerateIndexHtml();
GenerateEmbeddedJs();
TryCompressDist();
return true;
}
catch (Exception ex)
{
Log.LogError(ex.ToString(), false, true, null);
return false;
}
}
private void TryGenerateObfuscationKey()
{
if (ObfuscateAssemblies)
{
_obfuscationKey = Encoding.ASCII.GetBytes(Guid.NewGuid().ToString().Split('-')[0]);
}
}
private void PreloadAssemblies()
{
// Under some circumstances, the assemblies bundled with the bootstrapper do not
// get loaded properly by .NET Core. This is method forces the loading of those
// assemblies in order to let the loading find them automatically.
var path = Path.GetDirectoryName(new Uri(GetType().Assembly.GetName().CodeBase).LocalPath);
foreach (var file in Directory.GetFiles(path, "*.dll"))
{
_ = System.Reflection.Assembly.LoadFile(Path.Combine(path, file));
}
}
private void TryEnableLongPathAware()
{
if (EnableLongPathSupport)
{
// In some cases, particularly when using the Azure publish task
// long paths using the "\\?\" prefix is not supported. Fallback on
// standard paths in such cases.
try
{
var path = TryConvertLongPath(Path.GetFullPath(DistPath));
DirectoryCreateDirectory(path);
}
catch (ArgumentException e)
{
Log.LogMessage($"Long path format use failed, falling back to standard path (Error: {e.Message})");
EnableLongPathSupport = false;
}
}
IntermediateOutputPath = TryConvertLongPath(IntermediateOutputPath);
BaseIntermediateOutputPath = TryConvertLongPath(Path.GetFullPath(BaseIntermediateOutputPath));
DistPath = TryConvertLongPath(DistPath);
CurrentProjectPath = TryConvertLongPath(CurrentProjectPath);
CustomDebuggerPath = TryConvertLongPath(CustomDebuggerPath!);
}
private void ValidateEmscriptenWindowsAvailability()
{
if (EnableEmscriptenWindows && Environment.OSVersion.Platform != PlatformID.Win32NT)
{
EnableEmscriptenWindows = false;
}
}
private void TouchServiceWorker()
{
// The service worker file must change to be reloaded properly, add the dist digest
// as cache trasher.
var workerFilePath = Path.Combine(_finalPackagePath, ServiceWorkerFileName);
var workerBody = File.ReadAllText(workerFilePath);
workerBody = workerBody.Replace("$(CACHE_KEY)", Path.GetFileName(_remoteBasePackagePath));
workerBody = workerBody.Replace("$(REMOTE_BASE_PATH)", _remoteBasePackagePath + "/");
workerBody = workerBody.Replace("$(REMOTE_WEBAPP_PATH)", WebAppBasePath);
workerBody += $"\r\n\r\n// {Path.GetFileName(_managedPath)}";
File.WriteAllText(workerFilePath, workerBody);
// The service worker file must be placed at the root in order to specify the
// "./" scope to include index.html in the worker. Otherwise, offline mode cannot
// work if index.html is not cached.
MoveFileSafe(workerFilePath, Path.Combine(_distPath, ServiceWorkerFileName));
}
private void FileCopy(string source, string dest, bool overwrite = false)
{
var sourceFileName = PathHelper.FixupPath(source);
var destFileName = PathHelper.FixupPath(dest);
try
{
File.Copy(sourceFileName, destFileName, overwrite);
}
catch (Exception ex)
{
Log.LogError($"Failed to copy {sourceFileName} to {destFileName}: {ex.Message}");
throw;
}
}
private void DirectoryCreateDirectory(string directory)
{
var directoryName = PathHelper.FixupPath(directory);
try
{
Directory.CreateDirectory(directoryName);
}
catch (Exception /*e*/)
{
Log.LogError($"Failed to create directory [{directoryName}][{directory}]");
throw;
}
}
private void CleanupDist()
{
var unusedFiles = new[] {
"*.wast",
"*.bc",
"*.a",
};
foreach (var unusedFile in unusedFiles)
{
foreach (var file in Directory.EnumerateFiles(_workDistPath, unusedFile))
{
Log.LogMessage(MessageImportance.Low, $"Removing unused file {file}");
File.Delete(file);
}
}
}
private void TryCompressDist()
{
var hasCompressedExtensions = (CompressedExtensions?.Any() ?? false);
if (
!RuntimeDebuggerEnabled
&& GenerateCompressedFiles
&& hasCompressedExtensions
)
{
TryParseDistCompressionLayoutMode();
var compressibleExtensions = CompressedExtensions
.Select(e => e.ItemSpec);
Log.LogMessage(MessageImportance.Low, $"Compressing {string.Join(", ", compressibleExtensions)}");
var filesToCompress = compressibleExtensions
.SelectMany(e => Directory.GetFiles(_finalPackagePath, "*" + e, SearchOption.AllDirectories))
.Where(f => !Path.GetDirectoryName(f).Contains("_compressed_"))
.Distinct()
.ToArray();
if (_compressionLayoutMode == CompressionLayoutMode.Legacy)
{
CompressFiles(filesToCompress, "gz", GzipCompress);
}
CompressFiles(filesToCompress, "br", BrotliCompress);
}
else
{
Log.LogMessage(MessageImportance.Low,
$"Compression is disabled (RuntimeDebuggerEnabled:{RuntimeDebuggerEnabled}, " +
$"GenerateCompressedFiles:{GenerateCompressedFiles}, " +
$"hasCompressedExtensions:{hasCompressedExtensions})");
}
}
private void TryParseDistCompressionLayoutMode()
{
if (string.IsNullOrEmpty(DistCompressionLayoutMode))
{
var webConfigPath = Directory.GetFiles(_distPath, "web.config").FirstOrDefault();
if (!string.IsNullOrEmpty(webConfigPath)
&& File.ReadAllText(webConfigPath).Contains("_compressed_br"))
{
_compressionLayoutMode = CompressionLayoutMode.Legacy;
}
else
{
_compressionLayoutMode = CompressionLayoutMode.InPlace;
}
}
else
{
ParseEnumProperty(nameof(CompressionLayoutMode), DistCompressionLayoutMode!, out _compressionLayoutMode);
}
}
private void CompressFiles(string[] filesToCompress, string method, Action<string, string> compressHandler)
=> filesToCompress
.AsParallel()
.Select(fileName =>
{
var compressedPathBase = _compressionLayoutMode switch
{
CompressionLayoutMode.InPlace => _distPath,
CompressionLayoutMode.Legacy => Path.Combine(_distPath, "_compressed_" + method),
_ => throw new NotSupportedException($"CompressionLayoutMode {_compressionLayoutMode} is not supported")
};
var compressedFileName = fileName;
compressedFileName = compressedFileName.Replace(_distPath, compressedPathBase);
if (_compressionLayoutMode == CompressionLayoutMode.InPlace)
{
compressedFileName += "." + method;
}
DirectoryCreateDirectory(Path.GetDirectoryName(compressedFileName));
if (File.Exists(compressedFileName))
{
if (File.GetCreationTime(compressedFileName) < File.GetCreationTime(fileName))
{
Log.LogMessage(MessageImportance.Low, $"Deleting {compressedFileName} as the source has changed");
File.Delete(compressedFileName);
}
}
Log.LogMessage($"Compressing {fileName}->{compressedFileName}");
compressHandler(fileName, compressedFileName);
return true;
})
.ToArray();
private void GzipCompress(string source, string destination)
{
using var inStream = File.Open(source, FileMode.Open, FileAccess.Read, FileShare.Read);
using var compressedFileStream = File.Create(destination);
using var compressionStream = new GZipStream(compressedFileStream, CompressionLevel.Optimal);
inStream.CopyTo(compressionStream);
}
private void BrotliCompress(string source, string destination)
{
using var input = File.Open(source, FileMode.Open, FileAccess.Read, FileShare.Read);
using var output = File.Create(destination);
using var bs = new BrotliSharpLib.BrotliStream(output, CompressionMode.Compress);
// By default, BrotliSharpLib uses a quality value of 1 and window size of 22 if the methods are not called.
bs.SetQuality(BrotliCompressionQuality);
/** bs.SetWindow(windowSize); **/
/** bs.SetCustomDictionary(customDict); **/
input.CopyTo(bs);
/* IMPORTANT: Only use the destination stream after closing/disposing the BrotliStream
as the BrotliStream must be closed in order to signal that no more blocks are being written
for the final block to be flushed out
*/
bs.Dispose();
}
private bool IsWSLRequired =>
Environment.OSVersion.Platform == PlatformID.Win32NT
&& !EnableEmscriptenWindows
&& (GetBitcodeFilesParams().Any() || _runtimeExecutionMode != RuntimeExecutionMode.Interpreter || ForceUseWSL || GenerateAOTProfile || UseAotProfile);
private bool UseAotProfile => (AotProfile?.Any() ?? false) && _runtimeExecutionMode == RuntimeExecutionMode.InterpreterAndAOT;
public Version CurrentEmscriptenVersion => Constants.DotnetRuntimeEmscriptenVersion;
public bool HasAdditionalPInvokeLibraries => AdditionalPInvokeLibraries is { } libs && libs.Length != 0;
public bool HasNativeCompile => NativeCompile is { } nativeCompile && nativeCompile.Length != 0;
private (int exitCode, string output, string error) RunProcess(
string executable,
string parameters,
string? workingDirectory = null,
(string variable, string value)[]? environmentVariables = null)
{
if (IsWSLRequired
&& !ForceDisableWSL
&& !EnableEmscriptenWindows
&& !executable.EndsWith("bash.exe", StringComparison.OrdinalIgnoreCase))
{
var unixPath = AlignPath(executable, escape: true);
var dotnetRuntimePath = Path.GetExtension(executable).ToLowerInvariant()
switch
{
".exe" => "mono",
".dll" => "dotnet",
_ => ""
};
var cwd = workingDirectory != null ? $"cd \\\"{AlignPath(workingDirectory, escape: true)}\\\" && " : "";
parameters = $"-c \" {cwd} {dotnetRuntimePath} {unixPath} " + parameters.Replace("\\", "\\\\").Replace("\"", "\\\"") + "\"";
executable = GetWSLBashExecutable();
}
else if (RuntimeHelpers.IsNetCore
&& (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)
|| RuntimeInformation.IsOSPlatform(OSPlatform.Linux)
)
)
{
if (executable.EndsWith(".exe", StringComparison.OrdinalIgnoreCase))
{
parameters = $"\"{executable}\" {parameters}";
executable = "mono";
}
if (executable.EndsWith(".dll", StringComparison.OrdinalIgnoreCase))
{
parameters = $"\"{executable}\" {parameters}";
executable = "dotnet";
}
}
else
{
if (executable.EndsWith(".dll", StringComparison.OrdinalIgnoreCase))
{
parameters = $"\"{executable}\" {parameters}";
executable = "dotnet";
}
}
var p = new Process
{
StartInfo =
{
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
FileName = executable,
Arguments = parameters
}
};
if(environmentVariables is not null)
{
foreach (var envVar in environmentVariables)
{
p.StartInfo.Environment.Add(envVar.variable, envVar.value);
}
}
if (workingDirectory != null)
{
p.StartInfo.WorkingDirectory = workingDirectory;
}
Log.LogMessage($"Running [{p.StartInfo.WorkingDirectory}]: {p.StartInfo.FileName} {p.StartInfo.Arguments}");
var output = new StringBuilder();
var error = new StringBuilder();
var elapsed = Stopwatch.StartNew();
p.OutputDataReceived += (s, e) => { if (e.Data != null) { Log.LogMessage($"[{elapsed.Elapsed}] {e.Data}"); output.Append(e.Data); } };
p.ErrorDataReceived += (s, e) => { if (e.Data != null) { Log.LogError($"[{elapsed.Elapsed}] {e.Data}"); error.Append(e.Data); } };
if (p.Start())
{
p.BeginOutputReadLine();
p.BeginErrorReadLine();
p.WaitForExit();
var exitCore = p.ExitCode;
p.Close();
return (exitCore, output.ToString(), error.ToString());
}
else
{
throw new Exception($"Failed to start [{executable}]");
}
}
private static string GetWSLBashExecutable()
{
string executable;
var basePaths = new[] {
Path.Combine(Environment.GetEnvironmentVariable("WINDIR"), "sysnative"), // 32 bits process
Path.Combine(Environment.GetEnvironmentVariable("WINDIR"), "System32"), // 64 bits process
};
var fullPaths = basePaths.Select(p => Path.Combine(p, "bash.exe"));
executable = fullPaths.FirstOrDefault(f => File.Exists(f));
if (string.IsNullOrEmpty(executable))
{
var allPaths = string.Join(";", fullPaths);
throw new InvalidOperationException(
$"WSL is required for this build but could not be found (Searched for [{allPaths}]). " +
$"WSL use may be explicitly disabled for CI Windows builds, see more details here: https://github.com/unoplatform/Uno.Wasm.Bootstrap#special-considerations-for-ci-servers-github-actions-azure-devops");
}
return executable;
}
private string AlignPath(string path, bool escape = false)
{
var trimmedPath = path.Replace("\\\\?\\", "");
string convertPath()
{
if(IsWSLRequired && !ForceDisableWSL && Path.IsPathRooted(path))
{
var drive = trimmedPath.Substring(0, 1).ToLowerInvariant();
var remainder = trimmedPath.Substring(3).Replace("\\", "/");
var r = $"/mnt/{drive}/{remainder}";
Log.LogMessage(MessageImportance.High, $"{path} -> {r}");
return r;
}
else
{
return trimmedPath;
}
}
var output = convertPath();
if (escape)
{
output = output.Replace("\"", "\\\"");
}
return output;
}
private void TryDeployDebuggerProxy()
{
var sdkName = Path.GetFileName(MonoWasmSDKPath);
if (!string.IsNullOrEmpty(CustomDebuggerPath))
{
CustomDebuggerPath = PathHelper.FixupPath(CustomDebuggerPath!);
}
var wasmDebuggerRootPath = Path.Combine(IntermediateOutputPath, "wasm-debugger");
DirectoryCreateDirectory(wasmDebuggerRootPath);
var debuggerBinBasePaths = new[] {
Path.Combine(MonoWasmSDKPath, "dbg-proxy", TargetFramework.ToLower()), // Compatibility with previous runtime packages
Path.Combine(MonoWasmSDKPath, "dbg-proxy", "net5", "Release"), // Compatibility with previous runtime packages
Path.Combine(MonoWasmSDKPath, "dbg-proxy", "net5")
};
var proxyBasePath = debuggerBinBasePaths.First(Directory.Exists);
// Write down the debugger file path so the static file server can find it
File.WriteAllText(Path.Combine(wasmDebuggerRootPath, ".debuggerinfo"), proxyBasePath);
}
private void GenerateServerAppFeaturesInfo()
// Write down an info file so the static file server can find it
=> File.WriteAllText(Path.Combine(IntermediateOutputPath, ".unoappfeatures"), BuildRuntimeFeatures());
private void RunPackager()
{
BuildReferencedAssembliesList();
var workAotPath = Path.Combine(IntermediateOutputPath, "workAot");
if (Directory.Exists(workAotPath))
{
Directory.Delete(workAotPath, true);
}
DirectoryCreateDirectory(workAotPath);
var referencePathsParameter = string.Join(" ", _referencedAssemblies.Select(Path.GetDirectoryName).Distinct().Select(r => $"--search-path=\"{AlignPath(r)}\""));
// Timezone support
var releaseTimeZoneData = Path.Combine(BuildTaskBasePath, "..", "tools", "support", "Uno.Wasm.TimezoneData.dll");
referencePathsParameter += $" \"{AlignPath(releaseTimeZoneData)}\"";
var metadataUpdaterPath = Path.Combine(BuildTaskBasePath, "..", "tools", "support", "Uno.Wasm.MetadataUpdater.dll");
if (RuntimeDebuggerEnabled)
{
referencePathsParameter += $" \"{AlignPath(metadataUpdaterPath)}\"";
}
var debugOption = RuntimeDebuggerEnabled ? "--debug" : "";
string packagerBinPath = string.IsNullOrWhiteSpace(PackagerBinPath) ? Path.Combine(MonoWasmSDKPath, "packager.exe") : PackagerBinPath!;
var appDirParm = $"--appdir=\"{AlignPath(_workDistPath)}\" ";
// Determines if the packager needs to be used.
var useFullPackager =
!ForceDisableWSL
&& (IsRuntimeAOT()
|| GetBitcodeFilesParams().Any()
|| IsWSLRequired
|| HasAdditionalPInvokeLibraries
|| HasNativeCompile
|| GenerateAOTProfile
|| EnableLogProfiler);
var emsdkPath = useFullPackager ? ValidateEmscripten() : "";
ValidateDotnet();
LinkerSetup();
var runtimeConfigurationParam = $"--runtime-config={RuntimeConfiguration.ToLowerInvariant()}" + (EnableThreads ? "-threads" : "") + " " + (EnableSimd ? "-simd" : "");
var pthreadPoolSizeParam = $"--pthread-pool-size={PThreadsPoolSize}";
var enableICUParam = EnableNetCoreICU ? "--icu" : "";
var monovmparams = $"--framework=net5 --runtimepack-dir=\"{AlignPath(MonoWasmSDKPath)}\" {enableICUParam} {pthreadPoolSizeParam} --illinker-path=\"{_linkerBinPath}\"";
var pass1ResponseContent = $"{runtimeConfigurationParam} {appDirParm} {monovmparams} --zlib {debugOption} {referencePathsParameter} \"{AlignPath(TryConvertLongPath(Path.GetFullPath(Assembly)))}\"";
var packagerPass1ResponseFile = Path.Combine(workAotPath, "packager-pass1.rsp");
File.WriteAllText(packagerPass1ResponseFile, pass1ResponseContent);
Log.LogMessage(MessageImportance.Low, $"Response file: {pass1ResponseContent}");
//
// Run the packager to create the original layout. The AOT will optionally run over this pass.
//
var packagerResults = RunProcess(packagerBinPath, $"\"@{AlignPath(packagerPass1ResponseFile)}\"", _workDistPath);
if (packagerResults.exitCode != 0)
{
throw new Exception("Failed to generate wasm layout (More details are available in diagnostics mode or using the MSBuild /bl switch)");
}
if (useFullPackager)
{
var extraEmccFlags = (ExtraEmccFlags?.Select(f => f.ItemSpec) ?? new string[0]).ToList();
var extraLinkerFlags = GetLinkerFeatureConfiguration();
var packagerParams = new List<string>();
var mixedModeExcluded = MixedModeExcludedAssembly
?.Select(a => a.ItemSpec)
.ToArray() ?? Array.Empty<string>();
var useAotProfile = !GenerateAOTProfile && UseAotProfile;
var aotProfileFilePath = TransformAOTProfile();
var mixedModeAotAssembliesParam = mixedModeExcluded.Any() && !useAotProfile ? "--skip-aot-assemblies=" + string.Join(",", mixedModeExcluded) : "";
var aotProfile = useAotProfile ? $"\"--aot-profile={AlignPath(aotProfileFilePath!)}\"" : "";
var dynamicLibraries = GetDynamicLibrariesParams();
var dynamicLibraryParams = dynamicLibraries.Any() ? "--pinvoke-libs=" + string.Join(",", dynamicLibraries) : "";
var bitcodeFiles = GetBitcodeFilesParams();
var bitcodeFilesParams = dynamicLibraries.Any() ? string.Join(" ", bitcodeFiles.Select(f => $"\"--native-lib={AlignPath(f)}\"")) : "";
var additionalNativeCompile = HasNativeCompile
? string.Join(" ", NativeCompile.Select(f => $"\"--native-compile={AlignPath(GetFilePaths(f).fullPath)}\""))
: "";
var emccExportedRuntimeMethodsParams =
string.Join(" ", GetEmccExportedRuntimeMethods().Select(f => $"\"--emcc-exported-runtime-method={f}\""));
if (_runtimeExecutionMode != RuntimeExecutionMode.Interpreter && GenerateAOTProfile)
{
Log.LogMessage($"Forcing Interpreter mode because GenerateAOTProfile is set");
_runtimeExecutionMode = RuntimeExecutionMode.Interpreter;
}
var aotMode = _runtimeExecutionMode switch
{
RuntimeExecutionMode.FullAOT => throw new NotSupportedException("FullAOT mode is not supported by this version of the .NET Runtime"), // "--aot",
RuntimeExecutionMode.InterpreterAndAOT => $"--aot-interp {mixedModeAotAssembliesParam}",
RuntimeExecutionMode.Interpreter => "",
_ => throw new NotSupportedException($"Mode {_runtimeExecutionMode} is not supported"),
};
var dedupOption = !EnableAOTDeduplication ? "--no-dedup" : "";
var aotOptions = $"{aotMode} {dedupOption} {dynamicLibraryParams} {bitcodeFilesParams} {additionalNativeCompile} {emccExportedRuntimeMethodsParams} --emscripten-sdkdir=\"{emsdkPath}\" --builddir=\"{AlignPath(workAotPath)}\"";
if (EnableEmccProfiling)
{
extraEmccFlags.Add("--profiling");
}
packagerParams.Add("--wasm-exceptions");
if (GenerateAOTProfile)
{
var aotProfilerSupport = Path.Combine(BuildTaskBasePath, "..", "tools", "support", "Uno.Wasm.AotProfiler.dll");
referencePathsParameter += $" \"{AlignPath(aotProfilerSupport)}\"";
}
if(string.IsNullOrEmpty(AotCompilerOptions) && EnableAotGSharedVT)
{
AotCompilerOptions = $"-O=gsharedvt";
}
if (EnableLogProfiler)
{
var logProfilerSupport = Path.Combine(BuildTaskBasePath, "..", "tools", "support", "Uno.Wasm.LogProfiler.dll");
referencePathsParameter += $" \"{AlignPath(logProfilerSupport)}\"";
}
var extraEmccFlagsPararm = string.Join(" ", extraEmccFlags).Replace("\\", "\\\\");
packagerParams.Add(appDirParm);
packagerParams.Add(debugOption);
packagerParams.Add(monovmparams);
packagerParams.Add("--zlib");
packagerParams.Add($"--illinker-path=\"{_linkerBinPath}\"");
packagerParams.Add("--enable-fs ");
packagerParams.Add($"--extra-emccflags=\"{extraEmccFlagsPararm} -l idbfs.js\" ");
packagerParams.Add($"--extra-linkerflags=\"{extraLinkerFlags}\"");
packagerParams.Add(runtimeConfigurationParam);
packagerParams.Add(aotOptions);
packagerParams.Add(aotProfile);
packagerParams.Add($"--aot-compiler-opts=\"{AotCompilerOptions}\"");
packagerParams.Add(EmccLinkOptimization ? "--emcc-link-optimization" : "");
packagerParams.Add(MonoILLinker ? "--linker --link-mode=all" : "");
packagerParams.Add(referencePathsParameter);
packagerParams.Add(GenerateAOTProfile ? "--profile=aot" : "");
packagerParams.Add(EnableLogProfiler ? "--profile=log" : "");
packagerParams.Add(!string.IsNullOrEmpty(WasmTunerBinPath) ? $"\"--wasm-tuner-path={AlignPath(Path.GetFullPath(WasmTunerBinPath))}\"" : "");
packagerParams.Add($"\"--linker-optimization-level={GetEmccLinkerOptimizationLevel()}\"");
packagerParams.Add($"\"{AlignPath(Path.GetFullPath(Assembly))}\"");
if (InvariantGlobalization)
{
packagerParams.Add("--invariant-globalization");
}
var packagerResponseFile = Path.Combine(workAotPath, "packager.rsp");
File.WriteAllLines(packagerResponseFile, packagerParams.Select(p => p.Replace("\\", "/")));
Log.LogMessage(MessageImportance.Low, $"Response file: {File.ReadAllText(packagerResponseFile)}");
var environmentVariables = new List<(string, string)>();
var aotPackagerResult = RunProcess(packagerBinPath, $"@\"{AlignPath(packagerResponseFile)}\"", _workDistPath, environmentVariables.ToArray());
if (aotPackagerResult.exitCode != 0)
{
throw new Exception("Failed to generate wasm layout (More details are available in diagnostics mode or using the MSBuild /bl switch)");
}
var ninjaPath = Path.Combine(MonoWasmSDKPath, "tools", "ninja.exe");
var ninjaResult = EnableEmscriptenWindows
? RunProcess("cmd", $"/c \"{emsdkPath}\\emsdk_env.bat 2>&1 && {ninjaPath} {NinjaAdditionalParameters}\"", workAotPath)
: RunProcess("ninja", $"{NinjaAdditionalParameters}", workAotPath);
if (ninjaResult.exitCode != 0)
{
throw new Exception("Failed to run emscripten. More details are available in diagnostics logging mode or using the MSBuild /bl switch, see https://aka.platform.uno/msbuild-troubleshoot.");
}
CleanupLinkerRemovedFiles(workAotPath);
}
else
{
if (ForceDisableWSL)
{
Log.LogWarning(
"WARNING: WebAssembly emscripten packaging has been explicitly disabled through" +
" WasmShellForceDisableWSL, the resulting compilation may not run properly.");
}
//
// Run the IL Linker on the interpreter based output, as the packager does not yet do it.
//
if (
MonoILLinker
)
{
var linkerInput = Path.Combine(IntermediateOutputPath, "linker-in");
var linkerResponse = Path.Combine(linkerInput, "linker.rsp");
var linkerParams = new List<string>();
if (Directory.Exists(linkerInput))
{
Directory.Delete(linkerInput, true);
}
Directory.Move(_managedPath, linkerInput);
DirectoryCreateDirectory(_managedPath);
var assemblyPath = Path.Combine(linkerInput, Path.GetFileName(Assembly));
var linkerSearchPaths = _referencedAssemblies.Select(Path.GetDirectoryName).Distinct().Select(p => $"-d \"{p}\" ");
linkerParams.AddRange(linkerSearchPaths);
linkerParams.Add($"-d \"{_bclPath}\"");
var frameworkBindings = new List<string>
{
};
var bindingsPath = frameworkBindings.Select(a => $"-a \"{Path.Combine(linkerInput, a)}\"");
linkerParams.AddRange(bindingsPath);
linkerParams.Add($" -a \"{releaseTimeZoneData}\"");
if (RuntimeDebuggerEnabled)
{
linkerParams.Add($" -a \"{metadataUpdaterPath}\"");
}
// Opts should be aligned with the monolinker call in packager.cs, validate for linker_args as well
linkerParams.Add($"--deterministic --disable-opt unreachablebodies --used-attrs-only true ");
// Metadata linking https://github.com/mono/linker/commit/fafb6cf6a385a8c753faa174b9ab7c3600a9d494
linkerParams.Add("--keep-metadata all ");
linkerParams.Add(GetLinkerFeatureConfiguration());
linkerParams.Add($"--verbose -b true -a \"{assemblyPath}\" -d \"{_managedPath}\"");
linkerParams.Add($"-out \"{_managedPath}\"");
File.WriteAllLines(linkerResponse, linkerParams);
Log.LogMessage(MessageImportance.Low, $"Response file: {File.ReadAllText(linkerResponse)}");
var linkerResults = RunProcess(
Path.Combine(_linkerBinPath, "illink.dll"),
$"\"@{linkerResponse}\"",