Skip to content

Commit

Permalink
[Xamarin.Android.Build.Tasks] Add Inputs for _GenerateJavaStubs (#9319)
Browse files Browse the repository at this point in the history
Context: xamarin/monodroid#1547

This commit updates the Inputs for the `_GenerateJavaStubs` and
`_GeneratePackageManagerJava` targets so that the
`@(AndroidEnvironment)` and `@(LibraryEnvironments)` items are only
included when we are building a release build, or a build which
embeds the assemblies into the apk.

This is so that we can eventually fast deploy these files to the
device; see also xamarin/monodroid#1547. 

To *not* attempt to (eventually) fast deploy `@(AndroidEnvironment)`
and `@(LibraryEnvironments)`, set the (*internal*!) MSBuild property
`$(_AndroidFastDeployEnvironmentFiles)` to False.

A new unit test has been added to make sure that the environment
values can be used correctly on device.
  • Loading branch information
dellis1972 authored and jonathanpeppers committed Sep 30, 2024
1 parent 1ce7ddc commit 1171f8d
Show file tree
Hide file tree
Showing 5 changed files with 85 additions and 16 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -257,10 +257,12 @@ public Foo ()
var doc = XDocument.Load (androidManifest);
Assert.IsNotNull(doc.Element ("manifest")?.Element ("queries")?.Element ("package"), $"There should be 1 package in the queries in {androidManifest}.");
// Check environment variable
var environmentFiles = EnvironmentHelper.GatherEnvironmentFiles (intermediate, "x86_64", required: true);
var environmentVariables = EnvironmentHelper.ReadEnvironmentVariables (environmentFiles);
Assert.IsTrue (environmentVariables.TryGetValue (env_var, out string actual), $"Environment should contain {env_var}");
Assert.AreEqual (env_val, actual, $"{env_var} should be {env_val}");
if (isRelease) {
var environmentFiles = EnvironmentHelper.GatherEnvironmentFiles (intermediate, "x86_64", required: true);
var environmentVariables = EnvironmentHelper.ReadEnvironmentVariables (environmentFiles);
Assert.IsTrue (environmentVariables.TryGetValue (env_var, out string actual), $"Environment should contain {env_var}");
Assert.AreEqual (env_val, actual, $"{env_var} should be {env_val}");
}

// Check Resource.designer.cs
if (!useDesignerAssembly) {
Expand Down
34 changes: 29 additions & 5 deletions src/Xamarin.Android.Build.Tasks/Xamarin.Android.Common.targets
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ Copyright (C) 2011-2012 Xamarin. All rights reserved.
<EmbedAssembliesIntoApk Condition=" '$(EmbedAssembliesIntoApk)' == '' And '$(Optimize)' != 'True' And '$(_XASupportsFastDev)' == 'True' ">False</EmbedAssembliesIntoApk>
<EmbedAssembliesIntoApk Condition=" '$(_XASupportsFastDev)' == 'False' ">True</EmbedAssembliesIntoApk>
<EmbedAssembliesIntoApk Condition=" '$(EmbedAssembliesIntoApk)' == '' ">True</EmbedAssembliesIntoApk>
<AndroidPreferNativeLibrariesWithDebugSymbols Condition=" '$(AndroidPreferNativeLibrariesWithDebugSymbols)' == '' ">False</AndroidPreferNativeLibrariesWithDebugSymbols>
<AndroidPreferNativeLibrariesWithDebugSymbols Condition=" '$(AndroidPreferNativeLibrariesWithDebugSymbols)' == '' ">False</AndroidPreferNativeLibrariesWithDebugSymbols>
<AndroidSkipJavacVersionCheck Condition="'$(AndroidSkipJavacVersionCheck)' == ''">False</AndroidSkipJavacVersionCheck>
<AndroidBuildApplicationPackage Condition=" '$(AndroidBuildApplicationPackage)' == ''">False</AndroidBuildApplicationPackage>
<AndroidGenerateLayoutBindings Condition=" '$(AndroidGenerateLayoutBindings)' == '' ">False</AndroidGenerateLayoutBindings>
Expand Down Expand Up @@ -289,6 +289,10 @@ Copyright (C) 2011-2012 Xamarin. All rights reserved.
<_NativeAssemblySourceDir>$(IntermediateOutputPath)android\</_NativeAssemblySourceDir>
<_AndroidUseNewTypemaps>True</_AndroidUseNewTypemaps>
<_SkipJniAddNativeMethodRegistrationAttributeScan Condition=" '$(_SkipJniAddNativeMethodRegistrationAttributeScan)' == '' ">False</_SkipJniAddNativeMethodRegistrationAttributeScan>

<_AndroidFastDeployEnvironmentFiles Condition=" '$(_AndroidFastDeployEnvironmentFiles)' == '' And '$(EmbedAssembliesIntoApk)' == 'False' ">True</_AndroidFastDeployEnvironmentFiles>
<_AndroidFastDeployEnvironmentFiles Condition=" '$(_AndroidFastDeployEnvironmentFiles)' == '' ">False</_AndroidFastDeployEnvironmentFiles>

</PropertyGroup>

<Choose>
Expand Down Expand Up @@ -1447,12 +1451,25 @@ because xbuild doesn't support framework reference assemblies.
_PrepareAssemblies;
_PrepareNativeAssemblySources;
$(_AfterPrepareAssemblies);
_GetGenerateJavaStubsInputs;
</_GenerateJavaStubsDependsOnTargets>
</PropertyGroup>

<Target Name="_GetGenerateJavaStubsInputs">
<ItemGroup>
<_GenerateJavaStubsInputs Include="@(_AndroidMSBuildAllProjects)" />
<_GenerateJavaStubsInputs Include="$(_ResolvedUserAssembliesHashFile)" />
<_GenerateJavaStubsInputs Include="@(_ResolvedUserMonoAndroidAssemblies)" />
<_GenerateJavaStubsInputs Include="$(_AndroidManifestAbs)" />
<_GenerateJavaStubsInputs Include="$(_AndroidBuildPropertiesCache)" />
<_GenerateJavaStubsInputs Include="@(AndroidEnvironment);@(LibraryEnvironments)" Condition=" '$(_AndroidFastDeployEnvironmentFiles)' != 'true' " />
<_EnvironmentFiles Include="@(AndroidEnvironment);@(LibraryEnvironments)" Condition=" '$(_AndroidFastDeployEnvironmentFiles)' != 'true' " />
</ItemGroup>
</Target>

<Target Name="_GenerateJavaStubs"
DependsOnTargets="$(_GenerateJavaStubsDependsOnTargets);$(BeforeGenerateAndroidManifest)"
Inputs="@(_AndroidMSBuildAllProjects);$(_ResolvedUserAssembliesHashFile);@(_ResolvedUserMonoAndroidAssemblies);$(_AndroidManifestAbs);$(_AndroidBuildPropertiesCache);@(AndroidEnvironment);@(LibraryEnvironments)"
Inputs="@(_GenerateJavaStubsInputs)"
Outputs="$(_AndroidStampDirectory)_GenerateJavaStubs.stamp">

<PropertyGroup>
Expand Down Expand Up @@ -1502,7 +1519,7 @@ because xbuild doesn't support framework reference assemblies.
LinkingEnabled="$(_LinkingEnabled)"
HaveMultipleRIDs="$(_HaveMultipleRIDs)"
IntermediateOutputDirectory="$(IntermediateOutputPath)"
Environments="@(AndroidEnvironment);@(LibraryEnvironments)">
Environments="@(_EnvironmentFiles)">
</GenerateJavaStubs>

<ItemGroup>
Expand Down Expand Up @@ -1685,12 +1702,19 @@ because xbuild doesn't support framework reference assemblies.
_GenerateAndroidRemapNativeCode;
_GenerateEmptyAndroidRemapNativeCode;
_IncludeNativeSystemLibraries;
_GetGeneratePackageManagerJavaInputs;
</_GeneratePackageManagerJavaDependsOn>
</PropertyGroup>

<Target Name="_GetGeneratePackageManagerJavaInputs">
<ItemGroup>
<_GeneratePackageManagerJavaInputs Include="@(_GenerateJavaStubsInputs)" />
</ItemGroup>
</Target>

<Target Name="_GeneratePackageManagerJava"
DependsOnTargets="$(_GeneratePackageManagerJavaDependsOn)"
Inputs="@(_AndroidMSBuildAllProjects);$(_ResolvedUserAssembliesHashFile);@(_ResolvedUserMonoAndroidAssemblies);$(_AndroidBuildPropertiesCache);@(AndroidEnvironment);@(LibraryEnvironments)"
Inputs="@(_GeneratePackageManagerJavaInputs)"
Outputs="$(_AndroidStampDirectory)_GeneratePackageManagerJava.stamp">
<!-- Create java needed for Mono runtime -->
<GeneratePackageManagerJava
Expand All @@ -1704,7 +1728,7 @@ because xbuild doesn't support framework reference assemblies.
EnvironmentOutputDirectory="$(IntermediateOutputPath)android"
TargetFrameworkVersion="$(TargetFrameworkVersion)"
Manifest="$(IntermediateOutputPath)android\AndroidManifest.xml"
Environments="@(AndroidEnvironment);@(LibraryEnvironments)"
Environments="@(_EnvironmentFiles)"
AndroidAotMode="$(AndroidAotMode)"
AndroidAotEnableLazyLoad="$(AndroidAotEnableLazyLoad)"
EnableLLVM="$(EnableLLVM)"
Expand Down
6 changes: 3 additions & 3 deletions src/native/monodroid/monodroid-glue.cc
Original file line number Diff line number Diff line change
Expand Up @@ -1401,18 +1401,18 @@ MonodroidRuntime::Java_mono_android_Runtime_initInternal (JNIEnv *env, jclass kl
jstring_wrapper jstr (env, lang);
set_environment_variable ("LANG", jstr);

AndroidSystem::setup_environment ();

set_environment_variable_for_directory ("TMPDIR", applicationDirs[SharedConstants::APP_DIRS_CACHE_DIR_INDEX]);
set_environment_variable_for_directory ("HOME", home);
create_xdg_directories_and_environment (home);
AndroidSystem::set_primary_override_dir (home);
AndroidSystem::create_update_dir (AndroidSystem::get_primary_override_dir ());

AndroidSystem::setup_environment ();

jstring_array_wrapper runtimeApks (env, runtimeApksJava);
AndroidSystem::setup_app_library_directories (runtimeApks, applicationDirs, haveSplitApks);

Logger::init_reference_logging (AndroidSystem::get_primary_override_dir ());
AndroidSystem::create_update_dir (AndroidSystem::get_primary_override_dir ());

#if DEBUG
setup_gc_logging ();
Expand Down
10 changes: 6 additions & 4 deletions src/native/runtime-base/android-system.cc
Original file line number Diff line number Diff line change
Expand Up @@ -612,9 +612,6 @@ AndroidSystem::setup_environment () noexcept
}
}

if (application_config.environment_variable_count == 0)
return;

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;
Expand All @@ -638,10 +635,15 @@ AndroidSystem::setup_environment () noexcept
log_warn (LOG_DEFAULT, "Failed to set environment variable: %s", strerror (errno));
}
#if defined (DEBUG)
// TODO: for debug read from file in the override directory named `environment`
log_debug (LOG_DEFAULT, "Loading environment from override directories.");
for (const char *od : override_dirs) {
if (od == nullptr) {
continue;
}
std::unique_ptr<char[]> env_override_file {Util::path_combine (od, OVERRIDE_ENVIRONMENT_FILE_NAME.data ())};
log_debug (LOG_DEFAULT, "%s", env_override_file.get ());
if (Util::file_exists (env_override_file.get ())) {
log_debug (LOG_DEFAULT, "Loading %s", env_override_file.get ());
setup_environment_from_override_file (env_override_file.get ());
}
}
Expand Down
41 changes: 41 additions & 0 deletions tests/MSBuildDeviceIntegration/Tests/InstallAndRunTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -954,6 +954,47 @@ public void SupportDesugaringStaticInterfaceMethods ()
);
}

[Test]
public void FastDeployEnvironmentFiles ([Values (false, true)] bool isRelease)
{
var proj = new XamarinAndroidApplicationProject {
ProjectName = nameof (FastDeployEnvironmentFiles),
RootNamespace = nameof (FastDeployEnvironmentFiles),
IsRelease = isRelease,
EnableDefaultItems = true,
OtherBuildItems = {
new BuildItem("AndroidEnvironment", "env.txt") {
TextContent = () => @"Foo=Bar
Bar34=Foo55",
}
}
};
proj.MainActivity = proj.DefaultMainActivity.Replace ("//${AFTER_ONCREATE}", @"
Console.WriteLine (""Foo="" + Environment.GetEnvironmentVariable(""Foo""));
Console.WriteLine (""Bar34="" + Environment.GetEnvironmentVariable(""Bar34""));");
var builder = CreateApkBuilder ();
Assert.IsTrue (builder.Build (proj), "`dotnet build` should succeed");
RunProjectAndAssert (proj, builder);

WaitForPermissionActivity (Path.Combine (Root, builder.ProjectDirectory, "permission-logcat.log"));
bool didLaunch = WaitForActivityToStart (proj.PackageName, "MainActivity",
Path.Combine (Root, builder.ProjectDirectory, "logcat.log"), 30);
Assert.IsTrue(didLaunch, "Activity should have started.");
var appStartupLogcatFile = Path.Combine (Root, builder.ProjectDirectory, "logcat.log");
var logcatOutput = File.ReadAllText (appStartupLogcatFile);

StringAssert.Contains (
"Foo=Bar",
logcatOutput,
"The Environment variable \"Foo\" was not set."
);
StringAssert.Contains (
"Bar34=Foo55",
logcatOutput,
"The Environment variable \"Bar34\" was not set."
);
}

[Test]
public void EnableAndroidStripILAfterAOT ([Values (false, true)] bool profiledAOT)
{
Expand Down

0 comments on commit 1171f8d

Please sign in to comment.