Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.ko.md
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,7 @@ export ANDROID_NDK_HOME="$ANDROID_HOME/ndk/29.0.14206865"
- [Debian rootfs 설치 과정](docs/rootfs-installation.ko.md)
- [Debian systemd와 SSH](docs/debian-systemd.ko.md)
- [하드웨어 코덱 worker 프로토콜](docs/hardware-codec-protocol.ko.md)
- [네이티브 출력 스키마](docs/native-output-schema.ko.md)
- [하드웨어 코덱 구현 결정 기록](docs/media-codec-bridge-plan.ko.md)
- [빌드와 배포](docs/building.ko.md)
- [내장 부트스트랩 런타임](bfu-runtime/README.ko.md)
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,7 @@ key is not a production signing identity.
- [Debian rootfs installation](docs/rootfs-installation.md)
- [Debian systemd and SSH](docs/debian-systemd.md)
- [Hardware codec worker protocol](docs/hardware-codec-protocol.md)
- [Native output schema](docs/native-output-schema.md)
- [Hardware codec implementation decision record](docs/media-codec-bridge-plan.md)
- [Build and release](docs/building.md)
- [Embedded bootstrap runtime](bfu-runtime/README.md)
Expand Down
1 change: 1 addition & 0 deletions app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,7 @@ dependencies {
implementation(libs.androidx.lifecycle.runtime.compose)
implementation(libs.androidx.navigation3.ui)
implementation(libs.kotlinx.serialization.core)
implementation(libs.kotlinx.serialization.json)
debugImplementation(libs.androidx.compose.ui.tooling)

testImplementation("junit:junit:4.13.2")
Expand Down
Binary file modified app/src/main/assets/bfu/bin/arm64-v8a/bfu-namespace-probe
Binary file not shown.
Binary file modified app/src/main/assets/bfu/bin/armeabi-v7a/bfu-namespace-probe
Binary file not shown.
Binary file modified app/src/main/assets/bfu/bin/x86_64/bfu-namespace-probe
Binary file not shown.
361 changes: 198 additions & 163 deletions app/src/main/cpp/bfu_namespace_probe.c

Large diffs are not rendered by default.

183 changes: 183 additions & 0 deletions app/src/main/cpp/dawnshell_json.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,183 @@
#ifndef DAWNSHELL_JSON_H
#define DAWNSHELL_JSON_H

/*
* Single-line JSON event writer for DawnShell's native helpers (JSON Lines,
* schema docs/native-output-schema.md). Write-only: no parser, no allocation.
* Every line starts with {"v":1,"ts":<epoch>,"event":"<name>"} and is always
* valid JSON. A field that does not fit is dropped and "truncated":true is set.
*/

#include <stdbool.h>
#include <stddef.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

#define DS_JSON_SCHEMA_VERSION 1
#define DS_JSON_RESERVE 40

/* Kept out of line: inlining the writer at every call site costs ~16 KiB per ABI. */
#define DS_JSON_OUTLINE static __attribute__((noinline, unused))

#ifndef DS_JSON_NOW
#define DS_JSON_NOW() ((long long) time(NULL))
#endif

typedef struct {
char *buf;
size_t cap;
size_t len;
int depth;
bool first;
bool overflow;
} DsJson;

DS_JSON_OUTLINE void ds_json_put(DsJson *j, const char *text, size_t length) {
if (j->overflow || j->len + length + DS_JSON_RESERVE > j->cap) {
j->overflow = true;
return;
}
memcpy(j->buf + j->len, text, length);
j->len += length;
}

static inline void ds_json_putc(DsJson *j, char c) {
ds_json_put(j, &c, 1);
}

static inline size_t ds_json_utf8_length(const unsigned char *s, size_t remaining) {
size_t need = s[0] >= 0xf0 ? 4 : s[0] >= 0xe0 ? 3 : s[0] >= 0xc2 ? 2 : 0;
if (need == 0 || need > remaining || s[0] > 0xf4) return 0;
unsigned code = s[0] & (0xffu >> (need + 1));
for (size_t i = 1; i < need; i++) {
if ((s[i] & 0xc0) != 0x80) return 0;
code = (code << 6) | (s[i] & 0x3fu);
}
static const unsigned minimum[5] = {0, 0, 0x80, 0x800, 0x10000};
if (code < minimum[need] || code > 0x10ffff || (code >= 0xd800 && code <= 0xdfff)) return 0;
return need;
}

DS_JSON_OUTLINE void ds_json_quoted(DsJson *j, const char *value) {
static const char hex[] = "0123456789abcdef";
ds_json_putc(j, '"');
const unsigned char *s = (const unsigned char *) (value != NULL ? value : "");
for (size_t i = 0; s[i] != '\0' && !j->overflow;) {
unsigned char c = s[i];
if (c == '"' || c == '\\') {
const char pair[2] = {'\\', (char) c};
ds_json_put(j, pair, 2);
} else if (c == '\n' || c == '\r' || c == '\t') {
const char pair[2] = {'\\', c == '\n' ? 'n' : c == '\r' ? 'r' : 't'};
ds_json_put(j, pair, 2);
} else if (c < 0x20) {
const char escape[6] = {'\\', 'u', '0', '0', hex[c >> 4], hex[c & 15]};
ds_json_put(j, escape, 6);
} else if (c < 0x80) {
ds_json_putc(j, (char) c);
} else {
size_t available = 1;
while (available < 4 && s[i + available] != '\0') available++;
size_t length = ds_json_utf8_length(s + i, available);
if (length == 0) {
ds_json_putc(j, '?');
} else {
ds_json_put(j, (const char *) s + i, length);
i += length;
continue;
}
}
i++;
}
ds_json_putc(j, '"');
}

/* Starts a field; ds_json_commit drops it again when it overflowed. */
static inline size_t ds_json_key(DsJson *j, const char *key) {
size_t start = j->len;
if (!j->first) ds_json_putc(j, ',');
j->first = false;
ds_json_quoted(j, key);
ds_json_putc(j, ':');
return start;
}

static inline void ds_json_commit(DsJson *j, size_t start) {
if (j->overflow) j->len = start;
}

DS_JSON_OUTLINE void ds_json_int(DsJson *j, const char *key, long long value) {
size_t start = ds_json_key(j, key);
char text[24];
size_t pos = sizeof(text);
unsigned long long magnitude = value < 0 ? 0ull - (unsigned long long) value : (unsigned long long) value;
do {
text[--pos] = (char) ('0' + magnitude % 10);
magnitude /= 10;
} while (magnitude != 0);
if (value < 0) text[--pos] = '-';
ds_json_put(j, text + pos, sizeof(text) - pos);
ds_json_commit(j, start);
}

DS_JSON_OUTLINE void ds_json_bool(DsJson *j, const char *key, bool value) {
size_t start = ds_json_key(j, key);
ds_json_put(j, value ? "true" : "false", value ? 4 : 5);
ds_json_commit(j, start);
}

DS_JSON_OUTLINE void ds_json_str(DsJson *j, const char *key, const char *value) {
size_t start = ds_json_key(j, key);
ds_json_quoted(j, value);
ds_json_commit(j, start);
}

DS_JSON_OUTLINE void ds_json_obj_begin(DsJson *j, const char *key) {
size_t start = ds_json_key(j, key);
ds_json_putc(j, '{');
ds_json_commit(j, start);
if (!j->overflow) j->depth = 1;
j->first = true;
}

DS_JSON_OUTLINE void ds_json_obj_end(DsJson *j) {
if (j->depth > 0) ds_json_putc(j, '}');
if (!j->overflow) j->depth = 0;
j->first = false;
}

DS_JSON_OUTLINE void ds_json_begin(DsJson *j, char *buf, size_t cap, const char *event) {
*j = (DsJson) {.buf = buf, .cap = cap, .first = true};
ds_json_putc(j, '{');
ds_json_int(j, "v", DS_JSON_SCHEMA_VERSION);
ds_json_int(j, "ts", DS_JSON_NOW());
ds_json_str(j, "event", event);
}

/* Closes the object, appends the newline and returns the line length. */
static inline size_t ds_json_finish(DsJson *j) {
if (j->depth > 0) {
j->buf[j->len++] = '}';
j->depth = 0;
}
if (j->overflow) {
memcpy(j->buf + j->len, ",\"truncated\":true", 17);
j->len += 17;
}
j->buf[j->len++] = '}';
j->buf[j->len++] = '\n';
return j->len;
}

/* One write(2) per line keeps lines intact on pipes up to PIPE_BUF. */
DS_JSON_OUTLINE void ds_json_emit(DsJson *j, int fd) {
size_t total = ds_json_finish(j);
for (size_t done = 0; done < total;) {
ssize_t count = write(fd, j->buf + done, total - done);
if (count <= 0) return;
done += (size_t) count;
}
}

#endif
10 changes: 3 additions & 7 deletions app/src/main/java/me/aroxu/dawnshell/BfuDebianRuntimeProbe.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,6 @@
final class BfuDebianRuntimeProbe {

private static final long PROBE_TIMEOUT_MS = 35_000L;
private static final String SUCCESS_MARKER = "BFU_DEBIAN_NAMESPACE_OK";
private static final String COMPAT_SUCCESS_MARKER =
"BFU_DEBIAN_COMPATIBILITY_OK";
private static final String LOG_FILE = "bfu-debian-runtime.log";

static final class Result {
Expand Down Expand Up @@ -72,15 +69,14 @@ static Result run(Context context, BfuRuntime.Layout layout)
? "probe-compat" : "probe";
String shellCommand = BfuSu.shellQuote(layout.namespaceProbeBinary.getAbsolutePath())
+ " " + operation + " " + BfuSu.shellQuote(BfuRootfsProbe.ROOTFS_PATH);
BfuSu.Result commandResult = BfuSu.run(shellCommand, PROBE_TIMEOUT_MS);
BfuSu.Result commandResult = BfuSu.runRaw(shellCommand, PROBE_TIMEOUT_MS);
boolean userUnlockedAfter = isUserUnlocked(context);
String marker = fallbackAllowed ? COMPAT_SUCCESS_MARKER : SUCCESS_MARKER;
boolean successful = commandResult.exitedSuccessfully()
&& commandResult.output.contains(marker);
&& NativeOutput.has(commandResult.output, fallbackAllowed ? "compat_ok" : "namespace_ok");
Result result = new Result(successful, commandResult.command,
commandResult.exitCode, commandResult.timedOut, userUnlockedBefore,
userUnlockedAfter, fallbackAllowed ? "compat" : "systemd",
commandResult.output);
BfuSu.sanitize(commandResult.output));
appendPersistentResult(deContext, result);
return result;
}
Expand Down
82 changes: 24 additions & 58 deletions app/src/main/java/me/aroxu/dawnshell/DebianLauncher.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,7 @@
import android.os.UserManager;
import android.util.Log;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
Expand Down Expand Up @@ -47,7 +45,7 @@ String summary() {
return "health_attempts=" + attempts
+ " health_exit=" + result.exitCode
+ " health_timeout=" + result.timedOut
+ " health_output=" + result.output;
+ " health_output=" + BfuSu.sanitize(result.output);
}
}

Expand All @@ -58,9 +56,8 @@ static boolean isRunning(BfuRuntime.Layout layout)
String command = BfuSu.shellQuote(layout.namespaceProbeBinary.getAbsolutePath())
+ " status " + BfuSu.shellQuote(BfuRootfsProbe.ROOTFS_PATH)
+ " " + BfuSu.shellQuote(layout.run.getAbsolutePath());
BfuSu.Result result = BfuSu.run(command, 12_000L);
return result.exitedSuccessfully()
&& result.output.contains("BFU_DEBIAN_RUNNING");
BfuSu.Result result = BfuSu.runRaw(command, 12_000L);
return result.exitedSuccessfully() && NativeOutput.has(result.output, "running");
}

static boolean run(Context context, BfuRuntime.Layout layout, Operation operation,
Expand All @@ -85,11 +82,11 @@ static boolean run(Context context, BfuRuntime.Layout layout, Operation operatio
timeoutMs = 12_000L;
}

BfuSu.Result result = BfuSu.run(command, timeoutMs);
BfuSu.Result result = BfuSu.runRaw(command, timeoutMs);
String summary = "command=" + result.command
+ " exit=" + result.exitCode
+ " timeout=" + result.timedOut
+ " output=" + result.output;
+ " output=" + BfuSu.sanitize(result.output);
appendLog(layout.lifecycleLog,
"ANDROID_RESULT operation=" + operation.name() + " " + summary);
boolean successful = result.exitedSuccessfully();
Expand All @@ -99,10 +96,10 @@ static boolean run(Context context, BfuRuntime.Layout layout, Operation operatio
health = checkHealth(layout, true);
successful = health.successful;
} else if (successful && operation == Operation.STATUS) {
if (result.output.contains("BFU_DEBIAN_RUNNING")) {
if (NativeOutput.has(result.output, "running")) {
health = checkHealth(layout, false);
successful = health.successful;
} else if (!result.output.contains("BFU_DEBIAN_STOPPED")) {
} else if (!NativeOutput.has(result.output, "stopped")) {
successful = false;
appendLog(layout.lifecycleLog,
"ANDROID_HEALTH skipped=state_not_running_or_stopped");
Expand All @@ -115,7 +112,9 @@ static boolean run(Context context, BfuRuntime.Layout layout, Operation operatio
+ " user_unlocked_before=" + userUnlockedBefore
+ " user_unlocked_after=" + userUnlockedAfter
+ " " + summary;
writeStatus(context, (successful ? "SUCCEEDED " : "FAILED ") + summary);
String events = health == null ? result.output : result.output + "\n" + health.result.output;
StatusStore.write(statusFile(context), (successful ? "SUCCEEDED " : "FAILED ") + summary,
NativeOutput.detail(events));
if (successful) {
Log.i(TAG, "Debian lifecycle " + summary);
} else {
Expand Down Expand Up @@ -161,21 +160,9 @@ private static HealthOutcome checkHealth(BfuRuntime.Layout layout,
BfuSu.Result result;
do {
attempts++;
result = BfuSu.run(command, HEALTH_COMMAND_TIMEOUT_MS);
boolean compatibility = result.output.contains("mode=compat");
boolean successful = result.exitedSuccessfully()
&& result.output.contains("BFU_DEBIAN_HEALTH")
&& result.output.contains("listen_22=true")
&& (compatibility
? result.output.contains("compat_ready=true")
: result.output.contains("system_state=running")
&& result.output.contains("dbus_service=active")
&& result.output.contains("dbus_bus=ok")
&& result.output.contains("ssh_service=active")
&& result.output.contains("boot_proof_service=active")
&& result.output.contains("boot_proof_marker=present")
&& result.output.contains("target_state=active")
&& result.output.contains("cgroup_delegation=delegated"));
result = BfuSu.runRaw(command, HEALTH_COMMAND_TIMEOUT_MS);
Health health = NativeOutput.health(result.output);
boolean successful = result.exitedSuccessfully() && health != null && health.getHealthy();
appendLog(layout.lifecycleLog,
"ANDROID_HEALTH attempt=" + attempts
+ " exit=" + result.exitCode
Expand All @@ -189,21 +176,17 @@ private static HealthOutcome checkHealth(BfuRuntime.Layout layout,
return new HealthOutcome(false, attempts, result);
}

static OperationStatus readOperationStatus(Context context) throws IOException {
return StatusStore.read(statusFile(context));
}

static String readStatus(Context context) throws IOException {
Context deContext = BfuPreferences.deviceProtectedContext(context);
File file = new File(deContext.getFilesDir(), STATUS_FILE);
if (!file.isFile()) return "";
try (FileInputStream input = new FileInputStream(file);
ByteArrayOutputStream output = new ByteArrayOutputStream()) {
byte[] buffer = new byte[512];
int count;
while (output.size() < 4096
&& (count = input.read(buffer, 0,
Math.min(buffer.length, 4096 - output.size()))) >= 0) {
output.write(buffer, 0, count);
}
return new String(output.toByteArray(), StandardCharsets.UTF_8).trim();
}
OperationStatus status = readOperationStatus(context);
return status == null ? "" : status.text();
}

private static File statusFile(Context context) {
return new File(BfuPreferences.deviceProtectedContext(context).getFilesDir(), STATUS_FILE);
}

static String readLogTail(Context context) throws IOException {
Expand Down Expand Up @@ -254,24 +237,7 @@ private static void appendLog(File file, String value) throws IOException {
}

private static void writeStatus(Context context, String value) throws IOException {
Context deContext = BfuPreferences.deviceProtectedContext(context);
File destination = new File(deContext.getFilesDir(), STATUS_FILE);
File temporary = new File(deContext.getFilesDir(), STATUS_FILE + ".new");
String contents = System.currentTimeMillis() + " " + value + "\n";
synchronized (FILE_LOCK) {
try (FileOutputStream output = new FileOutputStream(temporary, false)) {
output.write(contents.getBytes(StandardCharsets.UTF_8));
output.getFD().sync();
}
setOwnerOnly(temporary);
if (destination.exists() && !destination.delete()) {
throw new IOException("cannot replace lifecycle status");
}
if (!temporary.renameTo(destination)) {
throw new IOException("cannot publish lifecycle status");
}
setOwnerOnly(destination);
}
StatusStore.write(statusFile(context), value);
}

private static String utcTimestamp() {
Expand Down
Loading
Loading