Skip to content

armgit / rea

Public Imported from GitHub
0

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

fix(plist): keep negative-zero reals distinct from positive zero (#4839)

pablodiazjorge3b5605ecd21b
diff --git a/docs/native-investigation.md b/docs/native-investigation.md
index 432f68efd..dd749f80e 100644
--- a/docs/native-investigation.md
+++ b/docs/native-investigation.md
@@ -628,6 +628,12 @@ or a negative year, is reported as `{ "$plist_type": "date", "iso8601": null }`
with a counted limitation; the rest of the plist or archive is still decoded.
`inspect_plist` and Interface Builder decoding use the same projection.
+A negative-zero real is reported as `{ "$plist_type": "real", "value": "-0" }`
+because a JSON number cannot carry the sign of zero. `inspect_plist` and
+`inspect_keyed_archive` count these values in a limitation, and Interface
+Builder node attributes use the same value. Positive zero and integer zero,
+including an `<integer>-0</integer>` literal, remain the number `0`.
+
## Locate a byte signature
Use `search_bytes` after opening a target with Ghidra to locate a known constant
diff --git a/src/artifacts/apple/KeyedArchiveReader.ts b/src/artifacts/apple/KeyedArchiveReader.ts
index b7b0d109b..71fd628f2 100644
--- a/src/artifacts/apple/KeyedArchiveReader.ts
+++ b/src/artifacts/apple/KeyedArchiveReader.ts
@@ -6,7 +6,10 @@ import {
AnalysisInputError,
AnalysisUnsupportedTargetError,
} from "../../domain/analysisErrorCore.js";
-import { unknownDateLimitation } from "../../domain/apple/plistValue.js";
+import {
+ negativeZeroRealLimitation,
+ unknownDateLimitation,
+} from "../../domain/apple/plistValue.js";
import { createPlistNumberProjection } from "../../domain/apple/plistNumbers.js";
import {
decodeBinaryPlistNumbers,
@@ -82,10 +85,12 @@ export const decodeKeyedArchiveBytes = (
: 0,
}
: parseXmlPropertyList(xmlText ?? "");
- const { unknownRealCount, unknownDateCount, ...graph } = projectKeyedArchive(
- parsed.value,
- selection,
- );
+ const {
+ unknownRealCount,
+ negativeZeroRealCount,
+ unknownDateCount,
+ ...graph
+ } = projectKeyedArchive(parsed.value, selection);
const numbers = createPlistNumberProjection(parsed.numberLiterals);
// Classify the serialized graph before projecting values to typed decimals.
// Numeric IDs, node kinds, references and pagination retain their original meaning.
@@ -115,6 +120,9 @@ export const decodeKeyedArchiveBytes = (
: [
`${String(unknownRealCount)} non-finite real value(s) are reported as { "$plist_type": "real", "value": null } because JSON evidence cannot preserve NaN vs infinity.`,
]),
+ ...(negativeZeroRealCount === 0
+ ? []
+ : [negativeZeroRealLimitation(negativeZeroRealCount)]),
...(unknownDateCount === 0
? []
: [unknownDateLimitation(unknownDateCount)]),
diff --git a/src/domain/apple/keyedArchive.ts b/src/domain/apple/keyedArchive.ts
index 65bcaa3e5..24c56db62 100644
--- a/src/domain/apple/keyedArchive.ts
+++ b/src/domain/apple/keyedArchive.ts
@@ -248,6 +248,7 @@ export const projectKeyedArchive = (
const ids = new Set(page.map(({ id }) => id));
return {
unknownRealCount: projected.unknownRealCount,
+ negativeZeroRealCount: projected.negativeZeroRealCount,
unknownDateCount: projected.unknownDateCount,
roots,
objects: page,
diff --git a/src/domain/apple/plistValue.test.ts b/src/domain/apple/plistValue.test.ts
index e8ff89cc7..fae48252b 100644
--- a/src/domain/apple/plistValue.test.ts
+++ b/src/domain/apple/plistValue.test.ts
@@ -12,10 +12,33 @@ it("projects an unrepresentable date as unknown and counts it", () => {
near: { $plist_type: "date", iso8601: "1970-01-01T00:00:00.000Z" },
},
unknownRealCount: 0,
+ negativeZeroRealCount: 0,
unknownDateCount: 1,
});
});
+it("keeps a negative-zero real distinct from positive zero and counts it", () => {
+ const observed: object[] = [];
+ const projected = projectPlistValue(
+ [-0, 0, 1.25, { $plist_type: "real", value: "-0" }],
+ (wrapper) => observed.push(wrapper),
+ );
+ expect(projected.negativeZeroRealCount).toBe(1);
+ expect(projected.unknownRealCount).toBe(0);
+ expect(Array.isArray(projected.value)).toBe(true);
+ if (!Array.isArray(projected.value)) throw new Error("Expected array");
+ expect(projected.value[0]).toEqual({ $plist_type: "real", value: "-0" });
+ expect(Object.is(projected.value[1], 0)).toBe(true);
+ expect(projected.value[2]).toBe(1.25);
+ // Only the generated wrapper is reported; the lookalike stays a dictionary.
+ expect(projected.value[3]).toEqual(projected.value[0]);
+ expect(observed).toHaveLength(1);
+ expect(observed[0]).toBe(projected.value[0]);
+ expect(JSON.stringify(projected.value)).toBe(
+ '[{"$plist_type":"real","value":"-0"},0,1.25,{"$plist_type":"real","value":"-0"}]',
+ );
+});
+
it("rejects excessive plist nesting without exhausting the stack", () => {
const deep: unknown[] = [];
let cursor = deep;
diff --git a/src/domain/apple/plistValue.ts b/src/domain/apple/plistValue.ts
index 1131d8bd7..28ebe08a1 100644
--- a/src/domain/apple/plistValue.ts
+++ b/src/domain/apple/plistValue.ts
@@ -15,6 +15,8 @@ export interface ProjectedPlistValue {
readonly value: JsonValue;
/** Reals decoded as NaN, which the decoder also uses for ±infinity. */
readonly unknownRealCount: number;
+ /** Negative-zero reals, which a JSON number would report as positive zero. */
+ readonly negativeZeroRealCount: number;
/** Dates the decoder could not represent, reported without a timestamp. */
readonly unknownDateCount: number;
}
@@ -23,10 +25,21 @@ export interface ProjectedPlistValue {
export const unknownDateLimitation = (count: number): string =>
`${String(count)} date value(s) are reported as { "$plist_type": "date", "iso8601": null } because the decoder could not represent them, such as XML dates with years beyond 9999 or negative years, or dates outside the JavaScript date range.`;
+/** The typed scalar that keeps a negative-zero real distinct from positive zero. */
+export const negativeZeroReal = (): Record<string, JsonValue> => ({
+ $plist_type: "real",
+ value: "-0",
+});
+
+/** Limitation for results whose plist held negative-zero reals. */
+export const negativeZeroRealLimitation = (count: number): string =>
+ `${String(count)} negative-zero real value(s) are reported as { "$plist_type": "real", "value": "-0" } because a JSON number cannot carry the sign of zero.`;
+
/**
* Project a decoded plist into JSON. Data, dates and retained big integers become explicit
* `$plist_type` objects; a non-finite real becomes an explicit unknown
- * because the XML decoder reports NaN and ±infinity alike.
+ * because the XML decoder reports NaN and ±infinity alike, and a
+ * negative-zero real keeps its sign, which JSON serialization would drop.
*/
export const projectPlistValue = (
value: unknown,
@@ -34,6 +47,7 @@ export const projectPlistValue = (
onWrappedScalar?: (value: Record<string, JsonValue>) => void,
): ProjectedPlistValue => {
let unknownRealCount = 0;
+ let negativeZeroRealCount = 0;
let unknownDateCount = 0;
const scalar = (value: Record<string, JsonValue>): JsonValue => {
onWrappedScalar?.(value);
@@ -64,6 +78,11 @@ export const projectPlistValue = (
unknownRealCount += 1;
return scalar({ $plist_type: "real", value: null });
}
+ // Integer decoders never yield -0, so a signed zero here is a real.
+ if (typeof item === "number" && Object.is(item, -0)) {
+ negativeZeroRealCount += 1;
+ return scalar(negativeZeroReal());
+ }
if (typeof item === "bigint")
return scalar({ $plist_type: "integer", decimal: item.toString() });
if (Array.isArray(item)) {
@@ -94,5 +113,10 @@ export const projectPlistValue = (
return z.union([z.string(), z.number(), z.boolean(), z.null()]).parse(item);
};
const projected = project(value, 0);
- return { value: projected, unknownRealCount, unknownDateCount };
+ return {
+ value: projected,
+ unknownRealCount,
+ negativeZeroRealCount,
+ unknownDateCount,
+ };
};
diff --git a/src/domain/propertyListXml.test.ts b/src/domain/propertyListXml.test.ts
index 631fead7d..155178a12 100644
--- a/src/domain/propertyListXml.test.ts
+++ b/src/domain/propertyListXml.test.ts
@@ -53,6 +53,21 @@ it("retains partial numeric values with explicit incomplete metadata for unsuppo
expect(parsed.numberLiterals.incomplete).toBe(true);
});
+it("decodes a signed integer zero as zero and a negative-zero real with its sign", () => {
+ const parsed = parseXmlPropertyList(
+ "<plist><array><integer>-0</integer><integer>-0<!-- partial --></integer><real>-0.0</real><real>0.0</real></array></plist>",
+ );
+ expect(Array.isArray(parsed.value)).toBe(true);
+ if (!Array.isArray(parsed.value)) throw new Error("Expected array");
+ expect(parsed.value.map((item) => Object.is(item, -0))).toEqual([
+ false,
+ false,
+ true,
+ false,
+ ]);
+ expect(parsed.value).toEqual([0, 0, -0, 0]);
+});
+
it("interprets failures in omitted entries before reporting partial evidence", () => {
expect(() =>
parseXmlPropertyList(
diff --git a/src/domain/propertyListXml.ts b/src/domain/propertyListXml.ts
index 696f917ab..558d407d4 100644
--- a/src/domain/propertyListXml.ts
+++ b/src/domain/propertyListXml.ts
@@ -98,7 +98,9 @@ export const decodeXmlPropertyList = (document: Document) => {
: undefined;
if (exact === undefined) {
numbers.markIncomplete();
- return Number.parseInt(first.nodeValue ?? "", 10);
+ const partial = Number.parseInt(first.nodeValue ?? "", 10);
+ // An integer has no signed zero; keep -0 from reading as a real.
+ return partial === 0 ? 0 : partial;
}
numbers.integer(exact);
const decoded = Number(exact);
diff --git a/src/native/parsers/plist.test.ts b/src/native/parsers/plist.test.ts
index 1ad64bc63..7459f9c76 100644
--- a/src/native/parsers/plist.test.ts
+++ b/src/native/parsers/plist.test.ts
@@ -143,6 +143,31 @@ it("keeps integral XML reals beyond the safe range as reals", () => {
]);
});
+it("keeps negative-zero reals distinct in native JSON and XML evidence", () => {
+ for (const parsed of [
+ parsePlistJson(
+ '{"Negative":-0.0,"Spelled":-0,"Positive":0.0,"Integer":0,"Ratio":1.25}',
+ ),
+ parsePlistXml(
+ "<plist><dict><key>Negative</key><real>-0.0</real><key>Spelled</key><real>-0</real><key>Positive</key><real>0.0</real><key>Integer</key><integer>-0</integer><key>Ratio</key><real>1.25</real></dict></plist>",
+ ),
+ ]) {
+ if (!parsed.ok) throw parsed.error;
+ expect(JSON.stringify(parsed.value.value)).toBe(
+ '{"Negative":{"$plist_type":"real","value":"-0"},"Spelled":{"$plist_type":"real","value":"-0"},"Positive":0,"Integer":0,"Ratio":1.25}',
+ );
+ expect(parsed.value.limitations).toContain(
+ '2 negative-zero real value(s) are reported as { "$plist_type": "real", "value": "-0" } because a JSON number cannot carry the sign of zero.',
+ );
+ }
+});
+
+it("reports no negative-zero limitation for positive zero", () => {
+ const parsed = parsePlistJson('{"Positive":0.0,"Integer":0}');
+ if (!parsed.ok) throw parsed.error;
+ expect(parsed.value.limitations).toEqual([]);
+});
+
it("reports XML numbers whose integer or real origin is ambiguous", () => {
const parsed = parsePlistXml(
"<plist><array><integer>9007199254740993</integer><real>9007199254740992</real><data>AA==</data></array></plist>",
diff --git a/src/native/parsers/plist.ts b/src/native/parsers/plist.ts
index 5fb0fecab..5c79f6ade 100644
--- a/src/native/parsers/plist.ts
+++ b/src/native/parsers/plist.ts
@@ -3,6 +3,8 @@ import { z } from "zod";
import { AnalysisOutputError } from "../../domain/analysisErrorCore.js";
import type { JsonValue } from "../../domain/jsonValue.js";
import {
+ negativeZeroReal,
+ negativeZeroRealLimitation,
projectPlistValue,
unknownDateLimitation,
type ProjectedPlistValue,
@@ -42,17 +44,22 @@ const INTEGRAL_LITERAL = /^-?\d+$/u;
/**
* Decode plutil JSON, passing each integral number literal beyond the exact
- * range of a JavaScript number, with its source digits, to `unsafe`.
+ * range of a JavaScript number, with its source digits, to `unsafe`, and
+ * each negative zero to `negativeZero`.
*/
const decodePlistJson = (
output: string,
unsafe: (item: number, digits: string) => unknown,
+ negativeZero: (item: number) => unknown = (item) => item,
): unknown => {
// plutil output can carry a UTF-8 BOM, which JSON.parse rejects outright.
const text = output.replace(/^\uFEFF/u, "");
return JSON.parse(
text,
(_key: string, item: unknown, context?: { readonly source?: string }) => {
+ // A plist integer has no signed zero, so -0 can only come from a real.
+ if (typeof item === "number" && Object.is(item, -0))
+ return negativeZero(item);
const source = context?.source;
return typeof item !== "number" ||
Number.isSafeInteger(item) ||
@@ -95,6 +102,11 @@ export const parsePlistJson = (
let literals: PlistNumberLiterals | undefined;
let exactIntegerCount = 0;
let ambiguousNumberCount = 0;
+ let negativeZeroRealCount = 0;
+ const signedZero = (): unknown => {
+ negativeZeroRealCount += 1;
+ return negativeZeroReal();
+ };
const classify = (item: number, digits: string): unknown => {
const exact = BigInt(digits).toString();
const integer =
@@ -116,7 +128,7 @@ export const parsePlistJson = (
xmlConversion === undefined
? undefined
: parseXmlPropertyList(xmlConversion).numberLiterals;
- decoded = omitPrototypeKeys(decodePlistJson(output, classify));
+ decoded = omitPrototypeKeys(decodePlistJson(output, classify, signedZero));
} catch (cause: unknown) {
return err(
new AnalysisOutputError(
@@ -131,6 +143,7 @@ export const parsePlistJson = (
value,
bundle: projectPlistBundle(value),
limitations: [
+ ...negativeZeroLimitations(negativeZeroRealCount),
...(literals?.incomplete === true
? [incompletePlistNumberLimitation]
: []),
@@ -194,6 +207,7 @@ export const parsePlistXml = (
: [
`${String(projected.unknownRealCount)} non-finite real value(s) are reported as { "$plist_type": "real", "value": null } because the XML decoder does not distinguish NaN from infinity.`,
]),
+ ...negativeZeroLimitations(projected.negativeZeroRealCount),
...(projected.unknownDateCount === 0
? []
: [unknownDateLimitation(projected.unknownDateCount)]),
@@ -207,6 +221,9 @@ export const parsePlistXml = (
const prototypeKeyLimitations = (count: number): string[] =>
count === 0 ? [] : [omittedPrototypeKeysLimitation(count)];
+const negativeZeroLimitations = (count: number): string[] =>
+ count === 0 ? [] : [negativeZeroRealLimitation(count)];
+
const numberLimitations = (
exactIntegerCount: number,
ambiguousNumberCount: number,
diff --git a/tests/acceptance/applications/keyedArchiveScalarKinds.test.ts b/tests/acceptance/applications/keyedArchiveScalarKinds.test.ts
index c9921bc44..e709663f6 100644
--- a/tests/acceptance/applications/keyedArchiveScalarKinds.test.ts
+++ b/tests/acceptance/applications/keyedArchiveScalarKinds.test.ts
@@ -155,6 +155,93 @@ cliTest.for(["xml", "binary"] as const)(
},
);
+cliTest.for(["xml", "binary"] as const)(
+ "keeps a negative-zero real distinct from positive zero in a %s keyed archive",
+ async (format, { cli }) => {
+ const root = await createTestTempDirectory("rea-keyed-signed-zero-");
+ const archive = {
+ $archiver: "NSKeyedArchiver",
+ $version: 100000,
+ $top: {
+ negative: { CF$UID: 1 },
+ positive: { CF$UID: 2 },
+ control: { CF$UID: 3 },
+ },
+ $objects: ["$null", 1.5, 0.25, 1.25],
+ };
+ // plist@5 writes -0 and 0 as integers, so encode placeholder reals and
+ // patch them to the zeros an archiver serializes.
+ let bytes: Buffer;
+ if (format === "xml") {
+ const xml = build(archive);
+ expect(xml).toContain("<real>1.5</real>");
+ expect(xml).toContain("<real>0.25</real>");
+ bytes = Buffer.from(
+ xml
+ .replace("<real>1.5</real>", "<real>-0.0</real>")
+ .replace("<real>0.25</real>", "<real>0.0</real>"),
+ );
+ } else {
+ bytes = Buffer.from(buildBinary(archive));
+ for (const [placeholder, zero] of [
+ [1.5, -0],
+ [0.25, 0],
+ ] as const) {
+ const real = Buffer.alloc(9);
+ real[0] = 0x23;
+ real.writeDoubleBE(placeholder, 1);
+ const start = bytes.indexOf(real);
+ expect(start).toBeGreaterThanOrEqual(0);
+ bytes.writeDoubleBE(zero, start + 1);
+ }
+ }
+ const path = join(root, "archive.plist");
+ await writeFile(path, bytes);
+ const output = await cli.run({
+ arguments: ["inspect-keyed-archive", path, "--json"],
+ environment: {
+ HOME: root,
+ USERPROFILE: root,
+ REA_LOG_LEVEL: "silent",
+ REA_ANALYSIS_PROVIDER: "auto",
+ },
+ });
+ expect(output.exitCode, output.stderr).toBe(0);
+ const result = keyedArchiveResultSchema.parse(
+ parseEvidence(output.json).normalized_result,
+ );
+ const { call } = await connectLocalToolsMcp({
+ HOME: root,
+ USERPROFILE: root,
+ });
+ const opened = await call("open_binary", { path });
+ expect(opened.isError, JSON.stringify(opened)).not.toBe(true);
+ const mcp = await call("inspect_keyed_archive", {});
+ expect(mcp.isError, JSON.stringify(mcp)).not.toBe(true);
+ expect(
+ keyedArchiveResultSchema.parse(
+ parseEvidence(mcp.structuredContent).normalized_result,
+ ),
+ ).toEqual(result);
+ const [, negative, positive, control] = result.objects;
+ expect(negative).toMatchObject({
+ kind: "scalar",
+ status: "observed",
+ value: { $plist_type: "real", value: "-0" },
+ });
+ expect(positive).toMatchObject({ kind: "scalar", status: "observed" });
+ expect(Object.is(positive?.value, 0)).toBe(true);
+ expect(control?.value).toBe(1.25);
+ expect(JSON.stringify(result.objects.map(({ value }) => value))).toBe(
+ '["$null",{"$plist_type":"real","value":"-0"},0,1.25]',
+ );
+ expect(result.limitations).toContain(
+ '1 negative-zero real value(s) are reported as { "$plist_type": "real", "value": "-0" } because a JSON number cannot carry the sign of zero.',
+ );
+ expect(await readFile(path)).toEqual(bytes);
+ },
+);
+
cliTest(
"rejects scalar top dictionaries through the public CLI and MCP",
async ({ cli }) => {