Skip to content

Commit 8923c11

Browse files
dellis1972jonpryor
authored andcommitted
[Xamarin.Android.Build.Tasks] Response file support for AOT (#2062)
Fixes: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/609244 Fixes: https://developercommunity.visualstudio.com/content/problem/554407/vs2019-xamarinandroid-aot-command.html Fixes: #3407 Our AOT system has issues when a user uses non-ASCII characters and spaces on Windows. We used [`GetShortPathName()`][0] to get the old DOS 8.3 short names of paths to get around paths having spaces and unicode characters. However, short path name generation can be [disabled][1], in which case `GetShortPathName()` will return the long path name. Consequently, builds can fail when spaces appear in unexpected places: [aot-compiler stderr] Cannot open assembly 'Files': No such file or directory. Short path name generation can be disabled on a drive-by-drive basis, and our Azure DevOps build machines have short path name generation disabled on the `E:` drive used for builds. We really need to support paths with spaces and unicode characters. Rework the way we provide the `--aot` argument to the cross compilers so that it actually works in those scenarios. The first thing was how the arguments were parsed. `mono` uses the built-in system command line parser [`CommandLineToArgv()`][2] to parse arguments. Given the following `--aot` argument --aot=outfile="c:\Sandbox\repo\bin\BuildAotApplicationAndBundle AndÜmläüts_x86_True_True\obj\Release\libaot-Mono.Android.dll.so",asmwriter,mtriple=i686-linux-android,tool-prefix=C:\ProgramData\Microsoft\AndroidNDK\android-ndk-r13b\toolchains\x86-4.9\prebuilt\windows\bin\i686-linux-android-,ld-flags=C:\ProgramData\Microsoft\AndroidNDK\android-ndk-r13b\toolchains\x86-4.9\prebuilt\windows\lib\gcc\i686-linux-android\4.9.x\libgcc.a;C:\ProgramData\Microsoft\AndroidNDK\android-ndk-r13b\platforms\android-16\arch-x86\usr\lib\libc.so;C:\ProgramData\Microsoft\AndroidNDK\android-ndk-r13b\platforms\android-16\arch-x86\usr\lib\libm.so,temp-path="c:\Sandbox\repo\BuildAotApplicationAndBundle AndÜmläüts_x86_True_True\obj\Release\temp" This ends up as the following arguments, one per-line [0]: --aot=outfile="c:\Sandbox\repo\bin\BuildAotApplicationAndBundle [1]: AndÜmläüts_x86_True_True\obj\Release\libaot-Mono.Android.dll.so" [2]: ,asmwriter,mtriple=i686-linux-android,tool-prefix=C:\ProgramData\Microsoft\AndroidNDK\android-ndk-r13b\toolchains\x86-4.9\prebuilt\windows\bin\i686-linux-android-,ld-flags=C:\ProgramData\Microsoft\AndroidNDK\android-ndk-r13b\toolchains\x86-4.9\prebuilt\windows\lib\gcc\i686-linux-android\4.9.x\libgcc.a;C:\ProgramData\Microsoft\AndroidNDK\android-ndk-r13b\platforms\android-16\arch-x86\usr\lib\libc.so;C:\ProgramData\Microsoft\AndroidNDK\android-ndk-r13b\platforms\android-16\arch-x86\usr\lib\libm.so,temp-path="c:\Sandbox\repo\BuildAotApplicationAndBundle [3]: AndÜmläüts_x86_True_True\obj\Release\temp" As you can see the parameters have been split wherever there is a space. The solution to this is to double quote the ENTIRE argument and remove any quotes within the parameter list like: "--aot=outfile=c:\Sandbox\repo\bin\BuildAotApplicationAndBundle AndÜmläüts_x86_True_True\obj\Release\libaot-Mono.Android.dll.so,asmwriter,mtriple=i686-linux-android,tool-prefix=C:\ProgramData\Microsoft\AndroidNDK\android-ndk-r13b\toolchains\x86-4.9\prebuilt\windows\bin\i686-linux-android-,ld-flags=C:\ProgramData\Microsoft\AndroidNDK\android-ndk-r13b\toolchains\x86-4.9\prebuilt\windows\lib\gcc\i686-linux-android\4.9.x\libgcc.a;C:\ProgramData\Microsoft\AndroidNDK\android-ndk-r13b\platforms\android-16\arch-x86\usr\lib\libc.so;C:\ProgramData\Microsoft\AndroidNDK\android-ndk-r13b\platforms\android-16\arch-x86\usr\lib\libm.so,temp-path=c:\Sandbox\repo\BuildAotApplicationAndBundle AndÜmläüts_x86_True_True\obj\Release\temp" This allows Windows (and mac) to parse the parameters correctly as one value. There is another issue however. With the new argument line above, if the `temp-path=` path has a space in it then `mono` still has issues with that path. The good news is that we can use some domain knowledge to reduce not only the paths which need spaces but also the overall length of the argument. Because we know the cross compiler will be executed within `WorkingDirectory` we can shorten any path which is within that directory structure. `WorkingDirectory` is set to the directory of the projects `.csproj` file. So the following: E:\Some Project\My Project\obj\Release\aot\System.dll\ will become obj\Release\aot\System.dll\ This will fix the issue with the `temp-path=` argument. We end up with something like this "--aot=outfile=obj\Release\libaot-Mono.Android.dll.so,asmwriter,mtriple=i686-linux-android,tool-prefix=C:\ProgramData\Microsoft\AndroidNDK\android-ndk-r13b\toolchains\x86-4.9\prebuilt\windows\bin\i686-linux-android-,ld-flags=C:\ProgramData\Microsoft\AndroidNDK\android-ndk-r13b\toolchains\x86-4.9\prebuilt\windows\lib\gcc\i686-linux-android\4.9.x\libgcc.a;C:\ProgramData\Microsoft\AndroidNDK\android-ndk-r13b\platforms\android-16\arch-x86\usr\lib\libc.so;C:\ProgramData\Microsoft\AndroidNDK\android-ndk-r13b\platforms\android-16\arch-x86\usr\lib\libm.so,temp-path=obj\Release\temp" However we might also still start hitting the [command line length limit][3] on Windows. This is currently 8191 characters on Windows XP and later. So depending on where a user creates the project we might end up with a "too long" command line. To work around this issue we can make use of the new `mono --response=` argument. Instead of passing all the arguments to the cross compiler we can instead write them to a file and pass the path to that file as the `--response=` argument. This will reduce our command line length to be within an acceptable range unless the user creates a project in a very very deep directory structure. The final call will be like: ...\cross-arm --response="c:\Sandbox\repo\bin\BuildAotApplicationAndBundle AndÜmläüts_x86_True_True\obj\Release\Mono.Android.dll\response.txt" which works perfectly. This commit also updates the `BuildTest.BuildAotApplication()` and `BuildTest.BuildAotApplicationAndBundle()` unit tests to use paths with both spaces and non-ASCII characters to ensure we support both of those scenarios. [0]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getshortpathnamew [1]: https://support.microsoft.com/en-us/help/121007/how-to-disable-8-3-file-name-creation-on-ntfs-partitions [2]: https://docs.microsoft.com/en-us/windows/win32/api/shellapi/nf-shellapi-commandlinetoargvw [3]: https://support.microsoft.com/en-us/help/830473/command-prompt-cmd-exe-command-line-string-limitation
1 parent 97f345a commit 8923c11

File tree

4 files changed

+50
-35
lines changed

4 files changed

+50
-35
lines changed

src/Xamarin.Android.Build.Tasks/Tasks/Aapt.cs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
using System.Diagnostics;
55
using System.IO;
66
using System.Linq;
7+
using System.Text;
78
using System.Threading;
89
using System.Xml;
910
using System.Xml.Linq;
@@ -113,6 +114,7 @@ bool RunAapt (string commandLine, IList<OutputLine> output)
113114
UseShellExecute = false,
114115
RedirectStandardOutput = true,
115116
RedirectStandardError = true,
117+
StandardOutputEncoding = Encoding.UTF8,
116118
CreateNoWindow = true,
117119
WindowStyle = ProcessWindowStyle.Hidden,
118120
WorkingDirectory = WorkingDirectory,

src/Xamarin.Android.Build.Tasks/Tasks/Aapt2.cs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
using System.Threading;
88
using System.Xml;
99
using System.Xml.Linq;
10+
using System.Text;
1011
using Microsoft.Build.Utilities;
1112
using Microsoft.Build.Framework;
1213
using System.Text.RegularExpressions;
@@ -53,6 +54,7 @@ protected bool RunAapt (string commandLine, IList<OutputLine> output)
5354
UseShellExecute = false,
5455
RedirectStandardOutput = true,
5556
RedirectStandardError = true,
57+
StandardOutputEncoding = Encoding.UTF8,
5658
CreateNoWindow = true,
5759
WindowStyle = ProcessWindowStyle.Hidden,
5860
WorkingDirectory = WorkingDirectory,

src/Xamarin.Android.Build.Tasks/Tasks/Aot.cs

Lines changed: 41 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
using System.IO;
66
using System.Linq;
77
using System.Reflection;
8+
using System.Text;
89
using System.Threading;
910
using Microsoft.Build.Framework;
1011
using Microsoft.Build.Utilities;
@@ -174,14 +175,6 @@ static string GetNdkToolchainLibraryDir (string binDir, AndroidTargetArch arch)
174175
return GetNdkToolchainLibraryDir (binDir, NdkUtil.GetArchDirName (arch));
175176
}
176177

177-
static string GetShortPath (string path)
178-
{
179-
if (Environment.OSVersion.Platform != PlatformID.Win32NT)
180-
return QuoteFileName (path);
181-
var shortPath = KernelEx.GetShortPathName (Path.GetDirectoryName (path));
182-
return Path.Combine (shortPath, Path.GetFileName (path));
183-
}
184-
185178
static string QuoteFileName(string fileName)
186179
{
187180
var builder = new CommandLineBuilder();
@@ -283,12 +276,14 @@ bool RunParallelAotCompiler (List<string> nativeLibs)
283276
return;
284277
}
285278

286-
if (!RunAotCompiler (config.AssembliesPath, config.AotCompiler, config.AotOptions, config.AssemblyPath)) {
279+
if (!RunAotCompiler (config.AssembliesPath, config.AotCompiler, config.AotOptions, config.AssemblyPath, config.ResponseFile)) {
287280
LogCodedError ("XA3001", "Could not AOT the assembly: {0}", Path.GetFileName (config.AssemblyPath));
288281
Cancel ();
289282
return;
290283
}
291284

285+
File.Delete (config.ResponseFile);
286+
292287
lock (nativeLibs)
293288
nativeLibs.Add (config.OutputFile);
294289
}
@@ -362,6 +357,11 @@ IEnumerable<Config> GetAotConfigs ()
362357
if (!Directory.Exists (outdir))
363358
Directory.CreateDirectory (outdir);
364359

360+
// dont use a full path if the outdir is withing the WorkingDirectory.
361+
if (outdir.StartsWith (WorkingDirectory, StringComparison.InvariantCultureIgnoreCase)) {
362+
outdir = outdir.Replace (WorkingDirectory + Path.DirectorySeparatorChar, string.Empty);
363+
}
364+
365365
int level = 0;
366366
string toolPrefix = EnableLLVM
367367
? NdkUtil.GetNdkToolPrefix (AndroidNdkDirectory, arch, level = GetNdkApiLevel (AndroidNdkDirectory, AndroidApiLevel, arch))
@@ -389,19 +389,19 @@ IEnumerable<Config> GetAotConfigs ()
389389

390390
var libs = new List<string>();
391391
if (NdkUtil.UsingClangNDK) {
392-
libs.Add ($"-L{GetShortPath (toolchainLibDir)}");
393-
libs.Add ($"-L{GetShortPath (androidLibPath)}");
392+
libs.Add ($"-L{toolchainLibDir}");
393+
libs.Add ($"-L{androidLibPath}");
394394

395395
if (arch == AndroidTargetArch.Arm) {
396396
// Needed for -lunwind to work
397397
string compilerLibDir = Path.Combine (toolchainPath, "..", "sysroot", "usr", "lib", NdkUtil.GetArchDirName (arch));
398-
libs.Add ($"-L{GetShortPath (compilerLibDir)}");
398+
libs.Add ($"-L{compilerLibDir}");
399399
}
400400
}
401401

402-
libs.Add (GetShortPath (Path.Combine (toolchainLibDir, "libgcc.a")));
403-
libs.Add (GetShortPath (Path.Combine (androidLibPath, "libc.so")));
404-
libs.Add (GetShortPath (Path.Combine (androidLibPath, "libm.so")));
402+
libs.Add (Path.Combine (toolchainLibDir, "libgcc.a"));
403+
libs.Add (Path.Combine (androidLibPath, "libc.so"));
404+
libs.Add (Path.Combine (androidLibPath, "libm.so"));
405405

406406
ldFlags = string.Join(";", libs);
407407
}
@@ -423,25 +423,28 @@ IEnumerable<Config> GetAotConfigs ()
423423
aotOptions.Add ("profile-only");
424424
foreach (var p in Profiles) {
425425
var fp = Path.GetFullPath (p.ItemSpec);
426-
aotOptions.Add ($"profile={GetShortPath (fp)}");
426+
aotOptions.Add ($"profile={fp}");
427427
}
428428
}
429429
if (!string.IsNullOrEmpty (AotAdditionalArguments))
430430
aotOptions.Add (AotAdditionalArguments);
431431
if (sequencePointsMode == SequencePointsMode.Offline)
432-
aotOptions.Add ("msym-dir=" + GetShortPath (outdir));
432+
aotOptions.Add ($"msym-dir={outdir}");
433433
if (AotMode != AotMode.Normal)
434434
aotOptions.Add (AotMode.ToString ().ToLowerInvariant ());
435435

436-
aotOptions.Add ("outfile=" + GetShortPath (outputFile));
436+
aotOptions.Add ($"outfile={outputFile}");
437437
aotOptions.Add ("asmwriter");
438-
aotOptions.Add ("mtriple=" + mtriple);
439-
aotOptions.Add ("tool-prefix=" + GetShortPath (toolPrefix));
440-
aotOptions.Add ("ld-flags=" + ldFlags);
441-
aotOptions.Add ("llvm-path=" + GetShortPath (sdkBinDirectory));
442-
aotOptions.Add ("temp-path=" + GetShortPath (tempDir));
438+
aotOptions.Add ($"mtriple={mtriple}");
439+
aotOptions.Add ($"tool-prefix={toolPrefix}");
440+
aotOptions.Add ($"ld-flags={ldFlags}");
441+
aotOptions.Add ($"llvm-path={sdkBinDirectory}");
442+
aotOptions.Add ($"temp-path={tempDir}");
443443

444-
string aotOptionsStr = (EnableLLVM ? "--llvm " : "") + "--aot=" + string.Join (",", aotOptions);
444+
// we need to quote the entire --aot arguments here to make sure it is parsed
445+
// on windows as one argument. Otherwise it will be split up into multiple
446+
// values, which wont work.
447+
string aotOptionsStr = (EnableLLVM ? "--llvm " : "") + $"\"--aot={string.Join (",", aotOptions)}\"";
445448

446449
if (!string.IsNullOrEmpty (ExtraAotOptions)) {
447450
aotOptionsStr += (aotOptions.Count > 0 ? "," : "") + ExtraAotOptions;
@@ -461,23 +464,29 @@ IEnumerable<Config> GetAotConfigs ()
461464
}
462465

463466
var assembliesPath = Path.GetFullPath (Path.GetDirectoryName (resolvedPath));
464-
var assemblyPath = QuoteFileName (Path.GetFullPath (resolvedPath));
467+
var assemblyPath = Path.GetFullPath (resolvedPath);
465468

466-
yield return new Config (assembliesPath, QuoteFileName (aotCompiler), aotOptionsStr, assemblyPath, outputFile);
469+
yield return new Config (assembliesPath, aotCompiler, aotOptionsStr, assemblyPath, outputFile, Path.Combine (tempDir, "response.txt"));
467470
}
468471
}
469472
}
470473

471-
bool RunAotCompiler (string assembliesPath, string aotCompiler, string aotOptions, string assembly)
474+
bool RunAotCompiler (string assembliesPath, string aotCompiler, string aotOptions, string assembly, string responseFile)
472475
{
473476
var stdout_completed = new ManualResetEvent (false);
474477
var stderr_completed = new ManualResetEvent (false);
478+
479+
using (var sw = new StreamWriter (responseFile, append: false, encoding: new UTF8Encoding (encoderShouldEmitUTF8Identifier: false))) {
480+
sw.WriteLine (aotOptions + " " + QuoteFileName (assembly));
481+
}
482+
475483
var psi = new ProcessStartInfo () {
476-
FileName = aotCompiler,
477-
Arguments = aotOptions + " " + assembly,
484+
FileName = QuoteFileName (aotCompiler),
485+
Arguments = $"--response={QuoteFileName (responseFile)}",
478486
UseShellExecute = false,
479487
RedirectStandardOutput = true,
480488
RedirectStandardError = true,
489+
StandardOutputEncoding = Encoding.UTF8,
481490
CreateNoWindow=true,
482491
WindowStyle=ProcessWindowStyle.Hidden,
483492
WorkingDirectory = WorkingDirectory,
@@ -537,16 +546,18 @@ struct Config {
537546
public string AotOptions { get; }
538547
public string AssemblyPath { get; }
539548
public string OutputFile { get; }
549+
public string ResponseFile { get; }
540550

541551
public bool Valid { get; private set; }
542552

543-
public Config (string assembliesPath, string aotCompiler, string aotOptions, string assemblyPath, string outputFile)
553+
public Config (string assembliesPath, string aotCompiler, string aotOptions, string assemblyPath, string outputFile, string responseFile)
544554
{
545555
AssembliesPath = assembliesPath;
546556
AotCompiler = aotCompiler;
547557
AotOptions = aotOptions;
548558
AssemblyPath = assemblyPath;
549559
OutputFile = outputFile;
560+
ResponseFile = responseFile;
550561
Valid = true;
551562
}
552563

src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/BuildTest.cs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -732,9 +732,9 @@ public void BuildMkBundleApplicationReleaseAllAbi ()
732732
[Test]
733733
[TestCaseSource (nameof (AotChecks))]
734734
[Category ("Minor")]
735-
public void BuildAotApplication (string supportedAbis, bool enableLLVM, bool expectedResult)
735+
public void BuildAotApplicationAndÜmläüts (string supportedAbis, bool enableLLVM, bool expectedResult)
736736
{
737-
var path = Path.Combine ("temp", string.Format ("BuildAotApplication_{0}_{1}_{2}", supportedAbis, enableLLVM, expectedResult));
737+
var path = Path.Combine ("temp", string.Format ("BuildAotApplication AndÜmläüts_{0}_{1}_{2}", supportedAbis, enableLLVM, expectedResult));
738738
var proj = new XamarinAndroidApplicationProject () {
739739
IsRelease = true,
740740
BundleAssemblies = false,
@@ -768,7 +768,7 @@ public void BuildAotApplication (string supportedAbis, bool enableLLVM, bool exp
768768
// LLVM passes a direct path to libc.so, and we need to use the libc.so
769769
// which corresponds to the *minimum* SDK version specified in AndroidManifest.xml
770770
// Since we overrode minSdkVersion=16, that means we should use libc.so from android-16.
771-
var rightLibc = new Regex (@"^\s*\[AOT\].*cross-.*--llvm.*,ld-flags=.*android-16.arch-.*.usr.lib.libc\.so", RegexOptions.Multiline);
771+
var rightLibc = new Regex (@"\s*\[aot-compiler stdout].*android-16.arch-.*.usr.lib.libc\.so", RegexOptions.Multiline);
772772
var m = rightLibc.Match (string.Join ("\n",b.LastBuildOutput));
773773
Assert.IsTrue (m.Success, "AOT+LLVM should use libc.so from minSdkVersion!");
774774
}
@@ -803,9 +803,9 @@ public void BuildAotApplication (string supportedAbis, bool enableLLVM, bool exp
803803
[Test]
804804
[TestCaseSource (nameof (AotChecks))]
805805
[Category ("Minor")]
806-
public void BuildAotApplicationAndBundle (string supportedAbis, bool enableLLVM, bool expectedResult)
806+
public void BuildAotApplicationAndBundleAndÜmläüts (string supportedAbis, bool enableLLVM, bool expectedResult)
807807
{
808-
var path = Path.Combine ("temp", string.Format ("BuildAotApplicationAndBundle_{0}_{1}_{2}", supportedAbis, enableLLVM, expectedResult));
808+
var path = Path.Combine ("temp", string.Format ("BuildAotApplicationAndBundle AndÜmläüts_{0}_{1}_{2}", supportedAbis, enableLLVM, expectedResult));
809809
var proj = new XamarinAndroidApplicationProject () {
810810
IsRelease = true,
811811
BundleAssemblies = true,

0 commit comments

Comments
 (0)