Skip to content

armgit / rea

Public Imported from GitHub
0

Reverse engineer anything with agents, from app behavior down to native binaries.

fix(adb): preserve push target semantics

morluto50241b368bec
diff --git a/docs/adb-device-analysis.md b/docs/adb-device-analysis.md
index 56514bc62..f9f74c0d3 100644
--- a/docs/adb-device-analysis.md
+++ b/docs/adb-device-analysis.md
@@ -103,6 +103,11 @@ existing analysis families directly, for example
| `start_adb_activity` | **mutates device** | Starts an intent (`am start -a` with optional URI, component, and up to 16 typed extras); preserves the activity manager's verdict |
| `stop_adb_app` | **mutates device** | Force-stops every process of a package, ending a dynamic-analysis run |
+When `push_adb_file` receives an existing directory, adb places the local file
+inside it under the local basename; Evidence reports that effective file path
+while retaining the caller's directory path in the input parameters. The
+private read-only staging copy preserves the source file's executable bits.
+
For `inspect_adb_window`, `focus_contexts` retains each display header, its exact
display ID when recognized, and every focus declaration with its original line.
Declarations without a display header are explicitly `unscoped`. A missing
diff --git a/src/adb/AdbCommand.ts b/src/adb/AdbCommand.ts
index f3988ba97..1b5e1ca51 100644
--- a/src/adb/AdbCommand.ts
+++ b/src/adb/AdbCommand.ts
@@ -291,11 +291,36 @@ export const probeAdbPathExistence = async (
limits: AdbRunLimits,
signal: AbortSignal | undefined,
): Promise<Result<boolean, AnalysisError>> => {
+ return probeAdbPath(operation, serial, path, binary, limits, signal, "-e");
+};
+
+/** Only the clean true/false result of test -d establishes directory status. */
+export const probeAdbPathDirectory = async (
+ operation: string,
+ serial: string,
+ path: string,
+ binary: string,
+ limits: AdbRunLimits,
+ signal: AbortSignal | undefined,
+): Promise<Result<boolean, AnalysisError>> =>
+ probeAdbPath(operation, serial, path, binary, limits, signal, "-d");
+
+const probeAdbPath = async (
+ operation: string,
+ serial: string,
+ path: string,
+ binary: string,
+ limits: AdbRunLimits,
+ signal: AbortSignal | undefined,
+ predicate: "-d" | "-e",
+): Promise<Result<boolean, AnalysisError>> => {
+ const fact =
+ predicate === "-d" ? "destination_directory" : "destination_existence";
const probed = await runAdbCapture(
operation,
{ device: serial, path },
binary,
- adbArguments(serial, ["shell", "test", "-e", path]),
+ adbArguments(serial, ["shell", "test", predicate, path]),
{ ...limits, volatileOutput: true },
signal,
);
@@ -304,9 +329,9 @@ export const probeAdbPathExistence = async (
return ok(true);
return err(
new AnalysisProtocolError(
- "The ADB path existence probe returned unexpected output; destination existence is unknown",
+ `The ADB path ${predicate === "-d" ? "directory" : "existence"} probe returned unexpected output; destination status is unknown`,
{
- diagnostics: { destination_existence: "unknown" },
+ diagnostics: { [fact]: "unknown" },
capturedOutput: {
stdout: probed.value.stdout.toString("utf8"),
stderr: probed.value.stderr.toString("utf8"),
@@ -336,7 +361,7 @@ export const probeAdbPathExistence = async (
return err(
new AnalysisProtocolError(error.message, {
cause: error.cause,
- diagnostics: { destination_existence: "unknown" },
+ diagnostics: { [fact]: "unknown" },
capturedOutput: adbCommandCapturedOutput(failure),
}),
);
diff --git a/src/adb/AdbInputSnapshot.ts b/src/adb/AdbInputSnapshot.ts
index 357174a95..bc547f250 100644
--- a/src/adb/AdbInputSnapshot.ts
+++ b/src/adb/AdbInputSnapshot.ts
@@ -131,7 +131,9 @@ export const snapshotAdbInput = async (
"the file changed while its private snapshot was copied",
);
await destination.handle.sync();
- await destination.handle.chmod(0o400);
+ // Keep the private snapshot non-writable while preserving executable intent
+ // for adb push (which transmits the staged file's mode).
+ await destination.handle.chmod(0o400 | (initial.mode & 0o111));
snapshot = {
path: destinationPath,
bytes: position,
diff --git a/src/adb/AdbProvider.test.ts b/src/adb/AdbProvider.test.ts
index 5567fe869..814b269b6 100644
--- a/src/adb/AdbProvider.test.ts
+++ b/src/adb/AdbProvider.test.ts
@@ -1186,6 +1186,65 @@ exit 1`,
});
});
+it("preserves executable bits on the private snapshot consumed by adb push", async () => {
+ const { binary, root } = await writeAdbStub(
+ (stubRoot) => `if [ "$1" = "version" ]; then ${VERSION_BLOCK}; exit 0; fi
+if [ "$1" = "-s" ] && [ "$4" = "test" ]; then exit 1; fi
+if [ "$1" = "-s" ] && [ "$3" = "push" ]; then ls -ld "$4" | cut -c1-10 > "${join(stubRoot, "staged-mode")}"; exit 0; fi
+if [ "$1" = "-s" ] && [ "$4" = "sha256sum" ]; then exit 1; fi
+exit 1`,
+ );
+ const localFile = join(root, "executable");
+ await writeFile(localFile, "#!/bin/sh\nexit 0\n", { mode: 0o755 });
+ await chmod(localFile, 0o755);
+ const result = await providerOver(binary).execute({
+ operation: "push_adb_file",
+ input: {
+ serial: "emulator-5554",
+ local_path: localFile,
+ device_path: "/data/local/tmp/executable",
+ overwrite: false,
+ },
+ });
+ expect(result.ok).toBe(true);
+ expect(await readFile(join(root, "staged-mode"), "utf8")).toBe(
+ "-r-x--x--x\n",
+ );
+});
+
+it("reports and verifies the effective file path when adb targets a directory", async () => {
+ const { binary, root } = await writeAdbStub(
+ (stubRoot) => `if [ "$1" = "version" ]; then ${VERSION_BLOCK}; exit 0; fi
+if [ "$1" = "-s" ] && [ "$4" = "test" ]; then
+ if [ "$5" = "-d" ] && [ "$6" = "/data/local/tmp/drop/" ]; then exit 0; fi
+ if [ "$5" = "-e" ] && [ "$6" = "/data/local/tmp/drop/payload.bin" ]; then exit 1; fi
+fi
+if [ "$1" = "-s" ] && [ "$3" = "push" ]; then printf '%s' "$5" > "${join(stubRoot, "pushed-destination")}"; exit 0; fi
+if [ "$1" = "-s" ] && [ "$4" = "sha256sum" ]; then printf '%s %s\\n' '${PUSHED_DIGEST}' "$5"; exit 0; fi
+exit 1`,
+ );
+ const localFile = join(root, "payload.bin");
+ await writeFile(localFile, "push-payload");
+ const result = await providerOver(binary).execute({
+ operation: "push_adb_file",
+ input: {
+ serial: "emulator-5554",
+ local_path: localFile,
+ device_path: "/data/local/tmp/drop/",
+ overwrite: false,
+ },
+ });
+ if (!result.ok) throw new Error(result.error.message);
+ expect(await readFile(join(root, "pushed-destination"), "utf8")).toBe(
+ "/data/local/tmp/drop/",
+ );
+ expect(result.value.result).toMatchObject({
+ device_path: "/data/local/tmp/drop/payload.bin",
+ overwritten: false,
+ device_sha256: PUSHED_DIGEST,
+ });
+});
+
it("retains failed snapshot cleanup with completed push Evidence until close retries", async () => {
const { binary, root } = await writeAdbStub(
() => `if [ "$1" = "version" ]; then ${VERSION_BLOCK}; exit 0; fi
diff --git a/src/adb/AdbProvider.ts b/src/adb/AdbProvider.ts
index 30b2ebc68..7db817976 100644
--- a/src/adb/AdbProvider.ts
+++ b/src/adb/AdbProvider.ts
@@ -83,6 +83,7 @@ import {
runAdb,
runAdbCapture,
packageChangeRefusal,
+ probeAdbPathDirectory,
probeAdbPathExistence,
type AdbRunLimits,
} from "./AdbCommand.js";
@@ -2424,7 +2425,7 @@ export class AdbProvider {
operation,
signal,
);
- const existsProbe = await probeAdbPathExistence(
+ const directoryProbe = await probeAdbPathDirectory(
operation,
input.serial,
input.device_path,
@@ -2432,13 +2433,25 @@ export class AdbProvider {
{ timeoutMs: SETTINGS_TIMEOUT_MS, maxOutputBytes: 1024 },
signal,
);
+ if (!directoryProbe.ok) return directoryProbe;
+ const devicePath = directoryProbe.value
+ ? `${input.device_path}${input.device_path.endsWith("/") ? "" : "/"}${basename(localPath)}`
+ : input.device_path;
+ const existsProbe = await probeAdbPathExistence(
+ operation,
+ input.serial,
+ devicePath,
+ selection.binary,
+ { timeoutMs: SETTINGS_TIMEOUT_MS, maxOutputBytes: 1024 },
+ signal,
+ );
if (!existsProbe.ok) return existsProbe;
const deviceExists = existsProbe.value;
if (deviceExists && !input.overwrite)
return err(
new AnalysisOutputError(
operation,
- `The device path already exists and overwrite was not requested: ${input.device_path}`,
+ `The device path already exists and overwrite was not requested: ${devicePath}`,
),
);
const pushed = await runAdb(
@@ -2468,7 +2481,7 @@ export class AdbProvider {
client,
serial: input.serial,
local_path: localPath,
- device_path: input.device_path,
+ device_path: devicePath,
bytes: digest.bytes,
sha256: digest.sha256,
device_sha256: deviceDigest.device_sha256,
@@ -2488,9 +2501,9 @@ export class AdbProvider {
);
const deviceDigest = await runAdb(
operation,
- { device: input.serial, path: input.device_path },
+ { device: input.serial, path: devicePath },
selection.binary,
- adbArguments(input.serial, ["shell", "sha256sum", input.device_path]),
+ adbArguments(input.serial, ["shell", "sha256sum", devicePath]),
{ timeoutMs: SHELL_TIMEOUT_MS, maxOutputBytes: 1024 },
signal,
);
@@ -2547,7 +2560,7 @@ export class AdbProvider {
return err(
new AnalysisArtifactChangedError(
operation,
- input.device_path,
+ devicePath,
`The device-reported digest does not match the staged local file: ${localPath}`,
{
partialObservation: createEvidence(
diff --git a/src/contracts/adb/adbToolContracts.ts b/src/contracts/adb/adbToolContracts.ts
index e84f34a1e..4d1245c99 100644
--- a/src/contracts/adb/adbToolContracts.ts
+++ b/src/contracts/adb/adbToolContracts.ts
@@ -127,7 +127,7 @@ export const ADB_TOOL_CONTRACTS = [
name: "push_adb_file",
...toolContractMetadata("push_adb_file"),
description:
- "Push one local file to an absolute device path. A device-mutating tool: checks for an existing device file before transfer and refuses it unless overwrite is explicitly requested; this check is not an atomic create and another process can create the path before adb writes. When the device provides sha256sum, the transfer is verified by comparing it with the local digest.",
+ "Push one local file to an absolute device path. If the destination is an existing directory, adb places the file inside it under the local basename and the result reports that file path. A device-mutating tool: checks for an existing destination file before transfer and refuses it unless overwrite is explicitly requested; this check is not atomic and another process can create the path before adb writes. The private staged copy remains non-writable and preserves source executable bits. When the device provides sha256sum, the transfer is verified by comparing it with the local digest.",
kind: "adb-provider",
inputSchema: adbInputSchemas.push_adb_file,
outputSchema: evidenceResultOf(adbResultSchemas.push_adb_file),
diff --git a/tests/boundary/cli/adbCli.test.ts b/tests/boundary/cli/adbCli.test.ts
index dfb947d63..cd76936cf 100644
--- a/tests/boundary/cli/adbCli.test.ts
+++ b/tests/boundary/cli/adbCli.test.ts
@@ -83,6 +83,51 @@ exit 1
expect(await readFile(workspace.path("calls"), "utf8")).toBe("\nshell\n");
});
+it.skipIf(process.platform === "win32")(
+ "reports the file placed inside a push destination directory and preserves executable staging",
+ async () => {
+ const workspace = await createTestWorkspace("rea-adb-directory-push-cli-");
+ onTestFinished(() => removeTestWorkspace(workspace.root));
+ const source = await workspace.write("payload.bin", "#!/bin/sh\n");
+ await chmod(source, 0o755);
+ const digest = createHash("sha256").update("#!/bin/sh\n").digest("hex");
+ const adb = await workspace.write(
+ "adb",
+ `#!/bin/sh
+root=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
+if [ "$1" = version ]; then printf 'Android Debug Bridge version 1.0.41\\nVersion 34.0.5-cli\\n'; exit 0; fi
+if [ "$1" = -s ] && [ "$3" = shell ] && [ "$4" = test ]; then
+ if [ "$5" = -d ] && [ "$6" = /data/local/tmp/drop/ ]; then exit 0; fi
+ if [ "$5" = -e ]; then exit 1; fi
+fi
+if [ "$1" = -s ] && [ "$3" = push ]; then ls -ld "$4" | cut -c1-10 > "$root/staged-mode"; printf '%s' "$5" > "$root/push-target"; exit 0; fi
+if [ "$1" = -s ] && [ "$4" = sha256sum ]; then printf '%s %s\\n' '${digest}' "$5"; exit 0; fi
+exit 1
+`,
+ );
+ await chmod(adb, 0o755);
+ const output = await serve(
+ ["push-adb-file", "device", source, "/data/local/tmp/drop/", "--json"],
+ { REA_ADB_PATH: adb },
+ );
+ expect(output.exitCode).toBe(0);
+ const evidence = JSON.parse(output.stdout) as {
+ parameters: { device_path: string };
+ normalized_result: { device_path: string };
+ };
+ expect(evidence.parameters.device_path).toBe("/data/local/tmp/drop/");
+ expect(evidence.normalized_result.device_path).toBe(
+ "/data/local/tmp/drop/payload.bin",
+ );
+ expect(await readFile(workspace.path("staged-mode"), "utf8")).toBe(
+ "-r-x--x--x\n",
+ );
+ expect(await readFile(workspace.path("push-target"), "utf8")).toBe(
+ "/data/local/tmp/drop/",
+ );
+ },
+);
+
it.each([
[
["inspect-adb-client", "--json"],
diff --git a/tests/boundary/mcp/adbStartMcp.test.ts b/tests/boundary/mcp/adbStartMcp.test.ts
index a6a853063..8c4665c66 100644
--- a/tests/boundary/mcp/adbStartMcp.test.ts
+++ b/tests/boundary/mcp/adbStartMcp.test.ts
@@ -1,5 +1,6 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { Ajv2020 } from "ajv/dist/2020.js";
+import { createHash } from "node:crypto";
import { chmod, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect, it, onTestFinished } from "vitest";
@@ -12,6 +13,77 @@ import { createServer } from "../../../src/server/createServer.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
+it.skipIf(process.platform === "win32")(
+ "preserves caller destination and reports the effective pushed file path through MCP",
+ async () => {
+ const directory = await createTestTempDirectory("rea-adb-push-mcp-");
+ const localPath = join(directory, "payload.bin");
+ const adbPath = join(directory, "adb");
+ const stagedMode = join(directory, "staged-mode");
+ const destination = "/data/local/tmp/drop/";
+ const effectivePath = `${destination}payload.bin`;
+ const digest = createHash("sha256").update("push-payload").digest("hex");
+ await writeFile(localPath, "push-payload", { mode: 0o755 });
+ await chmod(localPath, 0o755);
+ await writeFile(
+ adbPath,
+ `#!/usr/bin/env node
+const fs = require("node:fs");
+const args = process.argv.slice(2);
+if (args[0] === "version") { process.stdout.write("Android Debug Bridge version 1.0.41\\nVersion 34.0.5-stub\\n"); }
+else if (args[0] === "-s" && args[2] === "shell" && args[3] === "test") {
+ if (args[4] === "-d" && args[5] === ${JSON.stringify(destination)}) process.exitCode = 0;
+ else process.exitCode = 1;
+} else if (args[0] === "-s" && args[2] === "push") {
+ fs.writeFileSync(${JSON.stringify(stagedMode)}, (fs.statSync(args[3]).mode & 0o7777).toString(8) + "\\n");
+} else if (args[0] === "-s" && args[2] === "shell" && args[3] === "sha256sum") {
+ process.stdout.write(${JSON.stringify(`${digest} ${effectivePath}\n`)});
+}
+`,
+ );
+ await chmod(adbPath, 0o755);
+ const server = createServer(
+ {
+ kind: "session",
+ session: createTestBinarySession(() => {
+ throw new Error("ADB push must not open a deep-analysis provider");
+ }),
+ },
+ {
+ adbDeviceAnalysis: new AdbProvider({
+ environment: { REA_ADB_PATH: adbPath },
+ }),
+ },
+ );
+ onTestFinished(() => server.close());
+ const [clientTransport, serverTransport] =
+ InMemoryTransport.createLinkedPair();
+ await server.connect(serverTransport);
+ const client = new Client({ name: "adb-push-boundary", version: "0.0.0" });
+ onTestFinished(() => client.close());
+ await client.connect(clientTransport);
+ const response = await client.callTool({
+ name: "push_adb_file",
+ arguments: {
+ serial: "emulator-5554",
+ local_path: localPath,
+ device_path: destination,
+ },
+ });
+ expect(response.isError).not.toBe(true);
+ const evidence = toolContract("push_adb_file").outputSchema.parse(
+ parseEvidence(JSON.parse(responseText(response))),
+ );
+ expect(evidence.parameters).toMatchObject({ device_path: destination });
+ expect(evidence.normalized_result).toMatchObject({
+ device_path: effectivePath,
+ overwritten: false,
+ device_sha256: digest,
+ });
+ expect(await readFile(stagedMode, "utf8")).toBe("511\n");
+ },
+);
+
const responseText = (response: { readonly content: readonly unknown[] }) =>
response.content
.flatMap((part) =>