[Xamarin.Android.Build.Tasks] libxamarin-app.so generation (#2718)

Xamarin.Android needs a lot of information in the runtime in order to
do its tasks.  Among this is are two bits of information that are
used during startup: type mappings (java-to-managed `.jm` files and
managed-to-java `.mj` files) and environment settings (variables and
system properties).  Historically, Xamarin.Android used these bits of
data (generated on the application build time) by writing them into
separate files (`*.mj`, `*.jm`, `environment`), storing them in the
`.apk`, and reading these files dynamically during startup.
an `environment`

However, none of this data is *actually* dynamic - it's known
beforehand and could be stored as static data right in the `.apk`.
The problem with this idea was that we had no way to put that
information into the application native bits at build time: it would
require the presence of a compiler (or native assembler) as well as
the native linker for the target platforms.  This would have required
having the Android NDK installed, which is a hefty requirement.

That said, the Android SDK currently ships a native linker within its
`build-tools` package, and we can also bundle within our packages the
`gas` native assembler for all the architectures we support.  This
allows us to generate simple native assembler code, compile it
and link into a shared library ***when packaging*** the application.

The way it works is that during the Xamarin.Android *SDK* build we
build a "stub" `libxamarin-app.so` library which the Xamarin.Android
`libmono-android.*.so` neé `libmonodroid.so` runtime libraries are
linked against.  The stub `libxamarin-app.so` library is *not*
distributed with the Xamarin.Android SDK; instead, the "real" version
is generated at build/packaging time and packaged with the runtime
within the `.apk`.  Since the "real" version is ABI-compatible with
the stub version, the dynamic loader doesn't care and loads and
resolves symbols just fine.

This allows us to dispense with memory allocation, loading
(potentially large) files from the `.apk` (lots of I/O, slow),
parsing text files to set environment variables (additional memory
allocation), etc.  All of the data is loaded for us by Android and we
simply access global variables from the `libxamarin-app.so` library.

The process, however, can be time consuming (sort of...) and in order
to allow fast deployment to work as quickly as possible, the debug
(and desktop/host - for the benefit of the UI Designer) builds of the
runtime also contain code to load both type maps and environment
variables from files stored inside one of the override directories.

The changes provide a speed-up of ~10ms, reducing the startup time
down to around 233ms for a release build of a Xamarin.Forms app on a
Pixel 3 XL.
This commit is contained in:
Marek Habersack 2019-04-17 20:31:34 +02:00 коммит произвёл Jonathan Pryor
Родитель 84c97da15b
Коммит decfbccf3e
50 изменённых файлов: 4127 добавлений и 302 удалений

Просмотреть файл

@ -193,7 +193,7 @@ define CREATE_THIRD_PARTY_NOTICES_RULE
prepare-tpn:: $(1)
$(1) $(topdir)/$(1): build-tools/ThirdPartyNotices/ThirdPartyNotices.csproj \
$(wildcard external/*.tpnitems src/*.tpnitems) \
$(wildcard external/*.tpnitems src/*.tpnitems build-tools/*.tpnitems) \
$(TPN_LICENSE_FILES)
$(call CREATE_THIRD_PARTY_NOTICES,$(1),$(2),$(3),$(4))
endef # CREATE_THIRD_PARTY_NOTICES_RULE

Просмотреть файл

@ -21,6 +21,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "api-merge", "build-tools\ap
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "remap-assembly-ref", "build-tools\remap-assembly-ref\remap-assembly-ref.csproj", "{C876DA71-8573-4CEF-9149-716D72455ED4}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "fetch-windows-assemblers", "build-tools\fetch-windows-assemblers\fetch-windows-assemblers.csproj", "{09518DF2-C7B1-4CDB-849A-9F91F4BEA925}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Core", "Core", "{04E3E11E-B47D-4599-8AFC-50515A95E715}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Java.Interop", "external\Java.Interop\src\Java.Interop\Java.Interop.csproj", "{94BD81F7-B06F-4295-9636-F8A3B6BDC762}"
@ -197,6 +199,10 @@ Global
{C876DA71-8573-4CEF-9149-716D72455ED4}.Debug|AnyCPU.Build.0 = Debug|Any CPU
{C876DA71-8573-4CEF-9149-716D72455ED4}.Release|AnyCPU.ActiveCfg = Release|Any CPU
{C876DA71-8573-4CEF-9149-716D72455ED4}.Release|AnyCPU.Build.0 = Release|Any CPU
{09518DF2-C7B1-4CDB-849A-9F91F4BEA925}.Debug|AnyCPU.ActiveCfg = Debug|Any CPU
{09518DF2-C7B1-4CDB-849A-9F91F4BEA925}.Debug|AnyCPU.Build.0 = Debug|Any CPU
{09518DF2-C7B1-4CDB-849A-9F91F4BEA925}.Release|AnyCPU.ActiveCfg = Release|Any CPU
{09518DF2-C7B1-4CDB-849A-9F91F4BEA925}.Release|AnyCPU.Build.0 = Release|Any CPU
{94BD81F7-B06F-4295-9636-F8A3B6BDC762}.Debug|AnyCPU.ActiveCfg = Debug|Any CPU
{94BD81F7-B06F-4295-9636-F8A3B6BDC762}.Debug|AnyCPU.Build.0 = Debug|Any CPU
{94BD81F7-B06F-4295-9636-F8A3B6BDC762}.Release|AnyCPU.ActiveCfg = Release|Any CPU

Просмотреть файл

@ -105,7 +105,7 @@
<ReplaceFileContents
SourceFile="..\scripts\XABuildConfig.cs.in"
DestinationFile="..\..\bin\Build$(Configuration)\XABuildConfig.cs"
Replacements="@NDK_MINIMUM_API_AVAILABLE@=$(_NDKMinimumApiAvailable);@NDK_RELEASE@=$(AndroidNdkVersion);@NDK_REVISION@=$(_NDKRevision);@NDK_VERSION_MAJOR@=$(_NDKVersionMajor);@NDK_VERSION_MINOR@=$(_NDKVersionMinor);@NDK_VERSION_MICRO@=$(_NDKVersionMicro);@NDK_ARMEABI_V7_API@=$(AndroidNdkApiLevel_ArmV7a);@NDK_ARM64_V8A_API@=$(AndroidNdkApiLevel_ArmV8a);@NDK_X86_API@=$(AndroidNdkApiLevel_X86);@NDK_X86_64_API@=$(AndroidNdkApiLevel_X86_64)">
Replacements="@NDK_MINIMUM_API_AVAILABLE@=$(_NDKMinimumApiAvailable);@NDK_RELEASE@=$(AndroidNdkVersion);@NDK_REVISION@=$(_NDKRevision);@NDK_VERSION_MAJOR@=$(_NDKVersionMajor);@NDK_VERSION_MINOR@=$(_NDKVersionMinor);@NDK_VERSION_MICRO@=$(_NDKVersionMicro);@NDK_ARMEABI_V7_API@=$(AndroidNdkApiLevel_ArmV7a);@NDK_ARM64_V8A_API@=$(AndroidNdkApiLevel_ArmV8a);@NDK_X86_API@=$(AndroidNdkApiLevel_X86);@NDK_X86_64_API@=$(AndroidNdkApiLevel_X86_64);@XA_SUPPORTED_ABIS@=$(AndroidSupportedTargetJitAbis.Replace(':',';'))">
</ReplaceFileContents>
</Target>
</Project>

Просмотреть файл

@ -0,0 +1,35 @@
<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Condition=" '$(TpnIncludeExternalDependencies)' == 'True' ">
<!-- The CRC32 code comes from:
https://github.com/force-net/Crc32.NET/blob/fbc1061b0cb53df2322d5aed33167a2e6335970b/Crc32.NET/SafeProxy.cs
License: MIT (https://github.com/force-net/Crc32.NET/blob/fbc1061b0cb53df2322d5aed33167a2e6335970b/LICENSE)
-->
<ThirdPartyNotice Include="force-net/crc32.net">
<LicenseText>
The MIT License (MIT)
Copyright (c) 2016 force
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
</LicenseText>
<SourceUrl>https://github.com/force-net/Crc32.NET</SourceUrl>
</ThirdPartyNotice>
</ItemGroup>
</Project>

Просмотреть файл

@ -0,0 +1,738 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
//
// Taken from:
// https://github.com/force-net/Crc32.NET/blob/fbc1061b0cb53df2322d5aed33167a2e6335970b/Crc32.NET/SafeProxy.cs
//
// License: MIT
// https://github.com/force-net/Crc32.NET/blob/fbc1061b0cb53df2322d5aed33167a2e6335970b/LICENSE
//
class CRC32
{
const uint Poly = 0xedb88320u;
readonly uint[] _table = new uint[16 * 256];
internal CRC32 ()
{
Init (Poly);
}
protected void Init (uint poly)
{
var table = _table;
for (uint i = 0; i < 256; i++) {
uint res = i;
for (int t = 0; t < 16; t++) {
for (int k = 0; k < 8; k++) res = (res & 1) == 1 ? poly ^ (res >> 1) : (res >> 1);
table[(t * 256) + i] = res;
}
}
}
public uint Append (uint crc, byte[] input, int offset, int length)
{
uint crcLocal = uint.MaxValue ^ crc;
uint[] table = _table;
while (length >= 16) {
var a = table[(3 * 256) + input[offset + 12]]
^ table[(2 * 256) + input[offset + 13]]
^ table[(1 * 256) + input[offset + 14]]
^ table[(0 * 256) + input[offset + 15]];
var b = table[(7 * 256) + input[offset + 8]]
^ table[(6 * 256) + input[offset + 9]]
^ table[(5 * 256) + input[offset + 10]]
^ table[(4 * 256) + input[offset + 11]];
var c = table[(11 * 256) + input[offset + 4]]
^ table[(10 * 256) + input[offset + 5]]
^ table[(9 * 256) + input[offset + 6]]
^ table[(8 * 256) + input[offset + 7]];
var d = table[(15 * 256) + ((byte)crcLocal ^ input[offset])]
^ table[(14 * 256) + ((byte)(crcLocal >> 8) ^ input[offset + 1])]
^ table[(13 * 256) + ((byte)(crcLocal >> 16) ^ input[offset + 2])]
^ table[(12 * 256) + ((crcLocal >> 24) ^ input[offset + 3])];
crcLocal = d ^ c ^ b ^ a;
offset += 16;
length -= 16;
}
while (--length >= 0)
crcLocal = table[(byte)(crcLocal ^ input[offset++])] ^ crcLocal >> 8;
return crcLocal ^ uint.MaxValue;
}
}
class app
{
const int EndFileChunkSize = 65535 + 22; // Maximum comment size + EOCD size
const uint EOCDSignature = 0x06054b50;
const uint CDHeaderSignature = 0x02014b50;
const uint LFHeaderSignature = 0x04034b50;
class EOCD
{
public uint Signature; // Signature (0x06054b50)
public ushort DiskNumber; // number of this disk
public ushort CDStartDisk; // number of the disk with the start of the central directory
public ushort TotalEntriesThisDisk; // total number of entries in the central directory on this disk
public ushort TotalEntries; // total number of entries in the central directory
public uint CDSize; // size of the central directory
public uint CDOffset; // offset of start of central directory with respect to the starting disk number
public ushort CommentLength; // .ZIP file comment length
};
class CDHeader
{
public uint Signature; // 0x02014b50
public ushort VersionMadeBy;
public ushort VersionNeededToExtract;
public ushort GeneralPurposeBitFlag;
public ushort CompressionMethod;
public ushort LastModFileTime;
public ushort LastModFileDate;
public uint CRC32;
public uint CompressedSize;
public uint UncompressedSize;
public ushort FileNameLength;
public ushort ExtraFieldLength;
public ushort FileCommentLength;
public ushort DiskNumberStart;
public ushort InternalFileAttributes;
public uint ExternalFileAttributes;
public uint RelativeOffsetOfLocalHeader;
public string FileName;
public byte[] ExtraField;
public string FileComment;
};
class LFHeader
{
public uint Signature; // 0x04034b50
public ushort VersionNeededToExtract;
public ushort GeneralPurposeBitFlag;
public ushort CompressionMethod;
public ushort LastModFileTime;
public ushort LastModFileDate;
public uint CRC32;
public uint CompressedSize;
public uint UncompressedSize;
public ushort FileNameLength;
public ushort ExtraFieldLength;
public string FileName;
public byte[] ExtraField;
};
static int Main (string[] args)
{
if (args.Length < 3) {
Console.WriteLine ("Usage: fetch-windows-assemblers NDK_VERSION DESTINATION_DIRECTORY NDK_URL");
return 1;
}
Task<bool> fetcher = FetchFiles (
args [0],
args [1],
new Uri (args [2])
);
fetcher.Wait ();
return fetcher.Result ? 0 : 1;
}
static async Task<bool> FetchFiles (string ndkVersion, string destinationDirectory, Uri url)
{
var neededFiles = new HashSet<string> (StringComparer.OrdinalIgnoreCase) {
$"android-ndk-r{ndkVersion}/toolchains/llvm/prebuilt/windows-x86_64/bin/i686-linux-android-as.exe",
$"android-ndk-r{ndkVersion}/toolchains/llvm/prebuilt/windows-x86_64/bin/arm-linux-androideabi-as.exe",
$"android-ndk-r{ndkVersion}/toolchains/llvm/prebuilt/windows-x86_64/bin/x86_64-linux-android-as.exe",
$"android-ndk-r{ndkVersion}/toolchains/llvm/prebuilt/windows-x86_64/bin/aarch64-linux-android-as.exe",
};
using (var httpClient = new HttpClient ()) {
bool success;
long size;
Console.WriteLine ($"Retrieving {url}");
(success, size) = await GetFileSize (httpClient, url);
if (!success)
return false;
Console.WriteLine ($" File size: {size}");
EOCD eocd;
(success, eocd) = await GetEOCD (httpClient, url, size);
if (!success) {
Console.Error.WriteLine ("Failed to find the End of Central Directory record");
return false;
}
if (eocd.DiskNumber != 0)
throw new NotSupportedException ("Multi-disk ZIP archives not supported");
Console.WriteLine ($" Central Directory offset: {eocd.CDOffset} (0x{eocd.CDOffset:x})");
Console.WriteLine ($" Central Directory size: {eocd.CDSize} (0x{eocd.CDSize})");
Console.WriteLine ($" Total Entries: {eocd.TotalEntries}");
Stream cd;
(success, cd) = await ReadCD (httpClient, url, eocd.CDOffset, eocd.CDSize, size);
if (!success) {
Console.Error.WriteLine ("Failed to read the Central Directory");
return false;
}
Console.WriteLine ();
Console.WriteLine ("Entries:");
if (!await ProcessEntries (httpClient, url, eocd, cd, neededFiles, destinationDirectory))
return false;
}
return true;
}
static async Task<bool> ProcessEntries (HttpClient httpClient, Uri url, EOCD eocd, Stream centralDirectory, HashSet<string> neededFiles, string destinationDirectory)
{
long foundEntries = 0;
using (var br = new BinaryReader (centralDirectory)) {
long nread = 0;
long nentries = 1;
while (nread < centralDirectory.Length && nentries <= eocd.TotalEntries) {
(bool success, CDHeader cdh) = ReadCDHeader (br, centralDirectory.Length, ref nread);
nentries++;
if (!success) {
Console.Error.WriteLine ($"Failed to read a Central Directory file header for entry {nentries}");
return false;
}
if (!neededFiles.Contains (cdh.FileName))
continue;
if (!await ReadEntry (httpClient, url, cdh, br, destinationDirectory))
return false;
foundEntries++;
}
}
if (foundEntries < neededFiles.Count) {
Console.WriteLine ($"Could not find all required binaries. Found {foundEntries} out of {neededFiles.Count}");
return false;
}
return true;
}
static async Task<bool> ReadEntry (HttpClient httpClient, Uri url, CDHeader cdh, BinaryReader br, string destinationDirectory)
{
string compressedFilePath = Path.Combine (destinationDirectory, $"{Path.GetFileName (cdh.FileName)}.deflated");
Console.WriteLine ($" {cdh.FileName} (offset: {cdh.RelativeOffsetOfLocalHeader})");
(bool success, Stream contentStream) = await ReadFileData (httpClient, url, cdh);
if (!success) {
Console.Error.WriteLine ("Failed to read file data");
return false;
}
using (var destFile = new BinaryWriter (File.OpenWrite (compressedFilePath))) {
using (var fbr = new BinaryReader (contentStream)) {
if (!await DownloadAndExtract (fbr, contentStream, destFile, compressedFilePath))
return CleanupAndReturn (false);
}
}
return CleanupAndReturn (true);
bool CleanupAndReturn (bool retval)
{
if (File.Exists (compressedFilePath))
File.Delete (compressedFilePath);
return retval;
}
}
static async Task<bool> DownloadAndExtract (BinaryReader fbr, Stream contentStream, BinaryWriter destFile, string destFileName)
{
long fread = 0;
(bool success, LFHeader lfh) = ReadLFHeader (fbr, contentStream.Length, ref fread);
if (!success) {
Console.Error.WriteLine ("Failed to read local file header");
return false;
}
uint dread = 0;
var buffer = new byte [8192];
while (fread <= contentStream.Length && dread < lfh.CompressedSize) {
uint toRead;
if (lfh.CompressedSize - dread < buffer.Length)
toRead = lfh.CompressedSize - dread;
else
toRead = (uint)buffer.Length;
int bread = await contentStream.ReadAsync (buffer, 0, (int)toRead);
if (bread == 0)
break;
destFile.Write (buffer, 0, bread);
fread += bread;
dread += (uint)bread;
}
destFile.Flush ();
destFile.Close ();
destFile.Dispose ();
Extract (destFileName, lfh.CRC32);
if (dread != lfh.CompressedSize)
Console.Error.WriteLine ($" Invalid data size: expected {lfh.CompressedSize} bytes, read {dread} bytes");
return true;
}
static void Extract (string compressedFilePath, uint crc32FromHeader)
{
string outputFile = Path.GetFileNameWithoutExtension (compressedFilePath);
using (var fs = File.OpenRead (compressedFilePath)) {
using (var dfs = File.OpenWrite (outputFile)) {
Extract (fs, dfs, crc32FromHeader);
}
}
}
static void Extract (Stream src, Stream dest, uint crc32FromHeader)
{
uint fileCRC = 0;
int fread = 0;
var crc32 = new CRC32 ();
var buffer = new byte [8192];
using (var iis = new DeflateStream (src, CompressionMode.Decompress)) {
while (true) {
fread = iis.Read(buffer, 0, buffer.Length);
if (fread <= 0)
break;
fileCRC = crc32.Append (fileCRC, buffer, 0, fread);
dest.Write (buffer, 0, fread);
}
dest.Flush ();
}
if (fileCRC != crc32FromHeader)
Console.Error.WriteLine ($" Invalid CRC32: expected 0x{crc32FromHeader:x}, got 0x{fileCRC:x}");
}
static async Task<(bool success, Stream data)> ReadFileData (HttpClient httpClient, Uri url, CDHeader cdh)
{
long fileOffset = cdh.RelativeOffsetOfLocalHeader;
long dataSize =
cdh.CompressedSize +
30 + // local file header size, the static portion
cdh.FileName.Length + // They're the same in both haders
cdh.ExtraFieldLength + // This may differ between headers...
16384; // ...so we add some extra padding
var req = new HttpRequestMessage (HttpMethod.Get, url);
req.Headers.ConnectionClose = true;
req.Headers.Range = new RangeHeaderValue (fileOffset, fileOffset + dataSize);
HttpResponseMessage resp = await httpClient.SendAsync (req).ConfigureAwait (false);
if (!resp.IsSuccessStatusCode) {
Console.Error.WriteLine ($"Failed to read file data: HTTP error {resp.StatusCode}");
return (false, null);
}
Stream s = await resp.Content.ReadAsStreamAsync ().ConfigureAwait (false);
if (s.Length < dataSize) {
Console.Error.WriteLine ($"Failed to read file data: invalid data length ({s.Length} < {dataSize})");
s.Dispose ();
return (false, null);
}
return (true, s);
}
static (bool success, LFHeader lfh) ReadLFHeader (BinaryReader cdr, long dataLength, ref long nread)
{
var lfh = new LFHeader ();
bool worked;
string whatFailed = null;
lfh.Signature = ReadUInt (cdr, dataLength, ref nread, out worked);
if (!worked || lfh.Signature != LFHeaderSignature) {
whatFailed = $"Signature ({lfh.Signature:x} != {LFHeaderSignature:x})";
goto failed;
}
lfh.VersionNeededToExtract = ReadUShort (cdr, dataLength, ref nread, out worked);
if (!worked) {
whatFailed = "VersionNeededToExtract";
goto failed;
}
lfh.GeneralPurposeBitFlag = ReadUShort (cdr, dataLength, ref nread, out worked);
if (!worked) {
whatFailed = "GeneralPurposeBitFlag";
goto failed;
}
lfh.CompressionMethod = ReadUShort (cdr, dataLength, ref nread, out worked);
if (!worked) {
whatFailed = "CompressionMethod";
goto failed;
}
lfh.LastModFileTime = ReadUShort (cdr, dataLength, ref nread, out worked);
if (!worked) {
whatFailed = "LastModFileTime";
goto failed;
}
lfh.LastModFileDate = ReadUShort (cdr, dataLength, ref nread, out worked);
if (!worked) {
whatFailed = "LastModFileDate";
goto failed;
}
lfh.CRC32 = ReadUInt (cdr, dataLength, ref nread, out worked);
if (!worked) {
whatFailed = "CRC32";
goto failed;
}
lfh.CompressedSize = ReadUInt (cdr, dataLength, ref nread, out worked);
if (!worked) {
whatFailed = "CompressedSize";
goto failed;
}
lfh.UncompressedSize = ReadUInt (cdr, dataLength, ref nread, out worked);
if (!worked) {
whatFailed = "UncompressedSize";
goto failed;
}
lfh.FileNameLength = ReadUShort (cdr, dataLength, ref nread, out worked);
if (!worked) {
whatFailed = "FileNameLength";
goto failed;
}
lfh.ExtraFieldLength = ReadUShort (cdr, dataLength, ref nread, out worked);
if (!worked) {
whatFailed = "ExtraFieldLength";
goto failed;
}
byte[] bytes = ReadBytes (cdr, lfh.FileNameLength, dataLength, ref nread, out worked);
if (!worked) {
whatFailed = "FileName (bytes)";
goto failed;
}
lfh.FileName = Encoding.ASCII.GetString (bytes);
if (!worked) {
whatFailed = "FileName (ASCII decode)";
goto failed;
}
if (lfh.ExtraFieldLength > 0) {
lfh.ExtraField = ReadBytes (cdr, lfh.ExtraFieldLength, dataLength, ref nread, out worked);
if (!worked) {
whatFailed = "ExtraField";
goto failed;
}
}
return (true, lfh);
failed:
if (!String.IsNullOrEmpty (whatFailed))
Console.Error.WriteLine ($"Failed to read a local file header field: {whatFailed}");
return (false, null);
}
static (bool success, CDHeader cdh) ReadCDHeader (BinaryReader cdr, long dataLength, ref long nread)
{
var cdh = new CDHeader ();
bool worked;
string whatFailed = null;
cdh.Signature = ReadUInt (cdr, dataLength, ref nread, out worked);
if (!worked || cdh.Signature != CDHeaderSignature) {
whatFailed = "Signature ({cdh.Signature:x} != {CDHeaderSignature:x})";
goto failed;
}
cdh.VersionMadeBy = ReadUShort (cdr, dataLength, ref nread, out worked);
if (!worked) {
whatFailed = "VersionMadeBy";
goto failed;
}
cdh.VersionNeededToExtract = ReadUShort (cdr, dataLength, ref nread, out worked);
if (!worked) {
whatFailed = "VersionNeededToExtract";
goto failed;
}
cdh.GeneralPurposeBitFlag = ReadUShort (cdr, dataLength, ref nread, out worked);
if (!worked) {
whatFailed = "GeneralPurposeBitFlag";
goto failed;
}
cdh.CompressionMethod = ReadUShort (cdr, dataLength, ref nread, out worked);
if (!worked) {
whatFailed = "CompressionMethod";
goto failed;
}
cdh.LastModFileTime = ReadUShort (cdr, dataLength, ref nread, out worked);
if (!worked) {
whatFailed = "LastModFileTime";
goto failed;
}
cdh.LastModFileDate = ReadUShort (cdr, dataLength, ref nread, out worked);
if (!worked) {
whatFailed = "LastModFileDate";
goto failed;
}
cdh.CRC32 = ReadUInt (cdr, dataLength, ref nread, out worked);
if (!worked) {
whatFailed = "CRC32";
goto failed;
}
cdh.CompressedSize = ReadUInt (cdr, dataLength, ref nread, out worked);
if (!worked) {
whatFailed = "CompressedSize";
goto failed;
}
cdh.UncompressedSize = ReadUInt (cdr, dataLength, ref nread, out worked);
if (!worked) {
whatFailed = "UncompressedSize";
goto failed;
}
cdh.FileNameLength = ReadUShort (cdr, dataLength, ref nread, out worked);
if (!worked) {
whatFailed = "FileNameLength";
goto failed;
}
cdh.ExtraFieldLength = ReadUShort (cdr, dataLength, ref nread, out worked);
if (!worked) {
whatFailed = "ExtraFieldLength";
goto failed;
}
cdh.FileCommentLength = ReadUShort (cdr, dataLength, ref nread, out worked);
if (!worked) {
whatFailed = "FileCommentLength";
goto failed;
}
cdh.DiskNumberStart = ReadUShort (cdr, dataLength, ref nread, out worked);
if (!worked) {
whatFailed = "DiskNumberStart";
goto failed;
}
cdh.InternalFileAttributes = ReadUShort (cdr, dataLength, ref nread, out worked);
if (!worked) {
whatFailed = "InternalFileAttributes";
goto failed;
}
cdh.ExternalFileAttributes = ReadUInt (cdr, dataLength, ref nread, out worked);
if (!worked) {
whatFailed = "ExternalFileAttributes";
goto failed;
}
cdh.RelativeOffsetOfLocalHeader = ReadUInt (cdr, dataLength, ref nread, out worked);
if (!worked) {
whatFailed = "RelativeOffsetOfLocalHeader";
goto failed;
}
byte[] bytes = ReadBytes (cdr, cdh.FileNameLength, dataLength, ref nread, out worked);
if (!worked) {
whatFailed = "FileName (bytes)";
goto failed;
}
cdh.FileName = Encoding.ASCII.GetString (bytes);
if (!worked) {
whatFailed = "FileName (ASCII decode)";
goto failed;
}
if (cdh.ExtraFieldLength > 0) {
cdh.ExtraField = ReadBytes (cdr, cdh.ExtraFieldLength, dataLength, ref nread, out worked);
if (!worked) {
whatFailed = "ExtraField";
goto failed;
}
}
if (cdh.FileCommentLength > 0) {
bytes = ReadBytes (cdr, cdh.FileCommentLength, dataLength, ref nread, out worked);
if (!worked) {
whatFailed = "FileComment (bytes)";
goto failed;
}
cdh.FileComment = Encoding.ASCII.GetString (bytes);
}
return (true, cdh);
failed:
if (!String.IsNullOrEmpty (whatFailed))
Console.Error.WriteLine ($"Failed to read a central directory header field: {whatFailed}");
return (false, null);
}
static ushort ReadUShort (BinaryReader br, long dataLength, ref long nread, out bool success)
{
success = false;
if (dataLength - nread < 2)
return 0;
ushort ret = br.ReadUInt16 ();
nread += 2;
success = true;
return ret;
}
static uint ReadUInt (BinaryReader br, long dataLength, ref long nread, out bool success)
{
success = false;
if (dataLength - nread < 4)
return 0;
uint ret = br.ReadUInt32 ();
nread += 4;
success = true;
return ret;
}
static byte[] ReadBytes (BinaryReader br, int neededBytes, long dataLength, ref long nread, out bool success)
{
success = false;
if (dataLength - nread < neededBytes)
return null;
byte[] ret = br.ReadBytes (neededBytes);
nread += neededBytes;
success = true;
return ret;
}
static async Task<(bool success, Stream cd)> ReadCD (HttpClient httpClient, Uri url, uint cdOffset, uint cdSize, long fileSize)
{
long fileOffset = cdOffset;
var req = new HttpRequestMessage (HttpMethod.Get, url);
req.Headers.ConnectionClose = true;
req.Headers.Range = new RangeHeaderValue (fileOffset, fileOffset + cdSize);
HttpResponseMessage resp = await httpClient.SendAsync (req).ConfigureAwait (false);
if (!resp.IsSuccessStatusCode) {
Console.Error.WriteLine ($"Failed to read Central Directory: HTTP error {resp.StatusCode}");
return (false, null);
}
Stream s = await resp.Content.ReadAsStreamAsync ().ConfigureAwait (false);
if (s.Length < cdSize) {
Console.Error.WriteLine ($"Failed to read Central Directory: invalid data length ({s.Length} < {cdSize})");
s.Dispose ();
return (false, null);
}
return (true, s);
}
static async Task<(bool success, EOCD eocd)> GetEOCD (HttpClient httpClient, Uri url, long fileSize)
{
long fileOffset = fileSize - EndFileChunkSize;
var req = new HttpRequestMessage (HttpMethod.Get, url);
req.Headers.ConnectionClose = true;
req.Headers.Range = new RangeHeaderValue (fileOffset, fileSize);
HttpResponseMessage resp = await httpClient.SendAsync (req).ConfigureAwait (false);
if (!resp.IsSuccessStatusCode)
return (false, null);
using (var eocdStream = await resp.Content.ReadAsStreamAsync ().ConfigureAwait (false)) {
using (var sr = new BinaryReader (eocdStream)) {
byte[] expected = {0x50, 0x4b, 0x05, 0x06};
int expectedPos = 0;
for (int i = 0; i < eocdStream.Length; i++) {
byte b = sr.ReadByte ();
if (b != expected [expectedPos]) {
expectedPos = 0;
continue;
}
if (expectedPos == expected.Length - 1) {
// We've found the signature
var eocd = new EOCD ();
eocd.Signature = 0x06054b50;
eocd.DiskNumber = sr.ReadUInt16 ();
eocd.CDStartDisk = sr.ReadUInt16 ();
eocd.TotalEntriesThisDisk = sr.ReadUInt16 ();
eocd.TotalEntries = sr.ReadUInt16 ();
eocd.CDSize = sr.ReadUInt32 ();
eocd.CDOffset = sr.ReadUInt32 ();
eocd.CommentLength = sr.ReadUInt16 ();
return (true, eocd);
}
expectedPos++;
if (expectedPos >= expected.Length)
expectedPos = 0;
}
}
}
return (false, null);
}
static async Task<(bool success, long size)> GetFileSize (HttpClient httpClient, Uri url)
{
var req = new HttpRequestMessage (HttpMethod.Head, url);
req.Headers.ConnectionClose = true;
HttpResponseMessage resp = await httpClient.SendAsync (req).ConfigureAwait (false);
if (!resp.IsSuccessStatusCode || !resp.Content.Headers.ContentLength.HasValue)
return (false, 0);
return (true, resp.Content.Headers.ContentLength.Value);
}
}

Просмотреть файл

@ -0,0 +1,40 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>
<ProjectGuid>{09518DF2-C7B1-4CDB-849A-9F91F4BEA925}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>fetchwindowsassemblers</RootNamespace>
<AssemblyName>fetch-windows-assemblers</AssemblyName>
<TargetFrameworkVersion>v4.7</TargetFrameworkVersion>
</PropertyGroup>
<Import Project="..\..\Configuration.props" />
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>..\..\bin\BuildDebug</OutputPath>
<DefineConstants>DEBUG;</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<ExternalConsole>true</ExternalConsole>
<PlatformTarget>x86</PlatformTarget>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
<Optimize>true</Optimize>
<OutputPath>..\..\bin\BuildRelease</OutputPath>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<ExternalConsole>true</ExternalConsole>
<PlatformTarget>x86</PlatformTarget>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Net.Http" />
</ItemGroup>
<ItemGroup>
<Compile Include="fetch-windows-assemblers.cs" />
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
</Project>

Просмотреть файл

@ -134,12 +134,21 @@
<_MSBuildFilesWin Include="$(MSBuildSrcDir)\proguard\bin\proguard.bat" />
<_MSBuildFilesWin Include="$(MSBuildSrcDir)\aapt2.exe" />
<_MSBuildFilesWin Include="$(MSBuildSrcDir)\libwinpthread-1.dll" />
<_MSBuildFilesWin Include="$(MSBuildSrcDir)\aarch64-linux-android-as.exe" Condition=" '$(HostOS)' != 'Windows' "/>
<_MSBuildFilesWin Include="$(MSBuildSrcDir)\arm-linux-androideabi-as.exe" Condition=" '$(HostOS)' != 'Windows' "/>
<_MSBuildFilesWin Include="$(MSBuildSrcDir)\i686-linux-android-as.exe" Condition=" '$(HostOS)' != 'Windows' "/>
<_MSBuildFilesWin Include="$(MSBuildSrcDir)\x86_64-linux-android-as.exe" Condition=" '$(HostOS)' != 'Windows' "/>
<_MSBuildLibHostFilesWin Include="$(MSBuildSrcDir)\lib\host-mxe-Win64\libmono-android.debug.dll" Condition=" '$(HostOS)' != 'Windows' " />
<_MSBuildLibHostFilesWin Include="$(MSBuildSrcDir)\lib\host-mxe-Win64\libmono-android.release.dll" Condition=" '$(HostOS)' != 'Windows' " />
<_MSBuildLibHostFilesWin Include="$(MSBuildSrcDir)\lib\host-mxe-Win64\libMonoPosixHelper.dll" />
<_MSBuildLibHostFilesWin Include="$(MSBuildSrcDir)\lib\host-mxe-Win64\libmonosgen-2.0.dll" />
<_MSBuildLibHostFilesWin Include="$(MSBuildSrcDir)\lib\host-mxe-Win64\libxamarin-app.dll" Condition=" '$(HostOS)' != 'Windows' " />
</ItemGroup>
<ItemGroup>
<_MSBuildFilesUnix Include="$(MSBuildSrcDir)\$(HostOS)\aarch64-linux-android-as" />
<_MSBuildFilesUnix Include="$(MSBuildSrcDir)\$(HostOS)\arm-linux-androideabi-as" />
<_MSBuildFilesUnix Include="$(MSBuildSrcDir)\$(HostOS)\i686-linux-android-as" />
<_MSBuildFilesUnix Include="$(MSBuildSrcDir)\$(HostOS)\x86_64-linux-android-as" />
<_MSBuildFilesUnix Include="$(MSBuildSrcDir)\$(HostOS)\illinkanalyzer" />
<_MSBuildFilesUnix Include="$(MSBuildSrcDir)\$(HostOS)\jit-times" />
<_MSBuildFilesUnix Include="$(MSBuildSrcDir)\$(HostOS)\mono" />
@ -153,6 +162,7 @@
<_MSBuildFilesUnix Include="$(MSBuildSrcDir)\lib\host-$(HostOS)\libmono-profiler-log.$(LibExtension)" />
<_MSBuildFilesUnix Include="$(MSBuildSrcDir)\lib\host-$(HostOS)\libMonoPosixHelper.$(LibExtension)" />
<_MSBuildFilesUnix Include="$(MSBuildSrcDir)\lib\host-$(HostOS)\libmonosgen-2.0.$(LibExtension)" />
<_MSBuildFilesUnix Include="$(MSBuildSrcDir)\lib\host-$(HostOS)\libxamarin-app.$(LibExtension)" />
<_MSBuildFilesUnix Include="$(MSBuildSrcDir)\libzip.5.0.$(LibExtension)" />
<_MSBuildFilesUnix Include="$(MSBuildSrcDir)\proguard\bin\proguard.sh" />
</ItemGroup>

Просмотреть файл

@ -98,7 +98,8 @@ _BUILD_STATUS_BUNDLE_INCLUDE = \
$(shell find . -name 'CMakeCache.txt') \
$(shell find . -name 'config.h') \
$(shell find . -name '.ninja_log') \
$(shell find . -name 'android-*.config.cache')
$(shell find . -name 'android-*.config.cache') \
bin/Build$(CONFIGURATION)/XABuildConfig.cs
_BUILD_STATUS_BASENAME = xa-build-status-v$(PRODUCT_VERSION).$(-num-commits-since-version-change)_$(OS_NAME)-$(OS_ARCH)_$(GIT_BRANCH)_$(GIT_COMMIT)-$(CONFIGURATION)
_BUILD_STATUS_ZIP_OUTPUT = $(_BUILD_STATUS_BASENAME).$(ZIP_EXTENSION)

Просмотреть файл

@ -5,6 +5,7 @@ namespace Xamarin.Android.Tools
{
static class XABuildConfig
{
public const string SupportedABIs = "@XA_SUPPORTED_ABIS@";
public const string NDKRevision = "@NDK_REVISION@";
public const string NDKRelease = "@NDK_RELEASE@";
public const int NDKMinimumApiAvailable = @NDK_MINIMUM_API_AVAILABLE@;
@ -15,6 +16,7 @@ namespace Xamarin.Android.Tools
{ "arm", @NDK_ARMEABI_V7_API@},
{ "arm64-v8a", @NDK_ARM64_V8A_API@},
{ "arm64", @NDK_ARM64_V8A_API@},
{ "aarch64", @NDK_ARM64_V8A_API@},
{ "x86", @NDK_X86_API@},
{ "x86_64", @NDK_X86_64_API@},
};

Просмотреть файл

@ -121,5 +121,633 @@
</LicenseText>
<SourceUrl>https://github.com/NuGet/NuGet.Client</SourceUrl>
</ThirdPartyNotice>
<!-- `Xamarin.Android.Build.Tasks/Xamarin.Android.Build.Tasks.csproj` copies various NDK utilities into the SDK -->
<ThirdPartyNotice Include="android/platform/ndk">
<LicenseText>
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. &lt;http://fsf.org/&gt;
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
</LicenseText>
<!-- binutils (source for gas) are not built as part of the NDK, see: https://android.googlesource.com/platform/ndk/+/master/docs/Toolchains.md -->
<SourceUrl>https://sourceware.org/git/gitweb.cgi?p=binutils-gdb.git;a=tree;f=gas</SourceUrl>
</ThirdPartyNotice>
</ItemGroup>
</Project>

Просмотреть файл

@ -74,7 +74,8 @@ Copyright (C) 2016 Xamarin. All rights reserved.
PackageNamingPolicy="$(AndroidPackageNamingPolicy)"
ApplicationJavaClass="$(AndroidApplicationJavaClass)"
FrameworkDirectories="$(_XATargetFrameworkDirectories);$(_XATargetFrameworkDirectories)Facades"
AcwMapFile="$(_AcwMapFile)">
AcwMapFile="$(_AcwMapFile)"
SupportedAbis="$(_BuildTargetAbis)">
</GenerateJavaStubs>
<ConvertCustomView
Condition="Exists('$(_CustomViewMapFile)')"
@ -100,7 +101,11 @@ Copyright (C) 2016 Xamarin. All rights reserved.
TlsProvider="$(AndroidTlsProvider)"
Debug="$(AndroidIncludeDebugSymbols)"
AndroidSequencePointsMode="$(_SequencePointsMode)"
EnableSGenConcurrent="$(AndroidEnableSGenConcurrent)">
EnableSGenConcurrent="$(AndroidEnableSGenConcurrent)"
IsBundledApplication="$(BundleAssemblies)"
SupportedAbis="$(_BuildTargetAbis)"
AndroidPackageName="$(_AndroidPackage)"
EnablePreloadAssembliesDefault="$(_AndroidEnablePreloadAssembliesDefault)">
<Output TaskParameter="BuildId" PropertyName="_XamarinBuildId" />
</GeneratePackageManagerJava>
</Target>

Просмотреть файл

@ -1,9 +0,0 @@
package mono.android.app;
public class XamarinAndroidEnvironmentVariables
{
// Variables are specified the in "name", "value" pairs
public static final String[] Variables = new String[] {
//@ENVVARS@
};
}

Просмотреть файл

@ -15,11 +15,12 @@ using Xamarin.Build;
namespace Xamarin.Android.Tasks
{
public enum AotMode
public enum AotMode : uint
{
Normal,
Hybrid,
Full
None = 0x0000,
Normal = 0x0001,
Hybrid = 0x0002,
Full = 0x0003,
}
public enum SequencePointsMode {
@ -99,6 +100,9 @@ namespace Xamarin.Android.Tasks
switch ((androidAotMode ?? string.Empty).ToLowerInvariant().Trim())
{
case "none":
aotMode = AotMode.None;
return true;
case "normal":
aotMode = AotMode.Normal;
return true;

Просмотреть файл

@ -43,6 +43,9 @@ namespace Xamarin.Android.Tasks
[Required]
public ITaskItem[] NativeLibraries { get; set; }
[Required]
public ITaskItem[] ApplicationSharedLibraries { get; set; }
public ITaskItem[] BundleNativeLibraries { get; set; }
public ITaskItem[] TypeMappings { get; set; }
@ -356,6 +359,13 @@ namespace Xamarin.Android.Tasks
return CompressionMethod.Default;
}
void AddNativeLibraryToArchive (ZipArchiveEx apk, string abi, string filesystemPath, string inArchiveFileName)
{
string archivePath = $"lib/{abi}/{inArchiveFileName}";
Log.LogDebugMessage ($"Adding native library: {filesystemPath} (APK path: {archivePath})");
apk.Archive.AddEntry (archivePath, File.OpenRead (filesystemPath), compressionMethod: GetCompressionMethod (archivePath));
}
void AddNativeLibrary (ZipArchiveEx apk, string abi, string filename, string inArchiveFileName = null)
{
string libPath = Path.Combine (MSBuildXamarinAndroidDirectory, "lib", abi);
@ -366,9 +376,7 @@ namespace Xamarin.Android.Tasks
path = debugPath;
}
string archivePath = string.Format ("lib/{0}/{1}", abi, inArchiveFileName ?? filename);
Log.LogDebugMessage ($"Adding native library: {path} (APK path: {archivePath})");
apk.Archive.AddEntry (archivePath, File.OpenRead (path), compressionMethod: GetCompressionMethod (archivePath));
AddNativeLibraryToArchive (apk, abi, path, inArchiveFileName ?? filename);
}
void AddProfilers (ZipArchiveEx apk, string abi)
@ -399,6 +407,13 @@ namespace Xamarin.Android.Tasks
foreach (var abi in abis) {
string library = string.Format ("libmono-android.{0}.so", _Debug ? "debug" : "release");
AddNativeLibrary (apk, abi, library, "libmonodroid.so");
foreach (ITaskItem item in ApplicationSharedLibraries) {
if (String.Compare (abi, item.GetMetadata ("abi"), StringComparison.Ordinal) != 0)
continue;
AddNativeLibraryToArchive (apk, abi, item.ItemSpec, Path.GetFileName (item.ItemSpec));
}
if (!use_shared_runtime) {
// include the sgen
AddNativeLibrary (apk, abi, "libmonosgen-2.0.so");

Просмотреть файл

@ -0,0 +1,214 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Threading;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Xamarin.Android.Tools;
using Xamarin.Build;
namespace Xamarin.Android.Tasks
{
public class CompileNativeAssembly : AsyncTask
{
sealed class Config
{
public string AssemblerPath;
public string AssemblerOptions;
public string InputSource;
}
[Required]
public ITaskItem[] Sources { get; set; }
[Required]
public bool DebugBuild { get; set; }
[Required]
public string WorkingDirectory { get; set; }
public override bool Execute ()
{
try {
return DoExecute ();
} catch (Exception e) {
// We don't want to present a wall of text to the end user...
Log.LogCodedError ("XA3001", $"Unable to generate `libxamarin-app.so`: {e.Message}");
// ...but having the full stack trace available is important for us, so log it here
// int the way that will make it included in XA builds on bots or in verbose end user
// builds but not otherwise.
LogDebugMessage ($"Full exception: {e}");
return false;
}
}
bool DoExecute ()
{
Yield ();
try {
var task = this.RunTask ( () => RunParallelAssembler ());
task.ContinueWith (Complete);
base.Execute ();
if (!task.Result)
return false;
} finally {
Reacquire ();
}
return !Log.HasLoggedErrors;
}
bool RunParallelAssembler ()
{
try {
this.ParallelForEach (GetAssemblerConfigs (),
config => {
if (!RunAssembler (config)) {
LogCodedError ("XA3001", $"Could not compile native assembly file: {Path.GetFileName (config.InputSource)}");
Cancel ();
return;
}
}
);
} catch (OperationCanceledException) {
return false;
}
return true;
}
bool RunAssembler (Config config)
{
var stdout_completed = new ManualResetEvent (false);
var stderr_completed = new ManualResetEvent (false);
var psi = new ProcessStartInfo () {
FileName = config.AssemblerPath,
Arguments = config.AssemblerOptions,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden,
WorkingDirectory = WorkingDirectory,
};
string assemblerName = Path.GetFileName (config.AssemblerPath);
LogDebugMessage ($"[Native Assembler] {psi.FileName} {psi.Arguments}");
using (var proc = new Process ()) {
proc.OutputDataReceived += (s, e) => {
if (e.Data != null)
OnOutputData (assemblerName, s, e);
else
stdout_completed.Set ();
};
proc.ErrorDataReceived += (s, e) => {
if (e.Data != null)
OnErrorData (assemblerName, s, e);
else
stderr_completed.Set ();
};
proc.StartInfo = psi;
proc.Start ();
proc.BeginOutputReadLine ();
proc.BeginErrorReadLine ();
CancellationToken.Register (() => { try { proc.Kill (); } catch (Exception) { } });
proc.WaitForExit ();
if (psi.RedirectStandardError)
stderr_completed.WaitOne (TimeSpan.FromSeconds (30));
if (psi.RedirectStandardOutput)
stdout_completed.WaitOne (TimeSpan.FromSeconds (30));
return proc.ExitCode == 0;
}
}
IEnumerable<Config> GetAssemblerConfigs ()
{
string sdkBinDirectory = MonoAndroidHelper.GetOSBinPath ();
foreach (ITaskItem item in Sources) {
string abi = item.GetMetadata ("abi")?.ToLowerInvariant ();
string prefix = String.Empty;
AndroidTargetArch arch;
switch (abi) {
case "armeabi-v7a":
prefix = Path.Combine (sdkBinDirectory, "arm-linux-androideabi");
arch = AndroidTargetArch.Arm;
break;
case "arm64":
case "arm64-v8a":
case "aarch64":
prefix = Path.Combine (sdkBinDirectory, "aarch64-linux-android");
arch = AndroidTargetArch.Arm64;
break;
case "x86":
prefix = Path.Combine (sdkBinDirectory, "i686-linux-android");
arch = AndroidTargetArch.X86;
break;
case "x86_64":
prefix = Path.Combine (sdkBinDirectory, "x86_64-linux-android");
arch = AndroidTargetArch.X86_64;
break;
default:
throw new NotSupportedException ($"Unsupported Android target architecture ABI: {abi}");
}
// We don't need the directory since our WorkingDirectory is (and must be) where all the
// sources are (because of the typemap.inc file being included by the other sources with
// a relative path of `.`)
string sourceFile = Path.GetFileName (item.ItemSpec);
var assemblerOptions = new List<string> {
"--warn",
"-o",
QuoteFileName (sourceFile.Replace (".s", ".o"))
};
if (DebugBuild)
assemblerOptions.Add ("-g");
assemblerOptions.Add (QuoteFileName (sourceFile));
string baseExecutablePath = $"{prefix}-as";
string executableDir = Path.GetDirectoryName (baseExecutablePath);
string executableName = MonoAndroidHelper.GetExecutablePath (executableDir, Path.GetFileName (baseExecutablePath));
yield return new Config {
InputSource = item.ItemSpec,
AssemblerPath = Path.Combine (executableDir, executableName),
AssemblerOptions = String.Join (" ", assemblerOptions),
};
}
}
void OnOutputData (string assemblerName, object sender, DataReceivedEventArgs e)
{
LogMessage ($"[{assemblerName} stdout] {e.Data}");
}
void OnErrorData (string assemblerName, object sender, DataReceivedEventArgs e)
{
LogMessage ($"[{assemblerName} stderr] {e.Data}");
}
static string QuoteFileName (string fileName)
{
var builder = new CommandLineBuilder ();
builder.AppendFileNameIfNotNull (fileName);
return builder.ToString ();
}
}
}

Просмотреть файл

@ -5,6 +5,8 @@ using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using System.Text;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Mono.Cecil;
@ -35,6 +37,9 @@ namespace Xamarin.Android.Tasks
[Required]
public ITaskItem [] FrameworkDirectories { get; set; }
[Required]
public string SupportedAbis { get; set; }
public string ManifestTemplate { get; set; }
public string[] MergedManifestDocuments { get; set; }
@ -285,13 +290,63 @@ namespace Xamarin.Android.Tasks
TypeNameMapGenerator createTypeMapGenerator () => UseSharedRuntime ?
new TypeNameMapGenerator (types, logger) :
new TypeNameMapGenerator (ResolvedAssemblies.Select (p => p.ItemSpec), logger);
using (var gen = createTypeMapGenerator ())
using (var stream = new MemoryStream ()) {
gen.WriteJavaToManaged (stream);
MonoAndroidHelper.CopyIfStreamChanged (stream, Path.Combine (OutputDirectory, "typemap.jm"));
stream.SetLength (0); //Reuse the stream
gen.WriteManagedToJava (stream);
MonoAndroidHelper.CopyIfStreamChanged (stream, Path.Combine (OutputDirectory, "typemap.mj"));
using (var gen = createTypeMapGenerator ()) {
using (var ms = new MemoryStream ()) {
UpdateWhenChanged (Path.Combine (OutputDirectory, "typemap.jm"), "jm", ms, gen.WriteJavaToManaged);
UpdateWhenChanged (Path.Combine (OutputDirectory, "typemap.mj"), "mj", ms, gen.WriteManagedToJava);
}
}
}
void UpdateWhenChanged (string path, string type, MemoryStream ms, Action<Stream> generator)
{
if (InstantRunEnabled) {
ms.SetLength (0);
generator (ms);
MonoAndroidHelper.CopyIfStreamChanged (ms, path);
}
string dataFilePath = $"{path}.inc";
using (var stream = new NativeAssemblyDataStream ()) {
generator (stream);
stream.Flush ();
MonoAndroidHelper.CopyIfStreamChanged (stream, dataFilePath);
var generatedFiles = new List <ITaskItem> ();
string mappingFieldName = $"{type}_typemap";
string dataFileName = Path.GetFileName (dataFilePath);
NativeAssemblerTargetProvider asmTargetProvider;
var utf8Encoding = new UTF8Encoding (false);
foreach (string abi in SupportedAbis.Split (new char[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries)) {
ms.SetLength (0);
switch (abi.Trim ()) {
case "armeabi-v7a":
asmTargetProvider = new ARMNativeAssemblerTargetProvider (is64Bit: false);
break;
case "arm64-v8a":
asmTargetProvider = new ARMNativeAssemblerTargetProvider (is64Bit: true);
break;
case "x86":
asmTargetProvider = new X86NativeAssemblerTargetProvider (is64Bit: false);
break;
case "x86_64":
asmTargetProvider = new X86NativeAssemblerTargetProvider (is64Bit: true);
break;
default:
throw new InvalidOperationException ($"Unknown ABI {abi}");
}
var asmgen = new TypeMappingNativeAssemblyGenerator (asmTargetProvider, stream, dataFileName, stream.MapByteCount, mappingFieldName);
string asmFileName = $"{path}.{abi.Trim ()}.s";
using (var sw = new StreamWriter (ms, utf8Encoding, bufferSize: 8192, leaveOpen: true)) {
asmgen.Write (sw, dataFileName);
MonoAndroidHelper.CopyIfStreamChanged (ms, asmFileName);
}
}
}
}
}

Просмотреть файл

@ -1,9 +1,11 @@
// Copyright (C) 2011 Xamarin, Inc. All rights reserved.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
@ -13,8 +15,6 @@ namespace Xamarin.Android.Tasks
{
public class GeneratePackageManagerJava : Task
{
const string EnvironmentFileName = "XamarinAndroidEnvironmentVariables.java";
Guid buildId = Guid.NewGuid ();
[Required]
@ -41,6 +41,18 @@ namespace Xamarin.Android.Tasks
[Required]
public string Manifest { get; set; }
[Required]
public bool IsBundledApplication { get; set; }
[Required]
public string SupportedAbis { get; set; }
[Required]
public string AndroidPackageName { get; set; }
[Required]
public bool EnablePreloadAssembliesDefault { get; set; }
public string Debug { get; set; }
public ITaskItem[] Environments { get; set; }
public string AndroidAotMode { get; set; }
@ -125,17 +137,18 @@ namespace Xamarin.Android.Tasks
void AddEnvironment ()
{
var environment = new StringWriter () {
NewLine = "\n",
};
if (EnableLLVM) {
WriteEnvironment ("mono.llvm", "true");
}
bool usesEmbeddedDSOs = false;
bool usesMonoAOT = false;
bool usesAssemblyPreload = EnablePreloadAssembliesDefault;
uint monoAOTMode = 0;
string androidPackageName = null;
var environmentVariables = new Dictionary<string, string> (StringComparer.Ordinal);
var systemProperties = new Dictionary<string, string> (StringComparer.Ordinal);
AotMode aotMode;
if (AndroidAotMode != null && Aot.GetAndroidAotMode (AndroidAotMode, out aotMode)) {
WriteEnvironment ("mono.aot", aotMode.ToString ().ToLowerInvariant());
usesMonoAOT = true;
monoAOTMode = (uint)aotMode;
}
bool haveLogLevel = false;
@ -150,7 +163,6 @@ namespace Xamarin.Android.Tasks
sequencePointsMode = SequencePointsMode.None;
foreach (ITaskItem env in Environments ?? new TaskItem[0]) {
environment.WriteLine ("\t\t// Source File: {0}", env.ItemSpec);
foreach (string line in File.ReadLines (env.ItemSpec)) {
var lineToWrite = line;
if (lineToWrite.StartsWith ("MONO_LOG_LEVEL=", StringComparison.Ordinal))
@ -168,72 +180,119 @@ namespace Xamarin.Android.Tasks
haveHttpMessageHandler = true;
if (lineToWrite.StartsWith ("XA_TLS_PROVIDER=", StringComparison.Ordinal))
haveTlsProvider = true;
WriteEnvironmentLine (lineToWrite);
if (lineToWrite.StartsWith ("__XA_DSO_IN_APK", StringComparison.Ordinal)) {
usesEmbeddedDSOs = true;
continue;
}
if (lineToWrite.StartsWith ("mono.enable_assembly_preload=", StringComparison.Ordinal)) {
int idx = lineToWrite.IndexOf ('=');
uint val;
if (idx < lineToWrite.Length - 1 && UInt32.TryParse (lineToWrite.Substring (idx + 1), out val)) {
usesAssemblyPreload = idx == 1;
}
continue;
}
AddEnvironmentVariableLine (lineToWrite);
}
}
if (_Debug && !haveLogLevel) {
WriteEnvironment (defaultLogLevel[0], defaultLogLevel[1]);
AddEnvironmentVariable (defaultLogLevel[0], defaultLogLevel[1]);
}
if (sequencePointsMode != SequencePointsMode.None && !haveMonoDebug) {
WriteEnvironment (defaultMonoDebug[0], defaultMonoDebug[1]);
AddEnvironmentVariable (defaultMonoDebug[0], defaultMonoDebug[1]);
}
if (!havebuildId)
WriteEnvironment ("XAMARIN_BUILD_ID", BuildId);
AddEnvironmentVariable ("XAMARIN_BUILD_ID", BuildId);
if (!haveHttpMessageHandler) {
if (HttpClientHandlerType == null)
WriteEnvironment (defaultHttpMessageHandler[0], defaultHttpMessageHandler[1]);
AddEnvironmentVariable (defaultHttpMessageHandler[0], defaultHttpMessageHandler[1]);
else
WriteEnvironment ("XA_HTTP_CLIENT_HANDLER_TYPE", HttpClientHandlerType.Trim ());
AddEnvironmentVariable ("XA_HTTP_CLIENT_HANDLER_TYPE", HttpClientHandlerType.Trim ());
}
if (!haveTlsProvider) {
if (TlsProvider == null)
WriteEnvironment (defaultTlsProvider[0], defaultTlsProvider[1]);
AddEnvironmentVariable (defaultTlsProvider[0], defaultTlsProvider[1]);
else
WriteEnvironment ("XA_TLS_PROVIDER", TlsProvider.Trim ());
AddEnvironmentVariable ("XA_TLS_PROVIDER", TlsProvider.Trim ());
}
if (!haveMonoGCParams) {
if (EnableSGenConcurrent)
WriteEnvironment ("MONO_GC_PARAMS", "major=marksweep-conc");
AddEnvironmentVariable ("MONO_GC_PARAMS", "major=marksweep-conc");
else
WriteEnvironment ("MONO_GC_PARAMS", "major=marksweep");
}
string environmentTemplate;
using (var sr = new StreamReader (typeof (BuildApk).Assembly.GetManifestResourceStream (EnvironmentFileName))) {
environmentTemplate = sr.ReadToEnd ();
AddEnvironmentVariable ("MONO_GC_PARAMS", "major=marksweep");
}
using (var ms = new MemoryStream ()) {
using (var sw = new StreamWriter (ms)) {
sw.Write (environmentTemplate.Replace ("//@ENVVARS@", environment.ToString ()));
sw.Flush ();
var utf8Encoding = new UTF8Encoding (false);
foreach (string abi in SupportedAbis.Split (new char[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries)) {
ms.SetLength (0);
NativeAssemblerTargetProvider asmTargetProvider;
string asmFileName = Path.Combine (EnvironmentOutputDirectory, $"environment.{abi.ToLowerInvariant ()}.s");
switch (abi.Trim ()) {
case "armeabi-v7a":
asmTargetProvider = new ARMNativeAssemblerTargetProvider (false);
break;
case "arm64-v8a":
asmTargetProvider = new ARMNativeAssemblerTargetProvider (true);
break;
case "x86":
asmTargetProvider = new X86NativeAssemblerTargetProvider (false);
break;
case "x86_64":
asmTargetProvider = new X86NativeAssemblerTargetProvider (true);
break;
default:
throw new InvalidOperationException ($"Unknown ABI {abi}");
}
var asmgen = new ApplicationConfigNativeAssemblyGenerator (asmTargetProvider, environmentVariables, systemProperties) {
IsBundledApp = IsBundledApplication,
UsesEmbeddedDSOs = usesEmbeddedDSOs,
UsesMonoAOT = usesMonoAOT,
UsesMonoLLVM = EnableLLVM,
UsesAssemblyPreload = usesAssemblyPreload,
MonoAOTMode = monoAOTMode.ToString ().ToLowerInvariant (),
AndroidPackageName = AndroidPackageName,
};
using (var sw = new StreamWriter (ms, utf8Encoding, bufferSize: 8192, leaveOpen: true)) {
asmgen.Write (sw, asmFileName);
MonoAndroidHelper.CopyIfStreamChanged (ms, asmFileName);
}
string dest = Path.GetFullPath (Path.Combine (EnvironmentOutputDirectory, EnvironmentFileName));
MonoAndroidHelper.CopyIfStreamChanged (ms, dest);
}
}
void WriteEnvironment (string name, string value)
void AddEnvironmentVariable (string name, string value)
{
environment.WriteLine ($"\t\t\"{ValidJavaString (name)}\", \"{ValidJavaString (value)}\",");
if (Char.IsUpper(name [0]) || !Char.IsLetter(name [0]))
environmentVariables [ValidAssemblerString (name)] = ValidAssemblerString (value);
else
systemProperties [ValidAssemblerString (name)] = ValidAssemblerString (value);
}
void WriteEnvironmentLine (string line)
void AddEnvironmentVariableLine (string l)
{
if (String.IsNullOrEmpty (line))
string line = l?.Trim ();
if (String.IsNullOrEmpty (line) || line [0] == '#')
return;
string[] nv = line.Split (new char[]{'='}, 2);
WriteEnvironment (nv[0].Trim (), nv.Length < 2 ? String.Empty : nv[1].Trim ());
AddEnvironmentVariable (nv[0].Trim (), nv.Length < 2 ? String.Empty : nv[1].Trim ());
}
string ValidJavaString (string s)
string ValidAssemblerString (string s)
{
return s.Replace ("\"", "\\\"");
}

Просмотреть файл

@ -0,0 +1,260 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Threading;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Xamarin.Android.Tools;
using Xamarin.Build;
namespace Xamarin.Android.Tasks
{
public class LinkApplicationSharedLibraries : AsyncTask
{
sealed class Config
{
public string LinkerPath;
public string LinkerOptions;
public string OutputSharedLibrary;
}
sealed class InputFiles
{
public List<string> ObjectFiles;
public string OutputSharedLibrary;
}
[Required]
public ITaskItem[] ObjectFiles { get; set; }
[Required]
public ITaskItem[] ApplicationSharedLibraries { get; set; }
[Required]
public bool DebugBuild { get; set; }
[Required]
public string AndroidNdkDirectory { get; set; }
public override bool Execute ()
{
try {
return DoExecute ();
} catch (Exception e) {
// We don't want to present a wall of text to the end user...
Log.LogCodedError ("XA3001", $"Unable to link `libxamarin-app.so`: {e.Message}");
// ...but having the full stack trace available is important for us, so log it here
// int the way that will make it included in XA builds on bots or in verbose end user
// builds but not otherwise.
LogDebugMessage ($"Full exception: {e}");
return false;
}
}
bool DoExecute ()
{
Yield ();
try {
var task = this.RunTask ( () => RunParallelLinker ());
task.ContinueWith (Complete);
base.Execute ();
if (!task.Result)
return false;
} finally {
Reacquire ();
}
return !Log.HasLoggedErrors;
}
bool RunParallelLinker ()
{
try {
this.ParallelForEach (GetLinkerConfigs (),
config => {
if (RunLinker (config))
return;
LogCodedError ("XA3001", $"Could not link native shared library: {Path.GetFileName (config.OutputSharedLibrary)}");
Cancel ();
return;
}
);
} catch (OperationCanceledException) {
return false;
}
return true;
}
bool RunLinker (Config config)
{
var stdout_completed = new ManualResetEvent (false);
var stderr_completed = new ManualResetEvent (false);
var psi = new ProcessStartInfo () {
FileName = config.LinkerPath,
Arguments = config.LinkerOptions,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden,
};
string targetDir = Path.GetDirectoryName (config.OutputSharedLibrary);
if (!Directory.Exists (targetDir))
Directory.CreateDirectory (targetDir);
string linkerName = Path.GetFileName (config.LinkerPath);
LogDebugMessage ($"[Native Linker] {psi.FileName} {psi.Arguments}");
using (var proc = new Process ()) {
proc.OutputDataReceived += (s, e) => {
if (e.Data != null)
OnOutputData (linkerName, s, e);
else
stdout_completed.Set ();
};
proc.ErrorDataReceived += (s, e) => {
if (e.Data != null)
OnErrorData (linkerName, s, e);
else
stderr_completed.Set ();
};
proc.StartInfo = psi;
proc.Start ();
proc.BeginOutputReadLine ();
proc.BeginErrorReadLine ();
CancellationToken.Register (() => { try { proc.Kill (); } catch (Exception) { } });
proc.WaitForExit ();
if (psi.RedirectStandardError)
stderr_completed.WaitOne (TimeSpan.FromSeconds (30));
if (psi.RedirectStandardOutput)
stdout_completed.WaitOne (TimeSpan.FromSeconds (30));
return proc.ExitCode == 0;
}
}
IEnumerable<Config> GetLinkerConfigs ()
{
var abis = new Dictionary <string, InputFiles> (StringComparer.Ordinal);
ITaskItem[] dsos = ApplicationSharedLibraries;
foreach (ITaskItem item in dsos) {
string abi = item.GetMetadata ("abi");
abis [abi] = GatherFilesForABI(item.ItemSpec, abi, ObjectFiles);
}
foreach (var kvp in abis) {
string abi = kvp.Key;
InputFiles inputs = kvp.Value;
AndroidTargetArch arch;
var linkerArgs = new List <string> {
"--unresolved-symbols=ignore-in-shared-libs",
"--export-dynamic",
"-soname", "libxamarin-app.so",
"-z", "relro",
"-z", "noexecstack",
"--enable-new-dtags",
"--eh-frame-hdr",
"-shared",
"--build-id",
"--warn-shared-textrel",
"--fatal-warnings",
"-o", QuoteFileName (inputs.OutputSharedLibrary),
};
string elf_arch;
switch (abi) {
case "armeabi-v7a":
arch = AndroidTargetArch.Arm;
linkerArgs.Add ("-X");
elf_arch = "armelf_linux_eabi";
break;
case "arm64":
case "arm64-v8a":
case "aarch64":
arch = AndroidTargetArch.Arm64;
linkerArgs.Add ("--fix-cortex-a53-843419");
elf_arch = "aarch64linux";
break;
case "x86":
arch = AndroidTargetArch.X86;
elf_arch = "elf_i386";
break;
case "x86_64":
arch = AndroidTargetArch.X86_64;
elf_arch = "elf_x86_64";
break;
default:
throw new NotSupportedException ($"Unsupported Android target architecture ABI: {abi}");
}
linkerArgs.Add ("-m");
linkerArgs.Add (elf_arch);
foreach (string file in inputs.ObjectFiles) {
linkerArgs.Add (QuoteFileName (file));
}
yield return new Config {
LinkerPath = NdkUtil.GetNdkTool (AndroidNdkDirectory, arch, "ld", XABuildConfig.ArchAPILevels [abi]),
LinkerOptions = String.Join (" ", linkerArgs),
OutputSharedLibrary = inputs.OutputSharedLibrary,
};
}
}
InputFiles GatherFilesForABI (string runtimeSharedLibrary, string abi, ITaskItem[] objectFiles)
{
return new InputFiles {
OutputSharedLibrary = runtimeSharedLibrary,
ObjectFiles = GetItemsForABI (abi, objectFiles),
};
}
List<string> GetItemsForABI (string abi, ITaskItem[] items)
{
var ret = new List <string> ();
foreach (ITaskItem item in items) {
if (String.Compare (abi, item.GetMetadata ("abi"), StringComparison.Ordinal) != 0)
continue;
ret.Add (item.ItemSpec);
}
return ret;
}
void OnOutputData (string linkerName, object sender, DataReceivedEventArgs e)
{
if (e.Data != null)
LogMessage ($"[{linkerName} stdout] {e.Data}");
}
void OnErrorData (string linkerName, object sender, DataReceivedEventArgs e)
{
if (e.Data != null)
LogMessage ($"[{linkerName} stderr] {e.Data}");
}
static string QuoteFileName (string fileName)
{
var builder = new CommandLineBuilder ();
builder.AppendFileNameIfNotNull (fileName);
return builder.ToString ();
}
}
}

Просмотреть файл

@ -6,6 +6,7 @@ using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
@ -16,17 +17,24 @@ namespace Xamarin.Android.Tasks
{
public static class NdkUtil
{
// We need it to work fine during our tests which are executed at the same time in various threads.
[ThreadStatic]
static bool usingClangNDK;
public static bool UsingClangNDK => usingClangNDK;
public static bool Init (string ndkPath)
{
return Init (null, ndkPath); // For tests which don't have access to a TaskLoggingHelper
}
public static bool Init (TaskLoggingHelper log, string ndkPath)
{
Version ndkVersion;
bool hasNdkVersion = GetNdkToolchainRelease (ndkPath ?? "", out ndkVersion);
if (!hasNdkVersion) {
log.LogCodedError ("XA5101",
log?.LogCodedError ("XA5101",
"Could not locate the Android NDK. Please make sure the Android NDK is installed in the Android SDK Manager, " +
"or if using a custom NDK path, please ensure the $(AndroidNdkDirectory) MSBuild property is set to the custom path.");
return false;

Просмотреть файл

@ -0,0 +1,34 @@
using System;
using System.Collections.Generic;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
namespace Xamarin.Android.Tasks
{
public class PrepareAbiItems : Task
{
[Required]
public string BuildTargetAbis { get; set; }
[Required]
public string ItemNamePattern { get; set; }
[Output]
public ITaskItem[] OutputItems { get; set; }
public override bool Execute ()
{
string[] abis = BuildTargetAbis.Split (new [] { ';', ',' }, StringSplitOptions.RemoveEmptyEntries);
var items = new List<ITaskItem> ();
foreach (string abi in abis) {
var item = new TaskItem (ItemNamePattern.Replace ("@abi@", abi));
item.SetMetadata ("abi", abi);
items.Add (item);
}
OutputItems = items.ToArray ();
return !Log.HasLoggedErrors;
}
}
}

Просмотреть файл

@ -444,8 +444,15 @@ namespace UnamedProject
start = DateTime.UtcNow;
Assert.IsTrue (b.Build (proj), "second build should have succeeded.");
// These files won't exist in OSS Xamarin.Android, thus the existence check and
// Assert.Ignore below. They will also not exist in the commercial version of
// Xamarin.Android unless fastdev is enabled.
foreach (var file in new [] { "typemap.mj", "typemap.jm" }) {
var info = new FileInfo (Path.Combine (intermediate, "android", file));
if (!info.Exists) {
Assert.Ignore ($"{info.Name} does not exist, timestamp check skipped");
continue;
}
Assert.IsTrue (info.LastWriteTimeUtc > start, $"`{file}` is older than `{start}`, with a timestamp of `{info.LastWriteTimeUtc}`!");
}
@ -1784,6 +1791,8 @@ namespace App1
[Test]
public void BuildApplicationWithMonoEnvironment ([Values ("", "Normal", "Offline")] string sequencePointsMode)
{
const string supportedAbis = "armeabi-v7a;x86";
var lib = new XamarinAndroidLibraryProject {
ProjectName = "Library1",
IsRelease = true,
@ -1803,25 +1812,27 @@ namespace App1
string linkSkip = KnownPackages.SupportV7AppCompat_27_0_2_1.Id;
app.SetProperty ("AndroidLinkSkip", linkSkip);
app.SetProperty ("_AndroidSequencePointsMode", sequencePointsMode);
app.SetProperty (app.ReleaseProperties, KnownProperties.AndroidSupportedAbis, supportedAbis);
using (var libb = CreateDllBuilder (Path.Combine ("temp", TestName, lib.ProjectName)))
using (var appb = CreateApkBuilder (Path.Combine ("temp", TestName, app.ProjectName))) {
Assert.IsTrue (libb.Build (lib), "Library build should have succeeded.");
Assert.IsTrue (appb.Build (app), "App should have succeeded.");
Assert.IsTrue (StringAssertEx.ContainsText (appb.LastBuildOutput, $"Save assembly: {linkSkip}"), $"{linkSkip} should be saved, and not linked!");
string javaEnv = Path.Combine (Root, appb.ProjectDirectory,
app.IntermediateOutputPath, "android", "src", "mono", "android", "app", "XamarinAndroidEnvironmentVariables.java");
Assert.IsTrue (File.Exists (javaEnv), $"Java environment source does not exist at {javaEnv}");
string[] lines = File.ReadAllLines (javaEnv);
Assert.IsTrue (lines.Any (x => x.Contains ("MONO_DEBUG") &&
x.Contains ("soft-breakpoints") &&
string.IsNullOrEmpty (sequencePointsMode) ? true : x.Contains ("gen-compact-seq-points")),
"The values from Mono.env should have been merged into environment");
string intermediateOutputDir = Path.Combine (Root, appb.ProjectDirectory, app.IntermediateOutputPath);
List<string> envFiles = EnvironmentHelper.GatherEnvironmentFiles (intermediateOutputDir, supportedAbis, true);
Dictionary<string, string> envvars = EnvironmentHelper.ReadEnvironmentVariables (envFiles);
Assert.IsTrue (envvars.Count > 0, $"No environment variables defined");
string dexFile = Path.Combine (Root, appb.ProjectDirectory, app.IntermediateOutputPath, "android", "bin", "classes.dex");
Assert.IsTrue (File.Exists (dexFile), $"dex file does not exist at {dexFile}");
Assert.IsTrue (DexUtils.ContainsClass ("Lmono/android/app/XamarinAndroidEnvironmentVariables;", dexFile, appb.AndroidSdkDirectory),
$"dex file {dexFile} does not contain the XamarinAndroidEnvironmentVariables class");
string monoDebugVar;
Assert.IsTrue (envvars.TryGetValue ("MONO_DEBUG", out monoDebugVar), "Environment should contain MONO_DEBUG");
Assert.IsFalse (String.IsNullOrEmpty (monoDebugVar), "Environment must contain MONO_DEBUG with a value");
Assert.IsTrue (monoDebugVar.IndexOf ("soft-breakpoints") >= 0, "Environment must contain MONO_DEBUG with 'soft-breakpoints' in its value");
if (!String.IsNullOrEmpty (sequencePointsMode))
Assert.IsTrue (monoDebugVar.IndexOf ("gen-compact-seq-points") >= 0, "The values from Mono.env should have been merged into environment");
EnvironmentHelper.AssertValidEnvironmentSharedLibrary (intermediateOutputDir, AndroidSdkPath, AndroidNdkPath, supportedAbis);
var assemblyDir = Path.Combine (Root, appb.ProjectDirectory, app.IntermediateOutputPath, "android", "assets");
var rp = new ReaderParameters { ReadSymbols = false };
@ -1841,29 +1852,32 @@ namespace App1
[Test]
public void CheckMonoDebugIsAddedToEnvironment ([Values ("", "Normal", "Offline")] string sequencePointsMode)
{
const string supportedAbis = "armeabi-v7a;x86";
var proj = new XamarinAndroidApplicationProject () {
IsRelease = true,
};
proj.SetProperty ("_AndroidSequencePointsMode", sequencePointsMode);
proj.SetProperty (proj.ReleaseProperties, KnownProperties.AndroidSupportedAbis, supportedAbis);
using (var b = CreateApkBuilder (Path.Combine ("temp", TestName))) {
b.Verbosity = LoggerVerbosity.Diagnostic;
Assert.IsTrue (b.Build (proj), "Build should have succeeded.");
string javaEnv = Path.Combine (Root, b.ProjectDirectory,
proj.IntermediateOutputPath, "android", "src", "mono", "android", "app", "XamarinAndroidEnvironmentVariables.java");
Assert.IsTrue (File.Exists (javaEnv), $"Java environment source does not exist at {javaEnv}");
string[] lines = File.ReadAllLines (javaEnv);
Assert.IsTrue (lines.Any (x =>
string.IsNullOrEmpty (sequencePointsMode)
? !x.Contains ("MONO_DEBUG")
: x.Contains ("MONO_DEBUG") && x.Contains ("gen-compact-seq-points")),
"environment {0} contain MONO_DEBUG=gen-compact-seq-points",
string.IsNullOrEmpty (sequencePointsMode) ? "should not" : "should");
string intermediateOutputDir = Path.Combine (Root, b.ProjectDirectory, proj.IntermediateOutputPath);
List<string> envFiles = EnvironmentHelper.GatherEnvironmentFiles (intermediateOutputDir, supportedAbis, true);
Dictionary<string, string> envvars = EnvironmentHelper.ReadEnvironmentVariables (envFiles);
Assert.IsTrue (envvars.Count > 0, $"No environment variables defined");
string dexFile = Path.Combine (Root, b.ProjectDirectory, proj.IntermediateOutputPath, "android", "bin", "classes.dex");
Assert.IsTrue (File.Exists (dexFile), $"dex file does not exist at {dexFile}");
Assert.IsTrue (DexUtils.ContainsClass ("Lmono/android/app/XamarinAndroidEnvironmentVariables;", dexFile, b.AndroidSdkDirectory),
$"dex file {dexFile} does not contain the XamarinAndroidEnvironmentVariables class");
string monoDebugVar;
bool monoDebugVarFound = envvars.TryGetValue ("MONO_DEBUG", out monoDebugVar);
if (String.IsNullOrEmpty (sequencePointsMode))
Assert.IsFalse (monoDebugVarFound, $"environment should not contain MONO_DEBUG={monoDebugVar}");
else {
Assert.IsTrue (monoDebugVarFound, "environment should contain MONO_DEBUG");
Assert.AreEqual ("gen-compact-seq-points", monoDebugVar, "environment should contain MONO_DEBUG=gen-compact-seq-points");
}
EnvironmentHelper.AssertValidEnvironmentSharedLibrary (intermediateOutputDir, AndroidSdkPath, AndroidNdkPath, supportedAbis);
}
}

Просмотреть файл

@ -46,6 +46,8 @@ namespace Xamarin.Android.Build.Tests
[Test]
public void CheckBuildIdIsUnique ()
{
const string supportedAbis = "armeabi-v7a;x86";
Dictionary<string, string> buildIds = new Dictionary<string, string> ();
var proj = new XamarinAndroidApplicationProject () {
IsRelease = true,
@ -54,7 +56,7 @@ namespace Xamarin.Android.Build.Tests
proj.SetProperty (proj.ReleaseProperties, "DebugSymbols", "true");
proj.SetProperty (proj.ReleaseProperties, "DebugType", "PdbOnly");
proj.SetProperty (proj.ReleaseProperties, KnownProperties.AndroidCreatePackagePerAbi, "true");
proj.SetProperty (proj.ReleaseProperties, KnownProperties.AndroidSupportedAbis, "armeabi-v7a;x86");
proj.SetProperty (proj.ReleaseProperties, KnownProperties.AndroidSupportedAbis, supportedAbis);
using (var b = CreateApkBuilder (Path.Combine ("temp", TestContext.CurrentContext.Test.Name))) {
b.Verbosity = Microsoft.Build.Framework.LoggerVerbosity.Diagnostic;
b.ThrowOnBuildFailure = false;
@ -67,27 +69,16 @@ namespace Xamarin.Android.Build.Tests
//NOTE: Windows is still generating mdb files here
extension = IsWindows ? "dll.mdb" : "pdb";
Assert.IsTrue (allFilesInArchive.Any (x => Path.GetFileName (x) == $"{proj.ProjectName}.{extension}"), $"{proj.ProjectName}.{extension} should exist in {archivePath}");
string javaEnv = Path.Combine (Root, b.ProjectDirectory,
proj.IntermediateOutputPath, "android", "src", "mono", "android", "app", "XamarinAndroidEnvironmentVariables.java");
Assert.IsTrue (File.Exists (javaEnv), $"Java environment source does not exist at {javaEnv}");
string[] lines = File.ReadAllLines (javaEnv);
string intermediateOutputDir = Path.Combine (Root, b.ProjectDirectory, proj.IntermediateOutputPath);
List<string> envFiles = EnvironmentHelper.GatherEnvironmentFiles (intermediateOutputDir, supportedAbis, true);
Dictionary<string, string> envvars = EnvironmentHelper.ReadEnvironmentVariables (envFiles);
Assert.IsTrue (envvars.Count > 0, $"No environment variables defined");
Assert.IsTrue (lines.Any (x => x.Contains ("\"XAMARIN_BUILD_ID\",")),
"The environment should contain a XAMARIN_BUILD_ID");
string buildID = lines.First (x => x.Contains ("\"XAMARIN_BUILD_ID\","))
.Trim ()
.Replace ("\", \"", "=")
.Replace ("\",", String.Empty)
.Replace ("\"", String.Empty);
string buildID;
Assert.IsTrue (envvars.TryGetValue ("XAMARIN_BUILD_ID", out buildID), "The environment should contain a XAMARIN_BUILD_ID");
buildIds.Add ("all", buildID);
string dexFile = Path.Combine (Root, b.ProjectDirectory, proj.IntermediateOutputPath, "android", "bin", "classes.dex");
Assert.IsTrue (File.Exists (dexFile), $"dex file does not exist at {dexFile}");
Assert.IsTrue (DexUtils.ContainsClass ("Lmono/android/app/XamarinAndroidEnvironmentVariables;", dexFile, b.AndroidSdkDirectory),
$"dex file {dexFile} does not contain the XamarinAndroidEnvironmentVariables class");
var msymDirectory = Path.Combine (Root, b.ProjectDirectory, proj.OutputPath, proj.PackageName + ".apk.mSYM");
Assert.IsTrue (File.Exists (Path.Combine (msymDirectory, "manifest.xml")), "manifest.xml should exist in", msymDirectory);
var doc = XDocument.Load (Path.Combine (msymDirectory, "manifest.xml"));
@ -98,7 +89,9 @@ namespace Xamarin.Android.Build.Tests
var buildId = buildIds.First ().Value;
Assert.IsTrue (doc.Element ("mono-debug")
.Elements ()
.Any (x => x.Name == "build-id" && x.Value == buildId.Replace ("XAMARIN_BUILD_ID=", "")), "build-id is has an incorrect value.");
.Any (x => x.Name == "build-id" && x.Value == buildId), "build-id is has an incorrect value.");
EnvironmentHelper.AssertValidEnvironmentSharedLibrary (intermediateOutputDir, AndroidSdkPath, AndroidNdkPath, supportedAbis);
}
}

Просмотреть файл

@ -63,10 +63,12 @@ namespace Xamarin.Android.Build.Tests
"lib/arm64-v8a/libmonodroid.so",
"lib/arm64-v8a/libmono-native.so",
"lib/arm64-v8a/libmonosgen-2.0.so",
"lib/arm64-v8a/libxamarin-app.so",
"lib/armeabi-v7a/libmono-btls-shared.so",
"lib/armeabi-v7a/libmonodroid.so",
"lib/armeabi-v7a/libmono-native.so",
"lib/armeabi-v7a/libmonosgen-2.0.so",
"lib/armeabi-v7a/libxamarin-app.so",
"manifest/AndroidManifest.xml",
"res/drawable-hdpi-v4/icon.png",
"res/drawable-mdpi-v4/icon.png",
@ -83,8 +85,6 @@ namespace Xamarin.Android.Build.Tests
"root/assemblies/System.Runtime.Serialization.dll",
"root/assemblies/UnnamedProject.dll",
"root/NOTICE",
"root/typemap.jm",
"root/typemap.mj",
//These are random files from Google Play Services .jar/.aar files
"root/build-data.properties",
"root/com/google/api/client/repackaged/org/apache/commons/codec/language/dmrules.txt",
@ -108,10 +108,12 @@ namespace Xamarin.Android.Build.Tests
"base/lib/arm64-v8a/libmonodroid.so",
"base/lib/arm64-v8a/libmono-native.so",
"base/lib/arm64-v8a/libmonosgen-2.0.so",
"base/lib/arm64-v8a/libxamarin-app.so",
"base/lib/armeabi-v7a/libmono-btls-shared.so",
"base/lib/armeabi-v7a/libmonodroid.so",
"base/lib/armeabi-v7a/libmono-native.so",
"base/lib/armeabi-v7a/libmonosgen-2.0.so",
"base/lib/armeabi-v7a/libxamarin-app.so",
"base/manifest/AndroidManifest.xml",
"base/native.pb",
"base/res/drawable-hdpi-v4/icon.png",
@ -129,8 +131,6 @@ namespace Xamarin.Android.Build.Tests
"base/root/assemblies/System.Runtime.Serialization.dll",
"base/root/assemblies/UnnamedProject.dll",
"base/root/NOTICE",
"base/root/typemap.jm",
"base/root/typemap.mj",
"BundleConfig.pb",
//These are random files from Google Play Services .jar/.aar files
"base/root/build-data.properties",

Просмотреть файл

@ -0,0 +1,458 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using NUnit.Framework;
using Xamarin.Android.Tasks;
using Xamarin.Android.Tools;
namespace Xamarin.Android.Build.Tests
{
class EnvironmentHelper
{
// This must be identical to the like-named structure in src/monodroid/jni/xamarin-app.h
public sealed class ApplicationConfig
{
public bool uses_mono_llvm;
public bool uses_mono_aot;
public bool uses_embedded_dsos;
public bool uses_assembly_preload;
public bool is_a_bundled_app;
public uint environment_variable_count;
public uint system_property_count;
public string android_package_name;
};
const uint ApplicationConfigFieldCount = 8;
static readonly object ndkInitLock = new object ();
static readonly char[] readElfFieldSeparator = new [] { ' ', '\t' };
static readonly Regex stringLabelRegex = new Regex ("^\\.L\\.str\\.[0-9]+:", RegexOptions.Compiled);
static readonly HashSet <string> expectedPointerTypes = new HashSet <string> (StringComparer.Ordinal) {
".long",
".quad",
".xword",
};
static readonly HashSet <string> expectedUInt32Types = new HashSet <string> (StringComparer.Ordinal) {
".word",
".long",
};
static readonly string[] requiredSharedLibrarySymbols = {
"app_environment_variables",
"app_system_properties",
"application_config",
"jm_typemap",
"jm_typemap_header",
"mj_typemap",
"mj_typemap_header",
"mono_aot_mode_name",
};
// Reads all the environment files, makes sure they all have identical contents in the
// `application_config` structure and returns the config if the condition is true
public static ApplicationConfig ReadApplicationConfig (List<string> envFilePaths)
{
if (envFilePaths.Count == 0)
return null;
ApplicationConfig app_config = ReadApplicationConfig (envFilePaths [0]);
for (int i = 1; i < envFilePaths.Count; i++) {
AssertApplicationConfigIsIdentical (app_config, envFilePaths [0], ReadApplicationConfig (envFilePaths[i]), envFilePaths[i]);
}
return app_config;
}
static ApplicationConfig ReadApplicationConfig (string envFile)
{
string[] lines = File.ReadAllLines (envFile, Encoding.UTF8);
var strings = new Dictionary<string, string> (StringComparer.Ordinal);
var pointers = new List <string> ();
var ret = new ApplicationConfig ();
bool gatherFields = false;
uint fieldCount = 0;
for (int i = 0; i < lines.Length; i++) {
string line = lines [i];
if (IsCommentLine (line))
continue;
string[] field;
if (stringLabelRegex.IsMatch (line)) {
string label = line.Substring (0, line.Length - 1);
line = lines [++i];
field = GetField (envFile, line, i);
AssertFieldType (envFile, ".asciz", field [0], i);
strings [label] = AssertIsAssemblerString (envFile, field [1], i);
continue;
}
if (String.Compare ("application_config:", line.Trim (), StringComparison.Ordinal) == 0) {
gatherFields = true;
continue;
}
if (!gatherFields)
continue;
field = GetField (envFile, line, i);
if (String.Compare (".zero", field [0], StringComparison.Ordinal) == 0)
continue; // structure padding
switch (fieldCount) {
case 0: // uses_mono_llvm: bool / .byte
AssertFieldType (envFile, ".byte", field [0], i);
ret.uses_mono_llvm = ConvertFieldToBool ("uses_mono_llvm", envFile, i, field [1]);
break;
case 1: // uses_mono_aot: bool / .byte
AssertFieldType (envFile, ".byte", field [0], i);
ret.uses_mono_aot = ConvertFieldToBool ("uses_mono_aot", envFile, i, field [1]);
break;
case 2: // uses_embedded_dsos: bool / .byte
AssertFieldType (envFile, ".byte", field [0], i);
ret.uses_embedded_dsos = ConvertFieldToBool ("uses_embedded_dsos", envFile, i, field [1]);
break;
case 3: // uses_assembly_preload: bool / .byte
AssertFieldType (envFile, ".byte", field [0], i);
ret.uses_assembly_preload = ConvertFieldToBool ("uses_assembly_preload", envFile, i, field [1]);
break;
case 4: // is_a_bundled_app: bool / .byte
AssertFieldType (envFile, ".byte", field [0], i);
ret.is_a_bundled_app = ConvertFieldToBool ("is_a_bundled_app", envFile, i, field [1]);
break;
case 5: // environment_variable_count: uint32_t / .word | .long
Assert.IsTrue (expectedUInt32Types.Contains (field [0]), $"Unexpected uint32_t field type in '{envFile}:{i}': {field [0]}");
ret.environment_variable_count = ConvertFieldToUInt32 ("environment_variable_count", envFile, i, field [1]);
break;
case 6: // system_property_count: uint32_t / .word | .long
Assert.IsTrue (expectedUInt32Types.Contains (field [0]), $"Unexpected uint32_t field type in '{envFile}:{i}': {field [0]}");
ret.system_property_count = ConvertFieldToUInt32 ("system_property_count", envFile, i, field [1]);
break;
case 7: // android_package_name: string / [pointer type]
Assert.IsTrue (expectedPointerTypes.Contains (field [0]), $"Unexpected pointer field type in '{envFile}:{i}': {field [0]}");
pointers.Add (field [1].Trim ());
break;
}
fieldCount++;
if (String.Compare (".size", field [0], StringComparison.Ordinal) == 0) {
fieldCount--;
Assert.IsTrue (field [1].StartsWith ("application_config", StringComparison.Ordinal), $"Mismatched .size directive in '{envFile}:{i}'");
break; // We've reached the end of the application_config structure
}
}
Assert.AreEqual (ApplicationConfigFieldCount, fieldCount, $"Invalid 'application_config' field count in environment file '{envFile}'");
Assert.AreEqual (1, pointers.Count, $"Invalid number of string pointers in 'application_config' structure in environment file '{envFile}'");
Assert.IsTrue (strings.TryGetValue (pointers [0], out ret.android_package_name), $"Invalid package name string pointer in 'application_config' structure in environment file '{envFile}'");
Assert.IsFalse (String.IsNullOrEmpty (ret.android_package_name), $"Package name field in 'application_config' in environment file '{envFile}' must not be null or empty");
return ret;
}
// Reads all the environment files, makes sure they contain the same environment variables (both count
// and contents) and then returns a dictionary filled with the variables.
public static Dictionary<string, string> ReadEnvironmentVariables (List<string> envFilePaths)
{
if (envFilePaths.Count == 0)
return null;
Dictionary<string, string> envvars = ReadEnvironmentVariables (envFilePaths [0]);
if (envFilePaths.Count == 1)
return envvars;
for (int i = 1; i < envFilePaths.Count; i++) {
AssertDictionariesAreEqual (envvars, envFilePaths [0], ReadEnvironmentVariables (envFilePaths[i]), envFilePaths[i]);
}
return envvars;
}
static Dictionary<string, string> ReadEnvironmentVariables (string envFile)
{
string[] lines = File.ReadAllLines (envFile, Encoding.UTF8);
var strings = new Dictionary<string, string> (StringComparer.Ordinal);
var pointers = new List <string> ();
bool gatherPointers = false;
for (int i = 0; i < lines.Length; i++) {
string line = lines [i];
if (IsCommentLine (line))
continue;
string[] field;
if (stringLabelRegex.IsMatch (line)) {
string label = line.Substring (0, line.Length - 1);
line = lines [++i];
field = GetField (envFile, line, i);
AssertFieldType (envFile, ".asciz", field [0], i);
strings [label] = AssertIsAssemblerString (envFile, field [1], i);
continue;
}
if (String.Compare ("app_environment_variables:", line.Trim (), StringComparison.Ordinal) == 0) {
gatherPointers = true;
continue;
}
if (!gatherPointers)
continue;
field = GetField (envFile, line, i);
if (String.Compare (".size", field [0], StringComparison.Ordinal) == 0) {
Assert.IsTrue (field [1].StartsWith ("app_environment_variables", StringComparison.Ordinal), $"Mismatched .size directive in '{envFile}:{i}'");
break; // We've reached the end of the environment variable array
}
Assert.IsTrue (expectedPointerTypes.Contains (field [0]), $"Unexpected pointer field type in '{envFile}:{i}': {field [0]}");
pointers.Add (field [1].Trim ());
}
var ret = new Dictionary <string, string> (StringComparer.Ordinal);
if (pointers.Count == 0)
return ret;
Assert.IsTrue (pointers.Count % 2 == 0, "Environment variable array must have an even number of elements");
for (int i = 0; i < pointers.Count; i += 2) {
string name;
Assert.IsTrue (strings.TryGetValue (pointers [i], out name), $"[name] String with label '{pointers [i]}' not found in '{envFile}'");
Assert.IsFalse (String.IsNullOrEmpty (name), $"Environment variable name must not be null or empty in {envFile} for string label '{pointers [i]}'");
string value;
Assert.IsTrue (strings.TryGetValue (pointers [i + 1], out value), $"[value] String with label '{pointers [i + 1]}' not found in '{envFile}'");
Assert.IsNotNull (value, $"Environnment variable value must not be null in '{envFile}' for string label '{pointers [i + 1]}'");
ret [name] = value;
}
return ret;
}
static bool IsCommentLine (string line)
{
string l = line?.Trim ();
return !String.IsNullOrEmpty (l) && l.StartsWith ("/*", StringComparison.Ordinal);
}
static string[] GetField (string file, string line, int lineNumber)
{
string[] ret = line?.Trim ()?.Split ('\t');
Assert.AreEqual (2, ret.Length, $"Invalid assembler field format in file '{file}:{lineNumber}': '{line}'");
return ret;
}
static void AssertFieldType (string file, string expectedType, string value, int lineNumber)
{
Assert.AreEqual (expectedType, value, $"Expected the '{expectedType}' field type in file '{file}:{lineNumber}': {value}");
}
static string AssertIsAssemblerString (string file, string value, int lineNumber)
{
string v = value.Trim ();
Assert.IsTrue (v.StartsWith ("\"") && v.EndsWith("\""), $"Field value is not a valid assembler string in '{file}:{lineNumber}': {v}");
return v.Trim ('"');
}
static void AssertDictionariesAreEqual (Dictionary <string, string> d1, string d1FileName, Dictionary <string, string> d2, string d2FileName)
{
Assert.AreEqual (d1.Count, d2.Count, $"File '{d2FileName}' has a different number of environment variables than file '{d2FileName}'");
foreach (var kvp in d1) {
string value;
Assert.IsTrue (d2.TryGetValue (kvp.Key, out value), $"File '{d2FileName}' does not contain environment variable '{kvp.Key}'");
Assert.AreEqual (kvp.Value, value, $"Value of environnment variable '{kvp.Key}' is different in file '{d2FileName}' than in file '{d1FileName}'");
}
}
static void AssertApplicationConfigIsIdentical (ApplicationConfig firstAppConfig, string firstEnvFile, ApplicationConfig secondAppConfig, string secondEnvFile)
{
Assert.AreEqual (firstAppConfig.uses_mono_llvm, secondAppConfig.uses_mono_llvm, $"Field 'uses_mono_llvm' has different value in environment file '{secondEnvFile}' than in environment file '{firstEnvFile}'");
Assert.AreEqual (firstAppConfig.uses_mono_aot, secondAppConfig.uses_mono_aot, $"Field 'uses_mono_aot' has different value in environment file '{secondEnvFile}' than in environment file '{firstEnvFile}'");
Assert.AreEqual (firstAppConfig.uses_embedded_dsos, secondAppConfig.uses_embedded_dsos, $"Field 'uses_embedded_dsos' has different value in environment file '{secondEnvFile}' than in environment file '{firstEnvFile}'");
Assert.AreEqual (firstAppConfig.is_a_bundled_app, secondAppConfig.is_a_bundled_app, $"Field 'is_a_bundled_app' has different value in environment file '{secondEnvFile}' than in environment file '{firstEnvFile}'");
Assert.AreEqual (firstAppConfig.environment_variable_count, secondAppConfig.environment_variable_count, $"Field 'environment_variable_count' has different value in environment file '{secondEnvFile}' than in environment file '{firstEnvFile}'");
Assert.AreEqual (firstAppConfig.system_property_count, secondAppConfig.system_property_count, $"Field 'system_property_count' has different value in environment file '{secondEnvFile}' than in environment file '{firstEnvFile}'");
Assert.AreEqual (firstAppConfig.android_package_name, secondAppConfig.android_package_name, $"Field 'android_package_name' has different value in environment file '{secondEnvFile}' than in environment file '{firstEnvFile}'");
}
public static List<string> GatherEnvironmentFiles (string outputDirectoryRoot, string supportedAbis, bool required)
{
var environmentFiles = new List <string> ();
foreach (string abi in supportedAbis.Split (';')) {
string envFilePath = Path.Combine (outputDirectoryRoot, "android", $"environment.{abi}.s");
Assert.IsTrue (File.Exists (envFilePath), $"Environment file {envFilePath} does not exist");
environmentFiles.Add (envFilePath);
}
if (required)
Assert.AreNotEqual (0, environmentFiles.Count, "No environment files found");
return environmentFiles;
}
public static void AssertValidEnvironmentSharedLibrary (string outputDirectoryRoot, string sdkDirectory, string ndkDirectory, string supportedAbis)
{
NdkUtil.Init (ndkDirectory);
MonoAndroidHelper.AndroidSdk = new AndroidSdkInfo ((arg1, arg2) => {}, sdkDirectory, ndkDirectory);
AndroidTargetArch arch;
foreach (string abi in supportedAbis.Split (';')) {
switch (abi) {
case "armeabi-v7a":
arch = AndroidTargetArch.Arm;
break;
case "arm64":
case "arm64-v8a":
case "aarch64":
arch = AndroidTargetArch.Arm64;
break;
case "x86":
arch = AndroidTargetArch.X86;
break;
case "x86_64":
arch = AndroidTargetArch.X86_64;
break;
default:
throw new Exception ("Unsupported Android target architecture ABI: " + abi);
}
string envSharedLibrary = Path.Combine (outputDirectoryRoot, "app_shared_libraries", abi, "libxamarin-app.so");
Assert.IsTrue (File.Exists (envSharedLibrary), $"Application environment SharedLibrary '{envSharedLibrary}' must exist");
// API level doesn't matter in this case
AssertSharedLibraryHasRequiredSymbols (envSharedLibrary, NdkUtil.GetNdkTool (ndkDirectory, arch, "readelf", 0));
}
}
static void AssertSharedLibraryHasRequiredSymbols (string dsoPath, string readElfPath)
{
var psi = new ProcessStartInfo {
FileName = readElfPath,
Arguments = $"--dyn-syms \"{dsoPath}\"",
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden,
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardOutput = true,
};
psi.StandardOutputEncoding = Encoding.UTF8;
psi.StandardErrorEncoding = Encoding.UTF8;
var stdout_completed = new ManualResetEventSlim (false);
var stderr_completed = new ManualResetEventSlim (false);
var stdout_lines = new List <string> ();
var stderr_lines = new List <string> ();
using (var process = new Process ()) {
process.StartInfo = psi;
process.OutputDataReceived += (s, e) => {
if (e.Data != null)
stdout_lines.Add (e.Data);
else
stdout_completed.Set ();
};
process.ErrorDataReceived += (s, e) => {
if (e.Data != null)
stderr_lines.Add (e.Data);
else
stderr_completed.Set ();
};
process.Start ();
process.BeginOutputReadLine ();
process.BeginErrorReadLine ();
bool exited = process.WaitForExit ((int)TimeSpan.FromSeconds (60).TotalMilliseconds);
bool stdout_done = stdout_completed.Wait (TimeSpan.FromSeconds (30));
bool stderr_done = stderr_completed.Wait (TimeSpan.FromSeconds (30));
if (!exited)
TestContext.Out.WriteLine ($"{psi.FileName} {psi.Arguments} timed out");
if (process.ExitCode != 0)
TestContext.Out.WriteLine ($"{psi.FileName} {psi.Arguments} returned with error code {process.ExitCode}");
if (!exited || process.ExitCode != 0) {
DumpLines ("stdout", stdout_lines);
DumpLines ("stderr", stderr_lines);
Assert.Fail ($"Failed to validate application environment SharedLibrary '{dsoPath}'");
}
}
var symbols = new HashSet<string> (StringComparer.Ordinal);
foreach (string line in stdout_lines) {
string[] fields = line.Split (readElfFieldSeparator, StringSplitOptions.RemoveEmptyEntries);
if (fields.Length < 8 || !fields [0].EndsWith (":", StringComparison.Ordinal))
continue;
string symbolName = fields [7].Trim ();
if (String.IsNullOrEmpty (symbolName))
continue;
symbols.Add (symbolName);
}
foreach (string symbol in requiredSharedLibrarySymbols) {
Assert.IsTrue (symbols.Contains (symbol), $"Symbol '{symbol}' is missing from '{dsoPath}'");
}
}
static void DumpLines (string streamName, List <string> lines)
{
if (lines == null || lines.Count == 0)
return;
TestContext.Out.WriteLine ($"{streamName}:");
foreach (string line in lines) {
TestContext.Out.WriteLine (line);
}
}
static bool ConvertFieldToBool (string fieldName, string envFile, int fileLine, string value)
{
Assert.AreEqual (1, value.Length, $"Field '{fieldName}' in {envFile}:{fileLine} is not a valid boolean value (too long)");
uint fv;
Assert.IsTrue (UInt32.TryParse (value, out fv), $"Field '{fieldName}' in {envFile}:{fileLine} is not a valid boolean value (not a valid integer)");
Assert.IsTrue (fv == 0 || fv == 1, $"Field '{fieldName}' in {envFile}:{fileLine} is not a valid boolean value (not a valid boolean value 0 or 1)");
return fv == 1;
}
static uint ConvertFieldToUInt32 (string fieldName, string envFile, int fileLine, string value)
{
Assert.IsTrue (value.Length > 0, $"Field '{fieldName}' in {envFile}:{fileLine} is not a valid uint32_t value (not long enough)");
uint fv;
Assert.IsTrue (UInt32.TryParse (value, out fv), $"Field '{fieldName}' in {envFile}:{fileLine} is not a valid uint32_t value (not a valid integer)");
return fv;
}
}
}

Просмотреть файл

@ -29,5 +29,6 @@
<Compile Include="$(MSBuildThisFileDirectory)Utilities\FilesTests.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\MockBuildEngine.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\MonoAndroidHelperTests.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\EnvironmentHelper.cs" />
</ItemGroup>
</Project>

Просмотреть файл

@ -0,0 +1,57 @@
using System;
using System.IO;
namespace Xamarin.Android.Tasks
{
class ARMNativeAssemblerTargetProvider : NativeAssemblerTargetProvider
{
public override bool Is64Bit { get; }
public override string PointerFieldType { get; }
public override string TypePrefix { get; }
public ARMNativeAssemblerTargetProvider (bool is64Bit)
{
Is64Bit = is64Bit;
PointerFieldType = is64Bit ? ".xword" : ".long";
TypePrefix = is64Bit ? "@" : "%";
}
public override string MapType <T> ()
{
if (typeof(T) == typeof(Int32) || typeof(T) == typeof(UInt32))
return Is64Bit ? ".word" : ".long";
return base.MapType <T> ();
}
public override void WriteFileHeader (StreamWriter output, string indent)
{
output.Write ($"{indent}.arch{indent}");
output.WriteLine (Is64Bit ? "armv8-a" : "armv7-a");
if (!Is64Bit) {
output.WriteLine ($"{indent}.syntax unified");
output.WriteLine ($"{indent}.eabi_attribute 67, \"2.09\"{indent}@ Tag_conformance");
output.WriteLine ($"{indent}.eabi_attribute 6, 10{indent}@ Tag_CPU_arch");
output.WriteLine ($"{indent}.eabi_attribute 7, 65{indent}@ Tag_CPU_arch_profile");
output.WriteLine ($"{indent}.eabi_attribute 8, 1{indent}@ Tag_ARM_ISA_use");
output.WriteLine ($"{indent}.eabi_attribute 9, 2{indent}@ Tag_THUMB_ISA_use");
output.WriteLine ($"{indent}.fpu{indent}vfpv3-d16");
output.WriteLine ($"{indent}.eabi_attribute 34, 1{indent}@ Tag_CPU_unaligned_access");
output.WriteLine ($"{indent}.eabi_attribute 15, 1{indent}@ Tag_ABI_PCS_RW_data");
output.WriteLine ($"{indent}.eabi_attribute 16, 1{indent}@ Tag_ABI_PCS_RO_data");
output.WriteLine ($"{indent}.eabi_attribute 17, 2{indent}@ Tag_ABI_PCS_GOT_use");
output.WriteLine ($"{indent}.eabi_attribute 20, 2{indent}@ Tag_ABI_FP_denormal");
output.WriteLine ($"{indent}.eabi_attribute 21, 0{indent}@ Tag_ABI_FP_exceptions");
output.WriteLine ($"{indent}.eabi_attribute 23, 3{indent}@ Tag_ABI_FP_number_model");
output.WriteLine ($"{indent}.eabi_attribute 24, 1{indent}@ Tag_ABI_align_needed");
output.WriteLine ($"{indent}.eabi_attribute 25, 1{indent}@ Tag_ABI_align_preserved");
output.WriteLine ($"{indent}.eabi_attribute 38, 1{indent}@ Tag_ABI_FP_16bit_format");
output.WriteLine ($"{indent}.eabi_attribute 18, 4{indent}@ Tag_ABI_PCS_wchar_t");
output.WriteLine ($"{indent}.eabi_attribute 26, 2{indent}@ Tag_ABI_enum_size");
output.WriteLine ($"{indent}.eabi_attribute 14, 0{indent}@ Tag_ABI_PCS_R9_use");
}
base.WriteFileHeader (output, indent);
}
}
}

Просмотреть файл

@ -0,0 +1,126 @@
using System;
using System.Collections.Generic;
using System.IO;
namespace Xamarin.Android.Tasks
{
class ApplicationConfigNativeAssemblyGenerator : NativeAssemblyGenerator
{
SortedDictionary <string, string> environmentVariables;
SortedDictionary <string, string> systemProperties;
uint stringCounter = 0;
public bool IsBundledApp { get; set; }
public bool UsesEmbeddedDSOs { get; set; }
public bool UsesMonoAOT { get; set; }
public bool UsesMonoLLVM { get; set; }
public bool UsesAssemblyPreload { get; set; }
public string MonoAOTMode { get; set; }
public string AndroidPackageName { get; set; }
public ApplicationConfigNativeAssemblyGenerator (NativeAssemblerTargetProvider targetProvider, IDictionary<string, string> environmentVariables, IDictionary<string, string> systemProperties)
: base (targetProvider)
{
if (environmentVariables != null)
this.environmentVariables = new SortedDictionary<string, string> (environmentVariables, StringComparer.Ordinal);
if (systemProperties != null)
this.systemProperties = new SortedDictionary<string, string> (systemProperties, StringComparer.Ordinal);
}
protected override void WriteSymbols (StreamWriter output)
{
if (String.IsNullOrEmpty (AndroidPackageName))
throw new InvalidOperationException ("Android package name must be set");
if (UsesMonoAOT && String.IsNullOrEmpty (MonoAOTMode))
throw new InvalidOperationException ("Mono AOT enabled but no AOT mode specified");
string stringLabel = GetStringLabel ();
WriteData (output, AndroidPackageName, stringLabel);
WriteDataSection (output, "application_config");
WriteSymbol (output, "application_config", TargetProvider.GetStructureAlignment (true), fieldAlignBytes: 4, isGlobal: true, alwaysWriteSize: true, structureWriter: () => {
// Order of fields and their type must correspond *exactly* to that in
// src/monodroid/jni/xamarin-app.h ApplicationConfig structure
WriteCommentLine (output, "uses_mono_llvm");
uint size = WriteData (output, UsesMonoLLVM);
WriteCommentLine (output, "uses_mono_aot");
size += WriteData (output, UsesMonoAOT);
WriteCommentLine (output, "uses_embedded_dsos");
size += WriteData (output, UsesEmbeddedDSOs);
WriteCommentLine (output, "uses_assembly_preload");
size += WriteData (output, UsesAssemblyPreload);
WriteCommentLine (output, "is_a_bundled_app");
size += WriteData (output, IsBundledApp);
WriteCommentLine (output, "environment_variable_count");
size += WriteData (output, environmentVariables == null ? 0 : environmentVariables.Count * 2);
WriteCommentLine (output, "system_property_count");
size += WriteData (output, systemProperties == null ? 0 : systemProperties.Count * 2);
WriteCommentLine (output, "android_package_name");
size += WritePointer (output, stringLabel);
return size;
});
stringLabel = GetStringLabel ();
WriteData (output, MonoAOTMode ?? String.Empty, stringLabel);
WriteDataSection (output, "mono_aot_mode_name");
WritePointer (output, stringLabel, "mono_aot_mode_name", isGlobal: true);
WriteNameValueStringArray (output, "app_environment_variables", environmentVariables);
WriteNameValueStringArray (output, "app_system_properties", systemProperties);
}
void WriteNameValueStringArray (StreamWriter output, string label, SortedDictionary<string, string> entries)
{
if (entries == null || entries.Count == 0) {
WriteDataSection (output, label);
WriteSymbol (output, label, TargetProvider.GetStructureAlignment (true), fieldAlignBytes: 4, isGlobal: true, alwaysWriteSize: true, structureWriter: null);
return;
}
var entry_labels = new List <string> ();
foreach (var kvp in entries) {
string name = kvp.Key;
string value = kvp.Value ?? String.Empty;
string stringLabel = GetStringLabel ();
WriteData (output, name, stringLabel);
entry_labels.Add (stringLabel);
stringLabel = GetStringLabel ();
WriteData (output, value, stringLabel);
entry_labels.Add (stringLabel);
}
WriteDataSection (output, label);
WriteSymbol (output, label, TargetProvider.GetStructureAlignment (true), fieldAlignBytes: 4, isGlobal: true, alwaysWriteSize: true, structureWriter: () => {
uint size = 0;
foreach (string l in entry_labels) {
size += WritePointer (output, l);
}
return size;
});
}
void WriteDataSection (StreamWriter output, string tag)
{
WriteSection (output, $".data.{tag}", hasStrings: false, writable: true);
}
string GetStringLabel ()
{
stringCounter++;
return $".L.str.{stringCounter}";
}
};
}

Просмотреть файл

@ -0,0 +1,65 @@
using System;
using System.IO;
namespace Xamarin.Android.Tasks
{
abstract class NativeAssemblerTargetProvider
{
public abstract bool Is64Bit { get; }
public abstract string PointerFieldType { get; }
public abstract string TypePrefix { get; }
public virtual string MapType <T> ()
{
if (typeof(T) == typeof(byte))
return ".byte";
if (typeof(T) == typeof(bool))
return ".byte";
if (typeof(T) == typeof(string))
return ".asciz";
throw new InvalidOperationException ($"Unable to map managed type {typeof(T)} to native assembly type");
}
public virtual uint GetTypeSize <T> (T field)
{
return GetTypeSize <T> ();
}
public virtual uint GetTypeSize <T> ()
{
if (typeof(T) == typeof(byte))
return 1u;
if (typeof(T) == typeof(bool))
return 1u;
if (typeof(T) == typeof(string))
return GetPointerSize();
if (typeof(T) == typeof(Int32) || typeof(T) == typeof(UInt32))
return 4u;
if (typeof(T) == typeof(Int64) || typeof(T) == typeof(UInt64))
return 8u;
throw new InvalidOperationException ($"Unable to map managed type {typeof(T)} to native assembly type");
}
public virtual uint GetStructureAlignment (bool hasPointers)
{
return (!hasPointers || !Is64Bit) ? 2u : 3u;
}
public virtual uint GetPointerSize ()
{
return Is64Bit ? 8u : 4u;
}
public virtual void WriteFileHeader (StreamWriter output, string indent)
{
}
}
}

Просмотреть файл

@ -0,0 +1,220 @@
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.IO;
using System.Text;
namespace Xamarin.Android.Tasks
{
class NativeAssemblyDataStream : Stream
{
const uint MapVersionFound = 0x0001;
const uint MapEntryCountFound = 0x0002;
const uint MapEntryLengthFound = 0x0004;
const uint MapValueOffsetFound = 0x0008;
const uint MapEverythingFound = MapVersionFound | MapEntryCountFound | MapEntryLengthFound | MapValueOffsetFound;
const string MapFieldVersion = "version";
const string MapFieldEntryCount = "entry-count";
const string MapFieldEntryLength = "entry-len";
const string MapFieldValueOffset = "value-offset";
const uint MaxFieldsInRow = 32;
MemoryStream outputStream;
StreamWriter outputWriter;
bool firstWrite = true;
uint rowFieldCounter;
SHA1CryptoServiceProvider sha1;
bool hashingFinished;
uint byteCount = 0;
public int MapVersion { get; set; } = -1;
public int MapEntryCount { get; set; } = -1;
public int MapEntryLength { get; set; } = -1;
public int MapValueOffset { get; set; } = -1;
public uint MapByteCount => byteCount;
public override bool CanRead => outputStream.CanRead;
public override bool CanSeek => outputStream.CanSeek;
public override bool CanWrite => outputStream.CanWrite;
public override long Length => outputStream.Length;
public override long Position {
get => outputStream.Position;
set => outputStream.Position = value;
}
public NativeAssemblyDataStream ()
{
outputStream = new MemoryStream ();
outputWriter = new StreamWriter (outputStream, new UTF8Encoding (false));
sha1 = new SHA1CryptoServiceProvider ();
sha1.Initialize ();
}
public byte[] GetStreamHash ()
{
if (!hashingFinished) {
sha1.TransformFinalBlock (new byte[0], 0, 0);
hashingFinished = true;
}
return sha1.Hash;
}
protected override void Dispose (bool disposing)
{
base.Dispose (disposing);
if (!disposing)
return;
outputWriter.Dispose ();
outputWriter = null;
outputStream = null;
}
public override void Flush ()
{
outputWriter.Flush ();
outputStream.Flush ();
}
public override int Read (byte[] buffer, int offset, int count)
{
return outputStream.Read (buffer, offset, count);
}
public override long Seek (long offset, SeekOrigin origin)
{
return outputStream.Seek (offset, origin);
}
public override void SetLength (long value)
{
outputStream.SetLength (value);
}
public override void Write (byte[] buffer, int offset, int count)
{
if (buffer == null)
throw new ArgumentNullException (nameof (buffer));
if (offset < 0)
throw new ArgumentOutOfRangeException (nameof (offset));
if (count < 0)
throw new ArgumentOutOfRangeException (nameof (count));
if (offset + count > buffer.Length)
throw new ArgumentException ($"The sum of the '{nameof (offset)}' and '{nameof (count)}' arguments is greater than the buffer length");
if (outputWriter == null)
throw new ObjectDisposedException (this.GetType ().Name);
if (!hashingFinished)
sha1.TransformBlock (buffer, offset, count, null, 0);
if (firstWrite) {
// Kind of a backward thing to do, but I wanted to avoid having to modfy (and bump the
// submodule of) Java.Interop. This should be Safe Enough™ (until it's not)
string line = Encoding.UTF8.GetString (buffer, offset, count);
// Format used by Java.Interop.Tools.JavaCallableWrappers.TypeNameMapGenerator:
//
// "version=1\u0000entry-count={0}\u0000entry-len={1}\u0000value-offset={2}\u0000"
//
string[] parts = line.Split ('\u0000');
if (parts.Length != 5)
HeaderFormatError ("invalid number of fields");
// Let's be just slightly flexible :P
uint foundMask = 0;
foreach (string p in parts) {
string field = p.Trim ();
if (String.IsNullOrEmpty (field))
continue;
string[] fieldParts = field.Split(new char[]{'='}, 2);
if (fieldParts.Length != 2)
HeaderFormatError ($"invalid field format '{field}'");
switch (fieldParts [0]) {
case MapFieldVersion:
foundMask |= MapVersionFound;
MapVersion = GetHeaderInteger (fieldParts[0], fieldParts [1]);
break;
case MapFieldEntryCount:
foundMask |= MapEntryCountFound;
MapEntryCount = GetHeaderInteger (fieldParts[0], fieldParts [1]);
break;
case MapFieldEntryLength:
foundMask |= MapEntryLengthFound;
MapEntryLength = GetHeaderInteger (fieldParts[0], fieldParts [1]);
break;
case MapFieldValueOffset:
foundMask |= MapValueOffsetFound;
MapValueOffset = GetHeaderInteger (fieldParts[0], fieldParts [1]);
break;
default:
HeaderFormatError ($"unknown field '{fieldParts [0]}'");
break;
}
}
if (foundMask != MapEverythingFound) {
var missingFields = new List <string> ();
if ((foundMask & MapVersionFound) == 0)
missingFields.Add (MapFieldVersion);
if ((foundMask & MapEntryCountFound) == 0)
missingFields.Add (MapFieldEntryCount);
if ((foundMask & MapEntryLengthFound) == 0)
missingFields.Add (MapFieldEntryLength);
if ((foundMask & MapValueOffsetFound) == 0)
missingFields.Add (MapFieldValueOffset);
var sb = new StringBuilder ("missing header field");
if (missingFields.Count > 1)
sb.Append ('s');
sb.Append (": ");
sb.Append (String.Join (", ", missingFields));
HeaderFormatError (sb.ToString ());
}
firstWrite = false;
rowFieldCounter = 0;
return;
}
for (int i = 0; i < count; i++) {
byteCount++;
if (rowFieldCounter == 0)
outputWriter.Write ("\t.byte ");
byte b = buffer [offset + i];
if (rowFieldCounter > 0)
outputWriter.Write (", ");
outputWriter.Write ($"0x{b:x02}");
rowFieldCounter++;
if (rowFieldCounter > MaxFieldsInRow) {
rowFieldCounter = 0;
outputWriter.WriteLine ();
}
}
void HeaderFormatError (string whatsWrong)
{
throw new InvalidOperationException ($"Java.Interop.Tools.JavaCallableWrappers.TypeNameMapGenerator header format changed: {whatsWrong}");
}
int GetHeaderInteger (string name, string value)
{
int ret;
if (!Int32.TryParse (value, out ret))
HeaderFormatError ($"failed to parse integer value from '{value}' for field '{name}'");
return ret;
}
}
};
}

Просмотреть файл

@ -0,0 +1,239 @@
using System;
using System.IO;
using System.Text;
namespace Xamarin.Android.Tasks
{
abstract class NativeAssemblyGenerator
{
uint structureByteCount;
uint structureAlignBytes;
bool writingStructure = false;
protected string Indent { get; } = "\t";
protected NativeAssemblerTargetProvider TargetProvider { get; }
protected NativeAssemblyGenerator (NativeAssemblerTargetProvider targetProvider)
{
if (targetProvider == null)
throw new ArgumentNullException (nameof (targetProvider));
TargetProvider = targetProvider;
}
public void Write (StreamWriter output, string outputFileName)
{
if (output == null)
throw new ArgumentNullException (nameof (output));
WriteFileHeader (output, outputFileName);
WriteSymbols (output);
output.Flush ();
}
protected virtual void WriteSymbols (StreamWriter output)
{
}
protected string HashToHex (byte[] dataHash)
{
var sb = new StringBuilder ();
foreach (byte b in dataHash)
sb.Append ($"{b:x02}");
return sb.ToString ();
}
protected void WriteEndLine (StreamWriter output, string comment = null, bool indent = true)
{
if (!String.IsNullOrEmpty (comment)) {
if (indent)
output.Write (Indent);
WriteComment (output, comment);
}
output.WriteLine ();
}
protected void WriteComment (StreamWriter output, string comment, bool indent = true)
{
output.Write ($"{(indent ? Indent : String.Empty)}/* {comment} */");
}
protected void WriteCommentLine (StreamWriter output, string comment, bool indent = true)
{
WriteComment (output, comment);
output.WriteLine ();
}
protected virtual void WriteFileHeader (StreamWriter output, string outputFileName)
{
TargetProvider.WriteFileHeader (output, Indent);
output.WriteLine ($"{Indent}.file{Indent}\"{Path.GetFileName (outputFileName)}\"");
}
protected virtual void WriteSection (StreamWriter output, string sectionName, bool hasStrings, bool writable)
{
output.Write ($"{Indent}.section{Indent}{sectionName},\"a"); // a - section is allocatable
if (hasStrings)
output.Write ("MS"); // M - section is mergeable, S - section contains zero-terminated strings
else if (writable)
output.Write ("w");
output.Write ($"\",{TargetProvider.TypePrefix}progbits");
if (hasStrings)
output.Write (",1");
output.WriteLine ();
}
// `alignBits` indicates the number of lowest bits that have to be cleared to 0 in order to align the
// following data structure, thus `2` would mean "align to 4 bytes", `3' would be "align to 8 bytes"
// etc. In general, if the data field contains a pointer the alignment should be to the platform's
// native pointer size, if not it should be 2 (for 4-byte alignment) in the case of the targets we
// support. Alignment is not necessary for standalone fields (i.e. not parts of a structure)
protected void WriteSymbol <T> (StreamWriter output, T symbolValue, string symbolName, ulong size, uint alignBits, bool isGlobal, bool isObject, bool alwaysWriteSize)
{
WriteSymbol (output, TargetProvider.MapType<T>(), QuoteValue (symbolValue), symbolName, size, alignBits, isGlobal, isObject, alwaysWriteSize);
}
protected void WriteSymbol (StreamWriter output, string symbolType, string symbolValue, string symbolName, ulong size, uint alignBits, bool isGlobal, bool isObject, bool alwaysWriteSize)
{
if (isObject)
output.WriteLine ($"{Indent}.type{Indent}{symbolName}, {TargetProvider.TypePrefix}object");
if (alignBits > 0)
output.WriteLine ($"{Indent}.p2align{Indent}{alignBits}");
if (isGlobal)
output.WriteLine ($"{Indent}.global{Indent}{symbolName}");
if (!String.IsNullOrEmpty (symbolName))
output.WriteLine ($"{symbolName}:");
if (!String.IsNullOrEmpty (symbolType) && !String.IsNullOrEmpty (symbolValue))
output.WriteLine ($"{Indent}{symbolType}{Indent}{symbolValue}");
if (alwaysWriteSize || size > 0)
output.WriteLine ($"{Indent}.size{Indent}{symbolName}, {size}");
}
protected void WriteSymbol (StreamWriter output, string label, uint size, bool isGlobal, bool isObject, bool alwaysWriteSize)
{
WriteSymbol (output, null, null, label, size, alignBits: 0, isGlobal: isGlobal, isObject: isObject, alwaysWriteSize: alwaysWriteSize);
}
protected void WriteSymbol (StreamWriter output, string symbolName, uint alignBits, uint fieldAlignBytes, bool isGlobal, bool alwaysWriteSize, Func<uint> structureWriter)
{
output.WriteLine ($"{Indent}.type{Indent}{symbolName}, {TargetProvider.TypePrefix}object");
if (alignBits > 0)
output.WriteLine ($"{Indent}.p2align{Indent}{alignBits}");
if (isGlobal)
output.WriteLine ($"{Indent}.global{Indent}{symbolName}");
if (!String.IsNullOrEmpty (symbolName))
output.WriteLine ($"{symbolName}:");
writingStructure = true;
structureByteCount = 0;
structureAlignBytes = fieldAlignBytes;
uint size = structureWriter != null ? structureWriter () : 0u;
writingStructure = false;
if (alwaysWriteSize || size > 0)
output.WriteLine ($"{Indent}.size{Indent}{symbolName}, {size}");
}
protected virtual string QuoteValue <T> (T value)
{
if (typeof(T) == typeof(string))
return $"\"{value}\"";
if (typeof(T) == typeof(bool))
return (bool)((object)value) ? "1" : "0";
return $"{value}";
}
protected uint WritePointer (StreamWriter output, string targetName, string label = null, bool isGlobal = false)
{
if (String.IsNullOrEmpty (targetName))
throw new ArgumentException ("must not be null or empty", nameof (targetName));
uint fieldSize = UpdateSize (output, targetName);
WriteSymbol (output, TargetProvider.PointerFieldType, targetName, label, size: 0, alignBits: 0, isGlobal: isGlobal, isObject: false, alwaysWriteSize: false);
return fieldSize;
}
uint WriteDataPadding (StreamWriter output, uint nextFieldSize, uint sizeSoFar)
{
if (!writingStructure || structureAlignBytes <= 1 || nextFieldSize == 1)
return 0;
uint alignment = sizeSoFar % structureAlignBytes;
if (alignment == 0)
return 0;
uint nbytes = structureAlignBytes - alignment;
output.WriteLine ($"{Indent}.zero{Indent}{nbytes}");
return nbytes;
}
protected uint WriteData (StreamWriter output, string value, string label, bool isGlobal = false)
{
if (String.IsNullOrEmpty (label))
throw new ArgumentException ("must not be null or empty", nameof (label));
if (value == null)
value = String.Empty;
WriteSection (output, $".rodata.{label}", hasStrings: true, writable: false);
WriteSymbol (output, value, label, size: (ulong)(value.Length + 1), alignBits: 0, isGlobal: isGlobal, isObject: true, alwaysWriteSize: true);
return TargetProvider.GetTypeSize (value);
}
uint UpdateSize <T> (StreamWriter output, T value)
{
uint fieldSize;
if (typeof (T) == typeof (string))
fieldSize = TargetProvider.GetPointerSize ();
else
fieldSize = TargetProvider.GetTypeSize (value);
fieldSize += WriteDataPadding (output, fieldSize, structureByteCount);
structureByteCount += fieldSize;
return fieldSize;
}
protected uint WriteData (StreamWriter output, byte value, string label = null, bool isGlobal = false)
{
uint fieldSize = UpdateSize (output, value);
WriteSymbol (output, value, label, size: 0, alignBits: 0, isGlobal: isGlobal, isObject: false, alwaysWriteSize: false);
return fieldSize;
}
protected uint WriteData (StreamWriter output, Int32 value, string label = null, bool isGlobal = false)
{
uint fieldSize = UpdateSize (output, value);
WriteSymbol (output, value, label, size: 0, alignBits: 0, isGlobal: isGlobal, isObject: false, alwaysWriteSize: false);
return fieldSize;
}
protected uint WriteData (StreamWriter output, UInt32 value, string label = null, bool isGlobal = false)
{
uint fieldSize = UpdateSize (output, value);
WriteSymbol (output, value, label, size: 0, alignBits: 0, isGlobal: isGlobal, isObject: false, alwaysWriteSize: false);
return fieldSize;
}
protected uint WriteData (StreamWriter output, Int64 value, string label = null, bool isGlobal = false)
{
uint fieldSize = UpdateSize (output, value);
WriteSymbol (output, value, label, size: 0, alignBits: 0, isGlobal: isGlobal, isObject: false, alwaysWriteSize: false);
return fieldSize;
}
protected uint WriteData (StreamWriter output, UInt64 value, string label = null, bool isGlobal = false)
{
uint fieldSize = UpdateSize (output, value);
WriteSymbol (output, value, label, size: 0, alignBits: 0, isGlobal: isGlobal, isObject: false, alwaysWriteSize: false);
return fieldSize;
}
protected uint WriteData (StreamWriter output, bool value, string label = null, bool isGlobal = false)
{
uint fieldSize = UpdateSize (output, value);
WriteSymbol (output, value, label, size: 0, alignBits: 0, isGlobal: isGlobal, isObject: false, alwaysWriteSize: false);
return fieldSize;
}
}
}

Просмотреть файл

@ -0,0 +1,71 @@
using System;
using System.IO;
using System.Text;
namespace Xamarin.Android.Tasks
{
class TypeMappingNativeAssemblyGenerator : NativeAssemblyGenerator
{
NativeAssemblyDataStream dataStream;
string dataFileName;
uint dataSize;
string mappingFieldName;
public TypeMappingNativeAssemblyGenerator (NativeAssemblerTargetProvider targetProvider, NativeAssemblyDataStream dataStream, string dataFileName, uint dataSize, string mappingFieldName)
: base (targetProvider)
{
if (dataStream == null)
throw new ArgumentNullException (nameof (dataStream));
if (String.IsNullOrEmpty (dataFileName))
throw new ArgumentException ("must not be null or empty", nameof (dataFileName));
if (String.IsNullOrEmpty (mappingFieldName))
throw new ArgumentException ("must not be null or empty", nameof (mappingFieldName));
this.dataStream = dataStream;
this.dataFileName = dataFileName;
this.dataSize = dataSize;
this.mappingFieldName = mappingFieldName;
}
protected override void WriteFileHeader (StreamWriter output, string outputFileName)
{
// The hash is written to make sure the assembly file which includes the data one is
// actually different whenever the data changes. Relying on mapping header values for this
// purpose would not be enough since the only change to the mapping might be a single-character
// change in one of the type names and we must be sure the assembly is rebuilt in all cases,
// thus the SHA1.
WriteEndLine (output, $"Data SHA1: {HashToHex (dataStream.GetStreamHash ())}", false);
base.WriteFileHeader (output, outputFileName);
}
protected override void WriteSymbols (StreamWriter output)
{
WriteMappingHeader (output, dataStream, mappingFieldName);
WriteCommentLine (output, "Mapping data");
WriteSymbol (output, mappingFieldName, dataSize, isGlobal: true, isObject: true, alwaysWriteSize: true);
output.WriteLine ($"{Indent}.include{Indent}\"{dataFileName}\"");
}
void WriteMappingHeader (StreamWriter output, NativeAssemblyDataStream dataStream, string mappingFieldName)
{
output.WriteLine ();
WriteCommentLine (output, "Mapping header");
WriteSection (output, $".data.{mappingFieldName}", hasStrings: false, writable: true);
WriteSymbol (output, $"{mappingFieldName}_header", alignBits: 2, fieldAlignBytes: 4, isGlobal: true, alwaysWriteSize: true, structureWriter: () => {
WriteCommentLine (output, "version");
WriteData (output, dataStream.MapVersion);
WriteCommentLine (output, "entry-count");
WriteData (output, dataStream.MapEntryCount);
WriteCommentLine (output, "entry-length");
WriteData (output, dataStream.MapEntryLength);
WriteCommentLine (output, "value-offset");
WriteData (output, dataStream.MapValueOffset);
return 16;
});
output.WriteLine ();
}
}
}

Просмотреть файл

@ -0,0 +1,24 @@
using System;
namespace Xamarin.Android.Tasks
{
class X86NativeAssemblerTargetProvider : NativeAssemblerTargetProvider
{
public override bool Is64Bit { get; }
public override string PointerFieldType { get; }
public override string TypePrefix { get; } = "@";
public X86NativeAssemblerTargetProvider (bool is64Bit)
{
Is64Bit = is64Bit;
PointerFieldType = is64Bit ? ".quad" : ".long";
}
public override string MapType <T> ()
{
if (typeof(T) == typeof(Int32) || typeof(T) == typeof(UInt32))
return ".long";
return base.MapType <T> ();
}
}
}

Просмотреть файл

@ -163,6 +163,7 @@
<Compile Include="Tasks\ResolveSdksTask.cs" />
<Compile Include="Tasks\CompileToDalvik.cs" />
<Compile Include="Tasks\AndroidToolTask.cs" />
<Compile Include="Tasks\PrepareAbiItems.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Mono.Android\ApplicationAttribute.Partial.cs" />
<Compile Include="Mono.Android\BroadcastReceiverAttribute.Partial.cs" />
@ -599,6 +600,15 @@
<Compile Include="Tasks\LayoutWidget.cs" />
<Compile Include="..\..\bin\Build$(Configuration)\XABuildConfig.cs" />
<Compile Include="Tasks\CheckGoogleSdkRequirements.cs" />
<Compile Include="Utilities\NativeAssemblyDataStream.cs" />
<Compile Include="Utilities\NativeAssemblyGenerator.cs" />
<Compile Include="Utilities\NativeAssemblerTargetProvider.cs" />
<Compile Include="Utilities\ARMNativeAssemblerTargetProvider.cs" />
<Compile Include="Utilities\X86NativeAssemblerTargetProvider.cs" />
<Compile Include="Utilities\TypeMappingNativeAssemblyGenerator.cs" />
<Compile Include="Utilities\ApplicationConfigNativeAssemblyGenerator.cs" />
<Compile Include="Tasks\CompileNativeAssembly.cs" />
<Compile Include="Tasks\LinkApplicationSharedLibraries.cs" />
<None Include="Resources\desugar_deploy.jar">
<Link>desugar_deploy.jar</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
@ -696,9 +706,6 @@
<EmbeddedResource Include="Resources\ApplicationRegistration.java">
<LogicalName>ApplicationRegistration.java</LogicalName>
</EmbeddedResource>
<EmbeddedResource Include="Resources\XamarinAndroidEnvironmentVariables.java">
<LogicalName>XamarinAndroidEnvironmentVariables.java</LogicalName>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Xamarin.Android.Tools.Aidl\Xamarin.Android.Tools.Aidl.csproj">
@ -788,6 +795,10 @@
<Project>{94BD81F7-B06F-4295-9636-F8A3B6BDC762}</Project>
<Name>Java.Interop</Name>
</ProjectReference>
<ProjectReference Include="..\..\build-tools\fetch-windows-assemblers\fetch-windows-assemblers.csproj">
<Project>{09518DF2-C7B1-4CDB-849A-9F91F4BEA925}</Project>
<Name>fetch-windows-assemblers</Name>
</ProjectReference>
</ItemGroup>
<Import Project="ILRepack.targets" />
</Project>

Просмотреть файл

@ -3,12 +3,15 @@
<UsingTask TaskName="Xamarin.Android.Tools.BootstrapTasks.GenerateProfile" AssemblyFile="..\..\bin\Build$(Configuration)\Xamarin.Android.Tools.BootstrapTasks.dll" />
<UsingTask TaskName="Xamarin.Android.Tools.BootstrapTasks.UnzipDirectoryChildren" AssemblyFile="..\..\bin\Build$(Configuration)\Xamarin.Android.Tools.BootstrapTasks.dll" />
<UsingTask AssemblyFile="..\..\bin\Build$(Configuration)\xa-prep-tasks.dll" TaskName="Xamarin.Android.BuildTools.PrepTasks.ReplaceFileContents" />
<UsingTask AssemblyFile="..\..\bin\Build$(Configuration)\xa-prep-tasks.dll" TaskName="Xamarin.Android.BuildTools.PrepTasks.Which" />
<Import Project="..\..\src\mono-runtimes\ProfileAssemblies.projitems" />
<Import Project="..\..\build-tools\scripts\XAVersionInfo.targets" />
<PropertyGroup>
<_SharedRuntimeBuildPath Condition=" '$(_SharedRuntimeBuildPath)' == '' ">$(XAInstallPrefix)xbuild-frameworks\MonoAndroid\</_SharedRuntimeBuildPath>
<_GeneratedProfileClass>$(MSBuildThisFileDirectory)$(IntermediateOutputPath)Profile.g.cs</_GeneratedProfileClass>
<BuildDependsOn>
_CopyNDKTools;
_GenerateXACommonProps;
$(BuildDependsOn);
_CopyExtractedMultiDexJar;
@ -128,6 +131,74 @@
<_SharedRuntimeAssemblies Include="$(_SharedRuntimeBuildPath)$(AndroidFrameworkVersion)\OpenTK.dll" />
<_SharedRuntimeAssemblies Include="$(_SharedRuntimeBuildPath)$(AndroidFrameworkVersion)\OpenTK-1.0.dll" />
</ItemGroup>
<Target Name="_PrepareNDKToolsItems">
<PropertyGroup>
<_PrebuiltToolchainDir Condition=" '$(HostOS)' == 'Linux' ">linux-x86_64</_PrebuiltToolchainDir>
<_PrebuiltToolchainDir Condition=" '$(HostOS)' == 'Darwin' ">darwin-x86_64</_PrebuiltToolchainDir>
<_PrebuiltToolchainDir Condition=" '$(HostOS)' == 'Windows' And '$(HostBits)' == '64' ">windows-x86_64</_PrebuiltToolchainDir>
<_PrebuiltToolchainDir Condition=" '$(HostOS)' == 'Windows' And '$(HostBits)' == '32' ">windows</_PrebuiltToolchainDir>
</PropertyGroup>
<ItemGroup>
<_ToolchainPrefix Include="aarch64-linux-android">
<ToolPrefix>aarch64-linux-android</ToolPrefix>
</_ToolchainPrefix>
<_ToolchainPrefix Include="arm-linux-androideabi">
<ToolPrefix>arm-linux-androideabi</ToolPrefix>
</_ToolchainPrefix>
<_ToolchainPrefix Include="x86">
<ToolPrefix>i686-linux-android</ToolPrefix>
</_ToolchainPrefix>
<_ToolchainPrefix Include="x86_64">
<ToolPrefix>x86_64-linux-android</ToolPrefix>
</_ToolchainPrefix>
</ItemGroup>
<Which
HostOS="$(HostOS)"
HostOSName="$(HostOsName)"
Program="$(AndroidNdkFullPath)/toolchains/%(_ToolchainPrefix.Identity)-4.9/prebuilt/$(_PrebuiltToolchainDir)/bin/%(_ToolchainPrefix.ToolPrefix)-as"
Required="True">
<Output TaskParameter="Location" PropertyName="_NDKToolLocation%(_ToolchainPrefix.Identity)" />
</Which>
<PropertyGroup>
<_NDKToolFileName>$([System.IO.Path]::GetFileName ('$(_NDKToolLocation)'))</_NDKToolFileName>
<_NDKToolDestinationBase>$(XAInstallPrefix)xbuild\Xamarin\Android</_NDKToolDestinationBase>
<_WinAsmDestDir>$(XAInstallPrefix)xbuild\Xamarin\Android</_WinAsmDestDir>
</PropertyGroup>
<ItemGroup>
<_NDKToolSource Include="$(_NDKToolLocation%(_ToolchainPrefix.Identity))" />
<_NDKToolDestination Condition=" '$(HostOS)' != 'Windows' " Include="$(_NDKToolDestinationBase)\$(HostOS)\$([System.IO.Path]::GetFileName ('$(_NDKToolLocation%(_ToolchainPrefix.Identity))'))" />
<_NDKToolDestination Condition=" '$(HostOS)' == 'Windows' " Include="$(_NDKToolDestinationBase)\$([System.IO.Path]::GetFileName ('$(_NDKToolLocation%(_ToolchainPrefix.Identity))'))" />
</ItemGroup>
</Target>
<Target Name="_FetchWindowsAssemblers"
Condition=" '$(HostOS)' != 'Windows' "
DependsOnTargets="_PrepareNDKToolsItems"
AfterTargets="Build"
Inputs="..\..\build-tools\scripts\Ndk.targets"
Outputs="$(_WinAsmDestDir)\%(_ToolchainPrefix.Identity)-as.exe">
<MakeDir
Directories="$(_WinAsmDestDir)"
/>
<Exec
Command="$(ManagedRuntime) $(MSBuildThisFileDirectory)..\..\bin\Build$(Configuration)\fetch-windows-assemblers.exe $(AndroidNdkVersion) &quot;$(_WinAsmDestDir)&quot; https://dl.google.com/android/repository/android-ndk-r$(AndroidNdkVersion)-windows-x86_64.zip"
WorkingDirectory="$(_WinAsmDestDir)"
/>
</Target>
<Target Name="_CopyNDKTools"
DependsOnTargets="_PrepareNDKToolsItems"
Inputs="@(_NDKToolSource)"
Outputs="@(_NDKToolDestination)">
<Copy
SourceFiles="@(_NDKToolSource)"
DestinationFiles="@(_NDKToolDestination)"
/>
</Target>
<Target Name="_GenerateMonoAndroidEnums"
BeforeTargets="CoreCompile"
Inputs="..\Mono.Android\obj\$(Configuration)\android-$(AndroidLatestStableApiLevel)\mcw\api.xml"

Просмотреть файл

@ -111,6 +111,9 @@ Copyright (C) 2011-2012 Xamarin. All rights reserved.
<UsingTask TaskName="Xamarin.Android.Tasks.Proguard" AssemblyFile="Xamarin.Android.Build.Tasks.dll" />
<UsingTask TaskName="Xamarin.Android.Tasks.DetermineJavaLibrariesToCompile" AssemblyFile="Xamarin.Android.Build.Tasks.dll" />
<UsingTask TaskName="Xamarin.Android.Tasks.CreateMultiDexMainDexClassList" AssemblyFile="Xamarin.Android.Build.Tasks.dll" />
<UsingTask TaskName="Xamarin.Android.Tasks.CompileNativeAssembly" AssemblyFile="Xamarin.Android.Build.Tasks.dll" />
<UsingTask TaskName="Xamarin.Android.Tasks.LinkApplicationSharedLibraries" AssemblyFile="Xamarin.Android.Build.Tasks.dll" />
<UsingTask TaskName="Xamarin.Android.Tasks.PrepareAbiItems" AssemblyFile="Xamarin.Android.Build.Tasks.dll" />
<!--
*******************************************
@ -286,6 +289,7 @@ Copyright (C) 2011-2012 Xamarin. All rights reserved.
<_AndroidLibraryFlatArchivesDirectory>$(IntermediateOutputPath)flata\</_AndroidLibraryFlatArchivesDirectory>
<_AndroidStampDirectory>$(IntermediateOutputPath)stamp\</_AndroidStampDirectory>
<_AndroidBuildIdFile>$(IntermediateOutputPath)buildid.txt</_AndroidBuildIdFile>
<_AndroidApplicationSharedLibraryPath>$(IntermediateOutputPath)app_shared_libraries\</_AndroidApplicationSharedLibraryPath>
<_ResolvedUserAssembliesHashFile>$(IntermediateOutputPath)resolvedassemblies.hash</_ResolvedUserAssembliesHashFile>
<!-- $(EnableProguard) is an obsolete property that should be removed at some stage. -->
@ -335,7 +339,9 @@ Copyright (C) 2011-2012 Xamarin. All rights reserved.
<AndroidMakeBundleKeepTemporaryFiles Condition=" '$(AndroidMakeBundleKeepTemporaryFiles)' == '' ">False</AndroidMakeBundleKeepTemporaryFiles>
<!-- If true it will cause all the assemblies in the apk to be preloaded on startup time -->
<AndroidEnablePreloadAssemblies Condition=" '$(AndroidEnablePreloadAssemblies)' == '' ">True</AndroidEnablePreloadAssemblies>
<_AndroidEnablePreloadAssembliesDefault>True</_AndroidEnablePreloadAssembliesDefault>
<AndroidEnablePreloadAssemblies Condition=" '$(AndroidEnablePreloadAssemblies)' == '' ">$(_AndroidEnablePreloadAssembliesDefault)</AndroidEnablePreloadAssemblies>
<_NativeAssemblySourceDir>$(IntermediateOutputPath)android\</_NativeAssemblySourceDir>
</PropertyGroup>
<Choose>
@ -2243,8 +2249,22 @@ because xbuild doesn't support framework reference assemblies.
</CreateItem>
</Target>
<Target Name="_PrepareNativeAssemblySources">
<PrepareAbiItems
BuildTargetAbis="$(_BuildTargetAbis)"
ItemNamePattern="$(_NativeAssemblySourceDir)typemap.jm.@abi@.s">
<Output TaskParameter="OutputItems" ItemName="_TypeMapAssemblySource" />
</PrepareAbiItems>
<PrepareAbiItems
BuildTargetAbis="$(_BuildTargetAbis)"
ItemNamePattern="$(_NativeAssemblySourceDir)typemap.mj.@abi@.s" >
<Output TaskParameter="OutputItems" ItemName="_TypeMapAssemblySource" />
</PrepareAbiItems>
</Target>
<Target Name="_GenerateJavaStubs"
DependsOnTargets="_SetLatestTargetFrameworkVersion;_PrepareAssemblies;$(_AfterPrepareAssemblies)"
DependsOnTargets="_SetLatestTargetFrameworkVersion;_PrepareAssemblies;$(_AfterPrepareAssemblies);_PrepareNativeAssemblySources"
Inputs="$(MSBuildAllProjects);@(_ResolvedUserMonoAndroidAssemblies);$(_AndroidManifestAbs);$(_AndroidBuildPropertiesCache);@(_AndroidResourceDest)"
Outputs="$(_AndroidStampDirectory)_GenerateJavaStubs.stamp">
<GenerateJavaStubs
@ -2270,8 +2290,10 @@ because xbuild doesn't support framework reference assemblies.
PackageNamingPolicy="$(AndroidPackageNamingPolicy)"
ApplicationJavaClass="$(AndroidApplicationJavaClass)"
FrameworkDirectories="$(_XATargetFrameworkDirectories);$(_XATargetFrameworkDirectories)Facades"
AcwMapFile="$(_AcwMapFile)">
AcwMapFile="$(_AcwMapFile)"
SupportedAbis="$(_BuildTargetAbis)">
</GenerateJavaStubs>
<ConvertCustomView
Condition="Exists('$(_CustomViewMapFile)')"
CustomViewMapFile="$(_CustomViewMapFile)"
@ -2350,6 +2372,14 @@ because xbuild doesn't support framework reference assemblies.
</ItemGroup>
</Target>
<Target Name="_PrepareEnvironmentAssemblySources">
<PrepareAbiItems
BuildTargetAbis="$(_BuildTargetAbis)"
ItemNamePattern="$(_NativeAssemblySourceDir)environment.@abi@.s">
<Output TaskParameter="OutputItems" ItemName="_EnvironmentAssemblySource" />
</PrepareAbiItems>
</Target>
<Target Name="_GenerateEnvironmentFiles" DependsOnTargets="_ReadAndroidManifest;_SetupEmbeddedDSOs;_SetupAssemblyPreload" />
<PropertyGroup>
@ -2359,20 +2389,22 @@ because xbuild doesn't support framework reference assemblies.
_AddStaticResources;
$(_AfterAddStaticResources);
_PrepareAssemblies;
_PrepareEnvironmentAssemblySources;
_SetupAssemblyPreload;
</_GeneratePackageManagerJavaDependsOn>
</PropertyGroup>
<Target Name="_GeneratePackageManagerJava"
DependsOnTargets="$(_GeneratePackageManagerJavaDependsOn)"
Inputs="$(MSBuildAllProjects);$(_ResolvedUserAssembliesHashFile);$(MSBuildProjectFile);$(_AndroidBuildPropertiesCache)"
Outputs="$(_AndroidStampDirectory)_GeneratePackageManagerJava.stamp">
Outputs="$(_AndroidStampDirectory)_GeneratePackageManagerJava.stamp;@(_EnvironmentAssemblySource)">
<!-- Create java needed for Mono runtime -->
<GeneratePackageManagerJava
ResolvedAssemblies="@(_ResolvedAssemblies)"
ResolvedUserAssemblies="@(_ResolvedUserAssemblies)"
MainAssembly="$(MonoAndroidLinkerInputDir)$(TargetFileName)"
OutputDirectory="$(IntermediateOutputPath)android\src\mono"
EnvironmentOutputDirectory="$(IntermediateOutputPath)android\src\mono\android\app"
EnvironmentOutputDirectory="$(IntermediateOutputPath)android"
UseSharedRuntime="$(AndroidUseSharedRuntime)"
TargetFrameworkVersion="$(TargetFrameworkVersion)"
Manifest="$(IntermediateOutputPath)android\AndroidManifest.xml"
@ -2384,6 +2416,10 @@ because xbuild doesn't support framework reference assemblies.
Debug="$(AndroidIncludeDebugSymbols)"
AndroidSequencePointsMode="$(_SequencePointsMode)"
EnableSGenConcurrent="$(AndroidEnableSGenConcurrent)"
IsBundledApplication="$(BundleAssemblies)"
SupportedAbis="$(_BuildTargetAbis)"
AndroidPackageName="$(_AndroidPackage)"
EnablePreloadAssembliesDefault="$(_AndroidEnablePreloadAssembliesDefault)"
>
<Output TaskParameter="BuildId" PropertyName="_XamarinBuildId" />
</GeneratePackageManagerJava>
@ -2834,6 +2870,55 @@ because xbuild doesn't support framework reference assemblies.
</ItemGroup>
</Target>
<Target Name="_PrepareNativeAssemblyItems">
<ItemGroup>
<_NativeAssemblyTarget Include="@(_TypeMapAssemblySource->Replace('.s', '.o'))">
<abi>%(_TypeMapAssemblySource.abi)</abi>
</_NativeAssemblyTarget>
<_NativeAssemblyTarget Include="@(_EnvironmentAssemblySource->Replace('.s', '.o'))">
<abi>%(_EnvironmentAssemblySource.abi)</abi>
</_NativeAssemblyTarget>
</ItemGroup>
</Target>
<Target Name="_CompileNativeAssemblySources"
DependsOnTargets="_PrepareNativeAssemblyItems"
Inputs="@(_TypeMapAssemblySource);@(_EnvironmentAssemblySource)"
Outputs="@(_NativeAssemblyTarget)">
<CompileNativeAssembly
Sources="@(_TypeMapAssemblySource);@(_EnvironmentAssemblySource)"
DebugBuild="$(AndroidIncludeDebugSymbols)"
WorkingDirectory="$(_NativeAssemblySourceDir)"
/>
</Target>
<Target Name="_PrepareApplicationSharedLibraryItems">
<ItemGroup>
<_XARuntimeArchitecture Include="$(_BuildTargetAbis)"/>
</ItemGroup>
<ItemGroup>
<_ApplicationSharedLibrary Include="$(_AndroidApplicationSharedLibraryPath)%(_XARuntimeArchitecture.Identity)\libxamarin-app.so">
<abi>%(_XARuntimeArchitecture.Identity)</abi>
</_ApplicationSharedLibrary>
</ItemGroup>
</Target>
<Target Name="_CreateApplicationSharedLibraries"
DependsOnTargets="_CompileNativeAssemblySources;_PrepareApplicationSharedLibraryItems"
Inputs="@(_NativeAssemblyTarget)"
Outputs="@(_ApplicationSharedLibrary)">
<LinkApplicationSharedLibraries
ObjectFiles="@(_NativeAssemblyTarget)"
ApplicationSharedLibraries="@(_ApplicationSharedLibrary)"
DebugBuild="$(AndroidIncludeDebugSymbols)"
AndroidNdkDirectory="$(_AndroidNdkDirectory)"
/>
<ItemGroup>
<FileWrites Include="@(_ApplicationSharedLibrary)" />
</ItemGroup>
</Target>
<PropertyGroup>
<_PrepareBuildApkDependsOnTargets>
_SetLatestTargetFrameworkVersion;
@ -2851,7 +2936,8 @@ because xbuild doesn't support framework reference assemblies.
_CreateBaseApk;
_PrepareAssemblies;
_ResolveSatellitePaths;
_CheckApkPerAbiFlag
_CheckApkPerAbiFlag;
_CreateApplicationSharedLibraries;
;_LintChecks
;_IncludeNativeSystemLibraries
;_CheckGoogleSdkRequirements
@ -2878,9 +2964,8 @@ because xbuild doesn't support framework reference assemblies.
;@(_ShrunkFrameworkAssemblies)
;@(AndroidNativeLibrary)
;@(_DexFile)
;$(_AndroidTypeMappingJavaToManaged)
;$(_AndroidTypeMappingManagedToJava)
;$(_AndroidBuildPropertiesCache)
;@(_ApplicationSharedLibrary)
</_BuildApkEmbedInputs>
</PropertyGroup>
@ -2953,6 +3038,7 @@ because xbuild doesn't support framework reference assemblies.
ResolvedUserAssemblies="@(_ResolvedUserAssemblies);@(_AndroidResolvedSatellitePaths)"
ResolvedFrameworkAssemblies="@(_ShrunkFrameworkAssemblies)"
NativeLibraries="@(AndroidNativeLibrary)"
ApplicationSharedLibraries="@(_ApplicationSharedLibrary)"
AdditionalNativeLibraryReferences="@(_AdditionalNativeLibraryReferences)"
EmbeddedNativeLibraryAssemblies="$(OutDir)$(TargetFileName);@(_ReferencePath);@(_ReferenceDependencyPaths)"
DalvikClasses="@(_DexFile)"
@ -2961,7 +3047,6 @@ because xbuild doesn't support framework reference assemblies.
UseSharedRuntime="$(AndroidUseSharedRuntime)"
Debug="$(AndroidIncludeDebugSymbols)"
PreferNativeLibrariesWithDebugSymbols="$(AndroidPreferNativeLibrariesWithDebugSymbols)"
TypeMappings="$(_AndroidTypeMappingJavaToManaged);$(_AndroidTypeMappingManagedToJava)"
JavaSourceFiles="@(AndroidJavaSource)"
JavaLibraries="@(AndroidJavaLibrary)"
AndroidSequencePointsMode="$(_SequencePointsMode)"
@ -2982,6 +3067,7 @@ because xbuild doesn't support framework reference assemblies.
ResolvedUserAssemblies="@(_ResolvedUserAssemblies);@(_AndroidResolvedSatellitePaths)"
ResolvedFrameworkAssemblies="@(_ShrunkFrameworkAssemblies)"
NativeLibraries="@(AndroidNativeLibrary)"
ApplicationSharedLibraries="@(_ApplicationSharedLibrary)"
AdditionalNativeLibraryReferences="@(_AdditionalNativeLibraryReferences)"
EmbeddedNativeLibraryAssemblies="$(OutDir)$(TargetFileName);@(ReferencePath);@(ReferenceDependencyPaths)"
DalvikClasses="@(_DexFile)"
@ -2990,7 +3076,6 @@ because xbuild doesn't support framework reference assemblies.
UseSharedRuntime="$(AndroidUseSharedRuntime)"
Debug="$(AndroidIncludeDebugSymbols)"
PreferNativeLibrariesWithDebugSymbols="$(AndroidPreferNativeLibrariesWithDebugSymbols)"
TypeMappings="$(_AndroidTypeMappingJavaToManaged);$(_AndroidTypeMappingManagedToJava)"
JavaSourceFiles="@(AndroidJavaSource)"
JavaLibraries="@(AndroidJavaLibrary)"
AndroidSequencePointsMode="$(_SequencePointsMode)"
@ -3344,6 +3429,7 @@ because xbuild doesn't support framework reference assemblies.
<RemoveDirFixed Directories="$(_AndroidAotBinDirectory)" Condition="Exists ('$(_AndroidAotBinDirectory)')" />
<RemoveDirFixed Directories="$(_AndroidLibraryFlatArchivesDirectory)" Condition="Exists ('$(_AndroidLibraryFlatArchivesDirectory)')" />
<RemoveDirFixed Directories="$(_AndroidStampDirectory)" Condition="Exists ('$(_AndroidStampDirectory)')" />
<RemoveDirFixed Directories="$(_AndroidApplicationSharedLibraryPath)" Condition="Exists ('$(_AndroidApplicationSharedLibraryPath)')" />
<Delete Files="$(MonoAndroidIntermediate)R.cs.flag" />
<Delete Files="$(MonoAndroidIntermediate)acw-map.txt" />
<Delete Files="$(MonoAndroidIntermediate)customview-map.txt" />

Просмотреть файл

@ -46,6 +46,12 @@ public class MonoPackageManager {
external0,
"../legacy/Android/data/" + context.getPackageName () + "/files/.__override__").getAbsolutePath ();
// Preload DSOs libmonodroid.so depends on so that the dynamic
// linker can resolve them when loading monodroid. This is not
// needed in the latest Android versions but is required in at least
// API 16 and since there's no inherent negative effect of doing it,
// we can do it unconditionally.
System.loadLibrary("xamarin-app");
System.loadLibrary("monodroid");
Runtime.init (
@ -63,9 +69,10 @@ public class MonoPackageManager {
externalLegacyDir
},
MonoPackageManager_Resources.Assemblies,
context.getPackageName (),
null, // unused
android.os.Build.VERSION.SDK_INT,
mono.android.app.XamarinAndroidEnvironmentVariables.Variables);
null // unused
);
mono.android.app.ApplicationRegistration.registerApplications ();

Просмотреть файл

@ -104,6 +104,7 @@ else()
add_definitions("-D_GNU_SOURCE")
if(APPLE)
add_definitions("-DAPPLE_OS_X")
set(CMAKE_MACOSX_RPATH 1)
set(HOST_BUILD_NAME "host-Darwin")
elseif(CMAKE_HOST_SYSTEM_NAME STREQUAL Linux)
if(NOT MINGW AND NOT WIN32)
@ -111,7 +112,7 @@ else()
set(HOST_BUILD_NAME "host-Linux")
if(EXISTS "/.flatpak-info")
add_definitions("-DLINUX_FLATPAK")
add_definitions("-DLINUX_FLATPAK")
endif()
endif()
endif()
@ -221,6 +222,9 @@ if(UNIX)
)
endif()
set(XAMARIN_APP_STUB_SOURCES ${SOURCES_DIR}/application_dso_stub.cc)
add_library(xamarin-app SHARED ${XAMARIN_APP_STUB_SOURCES})
set(SOURCES_FRAGMENT_FILE "sources.projitems")
file(WRITE ${SOURCES_FRAGMENT_FILE} "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n\
<Project xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n\
@ -236,6 +240,13 @@ file(APPEND ${SOURCES_FRAGMENT_FILE} " </ItemGroup>\n\
string(TOLOWER ${CMAKE_BUILD_TYPE} MONO_ANDROID_SUFFIX)
set(MONO_ANDROID_LIB "mono-android.${MONO_ANDROID_SUFFIX}")
add_library(${MONO_ANDROID_LIB} SHARED ${MONODROID_SOURCES})
if(APPLE)
add_custom_command(
TARGET ${MONO_ANDROID_LIB}
POST_BUILD
COMMAND xcrun install_name_tool -change "@rpath/libxamarin-app.dylib" "@loader_path/libxamarin-app.dylib" $<TARGET_FILE:${MONO_ANDROID_LIB}>
)
endif()
if(MINGW_ZLIB_LIBRARY_PATH)
set(LINK_LIBS "${MINGW_ZLIB_LIBRARY_PATH} ${EXTRA_LINKER_FLAGS}")
@ -249,4 +260,5 @@ elseif(NOT ANDROID)
set(LINK_LIBS "-pthread ${LINK_LIBS} -ldl")
endif()
target_link_libraries(${MONO_ANDROID_LIB} ${LINK_LIBS})
target_link_libraries(${MONO_ANDROID_LIB} ${LINK_LIBS} xamarin-app)

Просмотреть файл

@ -1,9 +1,11 @@
#include <limits.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <assert.h>
#include <ctype.h>
#include <dlfcn.h>
#include <fcntl.h>
#ifdef ANDROID
#include <sys/system_properties.h>
@ -24,20 +26,27 @@
#include "monodroid.h"
#include "monodroid-glue-internal.h"
#include "jni-wrappers.h"
#include "xamarin-app.h"
#if defined (DEBUG) || !defined (ANDROID)
namespace xamarin { namespace android { namespace internal {
struct BundledProperty {
char *name;
char *value;
int value_len;
char *name;
char *value;
uint32_t value_len;
struct BundledProperty *next;
};
}}}
#endif // DEBUG || !ANDROID
using namespace xamarin::android;
using namespace xamarin::android::internal;
#if defined (DEBUG) || !defined (ANDROID)
BundledProperty *AndroidSystem::bundled_properties = nullptr;
constexpr char AndroidSystem::OVERRIDE_ENVIRONMENT_FILE_NAME[];
#endif // DEBUG || !ANDROID
char* AndroidSystem::override_dirs [MAX_OVERRIDES];
const char **AndroidSystem::app_lib_directories;
size_t AndroidSystem::app_lib_directories_size = 0;
@ -70,6 +79,7 @@ static constexpr uint32_t PROP_NAME_MAX = 32;
static constexpr uint32_t PROP_VALUE_MAX = 92;
#endif
#if defined (DEBUG) || !defined (ANDROID)
BundledProperty*
AndroidSystem::lookup_system_property (const char *name)
{
@ -79,7 +89,51 @@ AndroidSystem::lookup_system_property (const char *name)
return p;
return nullptr;
}
#endif // DEBUG || !ANDROID
const char*
AndroidSystem::lookup_system_property (const char *name, uint32_t &value_len)
{
value_len = 0;
#if defined (DEBUG) || !defined (ANDROID)
BundledProperty *p = lookup_system_property (name);
if (p != nullptr) {
value_len = p->value_len;
return p->name;
}
#endif // DEBUG || !ANDROID
if (application_config.system_property_count == 0)
return nullptr;
if (application_config.system_property_count % 2 != 0) {
log_warn (LOG_DEFAULT, "Corrupted environment variable array: does not contain an even number of entries (%u)", application_config.environment_variable_count);
return nullptr;
}
const char *prop_name;
const char *prop_value;
for (size_t i = 0; i < application_config.system_property_count; i += 2) {
prop_name = app_system_properties[i];
if (prop_name == nullptr || *prop_name == '\0')
continue;
if (strcmp (prop_name, name) == 0) {
prop_value = app_system_properties [i + 1];
if (prop_value == nullptr || *prop_value == '\0') {
value_len = 0;
return "";
}
value_len = strlen (prop_value);
return prop_value;
}
}
return nullptr;
}
#if defined (DEBUG) || !defined (ANDROID)
void
AndroidSystem::add_system_property (const char *name, const char *value)
{
@ -114,6 +168,7 @@ AndroidSystem::add_system_property (const char *name, const char *value)
p->next = bundled_properties;
bundled_properties = p;
}
#endif // DEBUG || !ANDROID
#ifndef ANDROID
void
@ -187,10 +242,13 @@ AndroidSystem::monodroid_get_system_property (const char *name, char **value)
char *pvalue = sp_value;
int len = _monodroid__system_property_get (name, sp_value, sizeof (sp_value));
BundledProperty *p;
if (len <= 0 && (p = lookup_system_property (name)) != nullptr) {
pvalue = p->value;
len = p->value_len;
if (len <= 0) {
uint32_t plen;
const char *v = lookup_system_property (name, plen);
if (v != nullptr) {
pvalue = const_cast<char*> (v);
len = static_cast<int> (plen);
}
}
if (len >= 0 && value) {
@ -225,6 +283,7 @@ AndroidSystem::monodroid_read_file_into_memory (const char *path, char **value)
return r;
}
#if defined (DEBUG) || !defined (ANDROID)
int
AndroidSystem::_monodroid_get_system_property_from_file (const char *path, char **value)
{
@ -262,10 +321,12 @@ AndroidSystem::_monodroid_get_system_property_from_file (const char *path, char
}
return len;
}
#endif
int
AndroidSystem::monodroid_get_system_property_from_overrides (const char *name, char ** value)
{
#if defined (DEBUG) || !defined (ANDROID)
int result = -1;
for (size_t oi = 0; oi < MAX_OVERRIDES; ++oi) {
@ -281,6 +342,7 @@ AndroidSystem::monodroid_get_system_property_from_overrides (const char *name, c
return result;
}
}
#endif
return 0;
}
@ -718,95 +780,184 @@ AndroidSystem::get_gref_gc_threshold ()
return static_cast<int> ((max_gref_count * 90LL) / 100LL);
}
#if defined (DEBUG) || !defined (ANDROID)
void
AndroidSystem::setup_environment (jstring_wrapper& name, jstring_wrapper& value)
AndroidSystem::setup_environment (const char *name, const char *value)
{
const char *k = name.get_cstr ();
if (k == nullptr || *k == '\0')
if (name == nullptr || *name == '\0')
return;
const char *v = value.get_cstr ();
if (v == nullptr || *v == '\0')
const char *v = value;
if (v == nullptr)
v = "";
if (isupper (k [0]) || k [0] == '_') {
if (k [0] == '_') {
if (strcmp (k, "__XA_DSO_IN_APK") == 0) {
knownEnvVars.DSOInApk = true;
return;
}
}
setenv (k, v, 1);
if (isupper (name [0]) || name [0] == '_') {
if (setenv (name, v, 1) < 0)
log_warn (LOG_DEFAULT, "(Debug) Failed to set environment variable: %s", strerror (errno));
return;
}
if (k [0] == 'm') {
if (strcmp (k, "mono.aot") == 0) {
if (*v == '\0') {
knownEnvVars.MonoAOT = MonoAotMode::MONO_AOT_MODE_NONE;
return;
}
switch (v [0]) {
case 'n':
knownEnvVars.MonoAOT = MonoAotMode::MONO_AOT_MODE_NORMAL;
break;
case 'h':
knownEnvVars.MonoAOT = MonoAotMode::MONO_AOT_MODE_HYBRID;
break;
case 'f':
knownEnvVars.MonoAOT = MonoAotMode::MONO_AOT_MODE_FULL;
break;
default:
knownEnvVars.MonoAOT = MonoAotMode::MONO_AOT_MODE_UNKNOWN;
break;
}
if (knownEnvVars.MonoAOT != MonoAotMode::MONO_AOT_MODE_UNKNOWN)
log_info (LOG_DEFAULT, "Mono AOT mode: %s", v);
else
log_warn (LOG_DEFAULT, "Unknown Mono AOT mode: %s", v);
return;
}
if (strcmp (k, "mono.llvm") == 0) {
knownEnvVars.MonoLLVM = true;
return;
}
if (strcmp (k, "mono.enable_assembly_preload") == 0) {
if (*v == '\0')
knownEnvVars.EnableAssemblyPreload = KnownEnvironmentVariables::AssemblyPreloadDefault;
else if (v[0] == '1')
knownEnvVars.EnableAssemblyPreload = true;
else
knownEnvVars.EnableAssemblyPreload = false;
return;
}
}
add_system_property (k, v);
add_system_property (name, v);
}
void
AndroidSystem::setup_environment (JNIEnv *env, jobjectArray environmentVariables)
AndroidSystem::setup_environment_from_override_file (const char *path)
{
jsize envvarsLength = env->GetArrayLength (environmentVariables);
if (envvarsLength == 0)
monodroid_stat_t sbuf;
if (utils.monodroid_stat (path, &sbuf) < 0) {
log_warn (LOG_DEFAULT, "Failed to stat the environment override file %s: %s", path, strerror (errno));
return;
}
int fd = open (path, O_RDONLY);
if (fd < 0) {
log_warn (LOG_DEFAULT, "Failed to open the environment override file %s: %s", path, strerror (errno));
return;
}
char *buf = new char [sbuf.st_size];
ssize_t nread = 0;
ssize_t r;
do {
int i = nread;
r = read (fd, buf + i, sbuf.st_size - i);
if (r > 0)
nread += r;
} while (r < 0 && errno == EINTR);
if (nread < 0) {
log_warn (LOG_DEFAULT, "Failed to read the environment override file %s: %s", path, strerror (errno));
delete[] buf;
return;
}
// The file format is as follows (no newlines are used, this is just for illustration
// purposes, comments aren't part of the file either):
//
// # 10 ASCII characters formattted as a C++ hexadecimal number terminated with NUL: name
// # width (including the terminating NUL)
// 0x00000000\0
//
// # 10 ASCII characters formattted as a C++ hexadecimal number terminated with NUL: value
// # width (including the terminating NUL)
// 0x00000000\0
//
// # Variable name, terminated with NUL and padded to [name width] with NUL characters
// name\0
//
// # Variable value, terminated with NUL and padded to [value width] with NUL characters
// value\0
if (nread < OVERRIDE_ENVIRONMENT_FILE_HEADER_SIZE) {
log_warn (LOG_DEFAULT, "Invalid format of the environment override file %s: malformatted header", path);
delete[] buf;
return;
}
char *endptr;
unsigned long name_width = strtoul (buf, &endptr, 16);
if ((name_width == ULONG_MAX && errno == ERANGE) || (*buf != '\0' && *endptr != '\0')) {
log_warn (LOG_DEFAULT, "Malformed header of the environment override file %s: name width has invalid format", path);
delete[] buf;
return;
}
unsigned long value_width = strtoul (buf + 11, &endptr, 16);
if ((value_width == ULONG_MAX && errno == ERANGE) || (*buf != '\0' && *endptr != '\0')) {
log_warn (LOG_DEFAULT, "Malformed header of the environment override file %s: value width has invalid format", path);
delete[] buf;
return;
}
uint64_t data_width = name_width + value_width;
if (data_width > sbuf.st_size - OVERRIDE_ENVIRONMENT_FILE_HEADER_SIZE || (sbuf.st_size - OVERRIDE_ENVIRONMENT_FILE_HEADER_SIZE) % data_width != 0) {
log_warn (LOG_DEFAULT, "Malformed environment override file %s: invalid data size", path);
delete[] buf;
return;
}
uint64_t data_size = sbuf.st_size;
char *name = buf + OVERRIDE_ENVIRONMENT_FILE_HEADER_SIZE;
while (data_size > 0 && data_size >= data_width) {
if (*name == '\0') {
log_warn (LOG_DEFAULT, "Malformed environment override file %s: name at offset %lu is empty", path, name - buf);
delete[] buf;
return;
}
log_debug (LOG_DEFAULT, "Setting environment variable from the override file %s: '%s' = '%s'", path, name, name + name_width);
setup_environment (name, name + name_width);
name += data_width;
data_size -= data_width;
}
delete[] buf;
}
#endif // DEBUG || !ANDROID
void
AndroidSystem::setup_environment ()
{
if (is_mono_aot_enabled () && *mono_aot_mode_name != '\0') {
switch (mono_aot_mode_name [0]) {
case 'n':
aotMode = MonoAotMode::MONO_AOT_MODE_NORMAL;
break;
case 'h':
aotMode = MonoAotMode::MONO_AOT_MODE_HYBRID;
break;
case 'f':
aotMode = MonoAotMode::MONO_AOT_MODE_FULL;
break;
default:
aotMode = MonoAotMode::MONO_AOT_MODE_UNKNOWN;
break;
}
if (aotMode != MonoAotMode::MONO_AOT_MODE_UNKNOWN)
log_info (LOG_DEFAULT, "Mono AOT mode: %s", mono_aot_mode_name);
else
log_warn (LOG_DEFAULT, "Unknown Mono AOT mode: %s", mono_aot_mode_name);
}
if (application_config.environment_variable_count == 0)
return;
jstring_wrapper name (env), value (env);
for (jsize i = 0; (i + 1) < envvarsLength; i += 2) {
name = reinterpret_cast<jstring> (env->GetObjectArrayElement (environmentVariables, i));
value = reinterpret_cast<jstring> (env->GetObjectArrayElement (environmentVariables, i + 1));
setup_environment (name, value);
if (application_config.environment_variable_count % 2 != 0) {
log_warn (LOG_DEFAULT, "Corrupted environment variable array: does not contain an even number of entries (%u)", application_config.environment_variable_count);
return;
}
const char *var_name;
const char *var_value;
for (size_t i = 0; i < application_config.environment_variable_count; i += 2) {
var_name = app_environment_variables [i];
if (var_name == nullptr || *var_name == '\0')
continue;
var_value = app_environment_variables [i + 1];
if (var_value == nullptr)
var_value = "";
#if defined (DEBUG)
log_info (LOG_DEFAULT, "Setting environment variable '%s' to '%s'", var_name, var_value);
#endif
if (setenv (var_name, var_value, 1) < 0)
log_warn (LOG_DEFAULT, "Failed to set environment variable: %s", strerror (errno));
}
#if defined (DEBUG) || !defined (ANDROID)
// TODO: for debug read from file in the override directory named `environment`
for (size_t oi = 0; oi < MAX_OVERRIDES; oi++) {
char *env_override_file = utils.path_combine (override_dirs [oi], OVERRIDE_ENVIRONMENT_FILE_NAME);
if (utils.file_exists (env_override_file)) {
setup_environment_from_override_file (env_override_file);
}
delete[] env_override_file;
}
#endif
}
void

Просмотреть файл

@ -11,6 +11,7 @@
#include "util.h"
#include "cpu-arch.h"
#include "cppcompat.h"
#include "xamarin-app.h"
namespace xamarin { namespace android {
class jstring_wrapper;
@ -19,22 +20,18 @@ namespace xamarin { namespace android {
namespace xamarin { namespace android { namespace internal
{
#if defined (DEBUG) || !defined (ANDROID)
struct BundledProperty;
struct KnownEnvironmentVariables
{
static constexpr bool AssemblyPreloadDefault = true;
bool DSOInApk = false;
MonoAotMode MonoAOT = MonoAotMode::MONO_AOT_MODE_NONE;
bool MonoLLVM = false;
bool EnableAssemblyPreload = AssemblyPreloadDefault;
};
#endif
class AndroidSystem
{
private:
#if defined (DEBUG) || !defined (ANDROID)
static constexpr char OVERRIDE_ENVIRONMENT_FILE_NAME[] = "environment";
static constexpr uint32_t OVERRIDE_ENVIRONMENT_FILE_HEADER_SIZE = 22;
static BundledProperty *bundled_properties;
#endif
static const char* android_abi_names[CPU_KIND_X86_64+1];
#if defined (WINDOWS)
static std::mutex readdir_mutex;
@ -92,7 +89,7 @@ namespace xamarin { namespace android { namespace internal
static size_t app_lib_directories_size;
public:
void setup_environment (JNIEnv *env, jobjectArray environmentVariables);
void setup_environment ();
void setup_process_args (JNIEnv *env, jstring_array_wrapper &runtimeApks);
int monodroid_get_system_property (const char *name, char **value);
int monodroid_get_system_property_from_overrides (const char *name, char ** value);
@ -139,32 +136,43 @@ namespace xamarin { namespace android { namespace internal
#endif
bool is_assembly_preload_enabled () const
{
return knownEnvVars.EnableAssemblyPreload;
return application_config.uses_assembly_preload;
}
bool is_mono_llvm_enabled () const
{
return knownEnvVars.MonoLLVM;
return application_config.uses_mono_llvm;
}
bool is_mono_aot_enabled () const
{
return application_config.uses_mono_aot;
}
bool is_embedded_dso_mode_enabled () const
{
return knownEnvVars.DSOInApk;
return application_config.uses_embedded_dsos;
}
MonoAotMode get_mono_aot_mode () const
{
return knownEnvVars.MonoAOT;
return aotMode;
}
private:
#if defined (DEBUG) || !defined (ANDROID)
void add_system_property (const char *name, const char *value);
int get_max_gref_count_from_system ();
void setup_environment (jstring_wrapper& name, jstring_wrapper& value);
void setup_environment (const char *name, const char *value);
void setup_environment_from_override_file (const char *path);
BundledProperty* lookup_system_property (const char *name);
#endif
const char* lookup_system_property (const char *name, uint32_t &value_len);
int get_max_gref_count_from_system ();
void setup_process_args_apk (const char *apk, int index, int apk_count, void *user_data);
int _monodroid__system_property_get (const char *name, char *sp_value, size_t sp_value_len);
#if defined (DEBUG) || !defined (ANDROID)
int _monodroid_get_system_property_from_file (const char *path, char **value);
#endif
void copy_native_libraries_to_internal_location ();
void copy_file_to_internal_location (char *to_dir, char *from_dir, char *file);
void add_apk_libdir (const char *apk, int index, int apk_count, void *user_data);
@ -188,7 +196,7 @@ namespace xamarin { namespace android { namespace internal
#endif // !ANDROID
private:
int max_gref_count = 0;
KnownEnvironmentVariables knownEnvVars;
MonoAotMode aotMode = MonoAotMode::MONO_AOT_MODE_NONE;
};
}}}
#endif // !__ANDROID_SYSTEM_H

Просмотреть файл

@ -0,0 +1,28 @@
#include <stdint.h>
#include <stdlib.h>
#include "xamarin-app.h"
// This file MUST have valid values everywhere - the DSO it is compiled into is loaded by the
// designer on desktop.
TypeMapHeader jm_typemap_header = { 1, 0, 0, 0 };
uint8_t jm_typemap[] = { 0 };
TypeMapHeader mj_typemap_header = { 1, 0, 0, 0 };
uint8_t mj_typemap[] = { 0 };
ApplicationConfig application_config = {
.uses_mono_llvm = false,
.uses_mono_aot = false,
.uses_embedded_dsos = false,
.uses_assembly_preload = false,
.is_a_bundled_app = false,
.environment_variable_count = 0,
.system_property_count = 0,
.android_package_name = "com.xamarin.test",
};
const char* mono_aot_mode_name = "";
const char* app_environment_variables[] = {};
const char* app_system_properties[] = {};

Просмотреть файл

@ -19,8 +19,10 @@ extern "C" {
#include "embedded-assemblies.h"
#include "globals.h"
#include "monodroid-glue.h"
#include "xamarin-app.h"
namespace xamarin { namespace android { namespace internal {
#if defined (DEBUG) || !defined (ANDROID)
struct TypeMappingInfo {
char *source_apk;
char *source_entry;
@ -30,6 +32,7 @@ namespace xamarin { namespace android { namespace internal {
const char *mapping;
TypeMappingInfo *next;
};
#endif // DEBUG || !ANDROID
struct md_mmap_info {
void *area;
@ -47,8 +50,9 @@ const char *EmbeddedAssemblies::suffixes[] = {
};
constexpr char EmbeddedAssemblies::assemblies_prefix[];
#if defined (DEBUG) || !defined (ANDROID)
constexpr char EmbeddedAssemblies::override_typemap_entry_name[];
#endif
void EmbeddedAssemblies::set_assemblies_prefix (const char *prefix)
{
@ -131,9 +135,19 @@ EmbeddedAssemblies::TypeMappingInfo_compare_key (const void *a, const void *b)
return strcmp (reinterpret_cast <const char*> (a), reinterpret_cast <const char*> (b));
}
inline const char*
EmbeddedAssemblies::find_entry_in_type_map (const char *name, uint8_t map[], TypeMapHeader& header)
{
const char *e = reinterpret_cast<const char*> (bsearch (name, map, header.entry_count, header.entry_length, TypeMappingInfo_compare_key ));
if (e == nullptr)
return nullptr;
return e + header.value_offset;
}
inline const char*
EmbeddedAssemblies::typemap_java_to_managed (const char *java)
{
#if defined (DEBUG) || !defined (ANDROID)
for (TypeMappingInfo *info = java_to_managed_maps; info != nullptr; info = info->next) {
/* log_warn (LOG_DEFAULT, "# jonp: checking file: %s!%s for type '%s'", info->source_apk, info->source_entry, java); */
const char *e = reinterpret_cast<const char*> (bsearch (java, info->mapping, info->num_entries, info->entry_length, TypeMappingInfo_compare_key));
@ -141,12 +155,14 @@ EmbeddedAssemblies::typemap_java_to_managed (const char *java)
continue;
return e + info->value_offset;
}
return nullptr;
#endif
return find_entry_in_type_map (java, jm_typemap, jm_typemap_header);
}
inline const char*
EmbeddedAssemblies::typemap_managed_to_java (const char *managed)
{
#if defined (DEBUG) || !defined (ANDROID)
for (TypeMappingInfo *info = managed_to_java_maps; info != nullptr; info = info->next) {
/* log_warn (LOG_DEFAULT, "# jonp: checking file: %s!%s for type '%s'", info->source_apk, info->source_entry, managed); */
const char *e = reinterpret_cast <const char*> (bsearch (managed, info->mapping, info->num_entries, info->entry_length, TypeMappingInfo_compare_key));
@ -154,7 +170,8 @@ EmbeddedAssemblies::typemap_managed_to_java (const char *managed)
continue;
return e + info->value_offset;
}
return nullptr;
#endif
return find_entry_in_type_map (managed, mj_typemap, mj_typemap_header);
}
MONO_API const char *
@ -169,6 +186,7 @@ monodroid_typemap_managed_to_java (const char *managed)
return embeddedAssemblies.typemap_managed_to_java (managed);
}
#if defined (DEBUG) || !defined (ANDROID)
void
EmbeddedAssemblies::extract_int (const char **header, const char *source_apk, const char *source_entry, const char *key_name, int *value)
{
@ -235,6 +253,7 @@ EmbeddedAssemblies::add_type_mapping (TypeMappingInfo **info, const char *source
}
return true;
}
#endif // DEBUG || !ANDROID
md_mmap_info
EmbeddedAssemblies::md_mmap_apk_file (int fd, uLong offset, uLong size, const char* filename, const char* apk)
@ -381,17 +400,6 @@ EmbeddedAssemblies::gather_bundled_assemblies_from_apk (const char* apk, monodro
continue;
}
if (utils.ends_with (cur_entry_name, ".jm")) {
md_mmap_info map_info = md_mmap_apk_file (fd, offset, info.uncompressed_size, cur_entry_name, apk);
add_type_mapping (&java_to_managed_maps, apk, cur_entry_name, (const char*)map_info.area);
continue;
}
if (utils.ends_with (cur_entry_name, ".mj")) {
md_mmap_info map_info = md_mmap_apk_file (fd, offset, info.uncompressed_size, cur_entry_name, apk);
add_type_mapping (&managed_to_java_maps, apk, cur_entry_name, (const char*)map_info.area);
continue;
}
const char *prefix = get_assemblies_prefix();
if (strncmp (prefix, cur_entry_name, strlen (prefix)) != 0)
continue;
@ -469,6 +477,7 @@ EmbeddedAssemblies::gather_bundled_assemblies_from_apk (const char* apk, monodro
return true;
}
#if defined (DEBUG) || !defined (ANDROID)
void
EmbeddedAssemblies::try_load_typemaps_from_directory (const char *path)
{
@ -514,6 +523,7 @@ EmbeddedAssemblies::try_load_typemaps_from_directory (const char *path)
free (dir_path);
return;
}
#endif
size_t
EmbeddedAssemblies::register_from (const char *apk_file, monodroid_should_register should_register)

Просмотреть файл

@ -7,15 +7,21 @@
#include "unzip.h"
#include "ioapi.h"
struct TypeMapHeader;
namespace xamarin { namespace android { namespace internal {
#if defined (DEBUG) || !defined (ANDROID)
struct TypeMappingInfo;
#endif
struct md_mmap_info;
class EmbeddedAssemblies
{
private:
static constexpr char assemblies_prefix[] = "assemblies/";
#if defined (DEBUG) || !defined (ANDROID)
static constexpr char override_typemap_entry_name[] = ".__override__";
#endif
static const char *suffixes[];
public:
@ -23,7 +29,9 @@ namespace xamarin { namespace android { namespace internal {
using monodroid_should_register = bool (*)(const char *filename);
public:
#if defined (DEBUG) || !defined (ANDROID)
void try_load_typemaps_from_directory (const char *path);
#endif
void install_preload_hooks ();
const char* typemap_java_to_managed (const char *java);
const char* typemap_managed_to_java (const char *managed);
@ -53,7 +61,9 @@ namespace xamarin { namespace android { namespace internal {
bool gather_bundled_assemblies_from_apk (const char* apk, monodroid_should_register should_register);
MonoAssembly* open_from_bundles (MonoAssemblyName* aname, bool ref_only);
void extract_int (const char **header, const char *source_apk, const char *source_entry, const char *key_name, int *value);
#if defined (DEBUG) || !defined (ANDROID)
bool add_type_mapping (TypeMappingInfo **info, const char *source_apk, const char *source_entry, const char *addr);
#endif // DEBUG || !ANDROID
bool register_debug_symbols_for_assembly (const char *entry_name, MonoBundledAssembly *assembly, const mono_byte *debug_contents, int debug_size);
static md_mmap_info md_mmap_apk_file (int fd, uLong offset, uLong size, const char* filename, const char* apk);
@ -67,6 +77,7 @@ namespace xamarin { namespace android { namespace internal {
static MonoAssembly* open_from_bundles_full (MonoAssemblyName *aname, char **assemblies_path, void *user_data);
static MonoAssembly* open_from_bundles_refonly (MonoAssemblyName *aname, char **assemblies_path, void *user_data);
static int TypeMappingInfo_compare_key (const void *a, const void *b);
const char *find_entry_in_type_map (const char *name, uint8_t map[], TypeMapHeader& header);
const char* get_assemblies_prefix () const
{
@ -77,8 +88,10 @@ namespace xamarin { namespace android { namespace internal {
bool register_debug_symbols;
MonoBundledAssembly **bundled_assemblies;
size_t bundled_assemblies_count;
#if defined (DEBUG) || !defined (ANDROID)
TypeMappingInfo *java_to_managed_maps;
TypeMappingInfo *managed_to_java_maps;
#endif // DEBUG || !ANDROID
const char *assemblies_prefix_override = nullptr;
};
}}}

Просмотреть файл

@ -65,6 +65,7 @@ extern "C" {
#include "mkbundle-api.h"
#include "monodroid-glue-internal.h"
#include "globals.h"
#include "xamarin-app.h"
#ifndef WINDOWS
#include "xamarin_getifaddrs.h"
@ -215,6 +216,9 @@ mono_mkbundle_initialize_mono_api_ptr mono_mkbundle_initialize_mono_api;
static void
setup_bundled_app (const char *dso_name)
{
if (!application_config.is_a_bundled_app)
return;
static int dlopen_flags = RTLD_LAZY;
void *libapp = nullptr;
@ -481,7 +485,7 @@ should_register_file (const char *filename)
static void
gather_bundled_assemblies (JNIEnv *env, jstring_array_wrapper &runtimeApks, bool register_debug_symbols, int *out_user_assemblies_count)
{
#ifndef RELEASE
#if defined(DEBUG) || !defined (ANDROID)
for (size_t i = 0; i < AndroidSystem::MAX_OVERRIDES; ++i) {
const char *p = androidSystem.get_override_dir (i);
if (!utils.directory_exists (p))
@ -1177,6 +1181,7 @@ init_android_runtime (MonoDomain *domain, JNIEnv *env, jclass runtimeClass, jobj
lookup_bridge_info (domain, image, &osBridge.get_java_gc_bridge_type (i), &osBridge.get_java_gc_bridge_info (i));
}
// TODO: try looking up the method by its token
runtime = utils.monodroid_get_class_from_image (domain, image, "Android.Runtime", "JNIEnv");
method = monoFunctions.class_get_method_from_name (runtime, "Initialize", 1);
@ -1877,13 +1882,12 @@ Java_mono_android_Runtime_init (JNIEnv *env, jclass klass, jstring lang, jobject
TimeZone_class = utils.get_class_from_runtime_field (env, klass, "java_util_TimeZone", true);
jstring_wrapper jstr (env, packageName);
utils.monodroid_store_package_name (jstr.get_cstr ());
utils.monodroid_store_package_name (application_config.android_package_name);
jstr = lang;
jstring_wrapper jstr (env, lang);
set_environment_variable (env, "LANG", jstr);
androidSystem.setup_environment (env, environmentVariables);
androidSystem.setup_environment ();
jstr = reinterpret_cast <jstring> (env->GetObjectArrayElement (appDirs, 1));
set_environment_variable_for_directory (env, "TMPDIR", jstr);
@ -2008,13 +2012,15 @@ Java_mono_android_Runtime_init (JNIEnv *env, jclass klass, jstring lang, jobject
log_info (LOG_DEFAULT, "Probing for Mono AOT mode\n");
MonoAotMode mode = androidSystem.get_mono_aot_mode ();
if (mode == MonoAotMode::MONO_AOT_MODE_UNKNOWN)
mode = MonoAotMode::MONO_AOT_MODE_NONE;
if (androidSystem.is_mono_aot_enabled ()) {
MonoAotMode mode = androidSystem.get_mono_aot_mode ();
if (mode == MonoAotMode::MONO_AOT_MODE_UNKNOWN)
mode = MonoAotMode::MONO_AOT_MODE_NONE;
if (mode != MonoAotMode::MONO_AOT_MODE_NORMAL && mode != MonoAotMode::MONO_AOT_MODE_NONE) {
log_info (LOG_DEFAULT, "Enabling AOT mode in Mono");
monoFunctions.jit_set_aot_mode (mode);
if (mode != MonoAotMode::MONO_AOT_MODE_NORMAL && mode != MonoAotMode::MONO_AOT_MODE_NONE) {
log_info (LOG_DEFAULT, "Enabling AOT mode in Mono");
monoFunctions.jit_set_aot_mode (mode);
}
}
log_info (LOG_DEFAULT, "Probing if we should use LLVM\n");

Просмотреть файл

@ -26,16 +26,6 @@ constexpr int FALSE = 0;
#define MONODROID_PATH_SEPARATOR_CHAR '/'
#endif
#if WINDOWS
typedef struct _stat monodroid_stat_t;
#define monodroid_dir_t _WDIR
typedef struct _wdirent monodroid_dirent_t;
#else
typedef struct stat monodroid_stat_t;
#define monodroid_dir_t DIR
typedef struct dirent monodroid_dirent_t;
#endif
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
@ -50,6 +40,16 @@ typedef struct dirent monodroid_dirent_t;
#include "dylib-mono.h"
#include "jni-wrappers.h"
#if WINDOWS
typedef struct _stat monodroid_stat_t;
#define monodroid_dir_t _WDIR
typedef struct _wdirent monodroid_dirent_t;
#else
typedef struct stat monodroid_stat_t;
#define monodroid_dir_t DIR
typedef struct dirent monodroid_dirent_t;
#endif
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus

Просмотреть файл

@ -0,0 +1,40 @@
// Dear Emacs, this is a -*- C++ -*- header
#ifndef __XAMARIN_ANDROID_TYPEMAP_H
#define __XAMARIN_ANDROID_TYPEMAP_H
#include <stdint.h>
#include "monodroid.h"
struct TypeMapHeader
{
uint32_t version;
uint32_t entry_count;
uint32_t entry_length;
uint32_t value_offset;
};
struct ApplicationConfig
{
bool uses_mono_llvm;
bool uses_mono_aot;
bool uses_embedded_dsos;
bool uses_assembly_preload;
bool is_a_bundled_app;
uint32_t environment_variable_count;
uint32_t system_property_count;
const char *android_package_name;
};
MONO_API TypeMapHeader jm_typemap_header;
MONO_API uint8_t jm_typemap[];
MONO_API TypeMapHeader mj_typemap_header;
MONO_API uint8_t mj_typemap[];
MONO_API ApplicationConfig application_config;
MONO_API const char* app_environment_variables[];
MONO_API const char* app_system_properties[];
MONO_API const char* mono_aot_mode_name;
#endif // __XAMARIN_ANDROID_TYPEMAP_H

Просмотреть файл

@ -31,13 +31,13 @@
<!-- CMAKE_RUNTIME_OUTPUT_DIRECTORY is provided for the mingw cross builds. DLL outputs are treated as _runtime_ objects (as opposed to _library_ ones for .so, .dylib etc) by cmake
and so in order to put libmono-android.*.dll in the output dir we need to set this property. Since we build no executables here, it won't affect the non-DLL outputs. -->
<Exec
Command="$(CmakePath) %(_HostRuntime.CmakeFlags) -DCONFIGURATION=Release -DCMAKE_BUILD_TYPE=Debug -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=$(OutputPath)/%(_HostRuntime.OutputDirectory) -DCMAKE_RUNTIME_OUTPUT_DIRECTORY=$(OutputPath)/%(_HostRuntime.OutputDirectory) $(MSBuildThisFileDirectory)"
Command="$(CmakePath) %(_HostRuntime.CmakeFlags) -DCONFIGURATION=Release -DCMAKE_BUILD_TYPE=Debug -DCMAKE_ARCHIVE_OUTPUT_DIRECTORY=$(OutputPath)/%(_HostRuntime.OutputDirectory) -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=$(OutputPath)/%(_HostRuntime.OutputDirectory) -DCMAKE_RUNTIME_OUTPUT_DIRECTORY=$(OutputPath)/%(_HostRuntime.OutputDirectory) $(MSBuildThisFileDirectory)"
WorkingDirectory="$(IntermediateOutputPath)%(_HostRuntime.OutputDirectory)-Debug"
/>
<MakeDir Directories="$(IntermediateOutputPath)%(_HostRuntime.OutputDirectory)-Release" />
<Exec
Command="$(CmakePath) %(_HostRuntime.CmakeFlags) -DSTRIP_DEBUG=ON -DCONFIGURATION=Debug -DCMAKE_BUILD_TYPE=Release -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=$(OutputPath)/%(_HostRuntime.OutputDirectory) -DCMAKE_RUNTIME_OUTPUT_DIRECTORY=$(OutputPath)/%(_HostRuntime.OutputDirectory) $(MSBuildThisFileDirectory)"
Command="$(CmakePath) %(_HostRuntime.CmakeFlags) -DSTRIP_DEBUG=ON -DCONFIGURATION=Debug -DCMAKE_BUILD_TYPE=Release -DCMAKE_ARCHIVE_OUTPUT_DIRECTORY=$(OutputPath)/%(_HostRuntime.OutputDirectory) -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=$(OutputPath)/%(_HostRuntime.OutputDirectory) -DCMAKE_RUNTIME_OUTPUT_DIRECTORY=$(OutputPath)/%(_HostRuntime.OutputDirectory) $(MSBuildThisFileDirectory)"
WorkingDirectory="$(IntermediateOutputPath)%(_HostRuntime.OutputDirectory)-Release"
/>
</Target>
@ -47,13 +47,13 @@
Outputs="@(AndroidSupportedTargetJitAbi->'$(IntermediateOutputPath)\%(Identity)-Debug\CMakeCache.txt');@(AndroidSupportedTargetJitAbi->'$(IntermediateOutputPath)\%(Identity)-Release\CMakeCache.txt')">
<MakeDir Directories="$(IntermediateOutputPath)%(AndroidSupportedTargetJitAbi.Identity)-Debug" />
<Exec
Command="$(CmakePath) $(_CmakeAndroidFlags) -DCONFIGURATION=Release -DCMAKE_BUILD_TYPE=Debug -DANDROID_NATIVE_API_LEVEL=%(AndroidSupportedTargetJitAbi.ApiLevel) -DANDROID_PLATFORM=android-%(AndroidSupportedTargetJitAbi.ApiLevel) -DANDROID_ABI=%(AndroidSupportedTargetJitAbi.Identity) -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=$(OutputPath)%(AndroidSupportedTargetJitAbi.Identity) $(MSBuildThisFileDirectory)"
Command="$(CmakePath) $(_CmakeAndroidFlags) -DCONFIGURATION=Release -DCMAKE_BUILD_TYPE=Debug -DANDROID_NATIVE_API_LEVEL=%(AndroidSupportedTargetJitAbi.ApiLevel) -DANDROID_PLATFORM=android-%(AndroidSupportedTargetJitAbi.ApiLevel) -DANDROID_ABI=%(AndroidSupportedTargetJitAbi.Identity) -DCMAKE_ARCHIVE_OUTPUT_DIRECTORY=$(OutputPath)%(AndroidSupportedTargetJitAbi.Identity) -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=$(OutputPath)%(AndroidSupportedTargetJitAbi.Identity) $(MSBuildThisFileDirectory)"
WorkingDirectory="$(IntermediateOutputPath)%(AndroidSupportedTargetJitAbi.Identity)-Debug"
/>
<MakeDir Directories="$(IntermediateOutputPath)%(AndroidSupportedTargetJitAbi.Identity)-Release" />
<Exec
Command="$(CmakePath) $(_CmakeAndroidFlags) -DSTRIP_DEBUG=ON -DCONFIGURATION=Debug -DCMAKE_BUILD_TYPE=Release -DANDROID_NATIVE_API_LEVEL=%(AndroidSupportedTargetJitAbi.ApiLevel) -DANDROID_PLATFORM=android-%(AndroidSupportedTargetJitAbi.ApiLevel) -DANDROID_ABI=%(AndroidSupportedTargetJitAbi.Identity) -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=$(OutputPath)%(AndroidSupportedTargetJitAbi.Identity) $(MSBuildThisFileDirectory)"
Command="$(CmakePath) $(_CmakeAndroidFlags) -DSTRIP_DEBUG=ON -DCONFIGURATION=Debug -DCMAKE_BUILD_TYPE=Release -DANDROID_NATIVE_API_LEVEL=%(AndroidSupportedTargetJitAbi.ApiLevel) -DANDROID_PLATFORM=android-%(AndroidSupportedTargetJitAbi.ApiLevel) -DANDROID_ABI=%(AndroidSupportedTargetJitAbi.Identity) -DCMAKE_ARCHIVE_OUTPUT_DIRECTORY=$(OutputPath)%(AndroidSupportedTargetJitAbi.Identity) -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=$(OutputPath)%(AndroidSupportedTargetJitAbi.Identity) $(MSBuildThisFileDirectory)"
WorkingDirectory="$(IntermediateOutputPath)%(AndroidSupportedTargetJitAbi.Identity)-Release"
/>
</Target>
@ -61,7 +61,7 @@
<Target Name="_BuildAndroidRuntimes"
DependsOnTargets="_ConfigureAndroidRuntimes"
Inputs="@(_MonodroidSource);@(AndroidSupportedTargetJitAbi->'$(IntermediateOutputPath)\%(Identity)-Debug\CMakeCache.txt');@(AndroidSupportedTargetJitAbi->'$(IntermediateOutputPath)\%(Identity)-Release\CMakeCache.txt');jni\*.cc;jni\*.h;jni\**\*.c;;..\..\build-tools\scripts\Ndk.targets"
Outputs="@(AndroidSupportedTargetJitAbi->'$(OutputPath)\%(Identity)\libmono-android.debug.so');@(AndroidSupportedTargetJitAbi->'$(OutputPath)\%(Identity)\libmono-android.release.so')">
Outputs="@(AndroidSupportedTargetJitAbi->'$(OutputPath)\%(Identity)\libmono-android.debug.so');@(AndroidSupportedTargetJitAbi->'$(OutputPath)\%(Identity)\libmono-android.release.so');@(AndroidSupportedTargetJitAbi->'$(IntermediateOutputPath)\%(Identity)-Debug\libxamarin-app.so');@(AndroidSupportedTargetJitAbi->'$(IntermediateOutputPath)\%(Identity)-Release\libxamarin-app.so')">
<Exec
Command="$(NinjaPath) -v"
WorkingDirectory="$(IntermediateOutputPath)%(AndroidSupportedTargetJitAbi.Identity)-Debug"
@ -76,7 +76,7 @@
<Target Name="_BuildHostRuntimes"
DependsOnTargets="_GetBuildHostRuntimes;_CreateJavaInteropDllConfigs;_ConfigureHostRuntimes"
Inputs="@(_MonodroidSource);@(_HostRuntime->'$(IntermediatePath)%(OutputDirectory)-Debug\CMakeCache.txt');@(_HostRuntime->'$(IntermediatePath)%(OutputDirectory)-Release\CMakeCache.txt');jni\*.cc;jni\*.h;jni\**\*.c;"
Outputs="@(_HostRuntime->'$(OutputPath)%(OutputDirectory)\libmono-android.debug.%(NativeLibraryExtension)');@(_HostRuntime->'$(OutputPath)%(OutputDirectory)\libmono-android.release.%(NativeLibraryExtension)')">
Outputs="@(_HostRuntime->'$(OutputPath)%(OutputDirectory)\libmono-android.debug.%(NativeLibraryExtension)');@(_HostRuntime->'$(OutputPath)%(OutputDirectory)\libmono-android.release.%(NativeLibraryExtension)');@(_HostRuntime->'$(OutputPath)%(OutputDirectory)\libxamarin-app.%(NativeLibraryExtension)')">
<Message Text="Building host runtime %(_HostRuntime.Identity) in $(OutputPath)%(_HostRuntime.OutputDirectory)"/>
<MakeDir Directories="$(OutputPath)%(_HostRuntime.OutputDirectory)" />
@ -97,6 +97,7 @@
SourceFiles="@(_HostRuntime->'$(OutputPath)%(OutputDirectory)\libmono-android.release.%(NativeLibraryExtension)')"
DestinationFiles="@(_HostRuntime->'$(OutputPath)%(OutputDirectory)\libmono-android.release.d.%(NativeLibraryExtension)')"
/>
</Target>
<Target Name="_CleanRuntimes"
DependsOnTargets="_GetBuildHostRuntimes"

Просмотреть файл

@ -11,6 +11,7 @@ using System.Xml.XPath;
using Microsoft.Build.Framework;
using NUnit.Framework;
using Xamarin.Android.Build.Tests;
using Xamarin.ProjectTools;
using Xamarin.Tools.Zip;
@ -18,9 +19,9 @@ using XABuildPaths = global::Xamarin.Android.Build.Paths;
namespace EmbeddedDSOUnitTests
{
sealed class LocalBuilder : Builder
sealed class LocalBuilder : ProjectBuilder
{
public LocalBuilder ()
public LocalBuilder (string projectDir) : base (projectDir)
{
BuildingInsideVisualStudio = false;
}
@ -71,8 +72,13 @@ namespace EmbeddedDSOUnitTests
{
testProjectPath = PrepareProject (ProjectName);
string projectPath = Path.Combine (testProjectPath, $"{ProjectName}.csproj");
LocalBuilder builder = GetBuilder ("EmbeddedDSO");
bool success = builder.Build (projectPath, "SignAndroidPackage", new [] { "UnitTestsMode=true" });
LocalBuilder builder = GetBuilder ("EmbeddedDSO", testProjectPath);
string targetAbis = Xamarin.Android.Tools.XABuildConfig.SupportedABIs.Replace (";", ":");
bool success = builder.Build (projectPath, "SignAndroidPackage", new [] {
"UnitTestsMode=true",
$"Configuration={XABuildPaths.Configuration}",
$"AndroidSupportedTargetJitAbis=\"{targetAbis}\"",
});
Assert.That (success, Is.True, "Should have been built");
@ -102,28 +108,11 @@ namespace EmbeddedDSOUnitTests
[Test]
public void EnvironmentFileContents ()
{
string javaEnv = Path.Combine (testProjectPath, "obj", XABuildPaths.Configuration, "android", "src", "mono", "android", "app", "XamarinAndroidEnvironmentVariables.java");
Assert.That (new FileInfo (javaEnv), Does.Exist, $"File {javaEnv} should exist");
string[] envLines = File.ReadAllLines (javaEnv);
Assert.That (envLines.Any (l => !String.IsNullOrEmpty (l)), Is.True, $"Environment file {javaEnv} must contain at least one non-empty line");
bool found = false;
foreach (string line in envLines) {
if (String.IsNullOrEmpty (line))
continue;
if (line.IndexOf ("\"__XA_DSO_IN_APK\",") >= 0) {
found = true;
break;
}
}
Assert.That (found, Is.True, $"The `__XA_DSO_IN_APK` variable wasn't found in the environment file {javaEnv}");
string dexFile = Path.Combine (testProjectPath, "obj", XABuildPaths.Configuration, "android", "bin", "classes.dex");
Assert.That (new FileInfo (dexFile), Does.Exist, $"File {dexFile} should exist");
Assert.That (DexUtils.ContainsClass ("Lmono/android/app/XamarinAndroidEnvironmentVariables;", dexFile, androidSdkDir), Is.True, $"Dex file {dexFile} should contain the XamarinAndroidEnvironmentVariables class");
string intermediateOutputDir = Path.Combine (testProjectPath, "obj", XABuildPaths.Configuration);
List<string> envFiles = EnvironmentHelper.GatherEnvironmentFiles (intermediateOutputDir, Xamarin.Android.Tools.XABuildConfig.SupportedABIs, true);
EnvironmentHelper.ApplicationConfig app_config = EnvironmentHelper.ReadApplicationConfig (envFiles);
Assert.That (app_config, Is.Not.Null, "application_config must be present in the environment files");
Assert.That (app_config.uses_embedded_dsos, Is.True, "'uses_embedded_dsos' must be true in application_config");
}
[Test]
@ -283,9 +272,9 @@ namespace EmbeddedDSOUnitTests
File.Copy (from, to, true);
}
LocalBuilder GetBuilder (string baseLogFileName)
LocalBuilder GetBuilder (string baseLogFileName, string projectDir)
{
return new LocalBuilder {
return new LocalBuilder (projectDir) {
Verbosity = LoggerVerbosity.Diagnostic,
BuildLogFile = $"{baseLogFileName}.log"
};

Просмотреть файл

@ -34,6 +34,14 @@
<Reference Include="nunit.framework">
<HintPath>..\..\..\packages\NUnit.3.11.0\lib\net45\nunit.framework.dll</HintPath>
</Reference>
<Reference Include="Xamarin.Android.Build.Tasks">
<HintPath>..\..\..\bin\$(Configuration)\lib/xamarin.android\xbuild\Xamarin\Android\Xamarin.Android.Build.Tasks.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Xamarin.Android.Tools.AndroidSdk">
<HintPath>..\..\..\bin\$(Configuration)\lib/xamarin.android\xbuild\Xamarin\Android\Xamarin.Android.Tools.AndroidSdk.dll</HintPath>
<Private>True</Private>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="BuildTests.cs" />
@ -41,6 +49,10 @@
<Compile Include="..\..\..\bin\Test$(CONFIGURATION)/XABuildPaths.cs">
<Link>XABuildPaths.cs</Link>
</Compile>
<Compile Include="..\..\..\bin\Build$(CONFIGURATION)/XABuildConfig.cs">
<Link>XABuildConfig.cs</Link>
</Compile>
<Compile Include="..\..\..\src\Xamarin.Android.Build.Tasks\Tests\Xamarin.Android.Build.Tests\Utilities\EnvironmentHelper.cs" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />

Просмотреть файл

@ -2,6 +2,7 @@
export MONO_ENV_OPTIONS="--debug"
export USE_MSBUILD=1
export MSBUILD=msbuild
msbuild EmbeddedDSO-UnitTests.csproj
CONFIGURATION=${1:-Debug}
msbuild /p:Configuration=${CONFIGURATION} EmbeddedDSO-UnitTests.csproj
cd ../../../
exec mono --debug packages/NUnit.ConsoleRunner.3.9.0/tools/nunit3-console.exe bin/TestDebug/EmbeddedDSO/EmbeddedDSOUnitTests.dll
exec mono --debug packages/NUnit.ConsoleRunner.3.9.0/tools/nunit3-console.exe bin/Test${CONFIGURATION}/EmbeddedDSO/EmbeddedDSOUnitTests.dll

Просмотреть файл

@ -17,7 +17,6 @@
<MonoAndroidAssetsPrefix>Assets</MonoAndroidAssetsPrefix>
<AndroidUseLatestPlatformSdk>true</AndroidUseLatestPlatformSdk>
<AndroidUseSharedRuntime>false</AndroidUseSharedRuntime>
<AndroidSupportedAbis>armeabi-v7a;x86</AndroidSupportedAbis>
</PropertyGroup>
<PropertyGroup Condition=" '$(UnitTestsMode)' == 'true' ">
@ -29,6 +28,13 @@
</PropertyGroup>
<Import Project="$(RelativeRootPath)\Configuration.props" />
<PropertyGroup>
<!-- We have to limit the supported abis to the currently enabled set, since the PR builders don't build all architectures but,
eventually, we have to build for all the ABIs unconditionally here -->
<AndroidSupportedAbis>$(AndroidSupportedTargetJitAbisSplit)</AndroidSupportedAbis>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<Optimize>false</Optimize>