From 13decde58e112e0845562f9ef7ee5d17e22a0490 Mon Sep 17 00:00:00 2001 From: Jonathan Peppers Date: Tue, 22 Sep 2026 12:46:12 -0500 Subject: [PATCH 1/6] [xabt] Remove legacy FastDeploy Remove the legacy native-tool deployment path and make the adb-based FastDeploy implementation the sole strategy. Remove the lz4 submodule and obsolete build packaging, then rename the surviving task, tests, and developer documentation. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/dependabot.yml | 1 - .github/skills/update-tpn/SKILL.md | 3 +- .gitmodules | 4 - .lgtm.yml | 4 - .../guides/{FastDeploy2.md => FastDeploy.md} | 46 +- Documentation/release-notes/11795.md | 19 +- Microsoft.Android.slnx | 1 - THIRD-PARTY-NOTICES.TXT | 48 +- .../installers/create-installers.targets | 6 +- external/lz4 | 1 - .../Properties/Resources.Designer.cs | 31 - .../Properties/Resources.resx | 20 - .../{FastDeploy2.Adb.cs => FastDeploy.Adb.cs} | 6 +- ...oy2.Manifest.cs => FastDeploy.Manifest.cs} | 42 +- ...2.WarmState.cs => FastDeploy.WarmState.cs} | 42 +- .../Tasks/FastDeploy.cs | 1550 +++++++---------- .../Tasks/FastDeploy2.cs | 1191 ------------- ....cs => FastDeployJsonSerializerContext.cs} | 4 +- .../Tasks/GetPrimaryCpuAbi.cs | 8 +- .../Utilities/DeviceCache.cs | 9 +- .../Xamarin.Android.Common.Debugging.props | 2 - .../Xamarin.Android.Common.Debugging.targets | 38 +- .../DebuggingTasksTests.cs | 82 +- .../Common/BuildOutput.cs | 2 +- .../Tests/FastDevTest.cs | 74 +- .../Tests/PerformanceTest.cs | 2 +- .../AdbRunnerTests.cs | 2 +- tools/fastdev/Makefile | 21 - tools/fastdev/elfcleaner/CMakeLists.txt | 33 - tools/fastdev/fastdev.slnx | 3 - tools/fastdev/fastdevtools.csproj | 25 - tools/fastdev/fastdevtools.projitems | 47 - tools/fastdev/fastdevtools.targets | 57 - tools/fastdev/xamarin.cp/CMakeLists.txt | 52 - tools/fastdev/xamarin.cp/main.cc | 111 -- tools/fastdev/xamarin.find/CMakeLists.txt | 53 - tools/fastdev/xamarin.find/main.cc | 111 -- tools/fastdev/xamarin.stat/CMakeLists.txt | 53 - tools/fastdev/xamarin.stat/main.cc | 28 - tools/fastdev/xamarin.sync/CMakeLists.txt | 70 - tools/fastdev/xamarin.sync/main.cc | 212 --- 41 files changed, 829 insertions(+), 3285 deletions(-) rename Documentation/guides/{FastDeploy2.md => FastDeploy.md} (87%) delete mode 160000 external/lz4 rename src/Xamarin.Android.Build.Debugging.Tasks/Tasks/{FastDeploy2.Adb.cs => FastDeploy.Adb.cs} (99%) rename src/Xamarin.Android.Build.Debugging.Tasks/Tasks/{FastDeploy2.Manifest.cs => FastDeploy.Manifest.cs} (93%) rename src/Xamarin.Android.Build.Debugging.Tasks/Tasks/{FastDeploy2.WarmState.cs => FastDeploy.WarmState.cs} (77%) delete mode 100644 src/Xamarin.Android.Build.Debugging.Tasks/Tasks/FastDeploy2.cs rename src/Xamarin.Android.Build.Debugging.Tasks/Tasks/{FastDeploy2JsonSerializerContext.cs => FastDeployJsonSerializerContext.cs} (55%) delete mode 100644 tools/fastdev/Makefile delete mode 100644 tools/fastdev/elfcleaner/CMakeLists.txt delete mode 100644 tools/fastdev/fastdev.slnx delete mode 100644 tools/fastdev/fastdevtools.csproj delete mode 100644 tools/fastdev/fastdevtools.projitems delete mode 100644 tools/fastdev/fastdevtools.targets delete mode 100644 tools/fastdev/xamarin.cp/CMakeLists.txt delete mode 100644 tools/fastdev/xamarin.cp/main.cc delete mode 100644 tools/fastdev/xamarin.find/CMakeLists.txt delete mode 100644 tools/fastdev/xamarin.find/main.cc delete mode 100644 tools/fastdev/xamarin.stat/CMakeLists.txt delete mode 100644 tools/fastdev/xamarin.stat/main.cc delete mode 100644 tools/fastdev/xamarin.sync/CMakeLists.txt delete mode 100644 tools/fastdev/xamarin.sync/main.cc diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 25c446845a9..ed7118b331c 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -90,6 +90,5 @@ updates: interval: "daily" ignore: - dependency-name: "external/constexpr-xxh3" - - dependency-name: "external/lz4" - dependency-name: "external/robin-map" - dependency-name: "external/xxHash" diff --git a/.github/skills/update-tpn/SKILL.md b/.github/skills/update-tpn/SKILL.md index e87dde58734..b9795c9eda1 100644 --- a/.github/skills/update-tpn/SKILL.md +++ b/.github/skills/update-tpn/SKILL.md @@ -56,7 +56,6 @@ Read `.gitmodules` for all submodules. Current submodules and their license file | Submodule | URL | License File | |-----------|-----|-------------| | Java.Interop | https://github.com/dotnet/java-interop | `external/Java.Interop/LICENSE` | -| lz4 | https://github.com/dotnet/lz4 (fork of https://github.com/lz4/lz4) | `external/lz4/lib/LICENSE` | | xxHash | https://github.com/Cyan4973/xxHash | `external/xxHash/LICENSE` | | constexpr-xxh3 | https://github.com/chys87/constexpr-xxh3 | `external/constexpr-xxh3/LICENSE` | | robin-map | https://github.com/xamarin/robin-map (fork of https://github.com/Tessil/robin-map) | `external/robin-map/LICENSE` | @@ -99,7 +98,7 @@ The `src/Xamarin.Android.Build.Tasks/Linker/External/` directory contains vendor | Linker/External/ | mono/linker | https://github.com/mono/linker/ (MIT) | #### Native Libraries (from CMakeLists.txt) -Check `src/native/` CMakeLists.txt files for references to external native code. The submodules above (lz4, xxHash, libunwind, robin-map) are compiled into native libraries. +Check `src/native/` CMakeLists.txt files for references to external native code. The submodules above (xxHash, libunwind, robin-map) are compiled into native libraries. #### Android SDK Tools These are downloaded and shipped with the SDK: diff --git a/.gitmodules b/.gitmodules index f80c52e9798..b26e0783447 100644 --- a/.gitmodules +++ b/.gitmodules @@ -10,10 +10,6 @@ path = external/libunwind url = https://github.com/libunwind/libunwind.git branch = v1.8-stable -[submodule "external/lz4"] - path = external/lz4 - url = https://github.com/dotnet/lz4 - branch = net11.0 [submodule "external/robin-map"] path = external/robin-map url = https://github.com/xamarin/robin-map diff --git a/.lgtm.yml b/.lgtm.yml index 489b49ffd8f..24f5c49c270 100644 --- a/.lgtm.yml +++ b/.lgtm.yml @@ -1,6 +1,2 @@ queries: - exclude: cs/campaign/constantine -paths: - exclude: - # we don't ship lz4 tests - - external/lz4/tests diff --git a/Documentation/guides/FastDeploy2.md b/Documentation/guides/FastDeploy.md similarity index 87% rename from Documentation/guides/FastDeploy2.md rename to Documentation/guides/FastDeploy.md index ed3ecd93e66..63239a1f9f7 100644 --- a/Documentation/guides/FastDeploy2.md +++ b/Documentation/guides/FastDeploy.md @@ -1,16 +1,15 @@ -# FastDeploy2 +# FastDeploy -`FastDeploy2` is the fast-deployment strategy used by `Install` builds (it is the -default; the legacy strategy is still available as `FastDeploy`). Fast deployment -keeps the installed `.apk` small and avoids a full re-install on every `F5`: the +`FastDeploy` is the fast-deployment strategy used by `Install` builds. Fast +deployment keeps the installed `.apk` small and avoids a full re-install on every `F5`: the application assemblies (and, optionally, environment files) are pushed to the device separately and surfaced to the app through an *override directory*, so an inner-loop change only re-transfers the files that actually changed. -This document describes how the [`FastDeploy2`][task] MSBuild task works: the +This document describes how the [`FastDeploy`][task] MSBuild task works: the stages it runs, the `adb` commands it issues, and the properties that control it. -[task]: ../../src/Xamarin.Android.Build.Debugging.Tasks/Tasks/FastDeploy2.cs +[task]: ../../src/Xamarin.Android.Build.Debugging.Tasks/Tasks/FastDeploy.cs ## MSBuild properties @@ -19,9 +18,8 @@ properties intended for end users are: | Property | Default | Description | | --- | --- | --- | -| `$(_AndroidFastDevStrategy)` | `FastDeploy2` | `FastDeploy` or `FastDeploy2`. Set to `FastDeploy` to fall back to the legacy strategy. | -| `$(_AndroidFastDeployAppFileTransferMode)` | `Symlink` (for `FastDeploy2`) | How staged files are surfaced in the override directory: `Symlink` or `Copy`. | -| `$(AndroidFastDeploymentAdbCompressionAlgorithm)` | `any` | The `adb push -z` compression algorithm. `FastDeploy2` relies on a modern Android SDK Platform-Tools `adb` for multi-file `push -z` support. | +| `$(_AndroidFastDeployAppFileTransferMode)` | `Symlink` | How staged files are surfaced in the override directory: `Symlink` or `Copy`. | +| `$(AndroidFastDeploymentAdbCompressionAlgorithm)` | `any` | The `adb push -z` compression algorithm. `FastDeploy` relies on a modern Android SDK Platform-Tools `adb` for multi-file `push -z` support. | The following internal/unsupported properties tune or disable implementation details: @@ -36,31 +34,27 @@ details: ## On-device layout -* **Staging directory:** `/data/local/tmp/fastdeploy2//`. +* **Staging directory:** `/data/local/tmp/fastdeploy//`. Files are pushed here first (this location is writable by `adb` without `run-as`). * **Override directory:** `files/.__override__` inside the application's private data directory (resolved with `run-as`). The runtime loads assemblies from here in preference to the ones embedded in the `.apk`. -* **Manifest markers:** a `.fastdeploy2-manifest-hash` file is written to both the +* **Manifest markers:** a `.fastdeploy-manifest-hash` file is written to both the staging and override directories. It records the hash of the last successfully deployed manifest so the next build can detect whether the device is already up to date and skip redundant work. -After installing or reinstalling an APK, FastDeploy2 checks for orphaned staging +After installing or reinstalling an APK, FastDeploy checks for orphaned staging directories. In one `adb shell` command it enumerates staged `/` directories, compares them with `pm list packages --user `, and removes directories for packages that are no longer installed. Incremental deployments that do not install the APK skip cleanup entirely. -Changing `$(_AndroidFastDevStrategy)` or -`$(_AndroidFastDeployAppFileTransferMode)` invalidates the deployment -configuration. In particular, switching from `FastDeploy2` to legacy -`FastDeploy` removes the FastDeploy2-managed override tree before -`xamarin.sync` runs, so legacy deployment never attempts to overwrite -FastDeploy2 symlinks. The installed package and unrelated application data are -preserved. +Changing `$(_AndroidFastDeployAppFileTransferMode)` invalidates the deployment +configuration so the override tree is rebuilt using the selected transfer mode. +The installed package and unrelated application data are preserved. ## Stages @@ -72,7 +66,7 @@ is passed to every subsequent command as `adb -s …`. ### 2. Validate warm device state -When the APK and local FastDeploy2 manifest are current, one tagged +When the APK and local FastDeploy manifest are current, one tagged `adb shell` probe performs the warm-path validation. It reads both compatibility properties, the staging marker, the app-private path and override marker through `run-as`, and the current process id. If the app is running, the same shell @@ -149,7 +143,7 @@ This is the incremental core (`DeployFastDevFilesWithAdbPush`): `{ relative-path → (size, mtime) }` forms the manifest. A single SHA256 hash over the whole manifest is used as the device readiness marker (see below). 2. **Compare against the device.** The previous manifest is read from `obj`, and - the on-device `.fastdeploy2-manifest-hash` markers are read to confirm the + the on-device `.fastdeploy-manifest-hash` markers are read to confirm the device still matches it. If the staging directory is not in the expected state it is reset: ``` @@ -192,7 +186,7 @@ This is the incremental core (`DeployFastDevFilesWithAdbPush`): The marker match is intentionally the fast-path filesystem contract; the task does not probe every expected directory before each upload. If a push reports -that an expected remote path is missing or has the wrong file type, FastDeploy2 +that an expected remote path is missing or has the wrong file type, FastDeploy discards the incremental state, clears the staging and override trees, and retries once as a full deployment. A successful retry rewrites both remote markers and the local manifest. @@ -206,7 +200,7 @@ diagnostics map to `XA0131`–`XA0137`. See the ## Command Compatibility -.NET for Android supports Android 7.0 (API level 24) and later. FastDeploy2's +.NET for Android supports Android 7.0 (API level 24) and later. FastDeploy's device-side commands are available by Android 6.0 (API level 23), before the supported device floor. The API levels below are approximate because shell utilities are not Android SDK APIs. @@ -214,15 +208,15 @@ utilities are not Android SDK APIs. Host-side `adb` commands depend on the installed Android SDK Platform-Tools version rather than the device API level: -| Command | FastDeploy2 use | Compatibility | +| Command | FastDeploy use | Compatibility | | --- | --- | --- | | `adb devices`, `adb -s shell ...` | Device selection and all device-side operations | Standard Platform-Tools commands | | `adb install -r -d [-t] [--user ]` | APK installation and replacement | Standard Platform-Tools command; `--user` corresponds to Android multi-user support introduced in API 17 | | `adb push -z ` | Batched compressed staging-file upload | Modern Platform-Tools capability; not controlled by the device application API level | -FastDeploy2 uses these device-side commands and shell features: +FastDeploy uses these device-side commands and shell features: -| Command or shell feature | FastDeploy2 use | Approximate availability | +| Command or shell feature | FastDeploy use | Approximate availability | | --- | --- | --- | | `sh`/mksh syntax, `[ ... ]`, `test`, `command -v`, `cd`, `pwd`, `echo`, globbing, command/parameter/arithmetic expansion, and redirection | Combined checks, override updates, and cleanup control flow | API 14; Android has used mksh since Android 4.0 | | `getprop` | Validate `run-as` compatibility properties | API 1 | diff --git a/Documentation/release-notes/11795.md b/Documentation/release-notes/11795.md index 541197933ad..4bd9e4c2ac4 100644 --- a/Documentation/release-notes/11795.md +++ b/Documentation/release-notes/11795.md @@ -1,24 +1,19 @@ #### Application build and deployment - [GitHub PR #11795](https://github.com/dotnet/android/pull/11795): - Added a faster `FastDeploy2` fast-deployment strategy, now the default for - app install fast deployment. Three new MSBuild properties control it: - - `$(_AndroidFastDevStrategy)`: `FastDeploy` or `FastDeploy2` (default). - Set to `FastDeploy` to fall back to the legacy strategy. - - `$(_AndroidFastDeployAppFileTransferMode)`: `Symlink` (default for - `FastDeploy2`) or `Copy`. + Improved the `FastDeploy` app install implementation. Two new MSBuild + properties control it: + - `$(_AndroidFastDeployAppFileTransferMode)`: `Symlink` (default) or `Copy`. - `$(AndroidFastDeploymentAdbCompressionAlgorithm)`: the `adb push -z` - compression algorithm, `any` by default. `FastDeploy2` relies on a modern + compression algorithm, `any` by default. `FastDeploy` relies on a modern Android SDK Platform-Tools `adb` for multi-file `push -z` support. Warm incremental deployments combine compatibility checks, package/marker inspection, process detection, and app termination into one live `adb shell` probe. They also skip redundant staging-directory creation and update both - success markers in one command. Switching between `FastDeploy2` and legacy - `FastDeploy` now clears incompatible override state without uninstalling the - app or deleting unrelated app data. If an incremental upload discovers that - expected remote staging paths are missing or have the wrong type, FastDeploy2 + success markers in one command. If an incremental upload discovers that + expected remote staging paths are missing or have the wrong type, FastDeploy retries once with a fresh staging and override deployment. - See the [FastDeploy2 guide](../guides/FastDeploy2.md) for a detailed + See the [FastDeploy guide](../guides/FastDeploy.md) for a detailed description of the deployment stages and the `adb` commands they run. diff --git a/Microsoft.Android.slnx b/Microsoft.Android.slnx index 9157735c0dc..496538f5e18 100644 --- a/Microsoft.Android.slnx +++ b/Microsoft.Android.slnx @@ -53,7 +53,6 @@ - diff --git a/THIRD-PARTY-NOTICES.TXT b/THIRD-PARTY-NOTICES.TXT index 5759a3f7d26..889ca0923ec 100644 --- a/THIRD-PARTY-NOTICES.TXT +++ b/THIRD-PARTY-NOTICES.TXT @@ -26,14 +26,13 @@ implication, estoppel or otherwise. 15. KonradKuczynski/ELFSharp (https://elfsharp.it/) 16. libunwind/libunwind (https://github.com/libunwind/libunwind) 17. lovettchris/SgmlReader (https://github.com/lovettchris/SgmlReader/) -18. lz4/lz4 (https://github.com/lz4/lz4/) -19. MiloszKrajewski/K4os.Compression.LZ4 (https://github.com/MiloszKrajewski/K4os.Compression.LZ4/) -20. mono/cecil (https://github.com/mono/cecil/) -21. mono/linker (https://github.com/mono/linker/) -22. nih-at/libzip (https://github.com/nih-at/libzip/) -23. NuGet/NuGet.Client (https://github.com/NuGet/NuGet.Client) -24. tessil/robin-map (https://github.com/Tessil/robin-map) -25. xamarin/LibZipSharp (https://github.com/xamarin/LibZipSharp/) +18. MiloszKrajewski/K4os.Compression.LZ4 (https://github.com/MiloszKrajewski/K4os.Compression.LZ4/) +19. mono/cecil (https://github.com/mono/cecil/) +20. mono/linker (https://github.com/mono/linker/) +21. nih-at/libzip (https://github.com/nih-at/libzip/) +22. NuGet/NuGet.Client (https://github.com/NuGet/NuGet.Client) +23. tessil/robin-map (https://github.com/Tessil/robin-map) +24. xamarin/LibZipSharp (https://github.com/xamarin/LibZipSharp/) %% Android API documentation NOTICES AND INFORMATION BEGIN HERE ================================================================ @@ -2281,38 +2280,6 @@ END OF libunwind/libunwind NOTICES AND INFORMATION END OF lovettchris/SgmlReader NOTICES AND INFORMATION -%% lz4/lz4 NOTICES AND INFORMATION BEGIN HERE -============================================= -LZ4 Library -Copyright (c) 2011-2020, Yann Collet -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -* Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - -* Redistributions in binary form must reproduce the above copyright notice, this - list of conditions and the following disclaimer in the documentation and/or - other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -============================================= -END OF lz4/lz4 NOTICES AND INFORMATION - - %% MiloszKrajewski/K4os.Compression.LZ4 NOTICES AND INFORMATION BEGIN HERE ========================================================================== MIT License @@ -2520,4 +2487,3 @@ SOFTWARE. ========================================================= END OF xamarin/LibZipSharp NOTICES AND INFORMATION - diff --git a/build-tools/installers/create-installers.targets b/build-tools/installers/create-installers.targets index 8cda3fd00cb..780682b1e3e 100644 --- a/build-tools/installers/create-installers.targets +++ b/build-tools/installers/create-installers.targets @@ -192,7 +192,7 @@ + and src/Xamarin.Android.Build.Debugging.Tasks. --> <_MSBuildFiles Include="$(MicrosoftAndroidSdkOutDir)ICSharpCode.SharpZipLib.dll" /> <_MSBuildFiles Include="$(MicrosoftAndroidSdkOutDir)ICSharpCode.SharpZipLib.pdb" /> @@ -214,10 +214,6 @@ <_MSBuildFiles Include="$(MicrosoftAndroidSdkOutDir)Xamarin.Installer.Common.pdb" /> <_MSBuildFiles Include="$(MicrosoftAndroidSdkOutDir)Xamarin.Installer.Common.props" /> <_MSBuildFiles Include="$(MicrosoftAndroidSdkOutDir)Xamarin.Installer.Common.targets" /> - <_MSBuildFiles Include="@(AndroidSupportedTargetJitAbi->'$(MicrosoftAndroidSdkOutDir)lib\%(Identity)\xamarin.sync')" /> - <_MSBuildFiles Include="@(AndroidSupportedTargetJitAbi->'$(MicrosoftAndroidSdkOutDir)lib\%(Identity)\xamarin.find')" /> - <_MSBuildFiles Include="@(AndroidSupportedTargetJitAbi->'$(MicrosoftAndroidSdkOutDir)lib\%(Identity)\xamarin.stat')" /> - <_MSBuildFiles Include="@(AndroidSupportedTargetJitAbi->'$(MicrosoftAndroidSdkOutDir)lib\%(Identity)\xamarin.cp')" /> - /// Looks up a localized string similar to Unable to copy Fast Deployment tools to '{0}/{1}' on the target device. - ///This device might not be compatible with Fast Deployment. - ///Please set the 'EmbedAssembliesIntoApk' MSBuild property to 'true' to disable Fast Deployment in the Visual Studio project property pages, or edit the project file in a text editor.. - /// - internal static string XA0126_UnableToCopyFastDevTools { - get { - return ResourceManager.GetString("XA0126_UnableToCopyFastDevTools", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Error deploying '{0}' using '{1}: {2}'. - ///Please set the 'EmbedAssembliesIntoApk' MSBuild property to 'true' to disable Fast Deployment in the Visual Studio project property pages, or edit the project file in a text editor.. - /// - internal static string XA0127_ErrorDeployingFile { - get { - return ResourceManager.GetString("XA0127_ErrorDeployingFile", resourceCulture); - } - } - /// /// Looks up a localized string similar to The 'log.redirect-stdio' Android system property is set to 'true' on the target device or emulator. ///To enable compatibility with Fast Deployment, set the property to 'false' or reboot the device or emulator to clear the value.. @@ -155,16 +134,6 @@ internal static string XA0129_ErrorDeployingFile { } } - /// - /// Looks up a localized string similar to Sorry. Fast Deployment is only supported on devices running Android 5.0 (API level 21) or higher. - ///Please set the 'EmbedAssembliesIntoApk' MSBuild property to 'true' to disable Fast Deployment in the Visual Studio project property pages, or edit the project file in a text editor.. - /// - internal static string XA0130_FastDevNotSupported { - get { - return ResourceManager.GetString("XA0130_FastDevNotSupported", resourceCulture); - } - } - /// /// Looks up a localized string similar to The 'run-as' tool has been disabled on this device. Either enable it by activating the developer options on the device or by setting `ro.boot.disable_runas` to `false`.. /// diff --git a/src/Xamarin.Android.Build.Debugging.Tasks/Properties/Resources.resx b/src/Xamarin.Android.Build.Debugging.Tasks/Properties/Resources.resx index f4c6ea5ca2e..c41464ab0dc 100644 --- a/src/Xamarin.Android.Build.Debugging.Tasks/Properties/Resources.resx +++ b/src/Xamarin.Android.Build.Debugging.Tasks/Properties/Resources.resx @@ -140,22 +140,6 @@ ABI - is an acronym for Application Binary Interface. {0} - the target name the user supplied - - Unable to copy Fast Deployment tools to '{0}/{1}' on the target device. -This device might not be compatible with Fast Deployment. -Please set the 'EmbedAssembliesIntoApk' MSBuild property to 'true' to disable Fast Deployment in the Visual Studio project property pages, or edit the project file in a text editor. - The following are literal names and should not be translated: -{0} - A device path -{1} - A filename - - - Error deploying '{0}' using '{1}: {2}'. -Please set the 'EmbedAssembliesIntoApk' MSBuild property to 'true' to disable Fast Deployment in the Visual Studio project property pages, or edit the project file in a text editor. -The following are literal names and should not be translated: -{0} - A filename -{1} - The tool that was used to deploy the file. -{2} - The actual error that occured. - The 'log.redirect-stdio' Android system property is set to 'true' on the target device or emulator. To enable compatibility with Fast Deployment, set the property to 'false' or reboot the device or emulator to clear the value. @@ -165,10 +149,6 @@ To enable compatibility with Fast Deployment, set the property to 'false' or reb Please set the 'EmbedAssembliesIntoApk' MSBuild property to 'true' to disable Fast Deployment in the Visual Studio project property pages, or edit the project file in a text editor. The following are literal names and should not be translated: {0} - A filename - - - Sorry. Fast Deployment is only supported on devices running Android 5.0 (API level 21) or higher. -Please set the 'EmbedAssembliesIntoApk' MSBuild property to 'true' to disable Fast Deployment in the Visual Studio project property pages, or edit the project file in a text editor. The 'run-as' tool has been disabled on this device. Either enable it by activating the developer options on the device or by setting `ro.boot.disable_runas` to `false`. diff --git a/src/Xamarin.Android.Build.Debugging.Tasks/Tasks/FastDeploy2.Adb.cs b/src/Xamarin.Android.Build.Debugging.Tasks/Tasks/FastDeploy.Adb.cs similarity index 99% rename from src/Xamarin.Android.Build.Debugging.Tasks/Tasks/FastDeploy2.Adb.cs rename to src/Xamarin.Android.Build.Debugging.Tasks/Tasks/FastDeploy.Adb.cs index a6a8c65a6fc..a4d05b15d19 100644 --- a/src/Xamarin.Android.Build.Debugging.Tasks/Tasks/FastDeploy2.Adb.cs +++ b/src/Xamarin.Android.Build.Debugging.Tasks/Tasks/FastDeploy.Adb.cs @@ -8,10 +8,10 @@ namespace Xamarin.Android.Tasks { - public partial class FastDeploy2 + public partial class FastDeploy { // The high-level device operations below are implemented directly on top of `adb` - // (via RunAdbCommand / RunAdbShellCommand) so that FastDeploy2 does not depend on the + // (via RunAdbCommand / RunAdbShellCommand) so that FastDeploy does not depend on the // legacy Mono.AndroidTools / Xamarin.AndroidTools assemblies. /// @@ -279,7 +279,7 @@ public string GetFailureMessage () } /// - /// Thrown when adb install fails for a reason FastDeploy2 cannot recover from. The + /// Thrown when adb install fails for a reason FastDeploy cannot recover from. The /// is the ADB#### code reported to MSBuild. /// class FastDeployInstallException : Exception diff --git a/src/Xamarin.Android.Build.Debugging.Tasks/Tasks/FastDeploy2.Manifest.cs b/src/Xamarin.Android.Build.Debugging.Tasks/Tasks/FastDeploy.Manifest.cs similarity index 93% rename from src/Xamarin.Android.Build.Debugging.Tasks/Tasks/FastDeploy2.Manifest.cs rename to src/Xamarin.Android.Build.Debugging.Tasks/Tasks/FastDeploy.Manifest.cs index 391a19b742d..b47aad4dd47 100644 --- a/src/Xamarin.Android.Build.Debugging.Tasks/Tasks/FastDeploy2.Manifest.cs +++ b/src/Xamarin.Android.Build.Debugging.Tasks/Tasks/FastDeploy.Manifest.cs @@ -10,10 +10,10 @@ namespace Xamarin.Android.Tasks { - public partial class FastDeploy2 + public partial class FastDeploy { - const string RemoteStagingRootPath = "/data/local/tmp/fastdeploy2"; - const string ManifestHashMarker = ".fastdeploy2-manifest-hash"; + const string RemoteStagingRootPath = "/data/local/tmp/fastdeploy"; + const string ManifestHashMarker = ".fastdeploy-manifest-hash"; string RemoteStagingRoot => RemoteStagingRootPath; @@ -21,12 +21,12 @@ async Task CleanupRemoteStagingDirectories () { string command = CreateRemoteStagingCleanupCommand (RemoteStagingRoot); if (command.Length >= MaxShellCommandLength) { - LogDiagnostic ($"FastDeploy2 orphan staging cleanup command length {command.Length} exceeds the configured maximum of {MaxShellCommandLength}; cleanup will be skipped."); + LogDiagnostic ($"FastDeploy orphan staging cleanup command length {command.Length} exceeds the configured maximum of {MaxShellCommandLength}; cleanup will be skipped."); return; } AdbCommandResult result = await RunAdbShellCommand (command); if (result.ExitCode != 0) { - LogDiagnostic ($"FastDeploy2 orphan staging cleanup failed and will be skipped. Output: {result.Output}"); + LogDiagnostic ($"FastDeploy orphan staging cleanup failed and will be skipped. Output: {result.Output}"); } else if (!string.IsNullOrEmpty (result.StandardOutput)) { LogDiagnostic (result.StandardOutput); } @@ -40,7 +40,7 @@ static string CreateRemoteStagingCleanupCommand (string remoteStagingRoot) "for t in rm rmdir pm grep;do command -v \"$t\">/dev/null 2>&1||exit 0;done", "n=0;s=0;u=''", "for c in \"$r\"/*/*;do [ -d \"$c\" ]||continue;i=${c##*/};case \"$i\" in ''|*[!0-9]*)continue;;esac;case \" $u \" in *\" $i \"*)continue;;esac;u=\"$u $i\";p=$(pm list packages --user \"$i\");x=$?;if [ $x -ne 0 ]||[ -z \"$p\" ];then s=1;continue;fi;echo \"$p\"|grep -qv '^package:';[ $? -eq 1 ]||{ s=1;continue;};for d in \"$r\"/*/\"$i\";do [ -d \"$d\" ]||continue;q=${d%/*};a=${q##*/};echo \"$p\"|grep -Fqx \"package:$a\";x=$?;[ $x -eq 0 ]&&continue;if [ $x -ne 1 ];then s=1;continue;fi;if [ -L \"$r\" ]||[ -L \"$q\" ]||[ -L \"$d\" ];then s=1;continue;fi;if rm -rf \"$d\";then rmdir \"$q\" 2>/dev/null||true;n=$((n+1));else s=1;fi;done;done", - "echo \"FastDeploy2 orphan staging cleanup: removed $n directories\"", + "echo \"FastDeploy orphan staging cleanup: removed $n directories\"", "exit \"$s\"", }); } @@ -80,7 +80,7 @@ async Task DeployFastDevFilesWithAdbPush (string overridePath, bool forceF var changedFiles = GetChangedFiles (currentManifest, previousManifest); var removedFiles = GetRemovedFiles (currentManifest, previousManifest); - LogDiagnostic ($"FastDeploy2 manifest changed files: {changedFiles.Count}; removed files: {removedFiles.Count}."); + LogDiagnostic ($"FastDeploy manifest changed files: {changedFiles.Count}; removed files: {removedFiles.Count}."); foreach (var file in files) { if (changedFiles.Contains (file.RelativePath)) { @@ -96,7 +96,7 @@ async Task DeployFastDevFilesWithAdbPush (string overridePath, bool forceF if (filesRequiringDirectories.Count > 0) { string output = await CreateRemoteStagingDirectories (remoteStagingPath, filesRequiringDirectories); if (!string.IsNullOrEmpty (output) && IsShellError (output, "mkdir")) { - LogFastDeploy2Error ("XA0129", output, remoteStagingPath); + LogFastDeployError ("XA0129", output, remoteStagingPath); return false; } } @@ -108,10 +108,10 @@ async Task DeployFastDevFilesWithAdbPush (string overridePath, bool forceF UploadFilesResult uploadResult = await UploadChangedFiles (remoteStagingPath, files, changedFiles); if (!uploadResult.Success) { if (uploadResult.RemoteStateInvalid && !forceFreshDeployment) { - LogDiagnostic ($"FastDeploy2 remote staging state was incomplete. Retrying with a fresh deployment. Output: {uploadResult.Output}"); + LogDiagnostic ($"FastDeploy remote staging state was incomplete. Retrying with a fresh deployment. Output: {uploadResult.Output}"); return await DeployFastDevFilesWithAdbPush (overridePath, forceFreshDeployment: true); } - LogFastDeploy2Error ("XA0129", uploadResult.Output, uploadResult.RemoteDirectory); + LogFastDeployError ("XA0129", uploadResult.Output, uploadResult.RemoteDirectory); return false; } @@ -146,7 +146,7 @@ async Task UpdateOverrideShellSymlinks (string remoteStagingPath, string o var newFiles = previousSymlinkManifest == null ? new HashSet (currentManifest.Files.Keys, StringComparer.Ordinal) : new HashSet (currentManifest.Files.Keys.Where (file => !previousSymlinkManifest.Files.ContainsKey (file)), StringComparer.Ordinal); - LogDiagnostic ($"FastDeploy2 symlink update new files: {newFiles.Count}; removed files: {removedFiles.Count}."); + LogDiagnostic ($"FastDeploy symlink update new files: {newFiles.Count}; removed files: {removedFiles.Count}."); if (!await RunCombinedShellSymlinkUpdate (remoteStagingPath, overridePath, currentManifest, previousSymlinkManifest, newFiles, removedFiles)) { return await FallbackToCopy (remoteStagingPath, overridePath); @@ -252,7 +252,7 @@ IEnumerable BatchShellWords (string prefix, IEnumerable words, s async Task FallbackToCopy (string remoteStagingPath, string overridePath) { - LogDiagnostic ("FastDeploy2 symlink update failed; falling back to copy mode."); + LogDiagnostic ("FastDeploy symlink update failed; falling back to copy mode."); return await UpdateOverrideCopies (remoteStagingPath, overridePath, clearOverrideDirectory: true); } @@ -386,7 +386,7 @@ async Task RemoveRemoteStaleFiles (string remoteStagingPath, List var args = new [] { "shell" }.Concat (batch).ToArray (); var result = await RunAdbCommand (args); if (result.ExitCode != 0 || IsShellError (result.Output, "rm")) { - LogFastDeploy2Error ("XA0129", result.Output, remoteStagingPath); + LogFastDeployError ("XA0129", result.Output, remoteStagingPath); return false; } } @@ -397,7 +397,7 @@ async Task ResetRemoteStagingDirectory (string remoteStagingPath) { var result = await RunAdbCommand ("shell", "rm", "-rf", remoteStagingPath); if (result.ExitCode != 0 || IsShellError (result.Output, "rm")) { - LogFastDeploy2Error ("XA0129", result.Output, remoteStagingPath); + LogFastDeployError ("XA0129", result.Output, remoteStagingPath); return false; } return true; @@ -454,7 +454,7 @@ async Task ClearOverrideSymlinkState (string overridePath) string markerPath = CombineRemotePath (overridePath, ManifestHashMarker); string output = await RunAsShell ($"if test -f {QuoteShellArgument (markerPath)}; then rm -rf {QuoteShellArgument (overridePath)}; else rm -f {QuoteShellArgument (markerPath)}; fi"); if (RaiseRunAsError (output) || IsShellError (output, "rm")) { - LogFastDeploy2Error ("XA0129", output, overridePath); + LogFastDeployError ("XA0129", output, overridePath); return false; } return true; @@ -464,7 +464,7 @@ async Task ClearOverrideDirectory (string overridePath) { string output = await RunAs ("rm", "-rf", overridePath); if (RaiseRunAsError (output) || IsShellError (output, "rm")) { - LogFastDeploy2Error ("XA0129", output, overridePath); + LogFastDeployError ("XA0129", output, overridePath); return false; } return true; @@ -491,7 +491,7 @@ async Task MarkRemoteManifests (string remoteStagingPath, string overrideP result.ExitCode != 0 || IsShellError (result.Output, "mkdir") || IsShellError (result.Output, "printf")) { - LogFastDeploy2Error ("XA0129", result.Output, remoteMarkerPath); + LogFastDeployError ("XA0129", result.Output, remoteMarkerPath); return false; } return true; @@ -518,10 +518,10 @@ ManifestData LoadPreviousManifest () } try { - var manifest = JsonSerializer.Deserialize (File.ReadAllText (manifestFile), typeof (ManifestData), FastDeploy2JsonSerializerContext.Default) as ManifestData; + var manifest = JsonSerializer.Deserialize (File.ReadAllText (manifestFile), typeof (ManifestData), FastDeployJsonSerializerContext.Default) as ManifestData; return IsManifestForCurrentTarget (manifest) ? manifest : null; } catch (Exception ex) { - LogDiagnostic ($"Ignoring FastDeploy2 manifest '{manifestFile}'. {ex}"); + LogDiagnostic ($"Ignoring FastDeploy manifest '{manifestFile}'. {ex}"); return null; } } @@ -530,7 +530,7 @@ void WriteManifest (ManifestData manifest) { string manifestFile = GetManifestFilePath (); Directory.CreateDirectory (Path.GetDirectoryName (manifestFile)); - File.WriteAllText (manifestFile, JsonSerializer.Serialize (manifest, typeof (ManifestData), FastDeploy2JsonSerializerContext.Default)); + File.WriteAllText (manifestFile, JsonSerializer.Serialize (manifest, typeof (ManifestData), FastDeployJsonSerializerContext.Default)); } bool IsManifestForCurrentTarget (ManifestData manifest) @@ -571,7 +571,7 @@ string GetManifestFilePath () { return Path.Combine ( GetFullPath (IntermediateOutputPath), - "fastdeploy2", + "fastdeploy", GetSafeFileName (GetDeviceId ()), GetSafeFileName (PackageName), GetSafeFileName (GetUserId ()), diff --git a/src/Xamarin.Android.Build.Debugging.Tasks/Tasks/FastDeploy2.WarmState.cs b/src/Xamarin.Android.Build.Debugging.Tasks/Tasks/FastDeploy.WarmState.cs similarity index 77% rename from src/Xamarin.Android.Build.Debugging.Tasks/Tasks/FastDeploy2.WarmState.cs rename to src/Xamarin.Android.Build.Debugging.Tasks/Tasks/FastDeploy.WarmState.cs index 50a1b791186..3848e09897f 100644 --- a/src/Xamarin.Android.Build.Debugging.Tasks/Tasks/FastDeploy2.WarmState.cs +++ b/src/Xamarin.Android.Build.Debugging.Tasks/Tasks/FastDeploy.WarmState.cs @@ -7,16 +7,16 @@ namespace Xamarin.Android.Tasks { - public partial class FastDeploy2 + public partial class FastDeploy { - const string WarmRedirectTag = "__XA_FD2_REDIRECT__="; - const string WarmRunAsDisabledTag = "__XA_FD2_RUN_AS_DISABLED__="; - const string WarmRemoteHashTag = "__XA_FD2_REMOTE_HASH__="; - const string WarmPathTag = "__XA_FD2_PATH__="; - const string WarmOverrideHashTag = "__XA_FD2_OVERRIDE_HASH__="; - const string WarmPidTag = "__XA_FD2_PID__="; - const string WarmRunAsStatusTag = "__XA_FD2_RUN_AS_STATUS__="; - const string WarmForceStopStatusTag = "__XA_FD2_FORCE_STOP_STATUS__="; + const string WarmRedirectTag = "__XA_FD_REDIRECT__="; + const string WarmRunAsDisabledTag = "__XA_FD_RUN_AS_DISABLED__="; + const string WarmRemoteHashTag = "__XA_FD_REMOTE_HASH__="; + const string WarmPathTag = "__XA_FD_PATH__="; + const string WarmOverrideHashTag = "__XA_FD_OVERRIDE_HASH__="; + const string WarmPidTag = "__XA_FD_PID__="; + const string WarmRunAsStatusTag = "__XA_FD_RUN_AS_STATUS__="; + const string WarmForceStopStatusTag = "__XA_FD_FORCE_STOP_STATUS__="; DeviceManifestState warmDeviceManifestState; string warmDeviceManifestHash = ""; @@ -46,25 +46,25 @@ async Task TryRunWarmStateProbe (ManifestData previousMan runAsScript, }).Select (QuoteShellArgument)); string script = - $"fd2_redirect=$(getprop log.redirect-stdio); echo {QuoteShellArgument (WarmRedirectTag)}$fd2_redirect; " + - $"fd2_run_as_disabled=$(getprop ro.boot.disable_runas); echo {QuoteShellArgument (WarmRunAsDisabledTag)}$fd2_run_as_disabled; " + + $"fd_redirect=$(getprop log.redirect-stdio); echo {QuoteShellArgument (WarmRedirectTag)}$fd_redirect; " + + $"fd_run_as_disabled=$(getprop ro.boot.disable_runas); echo {QuoteShellArgument (WarmRunAsDisabledTag)}$fd_run_as_disabled; " + $"echo {QuoteShellArgument (WarmRemoteHashTag)}$(cat {QuoteShellArgument (remoteMarkerPath)} 2>/dev/null); " + - "if [ \"$fd2_redirect\" != true ] && [ \"$fd2_run_as_disabled\" != true ]; then " + - $"fd2_pid=$(pidof {packageName} 2>/dev/null || true); echo {QuoteShellArgument (WarmPidTag)}$fd2_pid; " + - $"{runAsCommand}; fd2_run_as_status=$?; echo {QuoteShellArgument (WarmRunAsStatusTag)}$fd2_run_as_status; " + - "fd2_force_stop_status=0; " + - $"if [ \"$fd2_run_as_status\" -eq 0 ] && [ -n \"$fd2_pid\" ]; then am force-stop {packageName}; fd2_force_stop_status=$?; fi; " + - $"echo {QuoteShellArgument (WarmForceStopStatusTag)}$fd2_force_stop_status; fi"; + "if [ \"$fd_redirect\" != true ] && [ \"$fd_run_as_disabled\" != true ]; then " + + $"fd_pid=$(pidof {packageName} 2>/dev/null || true); echo {QuoteShellArgument (WarmPidTag)}$fd_pid; " + + $"{runAsCommand}; fd_run_as_status=$?; echo {QuoteShellArgument (WarmRunAsStatusTag)}$fd_run_as_status; " + + "fd_force_stop_status=0; " + + $"if [ \"$fd_run_as_status\" -eq 0 ] && [ -n \"$fd_pid\" ]; then am force-stop {packageName}; fd_force_stop_status=$?; fi; " + + $"echo {QuoteShellArgument (WarmForceStopStatusTag)}$fd_force_stop_status; fi"; AdbCommandResult result = await RunAdbShellCommand (script); WarmStateProbeData data = ParseWarmStateProbeOutput (result.Output); if (data.HasRedirectStdio && string.Equals ("true", data.RedirectStdio, StringComparison.OrdinalIgnoreCase)) { - LogFastDeploy2Error ("XA0128", Resources.XA0128_RedirectStdioIsEnabled); + LogFastDeployError ("XA0128", Resources.XA0128_RedirectStdioIsEnabled); return WarmStateProbeOutcome.Failed; } if (data.HasRunAsDisabled && string.Equals ("true", data.RunAsDisabled, StringComparison.OrdinalIgnoreCase)) { - LogFastDeploy2Error ("XA0131", Resources.XA0131_DeveloperModeNotEnabled); + LogFastDeployError ("XA0131", Resources.XA0131_DeveloperModeNotEnabled); return WarmStateProbeOutcome.Failed; } @@ -73,7 +73,7 @@ async Task TryRunWarmStateProbe (ManifestData previousMan data.RunAsStatus != 0 || data.ForceStopStatus != 0 || string.IsNullOrEmpty (data.InternalPath)) { - LogDiagnostic ($"FastDeploy2 warm-state probe was inconclusive. Falling back to detailed device checks. Output: {result.Output}"); + LogDiagnostic ($"FastDeploy warm-state probe was inconclusive. Falling back to detailed device checks. Output: {result.Output}"); packageInfo = new PackageInfo (); return WarmStateProbeOutcome.NotEligible; } @@ -86,7 +86,7 @@ async Task TryRunWarmStateProbe (ManifestData previousMan OverrideHash = data.OverrideHash, }; warmProbeStoppedApp = true; - LogDiagnostic ("FastDeploy2 warm-state probe completed successfully."); + LogDiagnostic ("FastDeploy warm-state probe completed successfully."); return WarmStateProbeOutcome.Ready; } diff --git a/src/Xamarin.Android.Build.Debugging.Tasks/Tasks/FastDeploy.cs b/src/Xamarin.Android.Build.Debugging.Tasks/Tasks/FastDeploy.cs index f7687fb1a5e..0cdc30fe922 100644 --- a/src/Xamarin.Android.Build.Debugging.Tasks/Tasks/FastDeploy.cs +++ b/src/Xamarin.Android.Build.Debugging.Tasks/Tasks/FastDeploy.cs @@ -1,36 +1,49 @@ using System; using System.Collections.Generic; using System.Diagnostics; -using System.Text; using System.IO; using System.Linq; -using System.Net; -using System.Buffers; -using System.Text.Json; -using System.Text.Json.Serialization; +using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Android.Build.Tasks; -using Mono.AndroidTools; -using Xamarin.Android.Build.Debugging.Tasks.Properties; - -using K4os.Compression.LZ4; - using Microsoft.Build.Framework; +using Xamarin.Android.Build.Debugging.Tasks.Properties; +using Xamarin.Android.Tools; namespace Xamarin.Android.Tasks { - public class FastDeploy : AsyncTask + public partial class FastDeploy : AsyncTask { - const string XAToolsTempPath = "/data/local/tmp/.xatools"; const string OverridePath = "files/.__override__"; - const string ToolsPath = "files/.__tools__"; - const int MAX_COMMAND = 4096; - const int ADB_COMMAND_PADDING = 100; - + public override string TaskPrefix => "FD"; + /// + /// Number of stale override files to delete per rm invocation. Exposed as an + /// internal MSBuild property primarily so it can be lowered when testing batching behavior. + /// + public int StaleFileRemovalBatchSize { get; set; } = 100; + + /// + /// Number of files to copy per batch when staging fast-deployment files on the device. + /// Exposed as an internal MSBuild property primarily so it can be lowered when testing. + /// + public int CopyBatchSize { get; set; } = 25; + + /// + /// Maximum length (in characters) of a single adb shell command line before it is + /// split into multiple invocations. + /// + public int MaxShellCommandLength { get; set; } = 900; + + /// + /// Maximum length (in characters) of a single adb command line before it is split + /// into multiple invocations. + /// + public int MaxAdbCommandLength { get; set; } = 4096; + public string AdbTarget { get; set; } public string UploadFlagFile { get; set; } public bool EmbedAssembliesIntoApk { get; set; } @@ -42,27 +55,14 @@ public class FastDeploy : AsyncTask public string PackageFile { get; set; } public string PrimaryCpuAbi { get; set; } - public string ToolsAbi { get; set; } public ITaskItem [] FastDevFiles { get; set; } public bool PreserveUserData { get; set; } = true; - public bool ResetOverrideDirectory { get; set; } - [Required] - public string FastDevToolPath { get; set; } - - public string FastDevTool { get; set; } = "xamarin.sync"; - public string FastDevFindTool { get; set; } = "xamarin.find"; - public string FastDevStatTool { get; set; } = "xamarin.stat"; - public string FastDevCpTool { get; set; } = "xamarin.cp"; - - [Required] - public string ToolVersion { get; set; } + public bool DiagnosticLogging { get; set; } = false; - public bool DiagnosticLogging { get; set; } = false; - - public bool UsingAndroidNETSdk { get; set; } + public bool FastDeploySkipCleanup { get; set; } = false; public string UserID { get; set; } @@ -70,109 +70,49 @@ public class FastDeploy : AsyncTask [Required] public string IntermediateOutputPath { get; set; } - public ITaskItem[] EnvironmentFiles { get; set; } - - AndroidDevice Device; - DateTime lastUpload = DateTime.MinValue; - - internal class PackageInfo { - string internalPath = null; - public string InternalPath { - get { return internalPath; } - set { - internalPath = value?.Trim () ?? null; - } - } - public string ToolVersion { get; set; } - public int? BlockSize { get; set; } - public bool SupportsFastDev { get; set; } = true; - public bool IsSystemApplication { get; set; } = false; - public bool AdbIsRoot { get; set; } = false; - public string UserId { get; set; } = null; - public string PackageName { get; set; } = null; - public bool DiagnosticLogging { get; set; } = false; - public Action LogDebugMessage; + public ITaskItem [] EnvironmentFiles { get; set; } - } + public string AdbToolPath { get; set; } - private class DiagnosticData { - [JsonPropertyName ("Task")] - public string Task { get; set; } = nameof (FastDeploy); - [JsonPropertyName ("Properties")] - public Dictionary Properties { get; set; } = new Dictionary() { - { "target.prop.ro.product.build.version.sdk", "" }, - { "target.prop.ro.product.cpu.abilist", "" }, - { "target.prop.ro.product.manufacturer", "" }, - { "target.prop.ro.product.model", "" }, - { "target.prop.ro.product.cpu.abi", ""}, - { "deploy.error.code", ""}, - { "deploy.tool", "xamarin.sync" }, - { "deploy.result", "Success" }, - { "deploy.supports.fastdev", "True" }, - { "deploy.systemapp", "False" }, - { "deploy.duration.ms", "0" }, - { "pii.deploy.error", "" }, - { "pii.deploy.file", "" }, - }; + public string AdbToolExe { get; set; } - internal void SetProperty (string key, bool? value) - { - Properties[key] = value?.ToString () ?? "False"; - } - - internal void SetProperty (string key, int? value) - { - Properties[key] = value?.ToString () ?? "-1"; - } - - internal void SetProperty (string key, long? value) - { - Properties[key] = value?.ToString () ?? "-1"; - } - - internal void SetProperty (string key, string value) - { - Properties[key] = value ?? "unknown"; - } - } + public string AdbPushCompressionAlgorithm { get; set; } = "any"; - PackageInfo packageInfo; - Stopwatch stopWatch = new Stopwatch (); + public string AppFileTransferMode { get; set; } = "Copy"; + string DeviceId = ""; + PackageInfo packageInfo = new PackageInfo (); + DateTime lastUpload = DateTime.MinValue; Queue diagnosticLogs = new Queue (); + readonly object diagnosticLogsLock = new object (); - DiagnosticData diagnosticData = new DiagnosticData (); - - protected string ToolsFullPath { - get { return packageInfo.IsSystemApplication ? $"{packageInfo.InternalPath}/{ToolsPath}" : ToolsPath; } - } - - protected string OverrideFullPath { + string OverrideFullPath { get { return packageInfo.IsSystemApplication ? $"{packageInfo.InternalPath}/{OverridePath}" : OverridePath; } } - void StartTiming () - { - stopWatch.Restart (); - } + class PackageInfo { + string internalPath = null; + public string InternalPath { + get { return internalPath; } + set { internalPath = value?.Trim () ?? null; } + } - long GetElapsedTimeAndRestart () - { - stopWatch.Stop (); - long elapsedTime = stopWatch.ElapsedMilliseconds; - stopWatch.Restart (); - return elapsedTime; + public bool IsSystemApplication { get; set; } = false; + public bool AdbIsRoot { get; set; } = false; + public string UserId { get; set; } = null; + public string PackageName { get; set; } = null; + public int ProcessId { get; set; } = 0; } - void DebugHandler (string task, string message) - { - LogDiagnostic ($"DEBUG {task} {message} [{GetElapsedTimeAndRestart ()}ms]"); + class RemoteFileInfo { + public long Size { get; set; } + public long ModifiedTime { get; set; } } - void LogDebugMessageWithTiming (string message) - { - LogDiagnostic ($"{message} [{GetElapsedTimeAndRestart ()}ms]"); + class DirectPushFile { + public string LocalPath { get; set; } + public string RelativePath { get; set; } } void LogDiagnostic (string message) @@ -181,167 +121,113 @@ void LogDiagnostic (string message) LogDebugMessage (message); return; } - diagnosticLogs.Enqueue (message); + lock (diagnosticLogsLock) { + diagnosticLogs.Enqueue (message); + } } void PrintDiagnostics () { - while (diagnosticLogs.Count > 0) { - LogMessage (diagnosticLogs.Dequeue ()); - } - LogMessage ($"{diagnosticData.Task}"); - foreach (var t in diagnosticData.Properties) { - LogMessage ($"\t{t.Key}: {t.Value}"); + while (true) { + string message; + lock (diagnosticLogsLock) { + if (diagnosticLogs.Count == 0) { + break; + } + message = diagnosticLogs.Dequeue (); + } + LogMessage (message); } } - void LogDiagnosticDataError (string errorCode, string error, string file = "") - { - diagnosticData.SetProperty ("deploy.result", "Failed"); - if (!string.IsNullOrEmpty (file)) - diagnosticData.SetProperty ("pii.deploy.file", file); - diagnosticData.SetProperty ("pii.deploy.error", error); - diagnosticData.SetProperty ("deploy.error.code", errorCode); - } - - void SaveDiagnosticData (long ms) - { - JsonSerializerOptions options = new JsonSerializerOptions { - WriteIndented = true - }; - diagnosticData.SetProperty ("deploy.duration.ms", ms); - string newPath = Path.Combine(IntermediateOutputPath, "diagnostics", "fastdeploy.json"); - File.WriteAllText (newPath, JsonSerializer.Serialize (diagnosticData, options)); - } - public override bool Execute () { - Device = AndroidHelper.ParseTarget (AdbTarget, LogMessage, LogCodedError, logErrors: true, engine4: BuildEngine4); - if (Device == null) { + var device = AndroidHelper.ParseTarget (AdbTarget, LogMessage, LogCodedError, logErrors: true, engine4: BuildEngine4); + if (device == null) { PrintDiagnostics (); return false; } - LogMessage ($"Found device: {Device.ID}"); + DeviceId = device.ID ?? ""; + LogMessage ($"Found device: {DeviceId}"); if (string.IsNullOrEmpty (PrimaryCpuAbi) && !EmbedAssembliesIntoApk) { PrintDiagnostics (); - LogCodedError ("XA0010", Resources.XA0010_NoAbi, Device.ID); + LogCodedError ("XA0010", Resources.XA0010_NoAbi, DeviceId); return false; } + var flagFilePath = GetFullPath (UploadFlagFile); + lastUpload = File.GetLastWriteTimeUtc (flagFilePath); + LogDiagnostic ($"LastWriteTime of `{flagFilePath}`: {lastUpload}"); + var lifetime = RegisteredTaskObjectLifetime.AppDomain; - var key = ProjectSpecificTaskObjectKey ($"{Device.ID}_{PackageName}"); + var key = ProjectSpecificTaskObjectKey ($"{DeviceId}_{PackageName}_{GetType ().Name}"); if (!File.Exists (UploadFlagFile)) { packageInfo = new PackageInfo (); } else { - packageInfo = BuildEngine4.GetRegisteredTaskObjectAssemblyLocal(key, lifetime) ?? new PackageInfo (); + packageInfo = BuildEngine4.GetRegisteredTaskObjectAssemblyLocal (key, lifetime) ?? new PackageInfo (); } - packageInfo.DiagnosticLogging = DiagnosticLogging; - packageInfo.LogDebugMessage = LogDiagnostic; - AndroidLogger.Debug += DebugHandler; + try { - var flagFilePath = GetFullPath (UploadFlagFile); - lastUpload = File.GetLastWriteTimeUtc (flagFilePath); - LogDiagnostic ($"LastWriteTime of `{flagFilePath}`: {lastUpload}"); - StartTiming (); return base.Execute (); } finally { BuildEngine4.RegisterTaskObjectAssemblyLocal (key, packageInfo, lifetime, allowEarlyCollection: false); - stopWatch.Stop (); - AndroidLogger.Debug -= DebugHandler; } } public async override Task RunTaskAsync () { - var sw = new Stopwatch (); - sw.Restart (); try { await RunInstall (); } catch { PrintDiagnostics (); throw; - } finally { - sw.Stop(); - SaveDiagnosticData (sw.ElapsedMilliseconds); } } - public async Task RunInstall () + async Task RunInstall () { - await Device.EnsureProperties (CancellationToken).ConfigureAwait (false); - - diagnosticData.SetProperty ("target.prop.ro.product.build.version.sdk", Device.Properties?.BuildVersionSdk); - diagnosticData.SetProperty ("target.prop.ro.product.cpu.abilist", string.Join (";", Device.Properties?.ProductCpuAbiList ?? Array.Empty ())); - diagnosticData.SetProperty ("target.prop.ro.product.cpu.abi", PrimaryCpuAbi); - diagnosticData.SetProperty ("target.prop.ro.product.manufacturer", Device.Properties?.ProductManufacturer); - diagnosticData.SetProperty ("target.prop.ro.product.model", Device.Properties?.ProductModel); - - string redirectStdio = Device.Properties.Get ("log.redirect-stdio"); - if (redirectStdio != null && string.Equals ("true", redirectStdio.Trim (), StringComparison.OrdinalIgnoreCase)) { - LogDiagnosticDataError ("XA0128", Resources.XA0128_RedirectStdioIsEnabled); - PrintDiagnostics (); - LogCodedError ($"XA0128", Resources.XA0128_RedirectStdioIsEnabled); + WarmStateProbeOutcome warmState = await TryRunWarmStateProbe (LoadPreviousManifest ()); + if (warmState == WarmStateProbeOutcome.Failed) { return; } - string runAsDisabled = Device.Properties.Get ("ro.boot.disable_runas"); - if (runAsDisabled != null && string.Equals ("true", runAsDisabled.Trim (), StringComparison.OrdinalIgnoreCase)) { - LogDiagnosticDataError ("XA0131", Resources.XA0131_DeveloperModeNotEnabled); - PrintDiagnostics (); - LogCodedError ($"XA0131", Resources.XA0131_DeveloperModeNotEnabled); + if (warmState != WarmStateProbeOutcome.Ready) { + string redirectStdio = await GetDeviceProperty ("log.redirect-stdio"); + if (string.Equals ("true", redirectStdio, StringComparison.OrdinalIgnoreCase)) { + LogFastDeployError ("XA0128", Resources.XA0128_RedirectStdioIsEnabled); return; - } + } - await CheckAppInstalledAndDebuggable (PackageName); + string runAsDisabled = await GetDeviceProperty ("ro.boot.disable_runas"); + if (string.Equals ("true", runAsDisabled, StringComparison.OrdinalIgnoreCase)) { + LogFastDeployError ("XA0131", Resources.XA0131_DeveloperModeNotEnabled); + return; + } + + await CheckAppInstalledAndDebuggable (PackageName); + } if (EmbedAssembliesIntoApk) { - // we need to remove the .__override__ directory BEFORE we uninstall the debug apk. - // this is because run-as does NOT work on release apps. - await RemoveOverrideDirectory(); + await RemoveOverrideDirectory (); } + bool packageFileOutOfDate = !string.IsNullOrEmpty (PackageFile) && + (packageInfo.InternalPath.IndexOf ("unknown", StringComparison.OrdinalIgnoreCase) >= 0 || ReInstall || IsPackageFileOutOfDate ()); if (ReInstall && !string.IsNullOrEmpty (PackageFile)) { - await Device.UninstallPackage (PackageName, PreserveUserData, CancellationToken); + await UninstallPackage (PackageName, preserveData: PreserveUserData, user: UserID); } - if (!string.IsNullOrEmpty (PackageFile) && - (packageInfo.InternalPath.IndexOf ("unknown", StringComparison.OrdinalIgnoreCase) >= 0 || ReInstall || IsPackageFileOutOfDate ())) { + + if (packageFileOutOfDate) { try { - await InstallPackage (!(packageInfo.InternalPath.IndexOf ("unknown", StringComparison.OrdinalIgnoreCase) >= 0)); + await InstallPackage (); } catch (Exception ex) { - LogDiagnosticDataError (GetErrorCode (ex), ex.ToString ()); - PrintDiagnostics (); - LogCodedError (GetErrorCode (ex), ex.ToString ()); + LogFastDeployError (GetErrorCode (ex), ex.ToString ()); return; } - - // `pm install` can report success (or empty output) yet leave the package - // absent on the device; that only surfaces later as an opaque XA0137 run-as - // "couldn't stat /data/user/N/" failure during the post-install probe. - // Positively confirm the package landed via `pm path` and, if it did not, - // force a single reinstall before continuing. - if (!await IsPackageInstalled (PackageName)) { - LogDiagnostic ($"`pm path {PackageName}` reported no package after a successful-looking install; forcing a reinstall."); - diagnosticData.SetProperty ("deploy.reinstall.after.missing.package", value: true); - await LogAvailableDiskSpace (); - ReInstall = true; - try { - await InstallPackage (installed: false); - } catch (Exception ex) { - LogDiagnosticDataError (GetErrorCode (ex), ex.ToString ()); - PrintDiagnostics (); - LogCodedError (GetErrorCode (ex), ex.ToString ()); - return; - } - if (!await IsPackageInstalled (PackageName)) { - LogDiagnostic ($"`pm path {PackageName}` still reports no package after reinstall."); - LogDiagnosticDataError ("XA0132", Resources.XA0132_PackageNotInstalled); - PrintDiagnostics (); - LogCodedError ("XA0132", Resources.XA0132_PackageNotInstalled); - return; - } + if (!FastDeploySkipCleanup) { + await CleanupRemoteStagingDirectories (); } - if (!EmbedAssembliesIntoApk && packageInfo.InternalPath.IndexOf ("unknown", StringComparison.OrdinalIgnoreCase) >= 0) { packageInfo.InternalPath = null; await CheckAppInstalledAndDebuggable (PackageName); @@ -354,36 +240,16 @@ public async Task RunInstall () if (EmbedAssembliesIntoApk) return; - if (ResetOverrideDirectory && !await ResetOverrideDirectoryForConfigurationChange ()) { + if ((FastDevFiles?.Length ?? 0) == 0 && (EnvironmentFiles?.Length ?? 0) == 0) { return; } - if (!await InstallFastDevTools (ToolsFullPath)) { - return; - } - - if (FastDevFiles?.Any () ?? false) { + if (!warmProbeStoppedApp) { await TerminateApp (); - await DeployFastDevFiles (ToolsFullPath, OverrideFullPath); } - - return; - } - - async Task ResetOverrideDirectoryForConfigurationChange () - { - LogDebugMessage ($"Removing {OverrideFullPath} after the fast deployment configuration changed."); - string output = await Device.RunAs (packageInfo, "rm", "-Rf", OverrideFullPath); - if (RaiseRunAsError (output)) { - return false; + if (!await DeployFastDevFilesWithAdbPush (OverrideFullPath)) { + LogDiagnostic ("FastDeploy deployment did not complete successfully."); } - if (output.IndexOf ("rm:", StringComparison.OrdinalIgnoreCase) >= 0) { - LogDiagnosticDataError ("XA0129", output, OverrideFullPath); - PrintDiagnostics (); - LogCodedError ("XA0129", Resources.XA0129_ErrorDeployingFile, OverrideFullPath); - return false; - } - return true; } bool IsPackageFileOutOfDate () @@ -394,39 +260,32 @@ bool IsPackageFileOutOfDate () return lastUpload < lastPackage; } - int CompressLZ4 (ref byte [] data, int len, ref byte [] outBuffer, LZ4Level lZ4Level = LZ4Level.L00_FAST) - { - int compressedLength = LZ4Codec.Encode (data, 0, len, outBuffer, 0, outBuffer.Length, lZ4Level); - if (compressedLength < 0 || compressedLength >= outBuffer.Length) { - if (DiagnosticLogging) - LogDebugMessage ($"Sending Data Uncompressed."); - compressedLength = outBuffer.Length; - data.CopyTo (outBuffer, 0); - } - return compressedLength; - } - async Task CheckAppInstalledAndDebuggable (string packageName) { packageInfo.UserId = UserID; packageInfo.PackageName = packageName; + packageInfo.ProcessId = 0; await EnsureUserIsRunning (); - packageInfo.InternalPath = packageInfo.InternalPath ?? await QueryInternalPathWithRetry (); + string packageInfoOutput = IsSafePackageNameForShell (packageName) ? + await RunAs ("sh", "-c", $"pwd; pidof {packageName} 2>/dev/null || true") : + await RunAs ("pwd"); + ParsePackageInfoOutput (packageInfoOutput); + if (string.IsNullOrEmpty (packageInfo.InternalPath)) { + packageInfo.InternalPath = packageInfoOutput?.Trim (); + } if (packageInfo.InternalPath.IndexOf ("Permission denied", StringComparison.OrdinalIgnoreCase) >= 0) { - packageInfo.InternalPath = await Device.RunAs (packageInfo, "readlink", "-f", "."); + packageInfo.InternalPath = await RunAs ("readlink", "-f", "."); } if (packageInfo.InternalPath.IndexOf ("not an application", StringComparison.OrdinalIgnoreCase) >= 0) { LogDiagnostic ($"Package {packageInfo.PackageName} is a system application."); packageInfo.IsSystemApplication = true; - diagnosticData.SetProperty ("deploy.systemapp", value:true); - string whoami = await Device.RunShellCommand ("whoami"); - packageInfo.AdbIsRoot = whoami.Trim () == "root"; - LogDiagnostic ($"using {(packageInfo.AdbIsRoot ? "root" : $"su {packageInfo.UserId}")} to install fast deployment files. "); + var whoami = await RunAdbShellCommand ("whoami"); + packageInfo.AdbIsRoot = whoami.Output.Trim () == "root"; + LogDiagnostic ($"using {(packageInfo.AdbIsRoot ? "root" : $"su {packageInfo.UserId}")} to install fast deployment files."); packageInfo.InternalPath = $"/data/user/{(packageInfo.UserId ?? "0")}/{packageInfo.PackageName}"; return; } if (packageInfo.InternalPath.IndexOf ("not debuggable", StringComparison.OrdinalIgnoreCase) >= 0) { - // current install is not debuggable, so lets uninstall it LogDiagnostic ($"Package {packageInfo.PackageName} was not debuggable. Forcing ReInstall"); ReInstall = true; return; @@ -436,676 +295,618 @@ async Task CheckAppInstalledAndDebuggable (string packageName) return; } if (packageInfo.InternalPath.IndexOf ("Permission denied", StringComparison.OrdinalIgnoreCase) >= 0) { - // run-as is probably not supported. LogDiagnostic ("run-as not supported on this device."); - packageInfo.SupportsFastDev = false; - diagnosticData.SetProperty ("deploy.supports.fastdev", value: false); } - return; } - /// - /// Issues the first run-as <pkg> pwd query, retrying briefly while the - /// per-user data directory is not yet stat-able through run-as. - /// - /// - /// Immediately after pm install, the per-user data directory - /// /data/user/N/<pkg> may not yet be stat-able through run-as, - /// even for the primary user (id 0). During that window run-as returns - /// run-as: couldn't stat /data/user/N/<pkg>: No such file or directory, - /// which otherwise raises XA0137 and disables Fast Deployment. This races - /// install on the primary user ~daily in CI. Poll for a bounded period to let the - /// directory materialize before giving up. See - /// https://github.com/dotnet/android/issues/7821 and - /// https://github.com/dotnet/android/issues/11808. - /// Retry policy: up to 10 attempts with a 500 ms delay between each, giving - /// a maximum wait of 4.5 seconds before the error is surfaced as XA0137. - /// Only the transient couldn't stat … No such file or directory signature - /// (detected by ) triggers a retry; all other - /// run-as failures are surfaced immediately. - /// - async Task QueryInternalPathWithRetry () + static bool IsSafePackageNameForShell (string packageName) { - const int maxAttempts = 10; - var delay = TimeSpan.FromMilliseconds (500); - string result = await Device.RunAs (packageInfo, "pwd"); - for (int attempt = 1; attempt < maxAttempts && IsTransientRunAsStatRace (result); attempt++) { - LogDiagnostic ($"run-as could not stat the data directory for {packageInfo.PackageName} yet (attempt {attempt}/{maxAttempts}); retrying in {delay.TotalMilliseconds:0} ms. Output: {result?.Trim ()}"); - await Task.Delay (delay, CancellationToken); - result = await Device.RunAs (packageInfo, "pwd"); + if (string.IsNullOrEmpty (packageName)) { + return false; } - return result; + foreach (char c in packageName) { + if (!(char.IsLetterOrDigit (c) || c == '.' || c == '_')) { + return false; + } + } + return true; } - /// - /// Returns when a run-as result matches the transient - /// install-vs-run-as race signature (couldn't stat … No such file or directory), - /// i.e. the per-user data directory has not yet materialized after pm install. - /// - internal static bool IsTransientRunAsStatRace (string result) + void ParsePackageInfoOutput (string output) { - if (string.IsNullOrEmpty (result)) { - return false; + if (string.IsNullOrEmpty (output)) { + return; + } + + string [] lines = output.Replace ("\r", "").Split (new char [] { '\n' }, StringSplitOptions.None); + if (lines.Length > 0 && !string.IsNullOrEmpty (lines [0])) { + packageInfo.InternalPath = lines [0].Trim (); + } + if (lines.Length <= 1) { + return; + } + + string pidLine = lines [1].Trim (); + int space = pidLine.IndexOf (' '); + if (space >= 0) { + pidLine = pidLine.Substring (0, space); + } + if (int.TryParse (pidLine, out int pid)) { + packageInfo.ProcessId = pid; } - return result.IndexOf ("couldn't stat", StringComparison.OrdinalIgnoreCase) >= 0 && - result.IndexOf ("No such file or directory", StringComparison.OrdinalIgnoreCase) >= 0; } - /// - /// Ensures the secondary Android user targeted by this deployment is in the - /// 'running' state before any run-as query is issued against it. - /// - /// - /// pm install --user N <apk> registers the package but does - /// not materialize the per-user data directory /data/user/N/<pkg>; - /// that directory is only created once user N is brought to the running - /// state. Until then, every run-as <pkg> --user N invocation fails - /// with run-as: couldn't stat /data/user/N/<pkg>: No such file or - /// directory and raises XA0137. See - /// https://github.com/dotnet/android/issues/7821. - /// Empirical measurement on an arm64 API-34 emulator (N=50) showed that - /// without this step, 52% of installs fail run-as at t=0 and 30% - /// never recover even after 30 seconds of polling — i.e. polling alone is not - /// sufficient. am start-user -w N succeeds in 100/100 attempts within - /// ~134 ms median (max 363 ms), is idempotent, and is a cheap no-op when the - /// user is already running. The primary user (id 0) never requires this step, - /// so skip it to avoid any cost in the common case. - /// async Task EnsureUserIsRunning () { - var userId = (UserID ?? string.Empty).Trim (); + var userId = (UserID ?? "").Trim (); if (userId.Length == 0 || (int.TryParse (userId, out var id) && id == 0)) { return; } LogDiagnostic ($"Ensuring Android user {userId} is in the 'running' state before run-as queries."); - string output = await Device.RunShellCommand (CancellationToken, "am", "start-user", "-w", userId); - // `am start-user -w` normally prints `Success: user started`. Surface any - // output (success or failure, e.g. `Error: could not start user`) at the - // diagnostic level so build logs make the cause obvious if the subsequent - // `run-as` query fails. Do not attempt to interpret the output here: the - // existing run-as error path raises XA0137 deterministically on failure, - // and parsing `am`'s output for error markers risks false positives. + var result = await RunAdbShellCommand ("am", "start-user", "-w", userId); + string output = result.Output; LogDiagnostic ($"'am start-user -w {userId}' returned: {(string.IsNullOrWhiteSpace (output) ? "" : output.Trim ())}"); } - protected async Task RemoveOverrideDirectory () { - // remote //.__override__ directory has files in it. - // We can do that by using out tool stat. - string overrideExists = await Device.RunAs (packageInfo, $"{ToolsFullPath}/{FastDevStatTool}", OverrideFullPath); - if (!(overrideExists.IndexOf ("error:", StringComparison.OrdinalIgnoreCase) >= 0) && - !(overrideExists.IndexOf ("package not debuggable", StringComparison.OrdinalIgnoreCase) >= 0)) { - await Device.RunAs (packageInfo, "rm", "-Rf", OverrideFullPath); - } + async Task InstallPackage () + { + LogDebugMessage ($"Installing Package {PackageName}"); + await InstallApkWithRetry (PackageFile, reinstall: ReInstall, testOnly: IsTestOnly, user: UserID); + LogDebugMessage ($"Installed Package {PackageName}."); + } + + async Task RemoveOverrideDirectory () + { + await RunAs ("rm", "-Rf", OverrideFullPath); } - protected async Task TerminateApp () + async Task TerminateApp () { - var pid = await Device.GetProcessId (PackageName, CancellationToken); + var pid = packageInfo.ProcessId; + if (pid == 0 && packageInfo.IsSystemApplication) { + pid = await RunLoggedDeviceOperation ($"GetProcessId {PackageName}", () => GetProcessId (PackageName)); + } if (pid == 0) { LogDebugMessage ($"{PackageName} was not running, skipping kill"); return; } LogDebugMessage ($"Terminating {PackageName}..."); - await Device.KillProcessAndWaitForExit (PackageName, CancellationToken); - LogDebugMessageWithTiming ($"{PackageName} Terminated."); + await RunLoggedDeviceOperation ($"ForceStop {PackageName}", () => ForceStopPackage (PackageName)); + LogDebugMessage ($"{PackageName} Terminated."); } - protected async Task InstallPackage (bool installed = true) + async Task CreateRemoteStagingDirectories (string remoteStagingPath, HashSet stagedFiles) { - LogDebugMessage ($"Installing Package {PackageName}"); - try { - await Device.PushAndInstallPackageAsync (new PushAndInstallCommand { - ApkFile = PackageFile, - PackageName = PackageName, - ReInstall = ReInstall, - User = UserID, - TestOnly = IsTestOnly, - }, token: CancellationToken); - LogDebugMessageWithTiming ($"Installed Package {PackageName}."); - } catch (Exception exception) { - var ex = exception; - if (exception is AggregateException aex) { - ex = aex.Flatten ().InnerException; + var directories = new HashSet (StringComparer.Ordinal) { remoteStagingPath }; + foreach (var file in stagedFiles) { + string directory = GetDirectoryName (file); + if (!string.IsNullOrEmpty (directory)) { + directories.Add (CombineRemotePath (remoteStagingPath, directory)); } - if (!await ShouldThrowIfPackageInstallFailed (ex as PackageAlreadyExistsException)) { - LogDebugMessageWithTiming ($"Installed Package {PackageName}."); - return; - } - throw; } - return; + + var output = new StringBuilder (); + foreach (var batch in BatchArguments ("mkdir", "-p", directories)) { + output.Append ((await RunAdbShellCommand (batch.ToArray ())).Output); + } + return output.ToString (); } - /// - /// Confirms the package is actually present on the device via pm path <pkg>. - /// pm install can report success (or empty output) yet leave the package absent, - /// which otherwise only surfaces as an opaque XA0137 run-as "couldn't stat" failure - /// during the post-install probe. Returns when a package:/… - /// path is reported (or when there is no package name to query). - /// - async Task IsPackageInstalled (string packageName) + List PrepareDirectPushFiles () { - if (string.IsNullOrEmpty (packageName)) { - return true; + var files = new List (); + foreach (var file in FastDevFiles ?? []) { + string localPath = GetFullPath (file.ItemSpec); + if (!File.Exists (localPath)) { + LogDiagnostic ($"File '{file.ItemSpec}' does not exist. Skipping."); + continue; + } + if (Path.GetExtension (file.ItemSpec) == ".so") { + string abi = AndroidRidAbiHelper.GetNativeLibraryAbi (file); + if (abi != PrimaryCpuAbi) { + LogDebugMessage ($"NotifySync SkipCopyFile {GetAdbPushTargetPath (file)} abi not suitable for this device."); + continue; + } + } + + files.Add (new DirectPushFile { + LocalPath = localPath, + RelativePath = GetAdbPushTargetPath (file), + }); + LogDiagnostic ($"Prepared {file.ItemSpec} => {files [files.Count - 1].RelativePath}"); } - var args = new List { "pm", "path" }; - var userId = (UserID ?? string.Empty).Trim (); - if (userId.Length > 0) { - args.Add ("--user"); - args.Add (userId); + + if (EnvironmentFiles?.Length > 0) { + byte [] environmentData = CreateEnvironmentFileData (EnvironmentFiles, out DateTime newestFileDateTime); + if (environmentData.Length > 0) { + string environmentFile = Path.Combine (GetFullPath (IntermediateOutputPath), "fastdeploy-environment", PrimaryCpuAbi, "environment"); + WriteFileIfChanged (environmentFile, environmentData, newestFileDateTime); + files.Add (new DirectPushFile { + LocalPath = environmentFile, + RelativePath = $"{PrimaryCpuAbi}/environment", + }); + } } - args.Add (packageName); - string output = await Device.RunShellCommand (CancellationToken, args.ToArray ()); - LogDiagnostic ($"`pm path {packageName}` returned: {(string.IsNullOrWhiteSpace (output) ? "" : output.Trim ())}"); - return IsPackageInstalledOutput (output); + + return files; } - internal static bool IsPackageInstalledOutput (string output) + bool WriteFileIfChanged (string path, byte [] contents, DateTime modifiedDateTime) { - return !string.IsNullOrWhiteSpace (output) && - output.IndexOf ("package:", StringComparison.OrdinalIgnoreCase) >= 0; + if (!Files.HasBytesChanged (contents, path)) { + return false; + } + + Directory.CreateDirectory (Path.GetDirectoryName (path)); + File.WriteAllBytes (path, contents); + File.SetLastWriteTimeUtc (path, modifiedDateTime); + return true; } - /// - /// Logs the device's free space on the internal (/data) partition. A package that - /// vanishes right after a "successful" install is often a symptom of a full data partition - /// (test APKs accumulate on CI emulators), which pm install does not always surface - /// as INSTALL_FAILED_INSUFFICIENT_STORAGE. Best-effort: never throws. - /// - async Task LogAvailableDiskSpace () + string GetAdbPushTargetPath (ITaskItem file) { - try { - var disk = await Device.GetAvailableSpace (CancellationToken); - LogDiagnostic ($"Free space on /data: {disk.InternalSpace / (1024 * 1024)} MiB ({disk.InternalSpace} bytes)."); - diagnosticData.SetProperty ("deploy.data.free.bytes", disk.InternalSpace); - } catch (Exception ex) { - LogDiagnostic ($"Could not query device disk space: {ex.Message}"); + string targetPath = file.GetMetadata ("TargetPath"); + if (string.IsNullOrEmpty (targetPath)) { + LogDiagnostic ($"'TargetPath' metadata not found on '{file.ItemSpec}'. Falling back to 'DestinationSubPath'"); + targetPath = file.GetMetadata ("DestinationSubPath"); + } + if (!string.IsNullOrEmpty (targetPath)) { + return targetPath.Replace ("\\", "/"); } + return Path.GetFileName (file.ItemSpec); } - async Task ShouldThrowIfPackageInstallFailed (PackageAlreadyExistsException e) + byte [] CreateEnvironmentFileData (ITaskItem [] environments, out DateTime newestFileDateTime) { - if (e == null) - return true; + int maxKeyLength = 0; + int maxValueLength = 0; + newestFileDateTime = DateTime.MinValue; + var data = new Dictionary (); + foreach (ITaskItem env in environments ?? []) { + if (!File.Exists (env.ItemSpec)) + continue; + DateTime modifiedDateTime = File.GetLastWriteTimeUtc (env.ItemSpec); + if (modifiedDateTime > newestFileDateTime) + newestFileDateTime = modifiedDateTime; + foreach (string line in File.ReadLines (env.ItemSpec)) { + if (string.IsNullOrEmpty (line)) + continue; + int index = line.IndexOf ('='); + if (index == -1) { + LogDebugMessage ($"Skipping invalid environment line: {line}"); + continue; + } + var key = line.Substring (0, index); + var value = line.Substring (index + 1); + maxKeyLength = Math.Max (maxKeyLength, key.Length); + maxValueLength = Math.Max (maxValueLength, value.Length); + data [key] = value; + } + } - int s = (e.PackageFile ?? "").LastIndexOf ('/'); - string apkBasename = s >= 0 ? e.PackageFile.Substring (s+1) : e.PackageFile; + if (newestFileDateTime == DateTime.MinValue) { + return []; + } - // If the runtime already exists, ignore the error - // Sometimes android doesn't report it's installed when it is :/ - if (apkBasename != Path.GetFileName (PackageFile)) - return false; + maxKeyLength++; + maxValueLength++; - // Oops; things have gotten wedged (stale/interrupted install?) - // The file we tried to upload already exists on the device! - // Delete and try again. - LogDebugMessage (string.Format ("Package '{0}' already exists. Retrying...", PackageName)); - try { - // NOTE We NEED to delete the cache data too other wise the install will fail. - await Device.DeleteFile (e.PackageFile, true, CancellationToken); - } catch { - // Ebil, yes, but... - } - bool preserveData = !(e is RequiresUninstallException); - LogDebugMessage (string.Format ("Forcing complete uninstall of '{0}'... Preserving Data: {1}", PackageName, preserveData)); - var uninstallCommand = new PmUninstallCommand() { PackageName = PackageName, User = UserID, PreserveData = preserveData }; - await Device.UninstallPackage (uninstallCommand, cancellationToken: CancellationToken); - LogDebugMessage (string.Format ("Installing '{0}'...", PackageName)); - await Device.PushAndInstallPackageAsync (new PushAndInstallCommand { - ApkFile = PackageFile, - PackageName = PackageName, - ReInstall = false, - User = UserID - },token: CancellationToken); - return false; + using (var stream = new MemoryStream ()) + using (var binaryWriter = new BinaryWriter (stream, Encoding.ASCII)) { + binaryWriter.Write (Encoding.ASCII.GetBytes ("0x" + maxKeyLength.ToString ("X8") + '\0')); + binaryWriter.Write (Encoding.ASCII.GetBytes ("0x" + maxValueLength.ToString ("X8") + '\0')); + foreach (var kvp in data) { + binaryWriter.Write (Encoding.ASCII.GetBytes (kvp.Key.PadRight (maxKeyLength, '\0'))); + binaryWriter.Write (Encoding.ASCII.GetBytes (kvp.Value.PadRight (maxValueLength, '\0'))); + } + binaryWriter.Flush (); + return stream.ToArray (); + } } - protected async Task InstallFastDevTools (string toolPath) + async Task> GetRemoteFileData (string rootPath, bool runAs) { - if (string.Compare (packageInfo.ToolVersion ?? string.Empty, ToolVersion, StringComparison.OrdinalIgnoreCase) == 0) { - LogDebugMessage ($"FastDev Tools already installed for the app. {packageInfo.ToolVersion}"); - return true; + // The stat format must be quoted so that the `|` separators survive to the device + // shell. `adb shell` re-parses its arguments, so passing the format as an argv element + // (e.g. via RunAdbShellCommand (params string [])) would let the device shell treat the + // `|` characters as pipes. Building a single, explicitly quoted command string avoids it. + string findCommand = $"find {QuoteShellArgument (rootPath)} -type f -exec stat -c '%n|%s|%Y' {{}} +"; + string output; + if (runAs) { + output = await RunAsShell (findCommand); + if (RaiseRunAsError (output)) { + return null; + } + } else { + var result = await RunAdbShellCommand (findCommand); + output = result.Output; } - string output = await Device.RunAs (packageInfo, "cat", $"{toolPath}/version"); - if (string.Compare (output.Trim (), ToolVersion, StringComparison.OrdinalIgnoreCase) == 0) { - LogDebugMessage ($"FastDev Tools already installed for the app. {output}"); - packageInfo.ToolVersion = ToolVersion; - return true; + if (IsMissingDirectoryError (output)) { + return new Dictionary (StringComparer.Ordinal); + } + if (IsShellError (output, "find") || IsShellError (output, "stat")) { + LogFastDeployError ("XA0129", output, rootPath); + return null; } - output = await Device.RunAs (packageInfo, "mkdir", "-p", toolPath); - if (output.IndexOf ("run-as:", StringComparison.OrdinalIgnoreCase) >= 0 || - output.IndexOf ("mkdir:", StringComparison.OrdinalIgnoreCase) >= 0) { - if (!RaiseRunAsError (output)) { - LogDiagnosticDataError ("XA0130", output); - PrintDiagnostics (); - LogCodedError ($"XA0130", Resources.XA0130_FastDevNotSupported); + return ParseRemoteFileData (rootPath, output); + } + + Dictionary ParseRemoteFileData (string rootPath, string output) + { + var files = new Dictionary (StringComparer.Ordinal); + string prefix = rootPath.TrimEnd ('/') + "/"; + foreach (string line in output.Split (new char [] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)) { + var entries = line.Split (new char [] { '|' }, 3); + if (entries.Length != 3) { + LogDebugMessage ($"Ignoring remote file entry '{line}'. Line is incorrectly formatted."); + continue; } - return false; - } - // we have to do this as a normal shell command since running - // mkdir under `run-as` will result in a `permission-denied` error. - output = await Device.RunShellCommand ("mkdir", "-p", XAToolsTempPath); - if (output.IndexOf ("mkdir:", StringComparison.OrdinalIgnoreCase) >= 0) { - if (!RaiseRunAsError (output)) { - LogDiagnosticDataError ("XA0130", output); - PrintDiagnostics (); - LogCodedError ($"XA0130", Resources.XA0130_FastDevNotSupported); + string remoteFile = entries [0].Trim (); + if (!remoteFile.StartsWith (prefix, StringComparison.Ordinal)) { + LogDebugMessage ($"Ignoring remote file entry '{line}'. Path is outside '{rootPath}'."); + continue; } - return false; - } - - string toolAbi = string.IsNullOrEmpty (ToolsAbi) ? PrimaryCpuAbi : ToolsAbi; - var tools = new [] { FastDevFindTool, FastDevTool, FastDevStatTool, FastDevCpTool }; - foreach (var tool in tools) { - LogDebugMessage ($"Installing FastDev Tool {toolPath}/{tool} for {toolAbi}"); - if (!await PushFileToDevice (Device, PackageName, toolPath, Path.Combine (FastDevToolPath, toolAbi, tool), $"{toolPath}/{tool}", CancellationToken)) { - LogDiagnosticDataError ("XA0126", Resources.XA0126_UnableToCopyFastDevTools); - PrintDiagnostics (); - LogCodedError ($"XA0126", Resources.XA0126_UnableToCopyFastDevTools, toolPath, tool); - return false; + if (!long.TryParse (entries [1].Trim (), out long size) || !long.TryParse (entries [2].Trim (), out long mtime)) { + LogDebugMessage ($"Ignoring remote file entry '{line}'. Size or timestamp is invalid."); + continue; } + files [remoteFile.Substring (prefix.Length)] = new RemoteFileInfo { + Size = size, + ModifiedTime = mtime, + }; } - LogDebugMessage ($"Setting FastDev Tools Permissions"); - await Device.RunAs (packageInfo, "chmod", "700", $"{toolPath}/{FastDevTool}", $"{toolPath}/{FastDevFindTool}", $"{toolPath}/{FastDevStatTool}", $"{toolPath}/{FastDevCpTool}"); - LogDebugMessage ($"Installing FastDev Tools to {toolPath}/version"); - await PushFileTextToDevice (Device, PackageName, ToolVersion, Encoding.ASCII, $"{toolPath}/version", token: CancellationToken); - LogDebugMessage ($"Removing FastDev Tools temp directory."); - await Device.RunShellCommand ("rm", "-Rf", XAToolsTempPath); - packageInfo.ToolVersion = ToolVersion; - return true; + return files; } - async Task PushFileToDevice (AndroidDevice device, string packageName, string toolPath, string file, string target, CancellationToken token) + async Task RemoveStaleOverrideFiles (string overridePath, Dictionary stagedFiles, Dictionary overrideFiles) { - if (!File.Exists (file)) { - LogDebugMessage ($"File '{file}' does not exists. Skipping."); - return false; + var staleFiles = new List (); + foreach (var file in overrideFiles.Keys) { + if (!stagedFiles.ContainsKey (file)) { + staleFiles.Add (CombineRemotePath (overridePath, file)); + } } - using (var fs = File.OpenRead (file)) { - if (!await PushStreamToDevice (device, packageName, toolPath, fs, target, DateTime.UtcNow, token: token)) { + + LogDiagnostic ($"FastDeploy removing {staleFiles.Count} stale override files."); + foreach (var batch in BatchShellArguments (new [] { "rm", "-f" }, staleFiles, StaleFileRemovalBatchSize)) { + string output = await RunAs (batch.ToArray ()); + if (RaiseRunAsError (output) || IsShellError (output, "rm")) { + LogFastDeployError ("XA0129", output, overridePath); return false; } } return true; } - async Task PushFileTextToDevice (AndroidDevice device, string packageName, string fileContents, Encoding encoding, string target, CancellationToken token) + async Task CopyChangedFiles (string remoteStagingPath, string overridePath, Dictionary stagedFiles, Dictionary overrideFiles) { - using (var ms = new MemoryStream ()) { - using (var sw1 = new StreamWriter (ms, encoding, 1024, leaveOpen: true)) { - sw1.WriteLine (fileContents); - sw1.Flush (); + var changedFiles = new List (); + foreach (var file in stagedFiles) { + if (!overrideFiles.TryGetValue (file.Key, out RemoteFileInfo existing) || + existing.Size != file.Value.Size || + existing.ModifiedTime != file.Value.ModifiedTime) { + changedFiles.Add (file.Key); } - ms.Position = 0; - if (!await PushStreamToDevice (device, packageName, null, ms, target, DateTime.UtcNow, token: token)) { + } + + LogDiagnostic ($"FastDeploy copying {changedFiles.Count} changed override files."); + var filesByDirectory = GroupFilesByDirectory (changedFiles); + + foreach (var group in filesByDirectory) { + string targetDirectory = CombineRemotePath (overridePath, group.Key); + string output = await RunAs ("mkdir", "-p", targetDirectory); + if (RaiseRunAsError (output) || IsShellError (output, "mkdir")) { + LogFastDeployError ("XA0129", output, targetDirectory); return false; } + + // Remove the current destination files, then copy the freshly staged files in. + // `cp` overwrites anyway, so removing first (rather than interleaving per batch) + // is equivalent and lets each command batch independently by length. + var destinationFiles = group.Value.Select (file => CombineRemotePath (targetDirectory, Path.GetFileName (file))); + foreach (var batch in BatchShellArguments (new [] { "rm", "-f" }, destinationFiles, CopyBatchSize)) { + output = await RunAs (batch.ToArray ()); + if (RaiseRunAsError (output) || IsShellError (output, "rm")) { + LogFastDeployError ("XA0129", output, targetDirectory); + return false; + } + } + + var sourceFiles = group.Value.Select (file => CombineRemotePath (remoteStagingPath, file)); + foreach (var batch in BatchShellArguments (new [] { "cp", "-p" }, sourceFiles, CopyBatchSize, trailing: targetDirectory)) { + output = await RunAs (batch.ToArray ()); + if (RaiseRunAsError (output) || IsShellError (output, "cp")) { + LogFastDeployError ("XA0129", output, targetDirectory); + return false; + } + } } + return true; } - async Task PushStreamToDeviceWithTool (AndroidDevice device, string packageName, string toolPath, Stream stream, string target, DateTimeOffset modifiedDateTime, CancellationToken token = default (CancellationToken)) + IEnumerable> BatchArguments (string command, string option, IEnumerable values) { - string targetFile = Path.GetFileName (target); - try { - long wrote = await device.Push (stream, $"{XAToolsTempPath}/{targetFile}", cancellationToken: token); - LogDiagnostic ($"Pushed {wrote} to {XAToolsTempPath}/{targetFile}"); - string r = await device.RunAs (packageInfo, $"{toolPath}/{FastDevCpTool}", $"{XAToolsTempPath}/{targetFile}", target, $"{modifiedDateTime.ToUnixTimeMilliseconds ()}"); - if (r.IndexOf ("run-as:", StringComparison.OrdinalIgnoreCase) >= 0) { - TryGetRunAsErrorCode (r, out var err); - LogDiagnosticDataError (err.code, r, targetFile); - return false; + var batch = new List { command, option }; + int length = command.Length + option.Length + 2; + foreach (var value in values) { + int itemLength = value.Length + 3; + if (batch.Count > 2 && length + itemLength >= MaxShellCommandLength) { + yield return batch; + batch = new List { command, option }; + length = command.Length + option.Length + 2; } - LogDiagnostic ($"moved {XAToolsTempPath}/{targetFile} to {target}"); - LogDebugMessageWithTiming ($"Installed {target}."); - } catch (Exception ex) { - LogDebugMessageWithTiming ($"Failed to push {targetFile} to {target}. {ex}."); - LogDiagnosticDataError(GetErrorCode (ex),ex.ToString (), targetFile); - return false; + batch.Add (value); + length += itemLength; + } + if (batch.Count > 2) { + yield return batch; } - return true; } - async Task PushStreamToDevice (AndroidDevice device, string packageName, string toolPath, Stream stream, string target, DateTimeOffset modifiedDateTime, CancellationToken token = default (CancellationToken)) + /// + /// Splits into run-as shell command batches, capping each + /// batch by both items and + /// characters. Each batch starts with (e.g. rm -f) and, + /// when is set, ends with it (e.g. the destination directory of + /// a cp). Length is estimated the same way as (prefix, + /// trailing, and per-value quoting overhead) so a single command never overflows the device + /// shell's command-line limit even when a count-only cap would keep the batch too large. + /// + IEnumerable> BatchShellArguments (IReadOnlyList prefix, IEnumerable values, int maxCount, string trailing = null) { - string targetFile = Path.GetFileName (target); - try { - long wrote = await device.Push (stream, $"{XAToolsTempPath}/{targetFile}", cancellationToken: token); - LogDiagnostic ($"Pushed {wrote} to {XAToolsTempPath}/{targetFile}"); - string r = await device.RunAs (packageInfo, "cp", $"{XAToolsTempPath}/{targetFile}", target); - if (r.IndexOf ("run-as:", StringComparison.OrdinalIgnoreCase) >= 0) { - TryGetRunAsErrorCode (r, out var err); - LogDiagnosticDataError (err.code, r, targetFile); - return false; + int prefixLength = 0; + foreach (var arg in prefix) { + prefixLength += arg.Length + 3; + } + bool hasTrailing = !string.IsNullOrEmpty (trailing); + int trailingLength = hasTrailing ? trailing.Length + 3 : 0; + + var batch = new List (prefix); + int count = 0; + int length = prefixLength + trailingLength; + foreach (var value in values) { + int itemLength = value.Length + 3; + if (count > 0 && (count >= maxCount || length + itemLength >= MaxShellCommandLength)) { + if (hasTrailing) { + batch.Add (trailing); + } + yield return batch; + batch = new List (prefix); + count = 0; + length = prefixLength + trailingLength; } - LogDiagnostic ($"moved {XAToolsTempPath}/{targetFile} to {target}"); - await device.RunAs (packageInfo, "touch", "-t", $"{modifiedDateTime.ToString ("yyyyMMdd.HHmmss")}", target); - LogDebugMessageWithTiming ($"Installed {target}."); - } catch (Exception ex) { - LogDiagnosticDataError (GetErrorCode (ex),ex.ToString ()); - LogDebugMessageWithTiming ($"Failed to push {targetFile} to {target}. {ex}."); - return false; + batch.Add (value); + length += itemLength; + count++; + } + if (count > 0) { + if (hasTrailing) { + batch.Add (trailing); + } + yield return batch; } - return true; } - string GetTargetPath (ITaskItem file) + List CreatePushArgs (string localPath, string remotePath) { - string targetPath = file.GetMetadata ("TargetPath"); - if (string.IsNullOrEmpty (targetPath)) { - // fallback to DestinationSubPath - LogDiagnostic ($"'TargetPath' meta data not found on '{file.ItemSpec}'. Falling back to'DestinationSubPath'"); - targetPath = file.GetMetadata ("DestinationSubPath"); - } - return targetPath; + var args = CreatePushArgsPrefix (); + args.Add (localPath); + args.Add (remotePath); + return args; } - protected async Task DeployFastDevFiles (string toolPath, string overridePath) + List CreatePushArgsPrefix () { - // get the optimal blocksize from the device. This will help speed up transfer and disk writes. - LZ4Level lz4level = LZ4Level.L03_HC; - - LogDiagnostic ("Calculating subdirectories"); - HashSet directories = new HashSet (); - directories.Add (overridePath); - foreach (var file in FastDevFiles) { - string targetPath = GetTargetPath (file); - if (!string.IsNullOrEmpty (targetPath)) { - string dirName = Path.GetDirectoryName (targetPath).Replace ("\\", "/"); - if (!string.IsNullOrEmpty (dirName)) { - directories.Add ($"{overridePath}/{dirName}"); - LogDiagnostic ($"{targetPath} => {overridePath}/{dirName}"); - } - } - } - int length = ADB_COMMAND_PADDING + PackageName.Length; - List args = new List(directories.Count + 2); - args.Add ("mkdir"); - args.Add ("-p"); - foreach (var dir in directories) { - int newLength = dir.Length + 3; - if ((length + newLength) >= MAX_COMMAND) { - await Device.RunAs (packageInfo, args); - length = ADB_COMMAND_PADDING + PackageName.Length; - args.Clear (); - args.Add ("mkdir"); - args.Add ("-p"); - } - length += newLength; - args.Add (dir); + var args = new List { "push" }; + if (!string.IsNullOrEmpty (AdbPushCompressionAlgorithm)) { + args.Add ("-z"); + args.Add (AdbPushCompressionAlgorithm); } - await Device.RunAs (packageInfo, args); + return args; + } - string filelist = await Device.RunAs (packageInfo, $"{toolPath}/{FastDevFindTool}", DiagnosticLogging ? "-vd" : "-v", overridePath); - LogDiagnostic ($"{FastDevFindTool}: {filelist}"); - string [] files = Array.Empty (); - if (!(filelist.IndexOf ("error:", StringComparison.OrdinalIgnoreCase) >= 0)) { - files = filelist.Split (new char [] { '\n' }, StringSplitOptions.RemoveEmptyEntries); + int EstimateCommandLength (List args) + { + int length = 0; + foreach (var arg in args) { + length += arg.Length + 3; } - Dictionary fileData = new Dictionary (); - foreach (var file in files) { // file size mtime - if (file.IndexOf ("\t") == -1) { - LogDebugMessage ($"{FastDevFindTool}: Ignoring line '{file}'. Line is incorrectly formatted."); - continue; - } - var entires = file.Split (new char [] { '\t' }, StringSplitOptions.RemoveEmptyEntries); - if (entires.Length != 3) { - LogDebugMessage ($"{FastDevFindTool}: Ignoring line {file}. Input does not have 3 items."); - continue; - } - if (long.TryParse (entires [1].Trim (), out long fsize) && long.TryParse (entires [2].Trim (), out long mtime)) { - DateTimeOffset offset; - try { - offset = DateTimeOffset.FromUnixTimeMilliseconds (mtime); - } catch (ArgumentOutOfRangeException) { - offset = DateTimeOffset.MinValue; - } - fileData.Add (entires [0].Replace ("./", "").Trim (), (size: fsize, mtime: offset)); - } else { - LogDebugMessage ($"Failed to parse values for line {file}. Ignoring."); - } + return length; + } + + async Task RunAdbCommand (params string [] arguments) + { + return await RunAdbCommand (arguments, environmentVariables: null); + } + + async Task RunAdbShellCommand (params string [] arguments) + { + return await RunAdbCommand (new [] { "shell" }.Concat (arguments).ToArray ()); + } + + async Task RunAdbCommand (string [] arguments, Dictionary environmentVariables) + { + string adb = ResolveAdbPath (); + var adbArguments = new List (); + if (!string.IsNullOrEmpty (DeviceId) && !string.Equals (DeviceId, "any", StringComparison.OrdinalIgnoreCase)) { + adbArguments.Add ("-s"); + adbArguments.Add (DeviceId); + } + adbArguments.AddRange (arguments); + + var psi = ProcessUtils.CreateProcessStartInfo (adb, adbArguments.ToArray ()); + psi.WindowStyle = ProcessWindowStyle.Hidden; + + // psi.Arguments holds the exact, correctly quoted command line whenever ProcessUtils + // joined the arguments itself; it is empty when it used ProcessStartInfo.ArgumentList. + string commandLine = !string.IsNullOrEmpty (psi.Arguments) + ? psi.Arguments + : string.Join (" ", adbArguments.Select (a => $"[{a}]")); + LogDiagnostic ($"adb command: {psi.FileName} {commandLine}"); + + using var stdout = new StringWriter (); + using var stderr = new StringWriter (); + int exitCode = await ProcessUtils.StartProcess (psi, stdout, stderr, CancellationToken, environmentVariables); + var result = new AdbCommandResult { + ExitCode = exitCode, + StandardOutput = stdout.ToString ().Trim (), + StandardError = stderr.ToString ().Trim (), + }; + LogAdbCommandResult (result); + return result; + } + + void LogAdbCommandResult (AdbCommandResult result) + { + LogDiagnostic ($"adb exit code: {result.ExitCode}"); + LogAdbStream ("stdout", result.StandardOutput); + LogAdbStream ("stderr", result.StandardError); + } + + void LogAdbStream (string name, string value) + { + if (string.IsNullOrEmpty (value)) { + return; } - // remove known directories s they don't get deleted. - fileData.Remove ("links"); + LogDiagnostic ($"adb {name}:{Environment.NewLine}{value}"); + } - foreach (var file in FastDevFiles) { - if (!File.Exists (file.ItemSpec)) { - LogDebugMessage ($"File '{file.ItemSpec}' does not exists. Skipping."); - continue; - } - StartTiming (); - if (Path.GetExtension (file.ItemSpec) == ".so") { - string abi = AndroidRidAbiHelper.GetNativeLibraryAbi (file); - if (abi != PrimaryCpuAbi) { - LogDebugMessageWithTiming ($"NotifySync SkipCopyFile {file.ItemSpec} abi not suitable for this device."); - continue; - } - } - string targetPath = GetTargetPath (file); - if (!string.IsNullOrEmpty (targetPath)) { - targetPath = $"{targetPath}".Replace ("\\", "/"); - } else { - targetPath = $"{Path.GetFileName (file.ItemSpec)}"; - } - string filename = Path.GetFileName (file.ItemSpec); - var fi = new FileInfo (file.ItemSpec); - bool modified = true; - DateTimeOffset modifiedDateTime = File.GetLastWriteTimeUtc (file.ItemSpec); - DateTimeOffset remoteDateTime = DateTimeOffset.MinValue; - if (fileData.ContainsKey (targetPath)) { - remoteDateTime = fileData [targetPath].mtime; - modified = remoteDateTime.ToUnixTimeMilliseconds () < modifiedDateTime.ToUnixTimeMilliseconds () || fi.Length != fileData [targetPath].size; - } - if (!modified) { - LogDebugMessageWithTiming ($"NotifySync SkipCopyFile {file.ItemSpec}=>{targetPath} file is up to date."); - fileData.Remove (targetPath); - continue; - } - if (!await DeployFileWithFastDevTool (file, toolPath, overridePath, lz4level, modifiedDateTime)) { - diagnosticData.SetProperty ("deploy.result", "Failed"); - return; + async Task RunLoggedDeviceOperation (string operation, Func action) + { + LogDiagnostic ($"Device operation: {operation}"); + await action (); + LogDiagnostic ($"Device operation completed: {operation}"); + } + + async Task RunLoggedDeviceOperation (string operation, Func> action) + { + LogDiagnostic ($"Device operation: {operation}"); + T result = await action (); + LogDiagnostic ($"Device operation completed: {operation} => {result}"); + return result; + } + + List BuildRunAsArgs () + { + List args = new List (); + if (packageInfo.IsSystemApplication) { + if (!packageInfo.AdbIsRoot) { + args.Add ("su"); + args.Add (packageInfo.UserId ?? "0"); } - LogDebugMessageWithTiming ($"NotifySync CopyFile {file.ItemSpec}."); - LogDiagnostic ($"Local Modified Time '{modifiedDateTime.ToUnixTimeMilliseconds ()}' is newer than '{remoteDateTime.ToUnixTimeMilliseconds ()}'."); - fileData.Remove (targetPath); + return args; } - if (EnvironmentFiles?.Length > 0) { - string targetPath = $"{PrimaryCpuAbi}/environment"; - DateTimeOffset remoteDateTime = DateTimeOffset.MinValue; - if (fileData.ContainsKey (targetPath)) { - remoteDateTime = fileData [targetPath].mtime; - } - await DeployEnvironmentFiles (EnvironmentFiles, toolPath, overridePath, targetPath, remoteDateTime); - fileData.Remove (targetPath); - } - foreach (var file in fileData.Keys) { - // we need to remove unknown files from the .__override__ path - string targetFile = $"{file.Replace ("./", "")}"; - LogDebugMessage ($"Remove redundant file {OverrideFullPath}/{targetFile}"); - await Device.RunAs (packageInfo, "rm", "-Rf", $"{OverrideFullPath}/{targetFile}"); - } - // clean up the temp folder if we are not using the xamarin.sync tool - if (!packageInfo.SupportsFastDev) - await Device.RunShellCommand ("rm", "-Rf", XAToolsTempPath); - return; + args.Add ("run-as"); + args.Add (packageInfo.PackageName); + if (!string.IsNullOrEmpty (packageInfo.UserId)) { + args.Add ("--user"); + args.Add (packageInfo.UserId); + } + return args; } - async Task DeployFileWithFastDevTool (ITaskItem file, string toolPath, string overridePath, LZ4Level lz4level, DateTimeOffset modifiedDateTime) + async Task RunAs (params string [] arguments) { + List args = BuildRunAsArgs (); + args.AddRange (arguments); + var result = await RunAdbShellCommand (args.ToArray ()); + return result.Output; + } - using (var fs = File.OpenRead (file.ItemSpec)) { - string destination = overridePath; - // This bit handles subdirectories. - int bufferSize = LZ4Codec.MaximumOutputSize (fs.Length > int.MaxValue ? int.MaxValue : (int)fs.Length); - string targetPath = GetTargetPath (file); - if (!string.IsNullOrEmpty (targetPath)) { - destination += $"/{targetPath}".Replace ("\\", "/"); - } else { - destination += $"/{Path.GetFileName (file.ItemSpec)}"; - } - if (packageInfo.SupportsFastDev) { - byte [] buffer = ArrayPool.Shared.Rent (bufferSize); - byte [] compressed = ArrayPool.Shared.Rent (bufferSize); - try { - List args = DeviceExt.BuildArgs (DeviceExt.RunAsCommand, packageInfo); - args.AddRange (new string[] { $"{toolPath}/{FastDevTool}", $"{compressed.Length}", $"{fs.Length}", $"{destination}", $"{modifiedDateTime.ToUnixTimeMilliseconds ()}" }); - LogDiagnostic ($"executing: {string.Join (" ", args.ToArray ())}"); - var output = await Device.RunShellCommandStream (args.ToArray (), async (s) => { - int read = await fs.ReadAsync (buffer, 0, buffer.Length); - if (read == 0) - return false; - int compressedLength = CompressLZ4 (ref buffer, read, ref compressed, lz4level); - int l = IPAddress.HostToNetworkOrder (compressedLength); - var v = BitConverter.GetBytes (l); - try { - s.Write (v, 0, 4); - s.Write (compressed, 0, compressedLength); - } catch { - return false; - } - return true; - }, CancellationToken); - LogDiagnostic ($"FastDev of {file.ItemSpec} returned: {output}"); - - if (output.IndexOf ("error:", StringComparison.OrdinalIgnoreCase) >= 0) { - if (output.IndexOf ("from stdin.", StringComparison.OrdinalIgnoreCase) >= 0) { - LogDiagnostic ($"'{FastDevTool}' returned '{output}' when deploying '{destination}'. Falling back to backup deployment."); - diagnosticData.SetProperty ("pii.deploy.error", output); - diagnosticData.SetProperty ("pii.deploy.file", file.ItemSpec); - diagnosticData.SetProperty ("deploy.tool", value:"xamarin.cp"); - // Log warning and fallback to adb push style deployment. It will be slower... but it works. - } else { - LogDiagnosticDataError ("XA0127", output, file.ItemSpec); - PrintDiagnostics (); - LogCodedError ($"XA0127", Resources.XA0127_ErrorDeployingFile, destination, FastDevTool, output); - return false; - } - } - - if (output.IndexOf ($"wrote [{fs.Length}]", StringComparison.OrdinalIgnoreCase) >= 0) { - return true; - } - // we didn't write the file as we expected so use the backup path. - // this can happen is the devices supports run-as but does not support - // reading data in from stdin. Normally on older devices. - // if we get here, we will just reset the stream and drop through to the - // backup path. - packageInfo.SupportsFastDev = false; - fs.Position = 0; - } catch (Exception ex) { - LogDiagnostic ($"Hit exception. Falling back to slow deployment for {file.ItemSpec}. {ex}"); - diagnosticData.SetProperty ("pii.deploy.error", ex.ToString ()); - diagnosticData.SetProperty ("deploy.tool", value:"xamarin.cp"); - packageInfo.SupportsFastDev = false; - fs.Position = 0; - } finally { - ArrayPool.Shared.Return (buffer); - ArrayPool.Shared.Return (compressed); - } - } - if (!packageInfo.SupportsFastDev) { - if (!await PushStreamToDeviceWithTool (Device, PackageName, toolPath, fs, destination, modifiedDateTime, token: CancellationToken)) { - LogDiagnosticDataError ("XA0129", Resources.XA0129_ErrorDeployingFile, destination); - PrintDiagnostics (); - LogCodedError ($"XA0129", Resources.XA0129_ErrorDeployingFile, destination); - return false; - } - } + async Task RunAsShell (string script) + { + List args = BuildRunAsArgs (); + args.Add ("sh"); + args.Add ("-c"); + args.Add (script); + string command = string.Join (" ", args.Select (QuoteShellArgument)); + var result = await RunAdbShellCommand (command); + return result.Output; + } + + static string QuoteShellArgument (string value) + { + return "'" + value.Replace ("'", "'\"'\"'") + "'"; + } + + string ResolveAdbPath () + { + var exe = string.IsNullOrEmpty (AdbToolExe) ? "adb" : AdbToolExe; + return string.IsNullOrEmpty (AdbToolPath) ? exe : Path.Combine (AdbToolPath, exe); + } + + string GetRemoteAdbPushStagingPath () + { + return $"{RemoteStagingRoot}/{PackageName}/{GetUserId ()}"; + } + + string GetUserId () + { + return string.IsNullOrEmpty (UserID) ? "0" : UserID; + } + + string GetDeviceId () + { + if (!string.IsNullOrEmpty (DeviceId)) { + return DeviceId; } - return true; + return string.IsNullOrEmpty (AdbTarget) ? "any" : AdbTarget; } - async Task DeployEnvironmentFiles (ITaskItem[] environments, string toolPath, string overridePath, string targetPath, DateTimeOffset remoteFileModified) + void LogFastDeployError (string errorCode, string error, string file = "") { - int maxKeyLength = 0; - int maxValueLength = 0; - DateTimeOffset newestFileDateTime = DateTimeOffset.MinValue; - var data = new Dictionary (); - foreach (ITaskItem env in environments ?? Array.Empty ()) { - if (!File.Exists (env.ItemSpec)) - continue; - DateTimeOffset modifiedDateTime = File.GetLastWriteTimeUtc (env.ItemSpec); - if (modifiedDateTime > newestFileDateTime) - newestFileDateTime = modifiedDateTime; - foreach (string line in File.ReadLines (env.ItemSpec)) { - if (string.IsNullOrEmpty (line)) - continue; - int index = line.IndexOf ('='); - if (index == -1) { - LogDebugMessage ($"Skipping invalid environment line: {line}"); - continue; - } - var key = line.Substring (0, index); - var value = line.Substring (index + 1); - maxKeyLength = Math.Max (maxKeyLength, key.Length); - maxValueLength = Math.Max (maxValueLength, value.Length); - data [key] = value; - } + if (!string.IsNullOrEmpty (file)) { + LogDiagnostic ($"{errorCode} while deploying '{file}': {error}"); + } else { + LogDiagnostic ($"{errorCode}: {error}"); } + PrintDiagnostics (); + if (errorCode == "XA0129") { + LogCodedError (errorCode, Resources.XA0129_ErrorDeployingFile, file); + } else { + LogCodedError (errorCode, error); + } + } - // Length+1 so at least one trailing \0 for the longest value - maxKeyLength++; - maxValueLength++; + string GetFullPath (string dir) => Path.IsPathRooted (dir) ? dir : Path.GetFullPath (Path.Combine (WorkingDirectory, dir)); - if (newestFileDateTime <= remoteFileModified) { - LogDebugMessage ($"NotifySync SkipCopyFile @(AndroidEnvironment) files => {targetPath} file is up to date."); - return true; - } - var stream = new MemoryStream (); // dont use Pool as Device.Push dispose's the stream. - var binaryWriter = new BinaryWriter (stream, Encoding.ASCII); - binaryWriter.Write (Encoding.ASCII.GetBytes ("0x" + maxKeyLength.ToString ("X8") + '\0')); - binaryWriter.Write (Encoding.ASCII.GetBytes ("0x" + maxValueLength.ToString ("X8") + '\0')); - foreach (var kvp in data) { - binaryWriter.Write (Encoding.ASCII.GetBytes (kvp.Key.PadRight (maxKeyLength, '\0'))); - binaryWriter.Write (Encoding.ASCII.GetBytes (kvp.Value.PadRight (maxValueLength, '\0'))); - } - binaryWriter.Flush (); - binaryWriter.BaseStream.Position = 0; - await PushStreamToDeviceWithTool (Device, PackageName, toolPath, binaryWriter.BaseStream, $"{overridePath}/{targetPath}", DateTimeOffset.UtcNow, token: CancellationToken); - LogDebugMessageWithTiming ($"NotifySync CopyFile @(AndroidEnvironment) files."); - LogDiagnostic ($"Local Modified Time '{newestFileDateTime.ToUnixTimeMilliseconds ()}' is newer than '{remoteFileModified.ToUnixTimeMilliseconds ()}'."); - return true; + static string GetDirectoryName (string file) + { + return Path.GetDirectoryName (file)?.Replace ("\\", "/") ?? ""; } - string GetErrorCode (Exception ex) + static string CombineRemotePath (string rootPath, string relativePath) { - switch (ex) { - case IncompatibleCpuAbiException e: - return "ADB0020"; - case RequiresUninstallException e: - return "ADB0030"; - case SdkNotSupportedException e: - return "ADB0040"; - case PackageAlreadyExistsException e: - return "ADB0050"; - case InsufficientSpaceException e: - return "ADB0060"; - //NOTE: this one is a base class - case InstallFailedException e: - return "ADB0010"; - default: - return GetErrorCode (ex.Message); + return string.IsNullOrEmpty (relativePath) ? rootPath : $"{rootPath}/{relativePath}"; + } + + static Dictionary> GroupFilesByDirectory (IEnumerable files) + { + var filesByDirectory = new Dictionary> (StringComparer.Ordinal); + foreach (string file in files) { + string directory = GetDirectoryName (file); + if (!filesByDirectory.TryGetValue (directory, out List filesInDirectory)) { + filesInDirectory = new List (); + filesByDirectory.Add (directory, filesInDirectory); + } + filesInDirectory.Add (file); } + return filesByDirectory; } - static readonly List<(string error, string code, string message)> runas_codes = new List<(string error, string code, string message)> () { - { (error: "run-as is disabled", code: "XA0131", message: Resources.XA0131_DeveloperModeNotEnabled ) }, - { (error: "unknown", code: "XA0132", message: Resources.XA0132_PackageNotInstalled ) }, - { (error: "Permission denied", code: "XA0133", message: Resources.XA0133_RunAsPermissionDenied ) }, - { (error: "package not debuggable", code: "XA0134", message: Resources.XA0134_RunAsPackageNotDebuggable ) }, - { (error: "package not an application", code: "XA0135", message: Resources.XA0135_RunAsPackageNotAndApplication ) }, - { (error: "has corrupt installation", code: "XA0136", message: Resources.XA0136_RunAsCorruptInstallation ) }, - { (error: "users can run this program", code: "XA0137", message: Resources.XA0137_RunAsOSCorrupt ) }, - { (error: "set SELinux security context", code: "XA0137", message: Resources.XA0137_RunAsOSCorrupt ) }, - { (error: "to package's data directory", code: "XA0137", message: Resources.XA0137_RunAsOSCorrupt ) }, - { (error: "couldn't stat", code: "XA0137", message: Resources.XA0137_RunAsOSCorrupt ) }, - { (error: "has wrong owner", code: "XA0137", message: Resources.XA0137_RunAsOSCorrupt ) }, - { (error: "readable or writable by others", code: "XA0137", message: Resources.XA0137_RunAsOSCorrupt ) }, - { (error: "not a directory", code: "XA0137", message: Resources.XA0137_RunAsOSCorrupt ) }, - { (error: "run-as:", code: "XA0137", message: Resources.XA0137_RunAsOSCorrupt ) }, - }; + bool RaiseRunAsError (string error) + { + if (TryGetRunAsErrorCode (error, out var err)) { + LogDiagnostic ($"{err.code}: {err.message}"); + PrintDiagnostics (); + LogCodedError (err.code, err.message, error); + return true; + } + return false; + } bool TryGetRunAsErrorCode (string error, out (string error, string code, string message) errTuple) { @@ -1119,19 +920,14 @@ bool TryGetRunAsErrorCode (string error, out (string error, string code, string return false; } - bool RaiseRunAsError (string error) + string GetErrorCode (Exception ex) { - if (TryGetRunAsErrorCode (error, out var err)) { - LogDiagnosticDataError (err.code, err.message); - PrintDiagnostics (); - LogCodedError (err.code, err.message, error); - return true; + if (ex is FastDeployInstallException installException) { + return installException.ErrorCode; } - return false; + return GetErrorCode (ex.Message); } - string GetFullPath (string dir) => Path.IsPathRooted (dir) ? dir : Path.GetFullPath (Path.Combine (WorkingDirectory, dir)); - static string GetErrorCode (string message) { foreach (var errorCode in error_codes) @@ -1141,13 +937,62 @@ static string GetErrorCode (string message) return "ADB1000"; } - static readonly List<(string code, string message)> error_codes = new List<(string code , string message)> () { - { (code: "ADB0010", message: nameof (InstallFailedException)) }, - { (code: "ADB0020", message: nameof (IncompatibleCpuAbiException)) }, - { (code: "ADB0030", message: nameof (RequiresUninstallException)) }, - { (code: "ADB0040", message: nameof (SdkNotSupportedException)) }, - { (code: "ADB0050", message: nameof (PackageAlreadyExistsException)) }, - { (code: "ADB0060", message: nameof (InsufficientSpaceException)) }, + static bool IsShellError (string output, string command) + { + if (string.IsNullOrEmpty (output)) { + return false; + } + return output.IndexOf ($"{command}:", StringComparison.OrdinalIgnoreCase) >= 0 || + output.IndexOf ("No such file or directory", StringComparison.OrdinalIgnoreCase) >= 0 || + output.IndexOf ("Permission denied", StringComparison.OrdinalIgnoreCase) >= 0 || + output.IndexOf ("Read-only file system", StringComparison.OrdinalIgnoreCase) >= 0 || + output.IndexOf ("not found", StringComparison.OrdinalIgnoreCase) >= 0; + } + + static bool IsMissingDirectoryError (string output) + { + return !string.IsNullOrEmpty (output) && + output.IndexOf ("No such file or directory", StringComparison.OrdinalIgnoreCase) >= 0; + } + + internal struct AdbCommandResult + { + public int ExitCode; + public string StandardOutput; + public string StandardError; + + public string Output { + get { + if (string.IsNullOrEmpty (StandardOutput)) { + return StandardError ?? ""; + } + if (string.IsNullOrEmpty (StandardError)) { + return StandardOutput; + } + return $"{StandardOutput}{Environment.NewLine}{StandardError}"; + } + } + } + + static readonly List<(string error, string code, string message)> runas_codes = new List<(string error, string code, string message)> () { + { (error: "run-as is disabled", code: "XA0131", message: Resources.XA0131_DeveloperModeNotEnabled ) }, + { (error: "Could not set capabilities", code: "XA0131", message: Resources.XA0131_DeveloperModeNotEnabled ) }, + { (error: "unknown", code: "XA0132", message: Resources.XA0132_PackageNotInstalled ) }, + { (error: "Permission denied", code: "XA0133", message: Resources.XA0133_RunAsPermissionDenied ) }, + { (error: "package not debuggable", code: "XA0134", message: Resources.XA0134_RunAsPackageNotDebuggable ) }, + { (error: "package not an application", code: "XA0135", message: Resources.XA0135_RunAsPackageNotAndApplication ) }, + { (error: "has corrupt installation", code: "XA0136", message: Resources.XA0136_RunAsCorruptInstallation ) }, + { (error: "users can run this program", code: "XA0137", message: Resources.XA0137_RunAsOSCorrupt ) }, + { (error: "set SELinux security context", code: "XA0137", message: Resources.XA0137_RunAsOSCorrupt ) }, + { (error: "to package's data directory", code: "XA0137", message: Resources.XA0137_RunAsOSCorrupt ) }, + { (error: "couldn't stat", code: "XA0137", message: Resources.XA0137_RunAsOSCorrupt ) }, + { (error: "has wrong owner", code: "XA0137", message: Resources.XA0137_RunAsOSCorrupt ) }, + { (error: "readable or writable by others", code: "XA0137", message: Resources.XA0137_RunAsOSCorrupt ) }, + { (error: "not a directory", code: "XA0137", message: Resources.XA0137_RunAsOSCorrupt ) }, + { (error: "run-as:", code: "XA0137", message: Resources.XA0137_RunAsOSCorrupt ) }, + }; + + static readonly List<(string code, string message)> error_codes = new List<(string code, string message)> () { { (code: "ADB1001", message: "failed to create session") }, { (code: "ADB1002", message: "failed to finalize session") }, { (code: "ADB1003", message: "product directory not specified; set $ANDROID_PRODUCT_OUT") }, @@ -1343,45 +1188,4 @@ static string GetErrorCode (string message) { (code: "ADB1193", message: "failed to write") }, }; } - - internal static class DeviceExt - { - internal static string RunAsCommand = "run-as"; - - internal static List BuildArgs(string command, FastDeploy.PackageInfo packageInfo) - { - List args = new List (); - if (packageInfo.IsSystemApplication) { - if (!packageInfo.AdbIsRoot) { - args.Add ("su"); - args.Add (packageInfo.UserId ?? "0"); - } - return args; - } - args.Add (RunAsCommand); - args.Add (packageInfo.PackageName); - if (!string.IsNullOrEmpty (packageInfo.UserId)) { - args.Add("--user"); - args.Add(packageInfo.UserId); - } - return args; - } - - internal static async Task RunAs (this AndroidDevice Device, FastDeploy.PackageInfo packageInfo, IEnumerable arguments) - { - string [] args = arguments.ToArray (); - string result = await Device.RunAs (packageInfo, args); - packageInfo.LogDebugMessage ($"{args[0]} returned: {result}"); - return result; - } - - internal static async Task RunAs (this AndroidDevice Device, FastDeploy.PackageInfo packageInfo, params string [] arguments) - { - List args = BuildArgs(RunAsCommand, packageInfo); - args.AddRange (arguments); - string result = await Device.RunShellCommand (args.ToArray ()); - packageInfo.LogDebugMessage ($"{arguments[0]} returned: {result}"); - return result; - } - } } diff --git a/src/Xamarin.Android.Build.Debugging.Tasks/Tasks/FastDeploy2.cs b/src/Xamarin.Android.Build.Debugging.Tasks/Tasks/FastDeploy2.cs deleted file mode 100644 index 0231a89dcf8..00000000000 --- a/src/Xamarin.Android.Build.Debugging.Tasks/Tasks/FastDeploy2.cs +++ /dev/null @@ -1,1191 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading; -using System.Threading.Tasks; - -using Microsoft.Android.Build.Tasks; -using Microsoft.Build.Framework; -using Xamarin.Android.Build.Debugging.Tasks.Properties; -using Xamarin.Android.Tools; - -namespace Xamarin.Android.Tasks -{ - public partial class FastDeploy2 : AsyncTask - { - const string OverridePath = "files/.__override__"; - - public override string TaskPrefix => "FD2"; - - /// - /// Number of stale override files to delete per rm invocation. Exposed as an - /// internal MSBuild property primarily so it can be lowered when testing batching behavior. - /// - public int StaleFileRemovalBatchSize { get; set; } = 100; - - /// - /// Number of files to copy per batch when staging fast-deployment files on the device. - /// Exposed as an internal MSBuild property primarily so it can be lowered when testing. - /// - public int CopyBatchSize { get; set; } = 25; - - /// - /// Maximum length (in characters) of a single adb shell command line before it is - /// split into multiple invocations. - /// - public int MaxShellCommandLength { get; set; } = 900; - - /// - /// Maximum length (in characters) of a single adb command line before it is split - /// into multiple invocations. - /// - public int MaxAdbCommandLength { get; set; } = 4096; - - public string AdbTarget { get; set; } - public string UploadFlagFile { get; set; } - public bool EmbedAssembliesIntoApk { get; set; } - public bool ReInstall { get; set; } = false; - - [Required] - public string PackageName { get; set; } - - public string PackageFile { get; set; } - - public string PrimaryCpuAbi { get; set; } - - public ITaskItem [] FastDevFiles { get; set; } - - public bool PreserveUserData { get; set; } = true; - - public bool DiagnosticLogging { get; set; } = false; - - public bool FastDeploySkipCleanup { get; set; } = false; - - public string UserID { get; set; } - - public bool IsTestOnly { get; set; } - - [Required] - public string IntermediateOutputPath { get; set; } - - public ITaskItem [] EnvironmentFiles { get; set; } - - public string AdbToolPath { get; set; } - - public string AdbToolExe { get; set; } - - public string AdbPushCompressionAlgorithm { get; set; } = "any"; - - public string AppFileTransferMode { get; set; } = "Copy"; - - string DeviceId = ""; - PackageInfo packageInfo = new PackageInfo (); - DateTime lastUpload = DateTime.MinValue; - Queue diagnosticLogs = new Queue (); - readonly object diagnosticLogsLock = new object (); - - string OverrideFullPath { - get { return packageInfo.IsSystemApplication ? $"{packageInfo.InternalPath}/{OverridePath}" : OverridePath; } - } - - class PackageInfo { - string internalPath = null; - public string InternalPath { - get { return internalPath; } - set { internalPath = value?.Trim () ?? null; } - } - - public bool IsSystemApplication { get; set; } = false; - public bool AdbIsRoot { get; set; } = false; - public string UserId { get; set; } = null; - public string PackageName { get; set; } = null; - public int ProcessId { get; set; } = 0; - } - - class RemoteFileInfo { - public long Size { get; set; } - public long ModifiedTime { get; set; } - } - - class DirectPushFile { - public string LocalPath { get; set; } - public string RelativePath { get; set; } - } - - void LogDiagnostic (string message) - { - if (DiagnosticLogging) { - LogDebugMessage (message); - return; - } - lock (diagnosticLogsLock) { - diagnosticLogs.Enqueue (message); - } - } - - void PrintDiagnostics () - { - while (true) { - string message; - lock (diagnosticLogsLock) { - if (diagnosticLogs.Count == 0) { - break; - } - message = diagnosticLogs.Dequeue (); - } - LogMessage (message); - } - } - - public override bool Execute () - { - var device = AndroidHelper.ParseTarget (AdbTarget, LogMessage, LogCodedError, logErrors: true, engine4: BuildEngine4); - if (device == null) { - PrintDiagnostics (); - return false; - } - DeviceId = device.ID ?? ""; - LogMessage ($"Found device: {DeviceId}"); - - if (string.IsNullOrEmpty (PrimaryCpuAbi) && !EmbedAssembliesIntoApk) { - PrintDiagnostics (); - LogCodedError ("XA0010", Resources.XA0010_NoAbi, DeviceId); - return false; - } - - var flagFilePath = GetFullPath (UploadFlagFile); - lastUpload = File.GetLastWriteTimeUtc (flagFilePath); - LogDiagnostic ($"LastWriteTime of `{flagFilePath}`: {lastUpload}"); - - var lifetime = RegisteredTaskObjectLifetime.AppDomain; - var key = ProjectSpecificTaskObjectKey ($"{DeviceId}_{PackageName}_{GetType ().Name}"); - if (!File.Exists (UploadFlagFile)) { - packageInfo = new PackageInfo (); - } else { - packageInfo = BuildEngine4.GetRegisteredTaskObjectAssemblyLocal (key, lifetime) ?? new PackageInfo (); - } - - try { - return base.Execute (); - } finally { - BuildEngine4.RegisterTaskObjectAssemblyLocal (key, packageInfo, lifetime, allowEarlyCollection: false); - } - } - - public async override Task RunTaskAsync () - { - try { - await RunInstall (); - } catch { - PrintDiagnostics (); - throw; - } - } - - async Task RunInstall () - { - WarmStateProbeOutcome warmState = await TryRunWarmStateProbe (LoadPreviousManifest ()); - if (warmState == WarmStateProbeOutcome.Failed) { - return; - } - - if (warmState != WarmStateProbeOutcome.Ready) { - string redirectStdio = await GetDeviceProperty ("log.redirect-stdio"); - if (string.Equals ("true", redirectStdio, StringComparison.OrdinalIgnoreCase)) { - LogFastDeploy2Error ("XA0128", Resources.XA0128_RedirectStdioIsEnabled); - return; - } - - string runAsDisabled = await GetDeviceProperty ("ro.boot.disable_runas"); - if (string.Equals ("true", runAsDisabled, StringComparison.OrdinalIgnoreCase)) { - LogFastDeploy2Error ("XA0131", Resources.XA0131_DeveloperModeNotEnabled); - return; - } - - await CheckAppInstalledAndDebuggable (PackageName); - } - - if (EmbedAssembliesIntoApk) { - await RemoveOverrideDirectory (); - } - - bool packageFileOutOfDate = !string.IsNullOrEmpty (PackageFile) && - (packageInfo.InternalPath.IndexOf ("unknown", StringComparison.OrdinalIgnoreCase) >= 0 || ReInstall || IsPackageFileOutOfDate ()); - if (ReInstall && !string.IsNullOrEmpty (PackageFile)) { - await UninstallPackage (PackageName, preserveData: PreserveUserData, user: UserID); - } - - if (packageFileOutOfDate) { - try { - await InstallPackage (); - } catch (Exception ex) { - LogFastDeploy2Error (GetErrorCode (ex), ex.ToString ()); - return; - } - if (!FastDeploySkipCleanup) { - await CleanupRemoteStagingDirectories (); - } - if (!EmbedAssembliesIntoApk && packageInfo.InternalPath.IndexOf ("unknown", StringComparison.OrdinalIgnoreCase) >= 0) { - packageInfo.InternalPath = null; - await CheckAppInstalledAndDebuggable (PackageName); - if (RaiseRunAsError (packageInfo.InternalPath)) { - return; - } - } - } - - if (EmbedAssembliesIntoApk) - return; - - if ((FastDevFiles?.Length ?? 0) == 0 && (EnvironmentFiles?.Length ?? 0) == 0) { - return; - } - - if (!warmProbeStoppedApp) { - await TerminateApp (); - } - if (!await DeployFastDevFilesWithAdbPush (OverrideFullPath)) { - LogDiagnostic ("FastDeploy2 deployment did not complete successfully."); - } - } - - bool IsPackageFileOutOfDate () - { - var packageFile = GetFullPath (PackageFile); - var lastPackage = File.GetLastWriteTimeUtc (packageFile); - LogDiagnostic ($"LastWriteTime of `{packageFile}`: {lastPackage}"); - return lastUpload < lastPackage; - } - - async Task CheckAppInstalledAndDebuggable (string packageName) - { - packageInfo.UserId = UserID; - packageInfo.PackageName = packageName; - packageInfo.ProcessId = 0; - await EnsureUserIsRunning (); - string packageInfoOutput = IsSafePackageNameForShell (packageName) ? - await RunAs ("sh", "-c", $"pwd; pidof {packageName} 2>/dev/null || true") : - await RunAs ("pwd"); - ParsePackageInfoOutput (packageInfoOutput); - if (string.IsNullOrEmpty (packageInfo.InternalPath)) { - packageInfo.InternalPath = packageInfoOutput?.Trim (); - } - if (packageInfo.InternalPath.IndexOf ("Permission denied", StringComparison.OrdinalIgnoreCase) >= 0) { - packageInfo.InternalPath = await RunAs ("readlink", "-f", "."); - } - if (packageInfo.InternalPath.IndexOf ("not an application", StringComparison.OrdinalIgnoreCase) >= 0) { - LogDiagnostic ($"Package {packageInfo.PackageName} is a system application."); - packageInfo.IsSystemApplication = true; - var whoami = await RunAdbShellCommand ("whoami"); - packageInfo.AdbIsRoot = whoami.Output.Trim () == "root"; - LogDiagnostic ($"using {(packageInfo.AdbIsRoot ? "root" : $"su {packageInfo.UserId}")} to install fast deployment files."); - packageInfo.InternalPath = $"/data/user/{(packageInfo.UserId ?? "0")}/{packageInfo.PackageName}"; - return; - } - if (packageInfo.InternalPath.IndexOf ("not debuggable", StringComparison.OrdinalIgnoreCase) >= 0) { - LogDiagnostic ($"Package {packageInfo.PackageName} was not debuggable. Forcing ReInstall"); - ReInstall = true; - return; - } - if (packageInfo.InternalPath.IndexOf ("unknown", StringComparison.OrdinalIgnoreCase) >= 0) { - LogDiagnostic ($"Package {packageInfo.PackageName} was not installed."); - return; - } - if (packageInfo.InternalPath.IndexOf ("Permission denied", StringComparison.OrdinalIgnoreCase) >= 0) { - LogDiagnostic ("run-as not supported on this device."); - } - } - - static bool IsSafePackageNameForShell (string packageName) - { - if (string.IsNullOrEmpty (packageName)) { - return false; - } - foreach (char c in packageName) { - if (!(char.IsLetterOrDigit (c) || c == '.' || c == '_')) { - return false; - } - } - return true; - } - - void ParsePackageInfoOutput (string output) - { - if (string.IsNullOrEmpty (output)) { - return; - } - - string [] lines = output.Replace ("\r", "").Split (new char [] { '\n' }, StringSplitOptions.None); - if (lines.Length > 0 && !string.IsNullOrEmpty (lines [0])) { - packageInfo.InternalPath = lines [0].Trim (); - } - if (lines.Length <= 1) { - return; - } - - string pidLine = lines [1].Trim (); - int space = pidLine.IndexOf (' '); - if (space >= 0) { - pidLine = pidLine.Substring (0, space); - } - if (int.TryParse (pidLine, out int pid)) { - packageInfo.ProcessId = pid; - } - } - - async Task EnsureUserIsRunning () - { - var userId = (UserID ?? "").Trim (); - if (userId.Length == 0 || (int.TryParse (userId, out var id) && id == 0)) { - return; - } - LogDiagnostic ($"Ensuring Android user {userId} is in the 'running' state before run-as queries."); - var result = await RunAdbShellCommand ("am", "start-user", "-w", userId); - string output = result.Output; - LogDiagnostic ($"'am start-user -w {userId}' returned: {(string.IsNullOrWhiteSpace (output) ? "" : output.Trim ())}"); - } - - async Task InstallPackage () - { - LogDebugMessage ($"Installing Package {PackageName}"); - await InstallApkWithRetry (PackageFile, reinstall: ReInstall, testOnly: IsTestOnly, user: UserID); - LogDebugMessage ($"Installed Package {PackageName}."); - } - - async Task RemoveOverrideDirectory () - { - await RunAs ("rm", "-Rf", OverrideFullPath); - } - - async Task TerminateApp () - { - var pid = packageInfo.ProcessId; - if (pid == 0 && packageInfo.IsSystemApplication) { - pid = await RunLoggedDeviceOperation ($"GetProcessId {PackageName}", () => GetProcessId (PackageName)); - } - if (pid == 0) { - LogDebugMessage ($"{PackageName} was not running, skipping kill"); - return; - } - LogDebugMessage ($"Terminating {PackageName}..."); - await RunLoggedDeviceOperation ($"ForceStop {PackageName}", () => ForceStopPackage (PackageName)); - LogDebugMessage ($"{PackageName} Terminated."); - } - - async Task CreateRemoteStagingDirectories (string remoteStagingPath, HashSet stagedFiles) - { - var directories = new HashSet (StringComparer.Ordinal) { remoteStagingPath }; - foreach (var file in stagedFiles) { - string directory = GetDirectoryName (file); - if (!string.IsNullOrEmpty (directory)) { - directories.Add (CombineRemotePath (remoteStagingPath, directory)); - } - } - - var output = new StringBuilder (); - foreach (var batch in BatchArguments ("mkdir", "-p", directories)) { - output.Append ((await RunAdbShellCommand (batch.ToArray ())).Output); - } - return output.ToString (); - } - - List PrepareDirectPushFiles () - { - var files = new List (); - foreach (var file in FastDevFiles ?? []) { - string localPath = GetFullPath (file.ItemSpec); - if (!File.Exists (localPath)) { - LogDiagnostic ($"File '{file.ItemSpec}' does not exist. Skipping."); - continue; - } - if (Path.GetExtension (file.ItemSpec) == ".so") { - string abi = AndroidRidAbiHelper.GetNativeLibraryAbi (file); - if (abi != PrimaryCpuAbi) { - LogDebugMessage ($"NotifySync SkipCopyFile {GetAdbPushTargetPath (file)} abi not suitable for this device."); - continue; - } - } - - files.Add (new DirectPushFile { - LocalPath = localPath, - RelativePath = GetAdbPushTargetPath (file), - }); - LogDiagnostic ($"Prepared {file.ItemSpec} => {files [files.Count - 1].RelativePath}"); - } - - if (EnvironmentFiles?.Length > 0) { - byte [] environmentData = CreateEnvironmentFileData (EnvironmentFiles, out DateTime newestFileDateTime); - if (environmentData.Length > 0) { - string environmentFile = Path.Combine (GetFullPath (IntermediateOutputPath), "fastdeploy2-environment", PrimaryCpuAbi, "environment"); - WriteFileIfChanged (environmentFile, environmentData, newestFileDateTime); - files.Add (new DirectPushFile { - LocalPath = environmentFile, - RelativePath = $"{PrimaryCpuAbi}/environment", - }); - } - } - - return files; - } - - bool WriteFileIfChanged (string path, byte [] contents, DateTime modifiedDateTime) - { - if (!Files.HasBytesChanged (contents, path)) { - return false; - } - - Directory.CreateDirectory (Path.GetDirectoryName (path)); - File.WriteAllBytes (path, contents); - File.SetLastWriteTimeUtc (path, modifiedDateTime); - return true; - } - - string GetAdbPushTargetPath (ITaskItem file) - { - string targetPath = file.GetMetadata ("TargetPath"); - if (string.IsNullOrEmpty (targetPath)) { - LogDiagnostic ($"'TargetPath' metadata not found on '{file.ItemSpec}'. Falling back to 'DestinationSubPath'"); - targetPath = file.GetMetadata ("DestinationSubPath"); - } - if (!string.IsNullOrEmpty (targetPath)) { - return targetPath.Replace ("\\", "/"); - } - return Path.GetFileName (file.ItemSpec); - } - - byte [] CreateEnvironmentFileData (ITaskItem [] environments, out DateTime newestFileDateTime) - { - int maxKeyLength = 0; - int maxValueLength = 0; - newestFileDateTime = DateTime.MinValue; - var data = new Dictionary (); - foreach (ITaskItem env in environments ?? []) { - if (!File.Exists (env.ItemSpec)) - continue; - DateTime modifiedDateTime = File.GetLastWriteTimeUtc (env.ItemSpec); - if (modifiedDateTime > newestFileDateTime) - newestFileDateTime = modifiedDateTime; - foreach (string line in File.ReadLines (env.ItemSpec)) { - if (string.IsNullOrEmpty (line)) - continue; - int index = line.IndexOf ('='); - if (index == -1) { - LogDebugMessage ($"Skipping invalid environment line: {line}"); - continue; - } - var key = line.Substring (0, index); - var value = line.Substring (index + 1); - maxKeyLength = Math.Max (maxKeyLength, key.Length); - maxValueLength = Math.Max (maxValueLength, value.Length); - data [key] = value; - } - } - - if (newestFileDateTime == DateTime.MinValue) { - return []; - } - - maxKeyLength++; - maxValueLength++; - - using (var stream = new MemoryStream ()) - using (var binaryWriter = new BinaryWriter (stream, Encoding.ASCII)) { - binaryWriter.Write (Encoding.ASCII.GetBytes ("0x" + maxKeyLength.ToString ("X8") + '\0')); - binaryWriter.Write (Encoding.ASCII.GetBytes ("0x" + maxValueLength.ToString ("X8") + '\0')); - foreach (var kvp in data) { - binaryWriter.Write (Encoding.ASCII.GetBytes (kvp.Key.PadRight (maxKeyLength, '\0'))); - binaryWriter.Write (Encoding.ASCII.GetBytes (kvp.Value.PadRight (maxValueLength, '\0'))); - } - binaryWriter.Flush (); - return stream.ToArray (); - } - } - - async Task> GetRemoteFileData (string rootPath, bool runAs) - { - // The stat format must be quoted so that the `|` separators survive to the device - // shell. `adb shell` re-parses its arguments, so passing the format as an argv element - // (e.g. via RunAdbShellCommand (params string [])) would let the device shell treat the - // `|` characters as pipes. Building a single, explicitly quoted command string avoids it. - string findCommand = $"find {QuoteShellArgument (rootPath)} -type f -exec stat -c '%n|%s|%Y' {{}} +"; - string output; - if (runAs) { - output = await RunAsShell (findCommand); - if (RaiseRunAsError (output)) { - return null; - } - } else { - var result = await RunAdbShellCommand (findCommand); - output = result.Output; - } - - if (IsMissingDirectoryError (output)) { - return new Dictionary (StringComparer.Ordinal); - } - if (IsShellError (output, "find") || IsShellError (output, "stat")) { - LogFastDeploy2Error ("XA0129", output, rootPath); - return null; - } - - return ParseRemoteFileData (rootPath, output); - } - - Dictionary ParseRemoteFileData (string rootPath, string output) - { - var files = new Dictionary (StringComparer.Ordinal); - string prefix = rootPath.TrimEnd ('/') + "/"; - foreach (string line in output.Split (new char [] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)) { - var entries = line.Split (new char [] { '|' }, 3); - if (entries.Length != 3) { - LogDebugMessage ($"Ignoring remote file entry '{line}'. Line is incorrectly formatted."); - continue; - } - string remoteFile = entries [0].Trim (); - if (!remoteFile.StartsWith (prefix, StringComparison.Ordinal)) { - LogDebugMessage ($"Ignoring remote file entry '{line}'. Path is outside '{rootPath}'."); - continue; - } - if (!long.TryParse (entries [1].Trim (), out long size) || !long.TryParse (entries [2].Trim (), out long mtime)) { - LogDebugMessage ($"Ignoring remote file entry '{line}'. Size or timestamp is invalid."); - continue; - } - files [remoteFile.Substring (prefix.Length)] = new RemoteFileInfo { - Size = size, - ModifiedTime = mtime, - }; - } - return files; - } - - async Task RemoveStaleOverrideFiles (string overridePath, Dictionary stagedFiles, Dictionary overrideFiles) - { - var staleFiles = new List (); - foreach (var file in overrideFiles.Keys) { - if (!stagedFiles.ContainsKey (file)) { - staleFiles.Add (CombineRemotePath (overridePath, file)); - } - } - - LogDiagnostic ($"FastDeploy2 removing {staleFiles.Count} stale override files."); - foreach (var batch in BatchShellArguments (new [] { "rm", "-f" }, staleFiles, StaleFileRemovalBatchSize)) { - string output = await RunAs (batch.ToArray ()); - if (RaiseRunAsError (output) || IsShellError (output, "rm")) { - LogFastDeploy2Error ("XA0129", output, overridePath); - return false; - } - } - return true; - } - - async Task CopyChangedFiles (string remoteStagingPath, string overridePath, Dictionary stagedFiles, Dictionary overrideFiles) - { - var changedFiles = new List (); - foreach (var file in stagedFiles) { - if (!overrideFiles.TryGetValue (file.Key, out RemoteFileInfo existing) || - existing.Size != file.Value.Size || - existing.ModifiedTime != file.Value.ModifiedTime) { - changedFiles.Add (file.Key); - } - } - - LogDiagnostic ($"FastDeploy2 copying {changedFiles.Count} changed override files."); - var filesByDirectory = GroupFilesByDirectory (changedFiles); - - foreach (var group in filesByDirectory) { - string targetDirectory = CombineRemotePath (overridePath, group.Key); - string output = await RunAs ("mkdir", "-p", targetDirectory); - if (RaiseRunAsError (output) || IsShellError (output, "mkdir")) { - LogFastDeploy2Error ("XA0129", output, targetDirectory); - return false; - } - - // Remove the current destination files, then copy the freshly staged files in. - // `cp` overwrites anyway, so removing first (rather than interleaving per batch) - // is equivalent and lets each command batch independently by length. - var destinationFiles = group.Value.Select (file => CombineRemotePath (targetDirectory, Path.GetFileName (file))); - foreach (var batch in BatchShellArguments (new [] { "rm", "-f" }, destinationFiles, CopyBatchSize)) { - output = await RunAs (batch.ToArray ()); - if (RaiseRunAsError (output) || IsShellError (output, "rm")) { - LogFastDeploy2Error ("XA0129", output, targetDirectory); - return false; - } - } - - var sourceFiles = group.Value.Select (file => CombineRemotePath (remoteStagingPath, file)); - foreach (var batch in BatchShellArguments (new [] { "cp", "-p" }, sourceFiles, CopyBatchSize, trailing: targetDirectory)) { - output = await RunAs (batch.ToArray ()); - if (RaiseRunAsError (output) || IsShellError (output, "cp")) { - LogFastDeploy2Error ("XA0129", output, targetDirectory); - return false; - } - } - } - - return true; - } - - IEnumerable> BatchArguments (string command, string option, IEnumerable values) - { - var batch = new List { command, option }; - int length = command.Length + option.Length + 2; - foreach (var value in values) { - int itemLength = value.Length + 3; - if (batch.Count > 2 && length + itemLength >= MaxShellCommandLength) { - yield return batch; - batch = new List { command, option }; - length = command.Length + option.Length + 2; - } - batch.Add (value); - length += itemLength; - } - if (batch.Count > 2) { - yield return batch; - } - } - - /// - /// Splits into run-as shell command batches, capping each - /// batch by both items and - /// characters. Each batch starts with (e.g. rm -f) and, - /// when is set, ends with it (e.g. the destination directory of - /// a cp). Length is estimated the same way as (prefix, - /// trailing, and per-value quoting overhead) so a single command never overflows the device - /// shell's command-line limit even when a count-only cap would keep the batch too large. - /// - IEnumerable> BatchShellArguments (IReadOnlyList prefix, IEnumerable values, int maxCount, string trailing = null) - { - int prefixLength = 0; - foreach (var arg in prefix) { - prefixLength += arg.Length + 3; - } - bool hasTrailing = !string.IsNullOrEmpty (trailing); - int trailingLength = hasTrailing ? trailing.Length + 3 : 0; - - var batch = new List (prefix); - int count = 0; - int length = prefixLength + trailingLength; - foreach (var value in values) { - int itemLength = value.Length + 3; - if (count > 0 && (count >= maxCount || length + itemLength >= MaxShellCommandLength)) { - if (hasTrailing) { - batch.Add (trailing); - } - yield return batch; - batch = new List (prefix); - count = 0; - length = prefixLength + trailingLength; - } - batch.Add (value); - length += itemLength; - count++; - } - if (count > 0) { - if (hasTrailing) { - batch.Add (trailing); - } - yield return batch; - } - } - - List CreatePushArgs (string localPath, string remotePath) - { - var args = CreatePushArgsPrefix (); - args.Add (localPath); - args.Add (remotePath); - return args; - } - - List CreatePushArgsPrefix () - { - var args = new List { "push" }; - if (!string.IsNullOrEmpty (AdbPushCompressionAlgorithm)) { - args.Add ("-z"); - args.Add (AdbPushCompressionAlgorithm); - } - return args; - } - - int EstimateCommandLength (List args) - { - int length = 0; - foreach (var arg in args) { - length += arg.Length + 3; - } - return length; - } - - async Task RunAdbCommand (params string [] arguments) - { - return await RunAdbCommand (arguments, environmentVariables: null); - } - - async Task RunAdbShellCommand (params string [] arguments) - { - return await RunAdbCommand (new [] { "shell" }.Concat (arguments).ToArray ()); - } - - async Task RunAdbCommand (string [] arguments, Dictionary environmentVariables) - { - string adb = ResolveAdbPath (); - var adbArguments = new List (); - if (!string.IsNullOrEmpty (DeviceId) && !string.Equals (DeviceId, "any", StringComparison.OrdinalIgnoreCase)) { - adbArguments.Add ("-s"); - adbArguments.Add (DeviceId); - } - adbArguments.AddRange (arguments); - - var psi = ProcessUtils.CreateProcessStartInfo (adb, adbArguments.ToArray ()); - psi.WindowStyle = ProcessWindowStyle.Hidden; - - // psi.Arguments holds the exact, correctly quoted command line whenever ProcessUtils - // joined the arguments itself; it is empty when it used ProcessStartInfo.ArgumentList. - string commandLine = !string.IsNullOrEmpty (psi.Arguments) - ? psi.Arguments - : string.Join (" ", adbArguments.Select (a => $"[{a}]")); - LogDiagnostic ($"adb command: {psi.FileName} {commandLine}"); - - using var stdout = new StringWriter (); - using var stderr = new StringWriter (); - int exitCode = await ProcessUtils.StartProcess (psi, stdout, stderr, CancellationToken, environmentVariables); - var result = new AdbCommandResult { - ExitCode = exitCode, - StandardOutput = stdout.ToString ().Trim (), - StandardError = stderr.ToString ().Trim (), - }; - LogAdbCommandResult (result); - return result; - } - - void LogAdbCommandResult (AdbCommandResult result) - { - LogDiagnostic ($"adb exit code: {result.ExitCode}"); - LogAdbStream ("stdout", result.StandardOutput); - LogAdbStream ("stderr", result.StandardError); - } - - void LogAdbStream (string name, string value) - { - if (string.IsNullOrEmpty (value)) { - return; - } - LogDiagnostic ($"adb {name}:{Environment.NewLine}{value}"); - } - - async Task RunLoggedDeviceOperation (string operation, Func action) - { - LogDiagnostic ($"Device operation: {operation}"); - await action (); - LogDiagnostic ($"Device operation completed: {operation}"); - } - - async Task RunLoggedDeviceOperation (string operation, Func> action) - { - LogDiagnostic ($"Device operation: {operation}"); - T result = await action (); - LogDiagnostic ($"Device operation completed: {operation} => {result}"); - return result; - } - - List BuildRunAsArgs () - { - List args = new List (); - if (packageInfo.IsSystemApplication) { - if (!packageInfo.AdbIsRoot) { - args.Add ("su"); - args.Add (packageInfo.UserId ?? "0"); - } - return args; - } - args.Add ("run-as"); - args.Add (packageInfo.PackageName); - if (!string.IsNullOrEmpty (packageInfo.UserId)) { - args.Add ("--user"); - args.Add (packageInfo.UserId); - } - return args; - } - - async Task RunAs (params string [] arguments) - { - List args = BuildRunAsArgs (); - args.AddRange (arguments); - var result = await RunAdbShellCommand (args.ToArray ()); - return result.Output; - } - - async Task RunAsShell (string script) - { - List args = BuildRunAsArgs (); - args.Add ("sh"); - args.Add ("-c"); - args.Add (script); - string command = string.Join (" ", args.Select (QuoteShellArgument)); - var result = await RunAdbShellCommand (command); - return result.Output; - } - - static string QuoteShellArgument (string value) - { - return "'" + value.Replace ("'", "'\"'\"'") + "'"; - } - - string ResolveAdbPath () - { - var exe = string.IsNullOrEmpty (AdbToolExe) ? "adb" : AdbToolExe; - return string.IsNullOrEmpty (AdbToolPath) ? exe : Path.Combine (AdbToolPath, exe); - } - - string GetRemoteAdbPushStagingPath () - { - return $"{RemoteStagingRoot}/{PackageName}/{GetUserId ()}"; - } - - string GetUserId () - { - return string.IsNullOrEmpty (UserID) ? "0" : UserID; - } - - string GetDeviceId () - { - if (!string.IsNullOrEmpty (DeviceId)) { - return DeviceId; - } - return string.IsNullOrEmpty (AdbTarget) ? "any" : AdbTarget; - } - - void LogFastDeploy2Error (string errorCode, string error, string file = "") - { - if (!string.IsNullOrEmpty (file)) { - LogDiagnostic ($"{errorCode} while deploying '{file}': {error}"); - } else { - LogDiagnostic ($"{errorCode}: {error}"); - } - PrintDiagnostics (); - if (errorCode == "XA0129") { - LogCodedError (errorCode, Resources.XA0129_ErrorDeployingFile, file); - } else { - LogCodedError (errorCode, error); - } - } - - string GetFullPath (string dir) => Path.IsPathRooted (dir) ? dir : Path.GetFullPath (Path.Combine (WorkingDirectory, dir)); - - static string GetDirectoryName (string file) - { - return Path.GetDirectoryName (file)?.Replace ("\\", "/") ?? ""; - } - - static string CombineRemotePath (string rootPath, string relativePath) - { - return string.IsNullOrEmpty (relativePath) ? rootPath : $"{rootPath}/{relativePath}"; - } - - static Dictionary> GroupFilesByDirectory (IEnumerable files) - { - var filesByDirectory = new Dictionary> (StringComparer.Ordinal); - foreach (string file in files) { - string directory = GetDirectoryName (file); - if (!filesByDirectory.TryGetValue (directory, out List filesInDirectory)) { - filesInDirectory = new List (); - filesByDirectory.Add (directory, filesInDirectory); - } - filesInDirectory.Add (file); - } - return filesByDirectory; - } - - bool RaiseRunAsError (string error) - { - if (TryGetRunAsErrorCode (error, out var err)) { - LogDiagnostic ($"{err.code}: {err.message}"); - PrintDiagnostics (); - LogCodedError (err.code, err.message, error); - return true; - } - return false; - } - - bool TryGetRunAsErrorCode (string error, out (string error, string code, string message) errTuple) - { - errTuple = (error: "unknown", code: "XA0132", message: error); - foreach (var err in runas_codes) { - if (error.IndexOf (err.error, StringComparison.OrdinalIgnoreCase) >= 0) { - errTuple = err; - return true; - } - } - return false; - } - - string GetErrorCode (Exception ex) - { - if (ex is FastDeployInstallException installException) { - return installException.ErrorCode; - } - return GetErrorCode (ex.Message); - } - - static string GetErrorCode (string message) - { - foreach (var errorCode in error_codes) - if (message.IndexOf (errorCode.message, StringComparison.OrdinalIgnoreCase) >= 0) - return errorCode.code; - - return "ADB1000"; - } - - static bool IsShellError (string output, string command) - { - if (string.IsNullOrEmpty (output)) { - return false; - } - return output.IndexOf ($"{command}:", StringComparison.OrdinalIgnoreCase) >= 0 || - output.IndexOf ("No such file or directory", StringComparison.OrdinalIgnoreCase) >= 0 || - output.IndexOf ("Permission denied", StringComparison.OrdinalIgnoreCase) >= 0 || - output.IndexOf ("Read-only file system", StringComparison.OrdinalIgnoreCase) >= 0 || - output.IndexOf ("not found", StringComparison.OrdinalIgnoreCase) >= 0; - } - - static bool IsMissingDirectoryError (string output) - { - return !string.IsNullOrEmpty (output) && - output.IndexOf ("No such file or directory", StringComparison.OrdinalIgnoreCase) >= 0; - } - - internal struct AdbCommandResult - { - public int ExitCode; - public string StandardOutput; - public string StandardError; - - public string Output { - get { - if (string.IsNullOrEmpty (StandardOutput)) { - return StandardError ?? ""; - } - if (string.IsNullOrEmpty (StandardError)) { - return StandardOutput; - } - return $"{StandardOutput}{Environment.NewLine}{StandardError}"; - } - } - } - - static readonly List<(string error, string code, string message)> runas_codes = new List<(string error, string code, string message)> () { - { (error: "run-as is disabled", code: "XA0131", message: Resources.XA0131_DeveloperModeNotEnabled ) }, - { (error: "Could not set capabilities", code: "XA0131", message: Resources.XA0131_DeveloperModeNotEnabled ) }, - { (error: "unknown", code: "XA0132", message: Resources.XA0132_PackageNotInstalled ) }, - { (error: "Permission denied", code: "XA0133", message: Resources.XA0133_RunAsPermissionDenied ) }, - { (error: "package not debuggable", code: "XA0134", message: Resources.XA0134_RunAsPackageNotDebuggable ) }, - { (error: "package not an application", code: "XA0135", message: Resources.XA0135_RunAsPackageNotAndApplication ) }, - { (error: "has corrupt installation", code: "XA0136", message: Resources.XA0136_RunAsCorruptInstallation ) }, - { (error: "users can run this program", code: "XA0137", message: Resources.XA0137_RunAsOSCorrupt ) }, - { (error: "set SELinux security context", code: "XA0137", message: Resources.XA0137_RunAsOSCorrupt ) }, - { (error: "to package's data directory", code: "XA0137", message: Resources.XA0137_RunAsOSCorrupt ) }, - { (error: "couldn't stat", code: "XA0137", message: Resources.XA0137_RunAsOSCorrupt ) }, - { (error: "has wrong owner", code: "XA0137", message: Resources.XA0137_RunAsOSCorrupt ) }, - { (error: "readable or writable by others", code: "XA0137", message: Resources.XA0137_RunAsOSCorrupt ) }, - { (error: "not a directory", code: "XA0137", message: Resources.XA0137_RunAsOSCorrupt ) }, - { (error: "run-as:", code: "XA0137", message: Resources.XA0137_RunAsOSCorrupt ) }, - }; - - static readonly List<(string code, string message)> error_codes = new List<(string code, string message)> () { - { (code: "ADB1001", message: "failed to create session") }, - { (code: "ADB1002", message: "failed to finalize session") }, - { (code: "ADB1003", message: "product directory not specified; set $ANDROID_PRODUCT_OUT") }, - { (code: "ADB1004", message: "server didn't ACK") }, - { (code: "ADB1005", message: "server killed by remote request") }, - { (code: "ADB1006", message: "timed out waiting for threads to finish reading from ADB server") }, - { (code: "ADB1007", message: "usage:") }, - { (code: "ADB1008", message: "bulkIn endpoint not assigned") }, - { (code: "ADB1009", message: "bulkOut endpoint not assigned") }, - { (code: "ADB1010", message: "cannot start server on remote host") }, - { (code: "ADB1011", message: "cap_clear_flag(INHERITABLE) failed") }, - { (code: "ADB1012", message: "cap_clear_flag(PEMITTED) failed") }, - { (code: "ADB1013", message: "cap_set_proc() failed") }, - { (code: "ADB1014", message: "Client not connected") }, - { (code: "ADB1015", message: "Could not find device interface") }, - { (code: "ADB1016", message: "Could not set SELinux context") }, - { (code: "ADB1017", message: "Could not start mdnsd") }, - { (code: "ADB1018", message: "could not start server") }, - { (code: "ADB1019", message: "couldn't allocate StdinReadArgs object") }, - { (code: "ADB1020", message: "couldn't create USB matching dictionary") }, - { (code: "ADB1021", message: "daemon started successfully") }, - { (code: "ADB1022", message: "daemon still not running") }, - { (code: "ADB1023", message: "error: no emulator detected") }, - { (code: "ADB1024", message: "error: shell command too long") }, - { (code: "ADB1025", message: "Failed to allocate key") }, - { (code: "ADB1026", message: "failed to allocate memory for ShellProtocol object") }, - { (code: "ADB1027", message: "failed to allocate new subprocess") }, - { (code: "ADB1028", message: "Failed to convert to public key") }, - { (code: "ADB1029", message: "failed to create pipe to report error") }, - { (code: "ADB1030", message: "failed to create run queue notify socketpair") }, - { (code: "ADB1031", message: "failed to empty run queue notify fd") }, - { (code: "ADB1032", message: "failed to encode RSA public key") }, - { (code: "ADB1033", message: "Failed to generate new key") }, - { (code: "ADB1034", message: "failed to get matching services") }, - { (code: "ADB1035", message: "failed to get user home directory") }, - { (code: "ADB1036", message: "Failed to get user key") }, - { (code: "ADB1037", message: "failed to make run queue notify socket nonblocking") }, - { (code: "ADB1038", message: "Failed to read key") }, - { (code: "ADB1039", message: "failed to register libusb hotplug callback") }, - { (code: "ADB1040", message: "failed to start daemon") }, - { (code: "ADB1041", message: "failed to write to run queue notify fd") }, - { (code: "ADB1042", message: "Key must be a null-terminated string") }, - { (code: "ADB1043", message: "Pipe stalled, clearing stall") }, - { (code: "ADB1044", message: "Public key too large to base64 encode") }, - { (code: "ADB1045", message: "reply fd for adb server to client communication not specified") }, - { (code: "ADB1046", message: "run queue notify fd was closed") }, - { (code: "ADB1047", message: "Unable to get interface class, subclass and protocol") }, - { (code: "ADB1048", message: "usb_read interface was null") }, - { (code: "ADB1049", message: "usb_write interface was null") }, - { (code: "ADB1050", message: "cannot fit pipe handle value into 32-bits") }, - { (code: "ADB1051", message: "connect error for create") }, - { (code: "ADB1052", message: "connect error for finalize") }, - { (code: "ADB1053", message: "connect error for write") }, - { (code: "ADB1054", message: "could not open adb service") }, - { (code: "ADB1055", message: "couldn't parse 'wait-for' command") }, - { (code: "ADB1056", message: "CreateFileW 'nul' failed") }, - { (code: "ADB1057", message: "only wrote") }, - { (code: "ADB1058", message: "error response") }, - { (code: "ADB1059", message: "failed to install") }, - { (code: "ADB1060", message: "failed to read block") }, - { (code: "ADB1061", message: "failed to write data") }, - { (code: "ADB1062", message: "invalid reply fd") }, - { (code: "ADB1063", message: "pre-KitKat sideload connection failed") }, - { (code: "ADB1064", message: "doesn't match this client") }, - { (code: "ADB1065", message: "sideload connection failed") }, - { (code: "ADB1066", message: "unable to connect for backup") }, - { (code: "ADB1067", message: "unable to connect for restore") }, - { (code: "ADB1068", message: "unable to connect for") }, - { (code: "ADB1069", message: "unexpected output length for") }, - { (code: "ADB1070", message: "expected 'any', 'local', or 'usb'") }, - { (code: "ADB1071", message: "attempted to close unregistered usb_handle for") }, - { (code: "ADB1072", message: "attempted to reinitialize adb_server_socket_spec") }, - { (code: "ADB1073", message: "cannot connect to daemon at") }, - { (code: "ADB1074", message: "Cannot mkdir") }, - { (code: "ADB1075", message: "Connection banner is too long") }, - { (code: "ADB1076", message: "Could not clear pipe stall both ends") }, - { (code: "ADB1077", message: "Could not install smartsocket listener") }, - { (code: "ADB1078", message: "Could not open interface") }, - { (code: "ADB1079", message: "Could not register mDNS service") }, - { (code: "ADB1080", message: "Couldn't create a device interface") }, - { (code: "ADB1081", message: "Couldn't grab device from interface") }, - { (code: "ADB1082", message: "Couldn't query the interface") }, - { (code: "ADB1083", message: "daemon not running; starting now at") }, - { (code: "ADB1084", message: "destroying fde not created by fdevent_create") }, - { (code: "ADB1085", message: "Encountered mDNS registration error") }, - { (code: "ADB1086", message: "not implemented on Win32") }, - { (code: "ADB1087", message: "could not connect to TCP port") }, - { (code: "ADB1088", message: "no emulator connected") }, - { (code: "ADB1089", message: "only supports allocating a pty") }, - { (code: "ADB1090", message: "failed to connect to socket") }, - { (code: "ADB1091", message: "failed to convert errno") }, - { (code: "ADB1092", message: "failed to initialize libusb") }, - { (code: "ADB1093", message: "Failed to parse key") }, - { (code: "ADB1094", message: "failed to set non-blocking mode for fd") }, - { (code: "ADB1095", message: "failed to start subprocess management thread") }, - { (code: "ADB1096", message: "failed to start subprocess") }, - { (code: "ADB1097", message: "FindDeviceInterface - could not get pipe properties") }, - { (code: "ADB1098", message: "Invalid base64 key") }, - { (code: "ADB1099", message: "Key too long") }, - { (code: "ADB1100", message: "No ':' found in shell service arguments") }, - { (code: "ADB1101", message: "observed inotify event for unmonitored path") }, - { (code: "ADB1102", message: "packet data length doesn't match payload") }, - { (code: "ADB1103", message: "Unable to create a device plug-in") }, - { (code: "ADB1104", message: "Unable to create an interface plug-in") }, - { (code: "ADB1105", message: "Unable to get number of endpoints") }, - { (code: "ADB1106", message: "unexpected type for") }, - { (code: "ADB1107", message: "Unknown socket type") }, - { (code: "ADB1108", message: "Unknown trace flag") }, - { (code: "ADB1109", message: "usb_read failed with status") }, - { (code: "ADB1110", message: "usb_write failed with status") }, - { (code: "ADB1111", message: "adb_socket_accept: failed to allocate accepted socket") }, - { (code: "ADB1112", message: "cannot create service socket pair") }, - { (code: "ADB1113", message: "cannot create socket pair") }, - { (code: "ADB1114", message: "Error generating token") }, - { (code: "ADB1115", message: "Error getting user key filename") }, - { (code: "ADB1116", message: "Failed to accept") }, - { (code: "ADB1117", message: "failed to create inotify fd") }, - { (code: "ADB1118", message: "Failed to get adbd socket") }, - { (code: "ADB1119", message: "failed to shutdown writes to FD") }, - { (code: "ADB1120", message: "Failed to write PK") }, - { (code: "ADB1121", message: "failed to write the exit code packet") }, - { (code: "ADB1122", message: "read of inotify event failed") }, - { (code: "ADB1123", message: "remote usb: 1 - write terminated") }, - { (code: "ADB1124", message: "remote usb: 2 - write terminated") }, - { (code: "ADB1125", message: "remote usb: read terminated (message)") }, - { (code: "ADB1126", message: "remote usb: terminated (data)") }, - { (code: "ADB1127", message: "select failed, closing subprocess pipes") }, - { (code: "ADB1128", message: "backup unable to create file") }, - { (code: "ADB1129", message: "cannot create thread") }, - { (code: "ADB1130", message: "cannot get executable path") }, - { (code: "ADB1131", message: "cannot make handle") }, - { (code: "ADB1132", message: "CreatePipe failed") }, - { (code: "ADB1133", message: "CreateProcessW failed") }, - { (code: "ADB1134", message: "error while reading for") }, - { (code: "ADB1135", message: "execl returned") }, - { (code: "ADB1136", message: "failed to duplicate file descriptor for") }, - { (code: "ADB1137", message: "failed to get file descriptor for") }, - { (code: "ADB1138", message: "failed to open duplicate stream for") }, - { (code: "ADB1139", message: "failed to open file") }, - { (code: "ADB1140", message: "failed to read command") }, - { (code: "ADB1141", message: "failed to read data from") }, - { (code: "ADB1142", message: "failed to read from") }, - { (code: "ADB1143", message: "failed to read package block") }, - { (code: "ADB1144", message: "failed to seek to package block") }, - { (code: "ADB1145", message: "failed to set binary mode for duplicate of") }, - { (code: "ADB1146", message: "failed to stat file") }, - { (code: "ADB1147", message: "failed to stat") }, - { (code: "ADB1148", message: "failed to unbuffer") }, - { (code: "ADB1149", message: "adb_socket_accept: accept on fd") }, - { (code: "ADB1150", message: "unable to open file") }, - { (code: "ADB1151", message: "unexpected result waiting for threads") }, - { (code: "ADB1152", message: "aio: got error event on") }, - { (code: "ADB1153", message: "aio: got error submitting") }, - { (code: "ADB1154", message: "aio: got error waiting") }, - { (code: "ADB1155", message: "cannot open bulk-in endpoint") }, - { (code: "ADB1156", message: "cannot open bulk-out endpoint") }, - { (code: "ADB1157", message: "cannot open control endpoint") }, - { (code: "ADB1158", message: "Can't load") }, - { (code: "ADB1159", message: "could not read ok from ADB Server") }, - { (code: "ADB1160", message: "couldn't allocate state_info") }, - { (code: "ADB1161", message: "Couldn't read") }, - { (code: "ADB1162", message: "cannot write to emulator") }, - { (code: "ADB1163", message: "error reading output FD") }, - { (code: "ADB1164", message: "error reading protocol FD") }, - { (code: "ADB1165", message: "error reading stdin FD") }, - { (code: "ADB1166", message: "write failure during connection") }, - { (code: "ADB1167", message: "failed to fcntl(F_GETFL) for fd") }, - { (code: "ADB1168", message: "failed to fcntl(F_SETFL) for fd") }, - { (code: "ADB1169", message: "failed to inotify_add_watch on path") }, - { (code: "ADB1170", message: "Failed to listen on") }, - { (code: "ADB1171", message: "failed to open directory") }, - { (code: "ADB1172", message: "Failed to write public key to") }, - { (code: "ADB1173", message: "failure closing FD") }, - { (code: "ADB1174", message: "pipe failed in launch_server") }, - { (code: "ADB1175", message: "poll() }, ret =") }, - { (code: "ADB1176", message: "remote usb: read overflow") }, - { (code: "ADB1177", message: "received framework auth socket connection again") }, - { (code: "ADB1178", message: "failed to claim adb interface for device") }, - { (code: "ADB1179", message: "failed to clear halt on device") }, - { (code: "ADB1180", message: "failed to get active config descriptor for device at") }, - { (code: "ADB1181", message: "failed to get device descriptor for device at") }, - { (code: "ADB1182", message: "failed to get serial from device at") }, - { (code: "ADB1183", message: "failed to open usb device at") }, - { (code: "ADB1184", message: "failed to set interface alt setting for device") }, - { (code: "ADB1185", message: "failed to submit zero-length write") }, - { (code: "ADB1186", message: "failed to submit") }, - { (code: "ADB1187", message: "Ignoring unknown shell service argument") }, - { (code: "ADB1188", message: "transfer failed:") }, - { (code: "ADB1189", message: "received empty serial from device at") }, - { (code: "ADB1190", message: "refusing to recurse into directory") }, - { (code: "ADB1191", message: "unmonitored event for") }, - { (code: "ADB1192", message: "Failed to open") }, - { (code: "ADB1193", message: "failed to write") }, - }; - } -} diff --git a/src/Xamarin.Android.Build.Debugging.Tasks/Tasks/FastDeploy2JsonSerializerContext.cs b/src/Xamarin.Android.Build.Debugging.Tasks/Tasks/FastDeployJsonSerializerContext.cs similarity index 55% rename from src/Xamarin.Android.Build.Debugging.Tasks/Tasks/FastDeploy2JsonSerializerContext.cs rename to src/Xamarin.Android.Build.Debugging.Tasks/Tasks/FastDeployJsonSerializerContext.cs index 933625c5dd5..fb289b6e00d 100644 --- a/src/Xamarin.Android.Build.Debugging.Tasks/Tasks/FastDeploy2JsonSerializerContext.cs +++ b/src/Xamarin.Android.Build.Debugging.Tasks/Tasks/FastDeployJsonSerializerContext.cs @@ -4,8 +4,8 @@ namespace Xamarin.Android.Tasks { [JsonSourceGenerationOptions (WriteIndented = true)] - [JsonSerializable (typeof (FastDeploy2.ManifestData))] - internal partial class FastDeploy2JsonSerializerContext : JsonSerializerContext + [JsonSerializable (typeof (FastDeploy.ManifestData))] + internal partial class FastDeployJsonSerializerContext : JsonSerializerContext { } } diff --git a/src/Xamarin.Android.Build.Debugging.Tasks/Tasks/GetPrimaryCpuAbi.cs b/src/Xamarin.Android.Build.Debugging.Tasks/Tasks/GetPrimaryCpuAbi.cs index c5129091d4b..80a79b6c331 100644 --- a/src/Xamarin.Android.Build.Debugging.Tasks/Tasks/GetPrimaryCpuAbi.cs +++ b/src/Xamarin.Android.Build.Debugging.Tasks/Tasks/GetPrimaryCpuAbi.cs @@ -41,8 +41,6 @@ public class GetPrimaryCpuAbi : AsyncTask [Output] public string ResultingAbi { get; set; } [Output] - public string ToolsAbi { get; set; } - [Output] public string RuntimeIdentifier { get; set; } [Output] public int SdkVersion { get; set; } @@ -92,9 +90,8 @@ public async override System.Threading.Tasks.Task RunTaskAsync () if (File.Exists (DevicePropertyCache)) { LogDebugMessage ($"Using cached properties: {DevicePropertyCache}"); doc = XDocument.Load (DevicePropertyCache); - if (DeviceCache.TryGet (doc, device.ID, device.LongOutput, out var cachedAbi, out var cachedToolsAbi, out var cachedSdkVersion, Log)) { + if (DeviceCache.TryGet (doc, device.ID, device.LongOutput, out var cachedAbi, out var cachedSdkVersion, Log)) { ResultingAbi = cachedAbi; - ToolsAbi = cachedToolsAbi; SdkVersion = cachedSdkVersion; RuntimeIdentifier = GetRuntimeIdentifier (); LogOutputs (); @@ -157,7 +154,7 @@ public async override System.Threading.Tasks.Task RunTaskAsync () SdkVersion = sdkver; LogOutputs (); - doc = DeviceCache.Update (doc, device.ID, ResultingAbi, ToolsAbi, SdkVersion, device.LongOutput); + doc = DeviceCache.Update (doc, device.ID, ResultingAbi, SdkVersion, device.LongOutput); if (doc.SaveIfChanged (DevicePropertyCache)) { LogDebugMessage ($"Saving: {DevicePropertyCache}"); } @@ -170,7 +167,6 @@ void DebugHandler (string task, string message) void LogOutputs () { LogDebugMessage ($" {nameof (ResultingAbi)}: {ResultingAbi}"); - LogDebugMessage ($" {nameof (ToolsAbi)}: {ToolsAbi}"); LogDebugMessage ($" {nameof (RuntimeIdentifier)}: {RuntimeIdentifier}"); LogDebugMessage ($" {nameof (SdkVersion)}: {SdkVersion}"); } diff --git a/src/Xamarin.Android.Build.Debugging.Tasks/Utilities/DeviceCache.cs b/src/Xamarin.Android.Build.Debugging.Tasks/Utilities/DeviceCache.cs index 066280b3281..4a64926c7ea 100644 --- a/src/Xamarin.Android.Build.Debugging.Tasks/Utilities/DeviceCache.cs +++ b/src/Xamarin.Android.Build.Debugging.Tasks/Utilities/DeviceCache.cs @@ -15,11 +15,10 @@ public static class DeviceCache /// The XDocument to update, or null to create a new one. /// The device ID. /// The device's ABI. - /// The tools ABI. /// The SDK version. /// The long output string from adb. /// The updated or newly created XDocument. - public static XDocument Update (XDocument doc, string deviceId, string resultingAbi, string toolsAbi, int sdkVersion, string longOutput) + public static XDocument Update (XDocument doc, string deviceId, string resultingAbi, int sdkVersion, string longOutput) { XElement devices; if (doc == null) { @@ -43,7 +42,6 @@ public static XDocument Update (XDocument doc, string deviceId, string resulting } deviceElement.SetElementValue ("ResultingAbi", resultingAbi); - deviceElement.SetElementValue ("ToolsAbi", toolsAbi); deviceElement.SetElementValue ("SdkVersion", sdkVersion); deviceElement.SetElementValue ("LongOutput", longOutput); @@ -57,14 +55,12 @@ public static XDocument Update (XDocument doc, string deviceId, string resulting /// The device ID to look up. /// The expected long output to validate the cache entry. /// The cached ABI if found and valid. - /// The cached tools ABI if found and valid. /// The cached SDK version if found and valid. /// Optional logger for debug messages. /// True if a valid cache entry was found, false otherwise. - public static bool TryGet (XDocument doc, string deviceId, string longOutput, out string resultingAbi, out string toolsAbi, out int sdkVersion, TaskLoggingHelper log = null) + public static bool TryGet (XDocument doc, string deviceId, string longOutput, out string resultingAbi, out int sdkVersion, TaskLoggingHelper log = null) { resultingAbi = null; - toolsAbi = null; sdkVersion = 0; if (doc == null) @@ -86,7 +82,6 @@ public static bool TryGet (XDocument doc, string deviceId, string longOutput, ou } resultingAbi = element.Element ("ResultingAbi")?.Value; - toolsAbi = element.Element ("ToolsAbi")?.Value ?? string.Empty; if (!int.TryParse (element.Element ("SdkVersion")?.Value, out sdkVersion)) return false; diff --git a/src/Xamarin.Android.Build.Debugging.Tasks/Xamarin.Android.Common.Debugging.props b/src/Xamarin.Android.Build.Debugging.Tasks/Xamarin.Android.Common.Debugging.props index d976a9c31d5..f15828862e9 100644 --- a/src/Xamarin.Android.Build.Debugging.Tasks/Xamarin.Android.Common.Debugging.props +++ b/src/Xamarin.Android.Build.Debugging.Tasks/Xamarin.Android.Common.Debugging.props @@ -25,7 +25,6 @@ Copyright (C) 2016 Xamarin. All rights reserved. 9999 $(ProjectDir)\gdb-symbols True - $(XamarinAndroidVersion) --user $(AndroidDeviceUserId) @@ -59,4 +58,3 @@ Copyright (C) 2016 Xamarin. All rights reserved. - diff --git a/src/Xamarin.Android.Build.Debugging.Tasks/Xamarin.Android.Common.Debugging.targets b/src/Xamarin.Android.Build.Debugging.Tasks/Xamarin.Android.Common.Debugging.targets index dd1a972b3b2..06af64e90b8 100644 --- a/src/Xamarin.Android.Build.Debugging.Tasks/Xamarin.Android.Common.Debugging.targets +++ b/src/Xamarin.Android.Build.Debugging.Tasks/Xamarin.Android.Common.Debugging.targets @@ -23,7 +23,6 @@ Copyright (C) 2016 Xamarin. All rights reserved. - @@ -61,9 +60,7 @@ Copyright (C) 2016 Xamarin. All rights reserved. <_DevicePropertyCache>$(IntermediateOutputPath)devices.cache <_UploadFlag>$(IntermediateOutputPath)upload.flag <_ConfigurationCacheDirectory>$(BaseIntermediateOutputPath).cache\ - <_AndroidFastDevStrategy Condition=" '$(_AndroidFastDevStrategy)' == '' ">FastDeploy2 - <_AndroidFastDeployAppFileTransferMode Condition=" '$(_AndroidFastDeployAppFileTransferMode)' == '' And '$(_AndroidFastDevStrategy)' == 'FastDeploy2' ">Symlink - <_AndroidFastDeployAppFileTransferMode Condition=" '$(_AndroidFastDeployAppFileTransferMode)' == '' ">Copy + <_AndroidFastDeployAppFileTransferMode Condition=" '$(_AndroidFastDeployAppFileTransferMode)' == '' ">Symlink @@ -117,7 +114,6 @@ Copyright (C) 2016 Xamarin. All rights reserved. RuntimeIdentifiers="$(RuntimeIdentifier);$(RuntimeIdentifiers)" Condition=" '$(DesignTimeBuild)' != 'true' and '$(_ComputeFilesToPublishForRuntimeIdentifiers)' != 'true' "> - @@ -258,7 +254,7 @@ Copyright (C) 2016 Xamarin. All rights reserved. - <_ConfigurationCacheItems Include="$(Configuration)|$(Platform)|$(AdbTarget)|$(_AndroidFastDevStrategy)|$(_AndroidFastDeployAppFileTransferMode)" /> + <_ConfigurationCacheItems Include="$(Configuration)|$(Platform)|$(AdbTarget)|$(_AndroidFastDeployAppFileTransferMode)" /> @@ -330,8 +326,8 @@ Copyright (C) 2016 Xamarin. All rights reserved. <_FastDeploymentDiagnosticLogging Condition=" '$(_FastDeploymentDiagnosticLogging)' == '' ">False any <_AndroidFastDeployStaleFileRemovalBatchSize Condition=" '$(_AndroidFastDeployStaleFileRemovalBatchSize)' == '' ">100 @@ -339,9 +335,6 @@ Copyright (C) 2016 Xamarin. All rights reserved. <_AndroidFastDeployMaxShellCommandLength Condition=" '$(_AndroidFastDeployMaxShellCommandLength)' == '' ">900 <_AndroidFastDeployMaxAdbCommandLength Condition=" '$(_AndroidFastDeployMaxAdbCommandLength)' == '' ">4096 - @@ -354,47 +347,24 @@ Copyright (C) 2016 Xamarin. All rights reserved. <_EnvironmentFiles Include="@(AndroidEnvironment);@(LibraryEnvironments)" /> - files = FastDeploy2.GetFilesRequiringStagingDirectories (currentFiles, previousFiles); + HashSet files = FastDeploy.GetFilesRequiringStagingDirectories (currentFiles, previousFiles); CollectionAssert.AreEquivalent ( new [] { "arm64-v8a/fr/App.resources.dll" }, @@ -151,7 +151,7 @@ public void FastDeploy2PlansOnlyNewStagingDirectories () } [Test] - public void FastDeploy2PlansAllStagingDirectoriesAfterReset () + public void FastDeployPlansAllStagingDirectoriesAfterReset () { var currentFiles = new [] { "App.dll", @@ -159,7 +159,7 @@ public void FastDeploy2PlansAllStagingDirectoriesAfterReset () "arm64-v8a/fr/App.resources.dll", }; - HashSet files = FastDeploy2.GetFilesRequiringStagingDirectories (currentFiles, previousFiles: null); + HashSet files = FastDeploy.GetFilesRequiringStagingDirectories (currentFiles, previousFiles: null); CollectionAssert.AreEquivalent (currentFiles, files); } @@ -167,15 +167,15 @@ public void FastDeploy2PlansAllStagingDirectoriesAfterReset () [TestCase ("adb: error: failed to copy: No such file or directory")] [TestCase ("adb: error: target '/data/local/tmp/app/arm64-v8a' is not a directory")] [TestCase ("remote couldn't create file: Is a directory")] - public void FastDeploy2DetectsInvalidRemoteFilesystem (string output) + public void FastDeployDetectsInvalidRemoteFilesystem (string output) { - Assert.IsTrue (FastDeploy2.IsUnexpectedRemoteFilesystemError (output)); + Assert.IsTrue (FastDeploy.IsUnexpectedRemoteFilesystemError (output)); } [Test] - public void FastDeploy2DoesNotResetForUnrelatedPushFailure () + public void FastDeployDoesNotResetForUnrelatedPushFailure () { - Assert.IsFalse (FastDeploy2.IsUnexpectedRemoteFilesystemError ("adb: error: device offline")); + Assert.IsFalse (FastDeploy.IsUnexpectedRemoteFilesystemError ("adb: error: device offline")); } [TestCase ("adb: error: device offline", false)] @@ -183,15 +183,15 @@ public void FastDeploy2DoesNotResetForUnrelatedPushFailure () [TestCase ("adb: failed to install app.apk: Broken pipe (32)", false)] [TestCase ("cmd: Failure calling service package: Security exception", false)] [TestCase ("Failure [INSTALL_FAILED_INSUFFICIENT_STORAGE]", false)] - public void FastDeploy2ClassifiesOnlyKnownTransientInstallFailures (string output, bool expected) + public void FastDeployClassifiesOnlyKnownTransientInstallFailures (string output, bool expected) { - Assert.AreEqual (expected, FastDeploy2.IsTransientInstallFailure (output)); + Assert.AreEqual (expected, FastDeploy.IsTransientInstallFailure (output)); } [Test] - public async Task FastDeploy2RetriesTransientInstallOnce () + public async Task FastDeployRetriesTransientInstallOnce () { - var task = new TestFastDeploy2 ( + var task = new TestFastDeploy ( CreateAdbResult (1, "adb: failed to install app.apk: cmd: Failure calling service package: Broken pipe (32)"), CreateAdbResult (0, "Success")); @@ -202,9 +202,9 @@ public async Task FastDeploy2RetriesTransientInstallOnce () } [Test] - public async Task FastDeploy2RetriesTransientInstallAfterUninstall () + public async Task FastDeployRetriesTransientInstallAfterUninstall () { - var task = new TestFastDeploy2 ( + var task = new TestFastDeploy ( CreateAdbResult (1, "Failure [INSTALL_FAILED_ALREADY_EXISTS]"), CreateAdbResult (1, "adb: failed to install app.apk: cmd: Failure calling service package: Broken pipe (32)"), CreateAdbResult (0, "Success")); @@ -217,9 +217,9 @@ public async Task FastDeploy2RetriesTransientInstallAfterUninstall () } [Test] - public void FastDeploy2DoesNotRetryTransientInstallTwiceAcrossUninstall () + public void FastDeployDoesNotRetryTransientInstallTwiceAcrossUninstall () { - var task = new TestFastDeploy2 ( + var task = new TestFastDeploy ( CreateAdbResult (1, "first failure: cmd: Failure calling service package: Broken pipe (32)"), CreateAdbResult (1, "Failure [INSTALL_FAILED_ALREADY_EXISTS]"), CreateAdbResult (1, "third failure: cmd: Failure calling service package: Broken pipe (32)")); @@ -242,9 +242,9 @@ public void FastDeploy2DoesNotRetryTransientInstallTwiceAcrossUninstall () } [Test] - public void FastDeploy2DoesNotRetrySemanticInstallFailure () + public void FastDeployDoesNotRetrySemanticInstallFailure () { - var task = new TestFastDeploy2 ( + var task = new TestFastDeploy ( CreateAdbResult (1, "Failure [INSTALL_FAILED_INSUFFICIENT_STORAGE]")); var exception = Assert.ThrowsAsync ( @@ -257,9 +257,9 @@ public void FastDeploy2DoesNotRetrySemanticInstallFailure () } [Test] - public void FastDeploy2PreservesBothTransientInstallAttempts () + public void FastDeployPreservesBothTransientInstallAttempts () { - var task = new TestFastDeploy2 ( + var task = new TestFastDeploy ( CreateAdbResult (1, "first failure: cmd: Failure calling service package: Broken pipe (32)"), CreateAdbResult (1, "second failure: cmd: Failure calling service package: Broken pipe (32)")); @@ -278,9 +278,9 @@ public void FastDeploy2PreservesBothTransientInstallAttempts () } [Test] - public void FastDeploy2PreservesOriginalFailureWhenRecoveryFails () + public void FastDeployPreservesOriginalFailureWhenRecoveryFails () { - var task = new TestFastDeploy2 ( + var task = new TestFastDeploy ( new InvalidOperationException ("package manager still unavailable"), CreateAdbResult (1, "cmd: Failure calling service package: Broken pipe (32)")); @@ -294,16 +294,16 @@ public void FastDeploy2PreservesOriginalFailureWhenRecoveryFails () Assert.AreEqual (1, task.RecoveryAttempts); } - static FastDeploy2.AdbCommandResult CreateAdbResult (int exitCode, string output) + static FastDeploy.AdbCommandResult CreateAdbResult (int exitCode, string output) { - return new FastDeploy2.AdbCommandResult { + return new FastDeploy.AdbCommandResult { ExitCode = exitCode, StandardOutput = output, StandardError = "", }; } - sealed class TestFastDeploy2 : FastDeploy2 + sealed class TestFastDeploy : FastDeploy { readonly Queue results; readonly Exception recoveryException; @@ -312,12 +312,12 @@ sealed class TestFastDeploy2 : FastDeploy2 public int UninstallAttempts { get; private set; } public int RecoveryAttempts { get; private set; } - public TestFastDeploy2 (params AdbCommandResult [] results) + public TestFastDeploy (params AdbCommandResult [] results) : this (recoveryException: null, results) { } - public TestFastDeploy2 (Exception recoveryException, params AdbCommandResult [] results) + public TestFastDeploy (Exception recoveryException, params AdbCommandResult [] results) { this.results = new Queue (results); this.recoveryException = recoveryException; diff --git a/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.ProjectTools/Common/BuildOutput.cs b/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.ProjectTools/Common/BuildOutput.cs index 668ecef3299..51fb5a135ba 100644 --- a/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.ProjectTools/Common/BuildOutput.cs +++ b/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.ProjectTools/Common/BuildOutput.cs @@ -176,7 +176,7 @@ public TimeSpan GetTargetOrTaskTime (string targetOrTask) /// /// /// This scans the build output for the Installed Package message written by the - /// FastDeploy and FastDeploy2 tasks. Both write it with + /// FastDeploy task. It writes the message with /// , so it is only present in the /// build output at or higher. /// At a lower verbosity this property would silently return false no matter what the diff --git a/tests/MSBuildDeviceIntegration/Tests/FastDevTest.cs b/tests/MSBuildDeviceIntegration/Tests/FastDevTest.cs index b20d06d1ad6..e3f31352934 100644 --- a/tests/MSBuildDeviceIntegration/Tests/FastDevTest.cs +++ b/tests/MSBuildDeviceIntegration/Tests/FastDevTest.cs @@ -39,17 +39,14 @@ public void FastDevSimpleBuild () } [Test] - [TestCase ("FastDeploy")] - [TestCase ("FastDeploy2")] - public void FastDeployUpdatesTypeMapAfterAssemblyEdit (string strategy) + public void FastDeployUpdatesTypeMapAfterAssemblyEdit () { const string logcatMessage = "FAST_DEPLOY_TYPEMAP_TEST_MESSAGE"; var proj = new XamarinAndroidApplicationProject { - PackageName = $"com.xamarin.fastdeploy_typemap_{strategy.ToLowerInvariant ()}", + PackageName = "com.xamarin.fastdeploy_typemap", }; proj.SetDefaultTargetDevice (); - proj.SetProperty ("_AndroidFastDevStrategy", strategy); // Fast deployment only syncs managed assemblies, so anything that changes the set of // Java-callable types has to go through a new .apk: new Java stubs, a new .dex, a new @@ -260,46 +257,10 @@ public void SkipFastDevAlreadyInstalledFile () } [Test] - public void FastDeploymentStrategyCanBeChanged () + public void FastDeployRestoresMissingRemoteDirectory () { var proj = new XamarinAndroidApplicationProject { - PackageName = "com.xamarin.fastdeployment_strategy_change", - }; - proj.MainActivity = proj.DefaultMainActivity; - proj.SetDefaultTargetDevice (); - proj.SetProperty ("_AndroidFastDevStrategy", "FastDeploy2"); - using (var builder = CreateApkBuilder ()) { - builder.Verbosity = LoggerVerbosity.Detailed; - Assert.IsTrue (builder.Install (proj), "FastDeploy2 install should have succeeded."); - - string assemblyPath = $"files/.__override__/{DeviceAbi}/UnnamedProject.dll"; - Assert.AreEqual ("symlink", GetOverrideFileKind (proj.PackageName, assemblyPath)); - RunAdbCommand ($"shell run-as {proj.PackageName} sh -c 'echo preserved > files/fastdeploy-strategy-marker'"); - Assert.IsTrue (builder.Clean (proj), "clean should have succeeded."); - - proj.MainActivity = proj.MainActivity.Replace ("clicks", "CLICKS"); - proj.Touch ("MainActivity.cs"); - proj.SetProperty ("_AndroidFastDevStrategy", "FastDeploy"); - Assert.IsTrue (builder.Install (proj, doNotCleanupOnUpdate: true), "FastDeploy install should have succeeded after FastDeploy2."); - Assert.AreEqual ("regular", GetOverrideFileKind (proj.PackageName, assemblyPath)); - Assert.AreEqual ("preserved", RunAdbCommand ($"shell run-as {proj.PackageName} cat files/fastdeploy-strategy-marker").Trim ()); - - proj.MainActivity = proj.MainActivity.Replace ("CLICKS", "Clicks"); - proj.Touch ("MainActivity.cs"); - proj.SetProperty ("_AndroidFastDevStrategy", "FastDeploy2"); - Assert.IsTrue (builder.Install (proj, doNotCleanupOnUpdate: true), "FastDeploy2 install should have succeeded after FastDeploy."); - Assert.AreEqual ("symlink", GetOverrideFileKind (proj.PackageName, assemblyPath)); - Assert.AreEqual ("preserved", RunAdbCommand ($"shell run-as {proj.PackageName} cat files/fastdeploy-strategy-marker").Trim ()); - - Assert.IsTrue (builder.Uninstall (proj), "uninstall should have succeeded."); - } - } - - [Test] - public void FastDeploy2RestoresMissingRemoteDirectory () - { - var proj = new XamarinAndroidApplicationProject { - PackageName = "com.xamarin.fastdeploy2_restore_remote", + PackageName = "com.xamarin.fastdeploy_restore_remote", }; proj.MainActivity = proj.DefaultMainActivity; proj.SetDefaultTargetDevice (); @@ -307,7 +268,7 @@ public void FastDeploy2RestoresMissingRemoteDirectory () builder.Verbosity = LoggerVerbosity.Detailed; Assert.IsTrue (builder.Install (proj), "initial install should have succeeded."); - string remoteDirectory = $"/data/local/tmp/fastdeploy2/{proj.PackageName}/0/{DeviceAbi}"; + string remoteDirectory = $"/data/local/tmp/fastdeploy/{proj.PackageName}/0/{DeviceAbi}"; RunAdbCommand ($"shell rm -rf {remoteDirectory}"); proj.MainActivity = proj.MainActivity.Replace ("clicks", "CLICKS"); @@ -322,27 +283,26 @@ public void FastDeploy2RestoresMissingRemoteDirectory () } [Test] - public void FastDeploy2CleansOrphanStagingDirectoriesAfterApkInstall () + public void FastDeployCleansOrphanStagingDirectoriesAfterApkInstall () { string [] orphanDirectories = { - "/data/local/tmp/fastdeploy2/com.xamarin.fastdeploy2_cleanup_one/0", - "/data/local/tmp/fastdeploy2/com.xamarin.fastdeploy2_cleanup_two/0", + "/data/local/tmp/fastdeploy/com.xamarin.fastdeploy_cleanup_one/0", + "/data/local/tmp/fastdeploy/com.xamarin.fastdeploy_cleanup_two/0", }; - string incrementalOrphanDirectory = "/data/local/tmp/fastdeploy2/com.xamarin.fastdeploy2_cleanup_incremental/0"; - string symlinkDirectory = "/data/local/tmp/fastdeploy2/com.xamarin.fastdeploy2_cleanup_symlink"; - string symlinkTargetDirectory = "/data/local/tmp/fastdeploy2_cleanup_symlink_target/0"; + string incrementalOrphanDirectory = "/data/local/tmp/fastdeploy/com.xamarin.fastdeploy_cleanup_incremental/0"; + string symlinkDirectory = "/data/local/tmp/fastdeploy/com.xamarin.fastdeploy_cleanup_symlink"; + string symlinkTargetDirectory = "/data/local/tmp/fastdeploy_cleanup_symlink_target/0"; var proj = new XamarinAndroidApplicationProject { - PackageName = "com.xamarin.fastdeploy2_cleanup", + PackageName = "com.xamarin.fastdeploy_cleanup", }; proj.MainActivity = proj.DefaultMainActivity; proj.SetDefaultTargetDevice (); - proj.SetProperty ("_AndroidFastDevStrategy", "FastDeploy2"); var installedProj = new XamarinAndroidApplicationProject { - PackageName = "com.xamarin.fastdeploy2_cleanup_installed", - ProjectName = "FastDeploy2CleanupInstalled", + PackageName = "com.xamarin.fastdeploy_cleanup_installed", + ProjectName = "FastDeployCleanupInstalled", }; installedProj.SetDefaultTargetDevice (); - string installedDirectory = $"/data/local/tmp/fastdeploy2/{installedProj.PackageName}/0"; + string installedDirectory = $"/data/local/tmp/fastdeploy/{installedProj.PackageName}/0"; using (var installedBuilder = CreateApkBuilder (Path.Combine ("temp", TestName, installedProj.ProjectName))) using (var builder = CreateApkBuilder (Path.Combine ("temp", TestName, proj.ProjectName))) { @@ -359,7 +319,7 @@ public void FastDeploy2CleansOrphanStagingDirectoriesAfterApkInstall () RunAdbCommand ($"shell touch {symlinkTargetDirectory}/outside.txt"); RunAdbCommand ($"shell ln -s {Path.GetDirectoryName (symlinkTargetDirectory).Replace ('\\', '/')} {symlinkDirectory}"); - Assert.IsTrue (builder.Install (proj), "FastDeploy2 install should have succeeded."); + Assert.IsTrue (builder.Install (proj), "FastDeploy install should have succeeded."); foreach (string directory in orphanDirectories) { Assert.AreEqual ("missing", RunAdbCommand ($"shell if test -e {directory}; then echo exists; else echo missing; fi").Trim (), @@ -374,7 +334,7 @@ public void FastDeploy2CleansOrphanStagingDirectoriesAfterApkInstall () RunAdbCommand ($"shell touch {incrementalOrphanDirectory}/orphan.txt"); proj.MainActivity = proj.MainActivity.Replace ("clicks", "CLICKS"); proj.Touch ("MainActivity.cs"); - Assert.IsTrue (builder.Install (proj, doNotCleanupOnUpdate: true, saveProject: false), "Incremental FastDeploy2 install should have succeeded."); + Assert.IsTrue (builder.Install (proj, doNotCleanupOnUpdate: true, saveProject: false), "Incremental FastDeploy install should have succeeded."); Assert.IsFalse (builder.Output.IsApkInstalled, "The APK should not have been reinstalled."); Assert.AreEqual ("exists", RunAdbCommand ($"shell if test -f {incrementalOrphanDirectory}/orphan.txt; then echo exists; else echo missing; fi").Trim (), "Cleanup should not run during an incremental deployment that skips APK installation."); diff --git a/tests/MSBuildDeviceIntegration/Tests/PerformanceTest.cs b/tests/MSBuildDeviceIntegration/Tests/PerformanceTest.cs index 118fd906e8b..2b9c09c1040 100644 --- a/tests/MSBuildDeviceIntegration/Tests/PerformanceTest.cs +++ b/tests/MSBuildDeviceIntegration/Tests/PerformanceTest.cs @@ -385,7 +385,7 @@ public void Install_CSharp_FromClean () builder.Verbosity = LoggerVerbosity.Quiet; builder.Install (proj); builder.AutomaticNuGetRestore = false; - ProfileTask (builder, "FastDeploy2", 20, b => { + ProfileTask (builder, "FastDeploy", 20, b => { b.Uninstall (proj); b.Install (proj); }); diff --git a/tests/Xamarin.Android.Tools.AndroidSdk-Tests/AdbRunnerTests.cs b/tests/Xamarin.Android.Tools.AndroidSdk-Tests/AdbRunnerTests.cs index d1b955e0a06..e2e7ef7a9f7 100644 --- a/tests/Xamarin.Android.Tools.AndroidSdk-Tests/AdbRunnerTests.cs +++ b/tests/Xamarin.Android.Tools.AndroidSdk-Tests/AdbRunnerTests.cs @@ -23,7 +23,7 @@ namespace Xamarin.Android.Tools.Tests; /// - MapAdbStateToStatus: used internally by ParseAdbDevicesOutput, public for extensibility /// - ListDevicesAsync: used by MAUI DevTools Adb provider (Providers/Android/Adb.cs) /// - WaitForDeviceAsync: used by MAUI DevTools Adb provider -/// - WaitForPackageManagerAsync: used by dotnet/android FastDeploy2 install recovery +/// - WaitForPackageManagerAsync: used by dotnet/android FastDeploy install recovery /// - StopEmulatorAsync: used by MAUI DevTools Adb provider /// - GetEmulatorAvdNameAsync: internal, used by ListDevicesAsync only /// diff --git a/tools/fastdev/Makefile b/tools/fastdev/Makefile deleted file mode 100644 index 808f47562a9..00000000000 --- a/tools/fastdev/Makefile +++ /dev/null @@ -1,21 +0,0 @@ -include ../../env.config -include $(TOP)/mk/build.make - -VERBOSITY=diag -SLN=fastdevtools.csproj -MSBUILD_ARGS=/verbosity:$(VERBOSITY) /nologo /restore -MSBUILD=msbuild $(MSBUILD_ARGS) -srcdir=$(shell pwd) - -OUTPUT_FIND = $(ENABLED_RUNTIMES:%=$(BUILDDIR)/lib/xamarin.android/xbuild/Xamarin/Android/lib/%/xamarin.find) -OUTPUT_STAT = $(ENABLED_RUNTIMES:%=$(BUILDDIR)/lib/xamarin.android/xbuild/Xamarin/Android/lib/%/xamarin.stat) -OUTPUT_SYNC = $(ENABLED_RUNTIMES:%=$(BUILDDIR)/lib/xamarin.android/xbuild/Xamarin/Android/lib/%/xamarin.sync) - -OUTPUT = $(OUTPUT_FIND) $(OUTPUT_STAT) $(OUTPUT_SYNC) -SRC = $(SLN) xamarin.find/CMakeLists.txt xamarin.find/main.cc xamarin.stat/CMakeLists.txt xamarin.stat/main.cc xamarin.sync/CMakeLists.txt xamarin.sync/main.cc - -all $(OUTPUT):: $(SRC) - -$(MSBUILD) $(SLN) /property:Configuration=$(CONFIGURATION) - -clean:: - -$(MSBUILD) $(SLN) /property:Configuration=$(CONFIGURATION) /t:Clean \ No newline at end of file diff --git a/tools/fastdev/elfcleaner/CMakeLists.txt b/tools/fastdev/elfcleaner/CMakeLists.txt deleted file mode 100644 index bba82e0fe5f..00000000000 --- a/tools/fastdev/elfcleaner/CMakeLists.txt +++ /dev/null @@ -1,33 +0,0 @@ -# Set the minimum version of CMake that can be used -# To find the cmake version run -# $ cmake --version -cmake_minimum_required(VERSION 3.5) - -# Set the project name -project (elfcleaner C CXX) - -set(CMAKE_CXX_STANDARD 17) -set(CMAKE_CXX_STANDARD_REQUIRED ON) -set(CMAKE_CXX_EXTENSIONS ON) - -set(CMAKE_C_STANDARD 99) -set(CMAKE_C_STANDARD_REQUIRED ON) - -if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) - message("Setting build type to 'Release' as none was specified.") - set(CMAKE_BUILD_TYPE Release CACHE STRING "Choose the type of build." FORCE) - # Set the possible values of build type for cmake-gui - set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Release" - "MinSizeRel" "Release") -endif() - -set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} -O2 -Wall") -set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -O2 -Wall") - -set(ELFCLEANER_SOURCES - ../../../external/termux-elf-cleaner/termux-elf-cleaner.cpp - ) - -# Add an executable -add_executable(elfcleaner ${ELFCLEANER_SOURCES}) -set_target_properties(elfcleaner PROPERTIES LINK_FLAGS_RELEASE -s) \ No newline at end of file diff --git a/tools/fastdev/fastdev.slnx b/tools/fastdev/fastdev.slnx deleted file mode 100644 index 0fc0df4ec07..00000000000 --- a/tools/fastdev/fastdev.slnx +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/tools/fastdev/fastdevtools.csproj b/tools/fastdev/fastdevtools.csproj deleted file mode 100644 index ef2e438ca8c..00000000000 --- a/tools/fastdev/fastdevtools.csproj +++ /dev/null @@ -1,25 +0,0 @@ - - - - - $(NoWarn);CA1305 - - - - 12 - netstandard2.0 - $(MicrosoftAndroidSdkOutDir)lib - false - - $(MicrosoftAndroidSdkOutDir.TrimEnd('\\').TrimEnd('/')) - - - - - - - - - - diff --git a/tools/fastdev/fastdevtools.projitems b/tools/fastdev/fastdevtools.projitems deleted file mode 100644 index 7ee0d0564ae..00000000000 --- a/tools/fastdev/fastdevtools.projitems +++ /dev/null @@ -1,47 +0,0 @@ - - - - - 21 - %(Identity) - - - 21 - %(Identity) - - - 16 - %(Identity) - - - 16 - %(Identity) - - - - - xamarin.sync - ..\..\..\..\xamarin.sync - $(DebuggingToolsOutputDirectory)\lib\%(FastDevBuildItems.Arch) - -DLZ4_SRC_DIR=../../../external/lz4/lib -DANDROID_NATIVE_API_LEVEL=%(FastDevBuildItems.NativeApiLevel) -DANDROID_PLATFORM=android-%(FastDevBuildItems.NativeApiLevel) - - - xamarin.find - ..\..\..\..\xamarin.find - $(DebuggingToolsOutputDirectory)\lib\%(FastDevBuildItems.Arch) - -DANDROID_NATIVE_API_LEVEL=%(FastDevBuildItems.NativeApiLevel) -DANDROID_PLATFORM=android-%(FastDevBuildItems.NativeApiLevel) - - - xamarin.stat - ..\..\..\..\xamarin.stat - $(DebuggingToolsOutputDirectory)\lib\%(FastDevBuildItems.Arch) - -DANDROID_NATIVE_API_LEVEL=%(FastDevBuildItems.NativeApiLevel) -DANDROID_PLATFORM=android-%(FastDevBuildItems.NativeApiLevel) - - - xamarin.cp - ..\..\..\..\xamarin.cp - $(DebuggingToolsOutputDirectory)\lib\%(FastDevBuildItems.Arch) - -DANDROID_NATIVE_API_LEVEL=%(FastDevBuildItems.NativeApiLevel) -DANDROID_PLATFORM=android-%(FastDevBuildItems.NativeApiLevel) - - - \ No newline at end of file diff --git a/tools/fastdev/fastdevtools.targets b/tools/fastdev/fastdevtools.targets deleted file mode 100644 index 50e991890cb..00000000000 --- a/tools/fastdev/fastdevtools.targets +++ /dev/null @@ -1,57 +0,0 @@ - - - - - - - <_CmakeToolPath Condition=" !Exists('$(CmakePath)') " Include="$(AndroidSdkDirectory)\cmake\*\bin\cmake*" /> - <_NinjaToolPath Condition=" !Exists('$(NinjaPath)') " Include="$(AndroidSdkDirectory)\cmake\*\bin\ninja*" /> - - - %(_CmakeToolPath.Identity) - cmake - %(_NinjaToolPath.Identity) - ninja - <_CmakeAndroidFlags>-GNinja -DENABLE_NDK=ON -DCMAKE_MAKE_PROGRAM="$(NinjaPath)" -DANDROID_TOOLCHAIN=clang -DANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES=ON - <_CmakeAndroidFlags>$(_CmakeAndroidFlags) -DCMAKE_TOOLCHAIN_FILE="$(AndroidNdkDirectory)/build/cmake/android.toolchain.cmake" - <_CmakeAndroidFlags>$(_CmakeAndroidFlags) -DANDROID_NDK="$(AndroidNdkDirectory)" -DCMAKE_BUILD_TYPE=Debug - - - - - - - - - - - $(IntermediateOutputPath)elfcleaner - ..\..\..\elfcleaner - elfcleaner - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/tools/fastdev/xamarin.cp/CMakeLists.txt b/tools/fastdev/xamarin.cp/CMakeLists.txt deleted file mode 100644 index 87c50a25f65..00000000000 --- a/tools/fastdev/xamarin.cp/CMakeLists.txt +++ /dev/null @@ -1,52 +0,0 @@ -# Set the minimum version of CMake that can be used -# To find the cmake version run -# $ cmake --version -cmake_minimum_required(VERSION 3.5) - -# Set the project name -project (xamarin.cp C CXX) -#set(CMAKE_FIND_LIBRARY_SUFFIXES ".a") -#find_package(ZLIB REQUIRED) - -set(CMAKE_CXX_STANDARD 17) -set(CMAKE_CXX_STANDARD_REQUIRED ON) -set(CMAKE_CXX_EXTENSIONS ON) - -set(CMAKE_C_STANDARD 99) -set(CMAKE_C_STANDARD_REQUIRED ON) - -option(ENABLE_NDK "Build with Android's NDK" OFF) - -if(ENABLE_NDK) - add_definitions("-DPLATFORM_ANDROID") - add_definitions("-DANDROID") - add_definitions("-DLINUX -Dlinux -D__linux__") -endif() - -if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) - message("Setting build type to 'Release' as none was specified.") - set(CMAKE_BUILD_TYPE Release CACHE STRING "Choose the type of build." FORCE) - # Set the possible values of build type for cmake-gui - set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Release" - "MinSizeRel" "Release") -endif() - -set(COMMON_COMPILER_OPTIONS - -O2 - -Wall - -fstack-protector-strong - -fstrict-return - -fno-omit-frame-pointer -) - -add_compile_options("$<$:${COMMON_COMPILER_OPTIONS}>") -add_compile_options("$<$:${COMMON_COMPILER_OPTIONS}>") -#set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "../../../../out/${ANDROID_ABI}") - -set(XAMARINCP_SOURCES - main.cc - ) - -# Add an executable -add_executable(xamarin.cp ${XAMARINCP_SOURCES}) -set_target_properties(xamarin.cp PROPERTIES LINK_FLAGS_RELEASE -s) diff --git a/tools/fastdev/xamarin.cp/main.cc b/tools/fastdev/xamarin.cp/main.cc deleted file mode 100644 index b4115f2530e..00000000000 --- a/tools/fastdev/xamarin.cp/main.cc +++ /dev/null @@ -1,111 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -void printHelp (); - -int main (int argc, char **argv) -{ - if (argc <= 3) { - printHelp (); - return 1; - } - - uint64_t modifieddatetime = strtoull (argv[3], nullptr, 10); - if (modifieddatetime == 0 || modifieddatetime == ULLONG_MAX || errno == ERANGE) { - fprintf(stderr, "error: invalid argument '%s'.", argv[4]); - printHelp (); - return 1; - } - - struct stat fi; - decltype (fi.st_blksize) blockSize; - int ret = stat (".", &fi); - - if (ret == 0 && fi.st_blksize >= 0) { - blockSize = fi.st_blksize; - } else { - blockSize = 4096; - } - - const char *sourcePath = argv[1]; - const char *destinationPath = argv[2]; - - FILE *sourceFile = fopen (sourcePath, "rb"); - if (sourceFile == nullptr) { - perror ("Error opening source file"); - return 1; - } - - if (access (destinationPath, F_OK) != -1) { - if (access (destinationPath, W_OK) == -1) { - if (chmod (destinationPath, S_IWUSR | S_IRUSR) == -1) { - if (remove (destinationPath) == -1) { - fprintf (stderr, "error: could not set write permissions on '%s': %s", destinationPath, strerror (errno)); - return 1; - } - } - } - } - - FILE *destinationFile = fopen (destinationPath, "wb"); - if (destinationFile == nullptr) { - perror ("Error opening destination file"); - fclose (sourceFile); - return 1; - } - - uint8_t buffer[blockSize]; - size_t bytesRead; - while ((bytesRead = fread(buffer, 1, sizeof(buffer), sourceFile)) > 0) { - if (fwrite (buffer, 1, bytesRead, destinationFile) != bytesRead) { - perror ("Error writing to destination file"); - fclose (sourceFile); - fclose (destinationFile); - return 1; - } - } - - fclose (sourceFile); - fclose (destinationFile); - - timeval modifiedtimes[] { - { - .tv_sec = static_cast (modifieddatetime / 1000), - .tv_usec = static_cast (modifieddatetime % 1000), - }, - - { - .tv_sec = static_cast (modifieddatetime / 1000), - .tv_usec = static_cast (modifieddatetime % 1000), - }, - }; - - utimes (argv[2], modifiedtimes); - if (chmod (argv[2], S_IRUSR) == -1) { - fprintf (stderr, "error: could not set read permissions on '%s'. %s", argv[2], strerror (errno)); - return 1; - } - - printf ("moved [%s] to [%s] modifieddate [%" PRId64 "]\n", argv[1], argv[2], modifieddatetime); - - return 0; -} - -void printHelp () -{ - printf ("xamarin.cp\n"); - printf ("Usage: xamarin.cp \n"); - printf ("\t : The source file to copy (required). \n"); - printf ("\t : The destination file(required). \n"); - printf ("\t : The modified date to use for this file in unix time.\n"); -} diff --git a/tools/fastdev/xamarin.find/CMakeLists.txt b/tools/fastdev/xamarin.find/CMakeLists.txt deleted file mode 100644 index efd6d0fb459..00000000000 --- a/tools/fastdev/xamarin.find/CMakeLists.txt +++ /dev/null @@ -1,53 +0,0 @@ -# Set the minimum version of CMake that can be used -# To find the cmake version run -# $ cmake --version -cmake_minimum_required(VERSION 3.5) - -# Set the project name -project (xamarin.find C CXX) -#set(CMAKE_FIND_LIBRARY_SUFFIXES ".a") -#find_package(ZLIB REQUIRED) - -set(CMAKE_CXX_STANDARD 17) -set(CMAKE_CXX_STANDARD_REQUIRED ON) -set(CMAKE_CXX_EXTENSIONS ON) - -set(CMAKE_C_STANDARD 99) -set(CMAKE_C_STANDARD_REQUIRED ON) - -option(ENABLE_NDK "Build with Android's NDK" OFF) - -if(ENABLE_NDK) - add_definitions("-DPLATFORM_ANDROID") - add_definitions("-DANDROID") - add_definitions("-DLINUX -Dlinux -D__linux__") -endif() - -if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) - message("Setting build type to 'Release' as none was specified.") - set(CMAKE_BUILD_TYPE Release CACHE STRING "Choose the type of build." FORCE) - # Set the possible values of build type for cmake-gui - set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Release" - "MinSizeRel" "Release") -endif() - -set(COMMON_COMPILER_OPTIONS - -O2 - -Wall - -fstack-protector-strong - -fstrict-return - -fno-omit-frame-pointer -) - -add_compile_options("$<$:${COMMON_COMPILER_OPTIONS}>") -add_compile_options("$<$:${COMMON_COMPILER_OPTIONS}>") -#set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "../../../../out/${ANDROID_ABI}") - - -set(XAMARINFIND_SOURCES - main.cc - ) - -# Add an executable -add_executable(xamarin.find ${XAMARINFIND_SOURCES}) -set_target_properties(xamarin.find PROPERTIES LINK_FLAGS_RELEASE -s) diff --git a/tools/fastdev/xamarin.find/main.cc b/tools/fastdev/xamarin.find/main.cc deleted file mode 100644 index 2f317cbba8c..00000000000 --- a/tools/fastdev/xamarin.find/main.cc +++ /dev/null @@ -1,111 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include - -constexpr uint64_t THOUSAND = 1000; - -void findAllFiles(const char *path); -void printHelp (); - -bool verbose = 0; -bool debug = 0; -int main(int argc, char **argv) -{ - if (argc <= 1) { - printHelp (); - return 1; - } - int opt; - while((opt = getopt (argc, argv, "vd")) != -1) { - switch (opt) - { - case 'v': - verbose = 1; - break; - case 'd': - debug = 1; - break; - default: - printHelp (); - return 1; - } - } - if (chdir (argv[optind]) == -1) { - fprintf (stderr, "error: failed to change current directory to '%s'. %s.", argv[optind], strerror (errno)); - return 1; - } - findAllFiles("."); - return 0; -} - -void printHelp () -{ - printf ("xamarin.find\n"); - printf ("Usage: xamarin.find -v -d \n"); - printf ("\t-v : Print Size and Last Modified Time of the files (optional)\n"); - printf ("\t-d : Print additional diagnostics\n"); - printf ("\t : The directory to recursively list the files for (required). \n"); -} - -/** - * find all files and sub-directories recursively - * expected output is relative path to file. - * - * For example a call to - * xamarin.find /data/data/com.foo.bar/files/.__overriide__ - * - * would result in - * ./a.dll - * ./fr-FR/a.resources.dll - * - * for filesize output use -v - * - * xamarin.find -v /data/data/com.foo.bar/files/.__overriide__ - * ./a.dll 1025 3765434 - * ./fr-FR/a.resources.dll 23 12431341 - */ -void findAllFiles(const char *basePath) -{ - struct dirent *dp; - DIR *dir = opendir(basePath); - - // Unable to open directory stream - if (!dir) - return; - - while ((dp = readdir(dir)) != NULL) { - if (strcmp(dp->d_name, ".") == 0 || strcmp(dp->d_name, "..") == 0) - continue; - // Construct new path from our base path - char *path = new char[strlen (basePath)+strlen(dp->d_name)+2]; - strcpy(path, basePath); - strcat(path, "/"); - strcat(path, dp->d_name); - - if (dp->d_type == DT_REG) { - if (verbose) { - struct stat fi; - stat(path, &fi); - int64_t tv_sec = static_cast (fi.st_mtim.tv_sec); - int64_t tv_nsec = static_cast (fi.st_mtim.tv_nsec); - if (debug) - printf ("DEBUG: %s size:%" PRId64 " mtime:%" PRId64 " tv_sec:%" PRId64 " tv_nsec:%" PRId64 "\n", path, - static_cast ((tv_sec * THOUSAND) + (tv_nsec / THOUSAND)),static_cast (fi.st_size), static_cast (fi.st_mtim.tv_sec), static_cast (fi.st_mtim.tv_nsec)); - printf("%s\t%" PRId64 "\t%" PRId64 "\n", path, static_cast (fi.st_size), static_cast ((tv_sec * THOUSAND) + (tv_nsec / THOUSAND))); - } else { - printf("%s\n", path); - } - } - - findAllFiles(path); - delete[] path; - } - - closedir(dir); -} \ No newline at end of file diff --git a/tools/fastdev/xamarin.stat/CMakeLists.txt b/tools/fastdev/xamarin.stat/CMakeLists.txt deleted file mode 100644 index 19af176744a..00000000000 --- a/tools/fastdev/xamarin.stat/CMakeLists.txt +++ /dev/null @@ -1,53 +0,0 @@ -# Set the minimum version of CMake that can be used -# To find the cmake version run -# $ cmake --version -cmake_minimum_required(VERSION 3.5) - -# Set the project name -project (xamarin.stat C CXX) -#set(CMAKE_FIND_LIBRARY_SUFFIXES ".a") -#find_package(ZLIB REQUIRED) - -set(CMAKE_CXX_STANDARD 17) -set(CMAKE_CXX_STANDARD_REQUIRED ON) -set(CMAKE_CXX_EXTENSIONS ON) - -set(CMAKE_C_STANDARD 99) -set(CMAKE_C_STANDARD_REQUIRED ON) - -option(ENABLE_NDK "Build with Android's NDK" OFF) - -if(ENABLE_NDK) - add_definitions("-DPLATFORM_ANDROID") - add_definitions("-DANDROID") - add_definitions("-DLINUX -Dlinux -D__linux__") -endif() - -if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) - message("Setting build type to 'Release' as none was specified.") - set(CMAKE_BUILD_TYPE Release CACHE STRING "Choose the type of build." FORCE) - # Set the possible values of build type for cmake-gui - set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Release" - "MinSizeRel" "Release") -endif() - -set(COMMON_COMPILER_OPTIONS - -O2 - -Wall - -fstack-protector-strong - -fstrict-return - -fno-omit-frame-pointer -) - -add_compile_options("$<$:${COMMON_COMPILER_OPTIONS}>") -add_compile_options("$<$:${COMMON_COMPILER_OPTIONS}>") -#set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "../../../../out/${ANDROID_ABI}") - - -set(XAMARINFIND_SOURCES - main.cc - ) - -# Add an executable -add_executable(xamarin.stat ${XAMARINFIND_SOURCES}) -set_target_properties(xamarin.stat PROPERTIES LINK_FLAGS_RELEASE -s) diff --git a/tools/fastdev/xamarin.stat/main.cc b/tools/fastdev/xamarin.stat/main.cc deleted file mode 100644 index 7966f996df7..00000000000 --- a/tools/fastdev/xamarin.stat/main.cc +++ /dev/null @@ -1,28 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include - -int main(int argc, char **argv) -{ - struct stat fi; - if (argc <= 1) { - printf("Usage: xamarin.stat PATH\n"); - return 1; - } - int r = stat(argv[1], &fi); - if (r != 0) { - fprintf (stderr, "error: File or Directory '%s' does not exist. %s.\n", argv[1], strerror (errno)); - return 1; - } - if (fi.st_size >= 0) { - printf("%" PRId64 "\t%" PRId64 "\t%" PRId64 "\n", static_cast (fi.st_blksize), static_cast (fi.st_size), static_cast ((fi.st_mtim.tv_sec * 1000) + (fi.st_mtim.tv_nsec / 1000))); - return 0; - } - fprintf (stderr, "error: File or Directory '%s' does not exist. %s.\n", argv[1], strerror (errno)); - return 1; -} \ No newline at end of file diff --git a/tools/fastdev/xamarin.sync/CMakeLists.txt b/tools/fastdev/xamarin.sync/CMakeLists.txt deleted file mode 100644 index 53f5cf8f4bb..00000000000 --- a/tools/fastdev/xamarin.sync/CMakeLists.txt +++ /dev/null @@ -1,70 +0,0 @@ -# Set the minimum version of CMake that can be used -# To find the cmake version run -# $ cmake --version -cmake_minimum_required(VERSION 3.5) - -# Set the project name -project (xamarin.sync C CXX) -#set(CMAKE_FIND_LIBRARY_SUFFIXES ".a") -#find_package(ZLIB REQUIRED) - -set(CMAKE_CXX_STANDARD 17) -set(CMAKE_CXX_STANDARD_REQUIRED ON) -set(CMAKE_CXX_EXTENSIONS ON) - -set(CMAKE_C_STANDARD 99) -set(CMAKE_C_STANDARD_REQUIRED ON) - -option(ENABLE_NDK "Build with Android's NDK" OFF) - -if(ENABLE_NDK) - add_definitions("-DPLATFORM_ANDROID") - add_definitions("-DANDROID") - add_definitions("-DLINUX -Dlinux -D__linux__") -endif() - -if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) - message("Setting build type to 'Release' as none was specified.") - set(CMAKE_BUILD_TYPE Release CACHE STRING "Choose the type of build." FORCE) - # Set the possible values of build type for cmake-gui - set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Release" - "MinSizeRel" "Release") -endif() - -set(COMMON_COMPILER_OPTIONS - -O2 - -Wall - -fstack-protector-strong - -fstrict-return - -fno-omit-frame-pointer -) - -add_compile_options("$<$:${COMMON_COMPILER_OPTIONS}>") -add_compile_options("$<$:${COMMON_COMPILER_OPTIONS}>") -#set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "../../../../out/${ANDROID_ABI}") - -if(NOT DEFINED ${LZ4_SRC_DIR}) - set(LZ4_SRC_DIR, "../../../external/lz4/lib") -endif() -set(LZ4_INCLUDE_DIR ${LZ4_SRC_DIR}) -set(LZ4_SOURCES - "${LZ4_SRC_DIR}/lz4.c" - ) - -include_directories(${LZ4_INCLUDE_DIR}) - -set(XAMARINCOPY_SOURCES - ${LZ4_SOURCES} - main.cc - ) - -# Add an executable -add_executable(xamarin.sync ${XAMARINCOPY_SOURCES}) -set_target_properties(xamarin.sync PROPERTIES LINK_FLAGS_RELEASE -s) - -#if(NOT APPLE) -# target_link_libraries(xamarin.sync -static) -#endif() - -#target_link_libraries(xamarin.sync "${ZLIB_LIBRARIES}") -#include_directories("${ZLIB_INCLUDE_DIRS}") \ No newline at end of file diff --git a/tools/fastdev/xamarin.sync/main.cc b/tools/fastdev/xamarin.sync/main.cc deleted file mode 100644 index a3f8963dcbd..00000000000 --- a/tools/fastdev/xamarin.sync/main.cc +++ /dev/null @@ -1,212 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -constexpr uint64_t BILLION = 1000000000; - -void printHelp (); -bool closeOutfile (FILE * fp); - -// Streams stdio to a destination for a given number of bytes -// Arguments size destination. -int main(int argc, char **argv) -{ - if (argc < 5) - { - printHelp (); - return 1; - } - - timespec start; - timespec end; - clock_gettime(CLOCK_MONOTONIC, &start); - - unsigned long defaultBuffersize = strtoul (argv[1], nullptr, 10); - if (defaultBuffersize == 0) { - fprintf(stderr, "error: invalid argument '%s'.", argv[1]); - printHelp (); - return 1; - } - unsigned long size = strtoul (argv[2], nullptr, 10); - if (size == 0) { - fprintf(stderr, "error: invalid argument '%s'.", argv[2]); - printHelp (); - return 1; - } - char * outfile = argv[3]; - - errno = 0; - uint64_t modifieddatetime = strtoull (argv[4], nullptr, 10); - if (modifieddatetime == 0 || modifieddatetime == ULLONG_MAX || errno == ERANGE) { - fprintf(stderr, "error: invalid argument '%s'.", argv[4]); - printHelp (); - return 1; - } - - int count = 0; - int inTotal = 0; - unsigned int bufferSize = defaultBuffersize; - unsigned int bufferHeader; - - char *compr = new char[defaultBuffersize]; - char *uncompr = new char[defaultBuffersize]; - - size_t n = 0; - struct pollfd fds[1]; - - int timeout = 1000 * 5; // Timeout in milliseconds (5 seconds) - - //fds[0].fd = fileno (stdin); // Get file descriptor for stdin - //fds[0].events = POLLIN | POLLPRI; // Listen for data available events. - if (access (outfile, F_OK) != -1) { - if (access (outfile, W_OK) == -1) { - if (chmod (outfile, S_IWUSR | S_IRUSR) == -1) { - if (remove (outfile) == -1) { - fprintf (stderr, "error: could not set write permissions on '%s': %s", outfile, strerror (errno)); - return 1; - } - } - } - } - - - FILE * fp = fopen(outfile, "w"); - if (fp == nullptr) { - fprintf(stderr, "error: could not open '%s'.", outfile); - return 1; - } - while (count < size) { - int pr = 1; - fds[0].fd = fileno (stdin); - fds[0].events = POLLIN | POLLPRI | POLLRDNORM | POLLRDBAND | POLLERR; - fds[0].revents = 0; - do { - pr = poll(fds, 1, timeout); - } while (pr == -1 && errno == EINTR); - - // printf ("DEBUG pr= %d\n", pr); - // if (fds[0].revents != 0) { - // printf ("DEBUG Read data ok. data = %d of %d\n", count, size); - // } - if (pr == 0) { - clock_gettime(CLOCK_MONOTONIC, &end); - uint64_t time_taken = BILLION * (end.tv_sec - start.tv_sec) + end.tv_nsec - start.tv_nsec; - fprintf (stderr, "error: Could not read data from stdin. The operation timed out. [%" PRIu64 "] ", time_taken); - if (fclose (fp) != 0) { - fprintf (stderr, "error: failed to read stdin data."); - } - return 1; - } - if (pr == -1) { - clock_gettime(CLOCK_MONOTONIC, &end); - uint64_t time_taken = BILLION * (end.tv_sec - start.tv_sec) + end.tv_nsec - start.tv_nsec; - fprintf (stderr, "error: Could not read data from stdin. An error '%s' occurred. [%" PRIu64 "]", strerror (errno), time_taken); - if (fclose (fp) != 0) { - fprintf (stderr, "error: failed to read stdin data."); - } - return 1; - } - // read length of compressed buffer this is a 4 byte (u_int) value. - n = fread(&bufferHeader, 1, sizeof(bufferHeader), stdin); - switch (n) - { - // We should only ever read 4 bytes of data for the header. - // If we don't that is an error and we should abort. - case 4: { - inTotal += 4; - bufferSize = ntohl (bufferHeader); - if (bufferSize > defaultBuffersize) { - delete [] compr; - delete [] uncompr; - fprintf(stderr, "error: Data length %lu CANNOT be greater than %lu. ", bufferSize, defaultBuffersize); - if (fclose (fp) != 0) { - fprintf(stderr, "error: failed to write '%s' during data length error.", outfile); - } - return 1; - } - n = fread (compr, 1, bufferSize, stdin); - inTotal += n; - int decompressed = 0; - if (n == defaultBuffersize) { - memcpy (uncompr, compr, n); - decompressed = n; - } else { - decompressed = LZ4_decompress_safe (compr, uncompr, n, defaultBuffersize); - } - if (decompressed > 0) { - n = fwrite (uncompr, 1, decompressed, fp); - if (n != decompressed || ferror (fp) != 0) { - delete [] compr; - delete [] uncompr; - fprintf (stderr, "error: Failed to write data to '%s'. %s", outfile, strerror (errno)); - if (fclose (fp) != 0) { - fprintf(stderr, "error: failed to write '%s' during data write failure.", outfile); - } - return 1; - } - count += n; - } - break; - } - default: { - delete [] compr; - delete [] uncompr; - fprintf(stderr, "error: Failed to read package length."); - if (fclose (fp) != 0) { - fprintf(stderr, "error: failed to write '%s' during package length failure.", outfile); - } - return 1; - } - } - } - if (fclose (fp) != 0) { - fprintf(stderr, "error: failed to write '%s'.", outfile); - delete [] compr; - delete [] uncompr; - return 1; - } - timeval modifiedtimes[] { - { - .tv_sec = static_cast (modifieddatetime / 1000), - .tv_usec = static_cast (modifieddatetime % 1000), - }, - - { - .tv_sec = static_cast (modifieddatetime / 1000), - .tv_usec = static_cast (modifieddatetime % 1000), - }, - }; - utimes (outfile, modifiedtimes); - if (chmod (outfile, S_IRUSR) == -1) { - fprintf (stderr, "error: could not set read permissions on '%s'. %s", outfile, strerror (errno)); - return 1; - } - delete [] compr; - delete [] uncompr; - clock_gettime(CLOCK_MONOTONIC, &end); - uint64_t time_taken = BILLION * (end.tv_sec - start.tv_sec) + end.tv_nsec - start.tv_nsec; - printf("wrote [%d] received [%d] time [%" PRIu64 "] modifieddate [%" PRId64 "]\n", count, inTotal, time_taken, modifieddatetime); - return 0; -} - -void printHelp () -{ - printf ("xamarin.sync\n"); - printf ("This tool reads encoded data from stdin and writes that data to disk."); - printf ("The incoming data are blocks of compressed L4Z data."); - printf ("Each block consists of a 4 byte length followed by the compressed data itself."); - printf ("Usage: xamarin.sync \n"); - printf ("\t : Size of the Buffer to use\n"); - printf ("\t : Size in Bytes of Input Stream\n"); - printf ("\t : File to write the data too.\n"); - printf ("\t : The modified date to use for this file in unix time.\n"); -} From 2a91cf80693e9a04d885954a605744b394a17a02 Mon Sep 17 00:00:00 2001 From: Jonathan Peppers Date: Tue, 22 Sep 2026 13:21:37 -0500 Subject: [PATCH 2/6] [tests] Remove legacy FastDeploy helper tests Delete tests for helper APIs that were removed with the legacy FastDeploy implementation. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../DebuggingTasksTests.cs | 64 ------------------- 1 file changed, 64 deletions(-) diff --git a/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/DebuggingTasksTests.cs b/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/DebuggingTasksTests.cs index 28ed72325f5..f42ff75d855 100644 --- a/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/DebuggingTasksTests.cs +++ b/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/DebuggingTasksTests.cs @@ -346,68 +346,4 @@ internal override Task WaitForInstallTransportRecovery () } - /// - /// Unit tests for helper methods that do not require a device. - /// - [TestFixture] - public class FastDeployTests - { - // Canonical transient race output produced by the Android run-as tool when - // the per-user data directory has not yet materialized after pm install. - static readonly string [] TransientRaceOutputs = { - "run-as: couldn't stat /data/user/0/com.example.app: No such file or directory", - "run-as: couldn't stat /data/user/10/com.example.app: No such file or directory", - // Verify case-insensitivity of the detection. - "run-as: Couldn't Stat /data/user/0/com.example.app: No Such File Or Directory", - // Extra surrounding whitespace / newlines as they may appear in raw adb output. - " run-as: couldn't stat /data/user/0/com.example.app: No such file or directory\n", - }; - - // Genuine run-as failures that must NOT be swallowed by the retry loop. - static readonly string [] NonTransientOutputs = { - // Null / empty — first guard in the implementation. - null, - "", - // Successful pwd output — the data directory already exists. - "/data/user/0/com.example.app", - // Package not debuggable. - "run-as: package 'com.example.app' is not debuggable", - // Package not installed. - "run-as: package 'com.example.app' is unknown", - // Permission denied (SELinux / policy). - "run-as: couldn't stat /data/user/0/com.example.app: Permission denied", - // Only one of the two required substrings — must not match. - "run-as: couldn't stat /data/user/0/com.example.app", - "No such file or directory", - }; - - [TestCaseSource (nameof (TransientRaceOutputs))] - public void IsTransientRunAsStatRace_ReturnsTrueForRaceSignature (string output) - { - Assert.IsTrue (FastDeploy.IsTransientRunAsStatRace (output), - $"Expected transient-race detection for: {output}"); - } - - [TestCaseSource (nameof (NonTransientOutputs))] - public void IsTransientRunAsStatRace_ReturnsFalseForNonTransientOutput (string output) - { - Assert.IsFalse (FastDeploy.IsTransientRunAsStatRace (output), - $"Expected no transient-race detection for: {output}"); - } - - [TestCase ("package:/data/app/~~hash/com.example.app-base/base.apk")] - [TestCase ("package:/data/app/~~hash/com.example.app-base/base.apk\npackage:/data/app/~~hash/com.example.app-split/split_config.en.apk")] - public void IsPackageInstalledOutput_ReturnsTrueForPackagePaths (string output) - { - Assert.IsTrue (FastDeploy.IsPackageInstalledOutput (output)); - } - - [TestCase (null)] - [TestCase ("")] - [TestCase ("Error: package com.example.app was not found")] - public void IsPackageInstalledOutput_ReturnsFalseWithoutPackagePath (string output) - { - Assert.IsFalse (FastDeploy.IsPackageInstalledOutput (output)); - } - } } From 49f43dad84315f28d5240e50b48c60642192a6a8 Mon Sep 17 00:00:00 2001 From: Jonathan Peppers Date: Tue, 22 Sep 2026 13:26:00 -0500 Subject: [PATCH 3/6] [tests] Remove stale FastDeploy install tests Delete tests and the helper subclass that referenced install internals removed with the legacy FastDeploy task. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../DebuggingTasksTests.cs | 157 ------------------ 1 file changed, 157 deletions(-) diff --git a/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/DebuggingTasksTests.cs b/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/DebuggingTasksTests.cs index f42ff75d855..026475d82c1 100644 --- a/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/DebuggingTasksTests.cs +++ b/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/DebuggingTasksTests.cs @@ -4,7 +4,6 @@ using System; using System.IO; using System.Linq; -using System.Threading.Tasks; using Xamarin.Android.Build; using Xamarin.Android.Tasks; using Xamarin.ProjectTools; @@ -188,162 +187,6 @@ public void FastDeployClassifiesOnlyKnownTransientInstallFailures (string output Assert.AreEqual (expected, FastDeploy.IsTransientInstallFailure (output)); } - [Test] - public async Task FastDeployRetriesTransientInstallOnce () - { - var task = new TestFastDeploy ( - CreateAdbResult (1, "adb: failed to install app.apk: cmd: Failure calling service package: Broken pipe (32)"), - CreateAdbResult (0, "Success")); - - await task.InstallApkWithRetry ("app.apk", reinstall: false, testOnly: false, user: ""); - - Assert.AreEqual (2, task.InstallAttempts); - Assert.AreEqual (1, task.RecoveryAttempts); - } - - [Test] - public async Task FastDeployRetriesTransientInstallAfterUninstall () - { - var task = new TestFastDeploy ( - CreateAdbResult (1, "Failure [INSTALL_FAILED_ALREADY_EXISTS]"), - CreateAdbResult (1, "adb: failed to install app.apk: cmd: Failure calling service package: Broken pipe (32)"), - CreateAdbResult (0, "Success")); - - await task.InstallApkWithRetry ("app.apk", reinstall: false, testOnly: false, user: ""); - - Assert.AreEqual (3, task.InstallAttempts); - Assert.AreEqual (1, task.UninstallAttempts); - Assert.AreEqual (1, task.RecoveryAttempts); - } - - [Test] - public void FastDeployDoesNotRetryTransientInstallTwiceAcrossUninstall () - { - var task = new TestFastDeploy ( - CreateAdbResult (1, "first failure: cmd: Failure calling service package: Broken pipe (32)"), - CreateAdbResult (1, "Failure [INSTALL_FAILED_ALREADY_EXISTS]"), - CreateAdbResult (1, "third failure: cmd: Failure calling service package: Broken pipe (32)")); - - var exception = Assert.ThrowsAsync ( - async () => await task.InstallApkWithRetry ("app.apk", reinstall: false, testOnly: false, user: "")); - - Assert.IsNotNull (exception); - Assert.AreEqual ("ADB0010", exception.ErrorCode); - Assert.That (exception.Message, Does.Contain ("Install attempt 1")); - Assert.That (exception.Message, Does.Contain ("first failure")); - Assert.That (exception.Message, Does.Contain ("Install attempt 2")); - Assert.That (exception.Message, Does.Contain ("INSTALL_FAILED_ALREADY_EXISTS")); - Assert.That (exception.Message, Does.Contain ("Install attempt 3")); - Assert.That (exception.Message, Does.Contain ("third failure")); - Assert.That (exception.Message, Does.Not.Contain ("Install attempt 4")); - Assert.AreEqual (3, task.InstallAttempts); - Assert.AreEqual (1, task.UninstallAttempts); - Assert.AreEqual (1, task.RecoveryAttempts); - } - - [Test] - public void FastDeployDoesNotRetrySemanticInstallFailure () - { - var task = new TestFastDeploy ( - CreateAdbResult (1, "Failure [INSTALL_FAILED_INSUFFICIENT_STORAGE]")); - - var exception = Assert.ThrowsAsync ( - async () => await task.InstallApkWithRetry ("app.apk", reinstall: false, testOnly: false, user: "")); - - Assert.IsNotNull (exception); - Assert.AreEqual ("ADB0060", exception.ErrorCode); - Assert.AreEqual (1, task.InstallAttempts); - Assert.AreEqual (0, task.RecoveryAttempts); - } - - [Test] - public void FastDeployPreservesBothTransientInstallAttempts () - { - var task = new TestFastDeploy ( - CreateAdbResult (1, "first failure: cmd: Failure calling service package: Broken pipe (32)"), - CreateAdbResult (1, "second failure: cmd: Failure calling service package: Broken pipe (32)")); - - var exception = Assert.ThrowsAsync ( - async () => await task.InstallApkWithRetry ("app.apk", reinstall: false, testOnly: false, user: "")); - - Assert.IsNotNull (exception); - Assert.AreEqual ("ADB0010", exception.ErrorCode); - Assert.That (exception.Message, Does.Contain ("Install attempt 1")); - Assert.That (exception.Message, Does.Contain ("first failure")); - Assert.That (exception.Message, Does.Contain ("ADB transport recovery")); - Assert.That (exception.Message, Does.Contain ("Install attempt 2")); - Assert.That (exception.Message, Does.Contain ("second failure")); - Assert.AreEqual (2, task.InstallAttempts); - Assert.AreEqual (1, task.RecoveryAttempts); - } - - [Test] - public void FastDeployPreservesOriginalFailureWhenRecoveryFails () - { - var task = new TestFastDeploy ( - new InvalidOperationException ("package manager still unavailable"), - CreateAdbResult (1, "cmd: Failure calling service package: Broken pipe (32)")); - - var exception = Assert.ThrowsAsync ( - async () => await task.InstallApkWithRetry ("app.apk", reinstall: false, testOnly: false, user: "")); - - Assert.IsNotNull (exception); - Assert.That (exception.Message, Does.Contain ("Failure calling service package: Broken pipe (32)")); - Assert.That (exception.Message, Does.Contain ("package manager still unavailable")); - Assert.AreEqual (1, task.InstallAttempts); - Assert.AreEqual (1, task.RecoveryAttempts); - } - - static FastDeploy.AdbCommandResult CreateAdbResult (int exitCode, string output) - { - return new FastDeploy.AdbCommandResult { - ExitCode = exitCode, - StandardOutput = output, - StandardError = "", - }; - } - - sealed class TestFastDeploy : FastDeploy - { - readonly Queue results; - readonly Exception recoveryException; - - public int InstallAttempts { get; private set; } - public int UninstallAttempts { get; private set; } - public int RecoveryAttempts { get; private set; } - - public TestFastDeploy (params AdbCommandResult [] results) - : this (recoveryException: null, results) - { - } - - public TestFastDeploy (Exception recoveryException, params AdbCommandResult [] results) - { - this.results = new Queue (results); - this.recoveryException = recoveryException; - BuildEngine = new MockBuildEngine (TestContext.Out); - PackageName = "com.example.app"; - } - - internal override Task RunInstallCommand (string apkFile, bool reinstall, bool testOnly, string user) - { - InstallAttempts++; - return Task.FromResult (results.Dequeue ()); - } - - internal override Task UninstallPackage (string packageName, bool preserveData, string user) - { - UninstallAttempts++; - return Task.CompletedTask; - } - - internal override Task WaitForInstallTransportRecovery () - { - RecoveryAttempts++; - return recoveryException == null ? Task.CompletedTask : Task.FromException (recoveryException); - } - } - } } From b15d2ecf9ea37ac7263404ecec2143b47f7d45ab Mon Sep 17 00:00:00 2001 From: Jonathan Peppers Date: Tue, 22 Sep 2026 13:43:23 -0500 Subject: [PATCH 4/6] [tests] Remove remaining stale FastDeploy tests Delete tests for internal helpers removed with the legacy FastDeploy implementation. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../DebuggingTasksTests.cs | 98 ------------------- 1 file changed, 98 deletions(-) diff --git a/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/DebuggingTasksTests.cs b/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/DebuggingTasksTests.cs index 026475d82c1..eea3f6cdef5 100644 --- a/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/DebuggingTasksTests.cs +++ b/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/DebuggingTasksTests.cs @@ -89,104 +89,6 @@ public void TestResolveToolsExists () CollectionAssert.Contains (secondTaskExecMessages, " Using cached MonoDroidSdk values"); } - [Test] - public void FastDeployParsesWarmStateProbe () - { - var state = FastDeploy.ParseWarmStateProbeOutput ( - """ - __XA_FD_REDIRECT__= - __XA_FD_RUN_AS_DISABLED__= - __XA_FD_REMOTE_HASH__=remote-hash - __XA_FD_PID__=123 456 - __XA_FD_PATH__=/data/user/0/com.example - __XA_FD_OVERRIDE_HASH__=override-hash - __XA_FD_RUN_AS_STATUS__=0 - __XA_FD_FORCE_STOP_STATUS__=0 - """); - - Assert.IsTrue (state.HasRequiredState); - Assert.AreEqual ("remote-hash", state.RemoteHash); - Assert.AreEqual ("override-hash", state.OverrideHash); - Assert.AreEqual ("/data/user/0/com.example", state.InternalPath); - Assert.AreEqual (123, state.ProcessId); - Assert.AreEqual (0, state.RunAsStatus); - Assert.AreEqual (0, state.ForceStopStatus); - } - - [Test] - public void FastDeployRejectsIncompleteWarmStateProbe () - { - var state = FastDeploy.ParseWarmStateProbeOutput ( - """ - __XA_FD_REDIRECT__= - __XA_FD_RUN_AS_DISABLED__=true - run-as: package not debuggable - """); - - Assert.IsFalse (state.HasRequiredState); - Assert.IsTrue (state.HasRunAsDisabled); - Assert.AreEqual ("true", state.RunAsDisabled); - } - - [Test] - public void FastDeployPlansOnlyNewStagingDirectories () - { - var previousFiles = new [] { - "arm64-v8a/App.dll", - "arm64-v8a/en-US/App.resources.dll", - }; - var currentFiles = new [] { - "arm64-v8a/App.dll", - "arm64-v8a/New.dll", - "arm64-v8a/en-US/App.resources.dll", - "arm64-v8a/fr/App.resources.dll", - }; - - HashSet files = FastDeploy.GetFilesRequiringStagingDirectories (currentFiles, previousFiles); - - CollectionAssert.AreEquivalent ( - new [] { "arm64-v8a/fr/App.resources.dll" }, - files); - } - - [Test] - public void FastDeployPlansAllStagingDirectoriesAfterReset () - { - var currentFiles = new [] { - "App.dll", - "arm64-v8a/App.dll", - "arm64-v8a/fr/App.resources.dll", - }; - - HashSet files = FastDeploy.GetFilesRequiringStagingDirectories (currentFiles, previousFiles: null); - - CollectionAssert.AreEquivalent (currentFiles, files); - } - - [TestCase ("adb: error: failed to copy: No such file or directory")] - [TestCase ("adb: error: target '/data/local/tmp/app/arm64-v8a' is not a directory")] - [TestCase ("remote couldn't create file: Is a directory")] - public void FastDeployDetectsInvalidRemoteFilesystem (string output) - { - Assert.IsTrue (FastDeploy.IsUnexpectedRemoteFilesystemError (output)); - } - - [Test] - public void FastDeployDoesNotResetForUnrelatedPushFailure () - { - Assert.IsFalse (FastDeploy.IsUnexpectedRemoteFilesystemError ("adb: error: device offline")); - } - - [TestCase ("adb: error: device offline", false)] - [TestCase ("adb: failed to install app.apk: cmd: Failure calling service package: Broken pipe (32)", true)] - [TestCase ("adb: failed to install app.apk: Broken pipe (32)", false)] - [TestCase ("cmd: Failure calling service package: Security exception", false)] - [TestCase ("Failure [INSTALL_FAILED_INSUFFICIENT_STORAGE]", false)] - public void FastDeployClassifiesOnlyKnownTransientInstallFailures (string output, bool expected) - { - Assert.AreEqual (expected, FastDeploy.IsTransientInstallFailure (output)); - } - } } From 38f923252d7bb4549716d79ba068a24a6275a5fc Mon Sep 17 00:00:00 2001 From: Jonathan Peppers Date: Tue, 22 Sep 2026 16:47:11 -0500 Subject: [PATCH 5/6] [tests] Preserve FastDeploy test coverage Restore tests for the surviving adb-based FastDeploy implementation while leaving legacy-only helper tests removed. Revert changes to the historical release notes. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- Documentation/release-notes/11795.md | 19 +- .../DebuggingTasksTests.cs | 255 ++++++++++++++++++ 2 files changed, 267 insertions(+), 7 deletions(-) diff --git a/Documentation/release-notes/11795.md b/Documentation/release-notes/11795.md index 4bd9e4c2ac4..541197933ad 100644 --- a/Documentation/release-notes/11795.md +++ b/Documentation/release-notes/11795.md @@ -1,19 +1,24 @@ #### Application build and deployment - [GitHub PR #11795](https://github.com/dotnet/android/pull/11795): - Improved the `FastDeploy` app install implementation. Two new MSBuild - properties control it: - - `$(_AndroidFastDeployAppFileTransferMode)`: `Symlink` (default) or `Copy`. + Added a faster `FastDeploy2` fast-deployment strategy, now the default for + app install fast deployment. Three new MSBuild properties control it: + - `$(_AndroidFastDevStrategy)`: `FastDeploy` or `FastDeploy2` (default). + Set to `FastDeploy` to fall back to the legacy strategy. + - `$(_AndroidFastDeployAppFileTransferMode)`: `Symlink` (default for + `FastDeploy2`) or `Copy`. - `$(AndroidFastDeploymentAdbCompressionAlgorithm)`: the `adb push -z` - compression algorithm, `any` by default. `FastDeploy` relies on a modern + compression algorithm, `any` by default. `FastDeploy2` relies on a modern Android SDK Platform-Tools `adb` for multi-file `push -z` support. Warm incremental deployments combine compatibility checks, package/marker inspection, process detection, and app termination into one live `adb shell` probe. They also skip redundant staging-directory creation and update both - success markers in one command. If an incremental upload discovers that - expected remote staging paths are missing or have the wrong type, FastDeploy + success markers in one command. Switching between `FastDeploy2` and legacy + `FastDeploy` now clears incompatible override state without uninstalling the + app or deleting unrelated app data. If an incremental upload discovers that + expected remote staging paths are missing or have the wrong type, FastDeploy2 retries once with a fresh staging and override deployment. - See the [FastDeploy guide](../guides/FastDeploy.md) for a detailed + See the [FastDeploy2 guide](../guides/FastDeploy2.md) for a detailed description of the deployment stages and the `adb` commands they run. diff --git a/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/DebuggingTasksTests.cs b/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/DebuggingTasksTests.cs index eea3f6cdef5..f42ff75d855 100644 --- a/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/DebuggingTasksTests.cs +++ b/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/DebuggingTasksTests.cs @@ -4,6 +4,7 @@ using System; using System.IO; using System.Linq; +using System.Threading.Tasks; using Xamarin.Android.Build; using Xamarin.Android.Tasks; using Xamarin.ProjectTools; @@ -89,6 +90,260 @@ public void TestResolveToolsExists () CollectionAssert.Contains (secondTaskExecMessages, " Using cached MonoDroidSdk values"); } + [Test] + public void FastDeployParsesWarmStateProbe () + { + var state = FastDeploy.ParseWarmStateProbeOutput ( + """ + __XA_FD_REDIRECT__= + __XA_FD_RUN_AS_DISABLED__= + __XA_FD_REMOTE_HASH__=remote-hash + __XA_FD_PID__=123 456 + __XA_FD_PATH__=/data/user/0/com.example + __XA_FD_OVERRIDE_HASH__=override-hash + __XA_FD_RUN_AS_STATUS__=0 + __XA_FD_FORCE_STOP_STATUS__=0 + """); + + Assert.IsTrue (state.HasRequiredState); + Assert.AreEqual ("remote-hash", state.RemoteHash); + Assert.AreEqual ("override-hash", state.OverrideHash); + Assert.AreEqual ("/data/user/0/com.example", state.InternalPath); + Assert.AreEqual (123, state.ProcessId); + Assert.AreEqual (0, state.RunAsStatus); + Assert.AreEqual (0, state.ForceStopStatus); + } + + [Test] + public void FastDeployRejectsIncompleteWarmStateProbe () + { + var state = FastDeploy.ParseWarmStateProbeOutput ( + """ + __XA_FD_REDIRECT__= + __XA_FD_RUN_AS_DISABLED__=true + run-as: package not debuggable + """); + + Assert.IsFalse (state.HasRequiredState); + Assert.IsTrue (state.HasRunAsDisabled); + Assert.AreEqual ("true", state.RunAsDisabled); + } + + [Test] + public void FastDeployPlansOnlyNewStagingDirectories () + { + var previousFiles = new [] { + "arm64-v8a/App.dll", + "arm64-v8a/en-US/App.resources.dll", + }; + var currentFiles = new [] { + "arm64-v8a/App.dll", + "arm64-v8a/New.dll", + "arm64-v8a/en-US/App.resources.dll", + "arm64-v8a/fr/App.resources.dll", + }; + + HashSet files = FastDeploy.GetFilesRequiringStagingDirectories (currentFiles, previousFiles); + + CollectionAssert.AreEquivalent ( + new [] { "arm64-v8a/fr/App.resources.dll" }, + files); + } + + [Test] + public void FastDeployPlansAllStagingDirectoriesAfterReset () + { + var currentFiles = new [] { + "App.dll", + "arm64-v8a/App.dll", + "arm64-v8a/fr/App.resources.dll", + }; + + HashSet files = FastDeploy.GetFilesRequiringStagingDirectories (currentFiles, previousFiles: null); + + CollectionAssert.AreEquivalent (currentFiles, files); + } + + [TestCase ("adb: error: failed to copy: No such file or directory")] + [TestCase ("adb: error: target '/data/local/tmp/app/arm64-v8a' is not a directory")] + [TestCase ("remote couldn't create file: Is a directory")] + public void FastDeployDetectsInvalidRemoteFilesystem (string output) + { + Assert.IsTrue (FastDeploy.IsUnexpectedRemoteFilesystemError (output)); + } + + [Test] + public void FastDeployDoesNotResetForUnrelatedPushFailure () + { + Assert.IsFalse (FastDeploy.IsUnexpectedRemoteFilesystemError ("adb: error: device offline")); + } + + [TestCase ("adb: error: device offline", false)] + [TestCase ("adb: failed to install app.apk: cmd: Failure calling service package: Broken pipe (32)", true)] + [TestCase ("adb: failed to install app.apk: Broken pipe (32)", false)] + [TestCase ("cmd: Failure calling service package: Security exception", false)] + [TestCase ("Failure [INSTALL_FAILED_INSUFFICIENT_STORAGE]", false)] + public void FastDeployClassifiesOnlyKnownTransientInstallFailures (string output, bool expected) + { + Assert.AreEqual (expected, FastDeploy.IsTransientInstallFailure (output)); + } + + [Test] + public async Task FastDeployRetriesTransientInstallOnce () + { + var task = new TestFastDeploy ( + CreateAdbResult (1, "adb: failed to install app.apk: cmd: Failure calling service package: Broken pipe (32)"), + CreateAdbResult (0, "Success")); + + await task.InstallApkWithRetry ("app.apk", reinstall: false, testOnly: false, user: ""); + + Assert.AreEqual (2, task.InstallAttempts); + Assert.AreEqual (1, task.RecoveryAttempts); + } + + [Test] + public async Task FastDeployRetriesTransientInstallAfterUninstall () + { + var task = new TestFastDeploy ( + CreateAdbResult (1, "Failure [INSTALL_FAILED_ALREADY_EXISTS]"), + CreateAdbResult (1, "adb: failed to install app.apk: cmd: Failure calling service package: Broken pipe (32)"), + CreateAdbResult (0, "Success")); + + await task.InstallApkWithRetry ("app.apk", reinstall: false, testOnly: false, user: ""); + + Assert.AreEqual (3, task.InstallAttempts); + Assert.AreEqual (1, task.UninstallAttempts); + Assert.AreEqual (1, task.RecoveryAttempts); + } + + [Test] + public void FastDeployDoesNotRetryTransientInstallTwiceAcrossUninstall () + { + var task = new TestFastDeploy ( + CreateAdbResult (1, "first failure: cmd: Failure calling service package: Broken pipe (32)"), + CreateAdbResult (1, "Failure [INSTALL_FAILED_ALREADY_EXISTS]"), + CreateAdbResult (1, "third failure: cmd: Failure calling service package: Broken pipe (32)")); + + var exception = Assert.ThrowsAsync ( + async () => await task.InstallApkWithRetry ("app.apk", reinstall: false, testOnly: false, user: "")); + + Assert.IsNotNull (exception); + Assert.AreEqual ("ADB0010", exception.ErrorCode); + Assert.That (exception.Message, Does.Contain ("Install attempt 1")); + Assert.That (exception.Message, Does.Contain ("first failure")); + Assert.That (exception.Message, Does.Contain ("Install attempt 2")); + Assert.That (exception.Message, Does.Contain ("INSTALL_FAILED_ALREADY_EXISTS")); + Assert.That (exception.Message, Does.Contain ("Install attempt 3")); + Assert.That (exception.Message, Does.Contain ("third failure")); + Assert.That (exception.Message, Does.Not.Contain ("Install attempt 4")); + Assert.AreEqual (3, task.InstallAttempts); + Assert.AreEqual (1, task.UninstallAttempts); + Assert.AreEqual (1, task.RecoveryAttempts); + } + + [Test] + public void FastDeployDoesNotRetrySemanticInstallFailure () + { + var task = new TestFastDeploy ( + CreateAdbResult (1, "Failure [INSTALL_FAILED_INSUFFICIENT_STORAGE]")); + + var exception = Assert.ThrowsAsync ( + async () => await task.InstallApkWithRetry ("app.apk", reinstall: false, testOnly: false, user: "")); + + Assert.IsNotNull (exception); + Assert.AreEqual ("ADB0060", exception.ErrorCode); + Assert.AreEqual (1, task.InstallAttempts); + Assert.AreEqual (0, task.RecoveryAttempts); + } + + [Test] + public void FastDeployPreservesBothTransientInstallAttempts () + { + var task = new TestFastDeploy ( + CreateAdbResult (1, "first failure: cmd: Failure calling service package: Broken pipe (32)"), + CreateAdbResult (1, "second failure: cmd: Failure calling service package: Broken pipe (32)")); + + var exception = Assert.ThrowsAsync ( + async () => await task.InstallApkWithRetry ("app.apk", reinstall: false, testOnly: false, user: "")); + + Assert.IsNotNull (exception); + Assert.AreEqual ("ADB0010", exception.ErrorCode); + Assert.That (exception.Message, Does.Contain ("Install attempt 1")); + Assert.That (exception.Message, Does.Contain ("first failure")); + Assert.That (exception.Message, Does.Contain ("ADB transport recovery")); + Assert.That (exception.Message, Does.Contain ("Install attempt 2")); + Assert.That (exception.Message, Does.Contain ("second failure")); + Assert.AreEqual (2, task.InstallAttempts); + Assert.AreEqual (1, task.RecoveryAttempts); + } + + [Test] + public void FastDeployPreservesOriginalFailureWhenRecoveryFails () + { + var task = new TestFastDeploy ( + new InvalidOperationException ("package manager still unavailable"), + CreateAdbResult (1, "cmd: Failure calling service package: Broken pipe (32)")); + + var exception = Assert.ThrowsAsync ( + async () => await task.InstallApkWithRetry ("app.apk", reinstall: false, testOnly: false, user: "")); + + Assert.IsNotNull (exception); + Assert.That (exception.Message, Does.Contain ("Failure calling service package: Broken pipe (32)")); + Assert.That (exception.Message, Does.Contain ("package manager still unavailable")); + Assert.AreEqual (1, task.InstallAttempts); + Assert.AreEqual (1, task.RecoveryAttempts); + } + + static FastDeploy.AdbCommandResult CreateAdbResult (int exitCode, string output) + { + return new FastDeploy.AdbCommandResult { + ExitCode = exitCode, + StandardOutput = output, + StandardError = "", + }; + } + + sealed class TestFastDeploy : FastDeploy + { + readonly Queue results; + readonly Exception recoveryException; + + public int InstallAttempts { get; private set; } + public int UninstallAttempts { get; private set; } + public int RecoveryAttempts { get; private set; } + + public TestFastDeploy (params AdbCommandResult [] results) + : this (recoveryException: null, results) + { + } + + public TestFastDeploy (Exception recoveryException, params AdbCommandResult [] results) + { + this.results = new Queue (results); + this.recoveryException = recoveryException; + BuildEngine = new MockBuildEngine (TestContext.Out); + PackageName = "com.example.app"; + } + + internal override Task RunInstallCommand (string apkFile, bool reinstall, bool testOnly, string user) + { + InstallAttempts++; + return Task.FromResult (results.Dequeue ()); + } + + internal override Task UninstallPackage (string packageName, bool preserveData, string user) + { + UninstallAttempts++; + return Task.CompletedTask; + } + + internal override Task WaitForInstallTransportRecovery () + { + RecoveryAttempts++; + return recoveryException == null ? Task.CompletedTask : Task.FromException (recoveryException); + } + } + } } From f230c37489bd7a70a0e397dc7c18029a7b04269a Mon Sep 17 00:00:00 2001 From: Jonathan Peppers Date: Tue, 22 Sep 2026 17:06:54 -0500 Subject: [PATCH 6/6] [tests] Build debugging tasks for FastDeploy tests Reference Xamarin.Android.Build.Debugging.Tasks as a project so clean descendant builds compile FastDeploy tests against the changed task assembly instead of a stale prebuilt DLL. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../Xamarin.Android.Build.Tests.csproj | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/Xamarin.Android.Build.Tests.csproj b/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/Xamarin.Android.Build.Tests.csproj index 7989975de14..90c9d88a106 100644 --- a/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/Xamarin.Android.Build.Tests.csproj +++ b/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/Xamarin.Android.Build.Tests.csproj @@ -20,21 +20,18 @@ - - $(MicrosoftAndroidSdkOutDir)Xamarin.Android.Build.Debugging.Tasks.dll - + -