Skip to content
Merged
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
22 changes: 21 additions & 1 deletion clients/android/src/main/cpp/hands_native_crash.c
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,9 @@ static struct sigaction g_previous[sizeof(g_fatal_signals) / sizeof(int)];
static char g_altstack[SIGSTKSZ * 2];
static struct hands_module g_modules[HANDS_MAX_MODULES];
static size_t g_module_count = 0;
/* Per-process identity set once at install; read-only in the handler. */
static uint64_t g_process_start_at = 0;
static char g_process_event_id[40];

static size_t hands_strlen(const char *text) {
size_t n = 0;
Expand Down Expand Up @@ -409,6 +412,12 @@ static void hands_signal_handler(int signo, siginfo_t *info, void *ucontext) {
hands_write_key_dec(fd, "crash_at", ts);
hands_write_key_dec(fd, "pid", (uint64_t)getpid());
hands_write_key_dec(fd, "tid", (uint64_t)tid);
if (g_process_start_at != 0) hands_write_key_dec(fd, "process_start_at", g_process_start_at);
if (g_process_event_id[0] != '\0') {
hands_write_text(fd, "process_event_id ");
hands_write_text(fd, g_process_event_id);
hands_write_text(fd, "\n");
}
hands_write_thread_name(fd, tid);
hands_write_context(fd, ucontext);
hands_write_modules(fd);
Expand All @@ -431,8 +440,19 @@ static void hands_signal_handler(int signo, siginfo_t *info, void *ucontext) {
}

JNIEXPORT void JNICALL
Java_build_hands_update_HandsNativeCrash_nativeInstall(JNIEnv *env, jclass clazz, jstring crash_dir) {
Java_build_hands_update_HandsNativeCrash_nativeInstall(JNIEnv *env, jclass clazz, jstring crash_dir,
jlong process_start_at, jstring process_event_id) {
(void)clazz;
g_process_start_at = process_start_at > 0 ? (uint64_t)process_start_at : 0;
g_process_event_id[0] = '\0';
if (process_event_id != NULL) {
const char *event_id = (*env)->GetStringUTFChars(env, process_event_id, NULL);
if (event_id != NULL) {
strncpy(g_process_event_id, event_id, sizeof(g_process_event_id) - 1);
g_process_event_id[sizeof(g_process_event_id) - 1] = '\0';
(*env)->ReleaseStringUTFChars(env, process_event_id, event_id);
}
}
const char *dir = (*env)->GetStringUTFChars(env, crash_dir, NULL);
if (dir == NULL) return;
strncpy(g_crash_dir, dir, sizeof(g_crash_dir) - 1);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,16 +56,44 @@ class HandsFeedback(
* @param attachments up to 9 files; ≤ 10 MB inline, up to 200 MB via
* presigned direct-to-R2 upload (server enforced)
* @param extras extra metadata merged into the ticket's metadata_json
* @return ticket id
* @param submissionId optional UUID idempotency key. Hands keeps one ticket per
* key: resending the same report returns the first ticket; a
* different crash/error report under the same key is merged into
* that ticket; any other reuse fails with HTTP 409.
* @return ticket id, or "" when the report was merged into an existing ticket whose
* id Hands does not disclose to anonymous clients. Use [submitReport] to
* tell the two apart.
*/
suspend fun submit(
message: String,
kind: String = "feedback",
contact: String? = null,
attachments: List<File> = emptyList(),
extras: Map<String, Any?> = emptyMap(),
): String = withContext(Dispatchers.IO) {
submissionId: String? = null,
): String = submitReport(message, kind, contact, attachments, extras, submissionId).ticketId.orEmpty()

/** Outcome of [submitReport]. */
data class Submission(
/** The ticket id; null only when [merged] and the id was not disclosed. */
val ticketId: String?,
/** True when Hands merged this report into the ticket already holding its submissionId. */
val merged: Boolean,
)

/** Same as [submit], but reports whether the submission was merged. */
suspend fun submitReport(
message: String,
kind: String = "feedback",
contact: String? = null,
attachments: List<File> = emptyList(),
extras: Map<String, Any?> = emptyMap(),
submissionId: String? = null,
): Submission = withContext(Dispatchers.IO) {
require(message.isNotBlank()) { "message must not be blank" }
require(submissionId == null || SUBMISSION_ID_PATTERN.matches(submissionId)) {
"submissionId must be a UUID"
}

val selected = attachments.filter { it.isFile }.take(MAX_ATTACHMENTS)
for (file in selected) {
Expand Down Expand Up @@ -121,6 +149,9 @@ class HandsFeedback(
if (!contact.isNullOrBlank()) {
bodyBuilder.addFormDataPart("contact", contact)
}
if (submissionId != null) {
bodyBuilder.addFormDataPart("submission_id", submissionId.lowercase(Locale.ROOT))
}
for (file in inline) {
bodyBuilder.addFormDataPart(
"attachments",
Expand Down Expand Up @@ -153,10 +184,8 @@ class HandsFeedback(
if (response.code !in 200..299) {
throw HandsFeedbackException(response.code, body.take(300))
}
// {"id":"…","status":"open","attachments":N}
JSONObject(body).optString("id").ifBlank {
throw HandsFeedbackException(response.code, "missing ticket id in response")
}
// {"id":"…","status":"open","attachments":N} or {"merged":true[,"id":"…"]}
parseSubmission(response.code, body)
}
}

Expand Down Expand Up @@ -248,9 +277,22 @@ class HandsFeedback(
}

companion object {
internal fun parseSubmission(code: Int, body: String): Submission {
val json = runCatching { JSONObject(body) }.getOrNull()
?: throw HandsFeedbackException(code, "response is not JSON")
val id = json.optString("id").takeIf(String::isNotBlank)
val merged = json.optBoolean("merged", false)
if (id == null && !merged) throw HandsFeedbackException(code, "missing ticket id in response")
return Submission(ticketId = id, merged = merged)
}

/** Hands Android SDK version reported in feedback/crash metadata. */
const val SDK_VERSION = BuildConfig.HANDS_SDK_VERSION

/** Same shape the server accepts for submission_id (UUID versions 1-8). */
internal val SUBMISSION_ID_PATTERN =
Regex("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$")

/** Server-enforced: at most 9 attachments per ticket. */
const val MAX_ATTACHMENTS = 9

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,12 @@ import android.app.ActivityManager
import android.app.ApplicationExitInfo
import android.content.Context
import android.os.Build
import android.os.Process
import android.os.SystemClock
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
import java.util.UUID
import kotlin.math.abs

/**
Expand All @@ -32,7 +35,27 @@ object HandsNativeCrash {
private const val MAX_EXIT_TRACE_BYTES = 2 * 1024 * 1024L

@JvmStatic
private external fun nativeInstall(crashDir: String)
private external fun nativeInstall(crashDir: String, processStartAt: Long, processEventId: String)

/**
* A random UUID for this process, written into any native crash record it
* leaves and used as that crash ticket's `submission_id`. Store it with your
* own launch record: a system-exit report for the same process sent with
* `HandsFeedback.submit(submissionId = it)` then shares one ticket with the
* native crash instead of creating a second one.
*/
@JvmStatic
val processEventId: String by lazy { UUID.randomUUID().toString() }

/**
* This process's start time, epoch milliseconds (from
* `Process.getStartElapsedRealtime`, so it does not depend on when the SDK
* is installed). Computed once per process.
*/
@JvmStatic
val processStartAt: Long by lazy {
System.currentTimeMillis() - (SystemClock.elapsedRealtime() - Process.getStartElapsedRealtime())
}

internal fun crashDir(context: Context): File =
File(context.filesDir, "quiver/native-crashes")
Expand All @@ -43,7 +66,7 @@ object HandsNativeCrash {
val dir = crashDir(context)
dir.mkdirs()
System.loadLibrary("handscrash")
nativeInstall(dir.absolutePath)
nativeInstall(dir.absolutePath, processStartAt, processEventId)
true
}.getOrDefault(false)
}
Expand All @@ -57,28 +80,31 @@ object HandsNativeCrash {
versionCode: Long? = null,
channel: String? = null,
clientKey: String? = null,
) {
): List<NativeCrashUpload> {
val results = mutableListOf<NativeCrashUpload>()
val dir = crashDir(context)
val records = (dir.listFiles { f -> f.name.endsWith(".qnc") } ?: emptyArray())
.sortedBy { it.name }
if (records.isEmpty()) return
if (records.isEmpty()) return results
// Retention: newest survive, same policy as HandsCrash.
records.dropLast(MAX_STORED).forEach {
it.delete()
deleteExitSidecars(it)
results += NativeCrashUpload.discarded()
}

val pending = records.takeLast(MAX_STORED).mapNotNull { record ->
val parsed = runCatching { parseRecord(record.readText()) }.getOrNull()
if (parsed == null) {
record.delete()
deleteExitSidecars(record)
results += NativeCrashUpload.discarded()
null
} else {
PendingRecord(record, parsed)
}
}
if (pending.isEmpty()) return
if (pending.isEmpty()) return results

// Reuse only a sidecar whose recorded QNC coordinates still match.
// Valid bindings also reserve the system exit identity so another QNC
Expand Down Expand Up @@ -129,14 +155,15 @@ object HandsNativeCrash {
}
val top = parsed.frames.firstOrNull()
val result = runCatching {
feedback.submit(
feedback.submitReport(
message = buildString {
append("Native crash: ").append(parsed.signalName)
parsed.threadName?.let { append(" on thread ").append(it) }
top?.let { append("\nat ").append(it.soname).append("+0x").append(it.offset.toString(16)) }
},
kind = "crash",
attachments = attachments,
submissionId = parsed.processEventId,
extras = buildMap {
put("crash_exception_class", parsed.signalName)
put("crash_top_frame", top?.let { "${it.soname}+0x${it.offset.toString(16)}" } ?: "")
Expand All @@ -150,6 +177,8 @@ object HandsNativeCrash {
parsed.signalCode?.let { put("crash_signal_code", it) }
parsed.faultAddress?.let { put("crash_fault_addr", "0x${it.toString(16)}") }
parsed.pid?.let { put("crash_process_id", it) }
parsed.processStartAt?.let { put("crash_process_start_at", it) }
parsed.processEventId?.let { put("crash_process_event_id", it) }
parsed.tid?.let { put("crash_thread_id", it) }
parsed.threadName?.let { put("crash_thread_name", it) }
parsed.registers["pc"]?.let { put("crash_context_pc", it) }
Expand All @@ -171,10 +200,60 @@ object HandsNativeCrash {
},
)
}
if (result.isSuccess) {
val submission = result.getOrNull()
val outcome = when {
submission == null -> NativeCrashUpload.Outcome.FAILED_WILL_RETRY
submission.merged -> NativeCrashUpload.Outcome.MERGED
else -> NativeCrashUpload.Outcome.UPLOADED
}
if (outcome != NativeCrashUpload.Outcome.FAILED_WILL_RETRY) {
record.delete()
deleteExitSidecars(record)
}
results += NativeCrashUpload(
outcome = outcome,
pid = parsed.pid,
processStartAt = parsed.processStartAt,
processEventId = parsed.processEventId,
crashAt = parsed.crashAt,
exitTimestamp = exitEvidence?.timestamp,
ticketId = submission?.ticketId,
)
}
return results
}

/**
* What happened to one pending native crash record in [uploadPending].
*
* - [Outcome.UPLOADED]: Hands accepted it as ticket [ticketId]; the record is gone.
* - [Outcome.MERGED]: Hands already had a ticket under this record's [processEventId]
* (for example the app reported the same process exit first, or an earlier upload's
* response was lost) and merged this record into it; the record is gone. [ticketId]
* is null unless the app submits as a trusted reporter.
* - [Outcome.FAILED_WILL_RETRY]: the upload failed; the record is kept for the next call.
* - [Outcome.DISCARDED]: the record was unreadable or over the retention limit and was
* deleted without uploading; every other field is null.
*
* [pid], [processStartAt] and [processEventId] identify the crashed process
* ([processEventId] is the value [HandsNativeCrash.processEventId] had in it);
* the last two are null for records written by SDKs before 0.13.2. [crashAt] is
* the crash time (epoch ms) and [exitTimestamp] the matched ApplicationExitInfo
* timestamp, when one was matched.
*/
data class NativeCrashUpload(
val outcome: Outcome,
val pid: Long?,
val processStartAt: Long?,
val processEventId: String?,
val crashAt: Long?,
val exitTimestamp: Long?,
val ticketId: String?,
) {
enum class Outcome { UPLOADED, MERGED, FAILED_WILL_RETRY, DISCARDED }

internal companion object {
fun discarded() = NativeCrashUpload(Outcome.DISCARDED, null, null, null, null, null, null)
}
}

Expand Down Expand Up @@ -202,6 +281,8 @@ object HandsNativeCrash {
val pid: Long?,
val tid: Long?,
val threadName: String?,
val processStartAt: Long? = null,
val processEventId: String? = null,
val arch: String?,
val registers: Map<String, String>,
val modules: List<NativeModule>,
Expand Down Expand Up @@ -287,6 +368,8 @@ object HandsNativeCrash {
var pid: Long? = null
var tid: Long? = null
var threadName: String? = null
var processStartAt: Long? = null
var processEventId: String? = null
var arch: String? = null
val contextFrames = mutableListOf<Pair<Long, String?>>()
val maps = mutableListOf<MapEntry>()
Expand All @@ -312,6 +395,11 @@ object HandsNativeCrash {
pid = trimmed.removePrefix("pid ").trim().toLongOrNull()
section == "header" && trimmed.startsWith("tid ") ->
tid = trimmed.removePrefix("tid ").trim().toLongOrNull()
section == "header" && trimmed.startsWith("process_start_at ") ->
processStartAt = trimmed.removePrefix("process_start_at ").trim().toLongOrNull()?.takeIf { it > 0 }
section == "header" && trimmed.startsWith("process_event_id ") ->
processEventId = trimmed.removePrefix("process_event_id ").trim().lowercase()
.takeIf { HandsFeedback.SUBMISSION_ID_PATTERN.matches(it) }
section == "header" && trimmed.startsWith("thread_name_hex ") ->
threadName = decodeHexUtf8(trimmed.removePrefix("thread_name_hex ").trim())
section == "registers" && trimmed.startsWith("arch ") ->
Expand Down Expand Up @@ -355,6 +443,8 @@ object HandsNativeCrash {
pid = pid,
tid = tid,
threadName = threadName,
processStartAt = processStartAt,
processEventId = processEventId,
arch = arch,
registers = registers,
modules = modules,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -215,4 +215,48 @@ class HandsNativeCrashTest {
)
assertTrue(assignments.isEmpty())
}

private val minimalFrames = """
registers
pc 0x70001234
frames
0x70001234 context_pc
modules
0x70000000-0x70010000 1de2e1c0bc046f0654f9fdc8173912735aeea751 /data/app/lib/arm64/libraft.so
maps
70000000-70010000 r-xp 00000000 00:00 0 /data/app/lib/arm64/libraft.so
""".trimIndent()

@Test
fun parsesProcessIdentityAndRejectsMalformedEventIds() {
val withIdentity = HandsNativeCrash.parseRecord(
"QNC2\nsignal 11\ncrash_at 1721810000123\npid 4123\nprocess_start_at 1721809990000\n" +
"process_event_id 3F2B9C1E-8D4A-4B6E-9C1F-2A7D5E8B0C34\n" + minimalFrames,
)!!
assertEquals(1721809990000L, withIdentity.processStartAt)
assertEquals("3f2b9c1e-8d4a-4b6e-9c1f-2a7d5e8b0c34", withIdentity.processEventId)

val malformed = HandsNativeCrash.parseRecord(
"QNC2\nsignal 11\ncrash_at 1\npid 1\nprocess_start_at 0\nprocess_event_id not-a-uuid\n" + minimalFrames,
)!!
assertNull(malformed.processStartAt)
assertNull(malformed.processEventId)

val legacy = HandsNativeCrash.parseRecord("QNC2\nsignal 11\ncrash_at 1\npid 1\n" + minimalFrames)!!
assertNull(legacy.processEventId)
}

@Test
fun mergedResponsesAreSuccessWithOrWithoutAnId() {
assertEquals(HandsFeedback.Submission("t1", false), HandsFeedback.parseSubmission(201, """{"id":"t1","status":"open"}"""))
assertEquals(HandsFeedback.Submission(null, true), HandsFeedback.parseSubmission(200, """{"merged":true}"""))
assertEquals(HandsFeedback.Submission("t1", true), HandsFeedback.parseSubmission(200, """{"id":"t1","merged":true}"""))
assertTrue(runCatching { HandsFeedback.parseSubmission(200, """{"status":"open"}""") }.exceptionOrNull() is HandsFeedbackException)
}

@Test
fun submissionIdPatternMatchesTheServer() {
assertTrue(HandsFeedback.SUBMISSION_ID_PATTERN.matches(java.util.UUID.randomUUID().toString()))
assertTrue(!HandsFeedback.SUBMISSION_ID_PATTERN.matches("3f2b9c1e8d4a4b6e9c1f2a7d5e8b0c34"))
}
}
Loading
Loading