mirror of
https://github.com/morluto/rea.git
synced 2026-11-22 22:45:47 +00:00
perf(artifacts/android): reuse ASAR snapshot descriptors and index JADX bridge lookups (#13361)
* perf(artifacts/android): reuse ASAR snapshot descriptors and index JADX bridge lookups * fix(android): cap retained external caller index and fall back to scan
This commit is contained in:
1 parent
cbafdaa8e3
commit
4d7a9710fe
15 files changed
+1290
-295
No files matched your search
+332
-127
@@ -26,7 +26,6 @@ import java.nio.file.Path;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.zip.CRC32;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipFile;
|
||||
@@ -50,22 +49,26 @@ class ReaJadxBridge {
|
||||
// once. Change BRIDGE_VERSION with any protocol change REA must not mix.
|
||||
static final String BRIDGE_NAME = "rea-jadx-bridge";
|
||||
static final String BRIDGE_VERSION = "12";
|
||||
private static final int DEFAULT_MAX_EXTERNAL_CALLER_INDEX_ENTRIES = 4096;
|
||||
private static final Gson JSON = new Gson();
|
||||
private final SessionHolder holder;
|
||||
private int maxExternalCallerIndexEntries = DEFAULT_MAX_EXTERNAL_CALLER_INDEX_ENTRIES;
|
||||
private JadxSession indexedSession;
|
||||
private Map<String, List<ClassSnapshot>> classes = Map.of();
|
||||
private List<ClassSnapshot> orderedClasses = List.of();
|
||||
private JadxSession manifestSession;
|
||||
private ManifestSnapshot manifestSnapshot;
|
||||
private ExternalInventory externalInventory;
|
||||
|
||||
private record MethodSnapshot(String name, String rawName, String shortId, List<String> bodyAbsenceMarkers,
|
||||
Map<String, Object> summary) {}
|
||||
private record MethodSnapshot(MethodNode methodNode, String name, String rawName, String shortId,
|
||||
int overloadIndex, List<String> bodyAbsenceMarkers, Map<String, Object> summary) {}
|
||||
private record ClassSnapshot(JavaClass node, List<MethodSnapshot> methods, Map<String, Object> summary,
|
||||
Map<String, Object> summaryWithValues) {}
|
||||
private record ManifestSnapshot(String text, Map<String, Object> summary) {}
|
||||
private record ExternalMethod(MethodInfo info, Map<String, Object> summary) {}
|
||||
private record ExternalCallerTarget(ClassSnapshot owner, MethodSnapshot method) {}
|
||||
private record ExternalInventory(JadxSession session, String className, String methodName,
|
||||
List<ExternalMethod> methods) {}
|
||||
List<ExternalMethod> methods, Map<String, List<ExternalCallerTarget>> callersByShortId) {}
|
||||
|
||||
private static final class InputFailure extends IllegalArgumentException {
|
||||
final String field;
|
||||
@@ -199,6 +202,9 @@ class ReaJadxBridge {
|
||||
}
|
||||
|
||||
private void clearManifest() {
|
||||
indexedSession = null;
|
||||
classes = Map.of();
|
||||
orderedClasses = List.of();
|
||||
manifestSession = null;
|
||||
manifestSnapshot = null;
|
||||
externalInventory = null;
|
||||
@@ -338,7 +344,13 @@ class ReaJadxBridge {
|
||||
|
||||
/** Match Android's standard root multidex carriers, without a basename guess. */
|
||||
private static boolean nativeDexEntry(String name) {
|
||||
return name.equals("classes.dex") || name.matches("classes[0-9]+\\.dex");
|
||||
if (name.equals("classes.dex")) return true;
|
||||
if (!name.startsWith("classes") || !name.endsWith(".dex") || name.length() <= 11) return false;
|
||||
for (int i = 7; i < name.length() - 4; i++) {
|
||||
char c = name.charAt(i);
|
||||
if (c < '0' || c > '9') return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static byte[] readNativeDex(ZipFile archive, ZipEntry entry) throws IOException {
|
||||
@@ -372,34 +384,38 @@ class ReaJadxBridge {
|
||||
|
||||
/** Raw DEX ownership precedes JADX's duplicate-class selection and aliases. */
|
||||
static Map<String, Object> nativeDeclarations(Path apk) {
|
||||
record DexZipEntry(ZipEntry entry, int entryIndex) {}
|
||||
NativeInventory inventory = new NativeInventory();
|
||||
try (ZipFile archive = new ZipFile(apk.toFile())) {
|
||||
Map<String, Integer> names = new HashMap<>();
|
||||
List<DexZipEntry> dexEntries = new ArrayList<>();
|
||||
int manifests = 0;
|
||||
int nextEntryIndex = 0;
|
||||
var directory = archive.entries();
|
||||
while (directory.hasMoreElements()) {
|
||||
checkNativeInterrupted();
|
||||
ZipEntry entry = directory.nextElement();
|
||||
if (!entry.isDirectory() && nativeDexEntry(entry.getName())) {
|
||||
int entryIndex = nextEntryIndex++;
|
||||
if (entry.isDirectory()) continue;
|
||||
String entryName = entry.getName();
|
||||
if (nativeDexEntry(entryName)) {
|
||||
inventory.dexEntries++;
|
||||
names.merge(entry.getName(), 1, Integer::sum);
|
||||
names.merge(entryName, 1, Integer::sum);
|
||||
dexEntries.add(new DexZipEntry(entry, entryIndex));
|
||||
} else if (entryName.equals("AndroidManifest.xml")) {
|
||||
manifests++;
|
||||
}
|
||||
if (!entry.isDirectory() && entry.getName().equals("AndroidManifest.xml"))
|
||||
names.merge(entry.getName(), 1, Integer::sum);
|
||||
}
|
||||
// Before any early return, so every result states whether splits hold code.
|
||||
inventory.manifestSplits = manifestSplitRequirements(archive,
|
||||
names.getOrDefault("AndroidManifest.xml", 0));
|
||||
inventory.manifestSplits = manifestSplitRequirements(archive, manifests);
|
||||
// Split facts share the retained JSON allowance; escaping is at most 6x.
|
||||
inventory.retainedBytes += 64L + 6L * inventory.manifestSplits.toString().length();
|
||||
long totalBytes = 0;
|
||||
int entryIndex = -1;
|
||||
directory = archive.entries();
|
||||
while (directory.hasMoreElements()) {
|
||||
for (DexZipEntry item : dexEntries) {
|
||||
checkNativeInterrupted();
|
||||
ZipEntry entry = directory.nextElement();
|
||||
entryIndex++;
|
||||
ZipEntry entry = item.entry();
|
||||
int entryIndex = item.entryIndex();
|
||||
String path = entry.getName();
|
||||
if (entry.isDirectory() || !nativeDexEntry(path)) continue;
|
||||
if (names.get(path) != 1) {
|
||||
inventory.unknown("Duplicate root DEX entry name cannot be selected uniquely by the ZIP reader: " + path);
|
||||
continue;
|
||||
@@ -419,14 +435,17 @@ class ReaJadxBridge {
|
||||
String type = cls.getType();
|
||||
if (!type.startsWith("L") || !type.endsWith(";"))
|
||||
throw new IllegalArgumentException("Class definition has no reference type");
|
||||
String className = type.substring(1, type.length() - 1).replace('/', '.');
|
||||
String className = null;
|
||||
// Passing false retains duplicate encoded method references too.
|
||||
for (Iterable<? extends DexBackedMethod> group : List.of(
|
||||
cls.getDirectMethods(false), cls.getVirtualMethods(false))) {
|
||||
for (int pass = 0; pass < 2; pass++) {
|
||||
Iterable<? extends DexBackedMethod> group =
|
||||
pass == 0 ? cls.getDirectMethods(false) : cls.getVirtualMethods(false);
|
||||
for (DexBackedMethod method : group) {
|
||||
checkNativeInterrupted();
|
||||
inventory.examinedMethods++;
|
||||
if ((method.getAccessFlags() & 0x100) == 0) continue;
|
||||
if (className == null)
|
||||
className = type.substring(1, type.length() - 1).replace('/', '.');
|
||||
String methodName = method.getName();
|
||||
String returnType = method.getReturnType();
|
||||
long characters = 2L + returnType.length();
|
||||
@@ -505,18 +524,27 @@ class ReaJadxBridge {
|
||||
}
|
||||
}
|
||||
|
||||
private static final ThreadLocal<DocumentBuilderFactory> MANIFEST_XML_FACTORIES =
|
||||
ThreadLocal.withInitial(() -> {
|
||||
try {
|
||||
// Match REA's existing JDK XML setup: document types are unsupported.
|
||||
// Parse an in-memory string; XInclude and external DTD/schema I/O stay disabled.
|
||||
DocumentBuilderFactory factory = DocumentBuilderFactory.newDefaultNSInstance();
|
||||
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
|
||||
factory.setXIncludeAware(false);
|
||||
factory.setAttribute(javax.xml.XMLConstants.ACCESS_EXTERNAL_DTD, "");
|
||||
factory.setAttribute(javax.xml.XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
|
||||
return factory;
|
||||
} catch (javax.xml.parsers.ParserConfigurationException failure) {
|
||||
throw new IllegalStateException("Root AndroidManifest.xml XML parser factory is unsupported", failure);
|
||||
}
|
||||
});
|
||||
|
||||
/** One namespace-aware XML owner for the decoded manifest text. */
|
||||
static Element manifestRoot(String xml) {
|
||||
Element root;
|
||||
try {
|
||||
// Match REA's existing JDK XML setup: document types are unsupported.
|
||||
// Parse an in-memory string; XInclude and external DTD/schema I/O stay disabled.
|
||||
DocumentBuilderFactory factory = DocumentBuilderFactory.newDefaultNSInstance();
|
||||
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
|
||||
factory.setXIncludeAware(false);
|
||||
factory.setAttribute(javax.xml.XMLConstants.ACCESS_EXTERNAL_DTD, "");
|
||||
factory.setAttribute(javax.xml.XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
|
||||
root = factory.newDocumentBuilder().parse(new InputSource(new StringReader(xml)))
|
||||
root = MANIFEST_XML_FACTORIES.get().newDocumentBuilder().parse(new InputSource(new StringReader(xml)))
|
||||
.getDocumentElement();
|
||||
} catch (javax.xml.parsers.ParserConfigurationException | org.xml.sax.SAXException
|
||||
| java.io.IOException failure) {
|
||||
@@ -560,76 +588,143 @@ class ReaJadxBridge {
|
||||
JadxSession current = session();
|
||||
if (indexedSession != current) {
|
||||
Map<String, List<ClassSnapshot>> index = new LinkedHashMap<>();
|
||||
List<ClassSnapshot> orderedList = List.of();
|
||||
if (!current.getClasses().isEmpty()) {
|
||||
JadxDecompiler decompiler = current.getClasses().get(0).getClassNode().root().getDecompiler();
|
||||
List<JavaClass> rawClasses = decompiler.getClassesWithInners();
|
||||
index = new LinkedHashMap<>(rawClasses.size() * 2);
|
||||
orderedList = new ArrayList<>(rawClasses.size());
|
||||
// JavaClass.getMethods/getFields/getInnerClasses all load code. Raw nodes do not.
|
||||
// Snapshot every identity before code generation can rewrite aliases or members.
|
||||
for (JavaClass cls : decompiler.getClassesWithInners()) {
|
||||
for (JavaClass cls : rawClasses) {
|
||||
ClassNode node = cls.getClassNode();
|
||||
List<MethodNode> ordered = new ArrayList<>(node.getMethods());
|
||||
ordered.sort(Comparator.comparing(MethodNode::getAlias));
|
||||
List<MethodSnapshot> methods = ordered.stream().map(method -> {
|
||||
String name = method.getAlias();
|
||||
String shortId = method.getMethodInfo().getShortId();
|
||||
String rawName = method.getMethodInfo().getName();
|
||||
if (!shortId.startsWith(rawName + "("))
|
||||
throw new IllegalStateException("JADX method ID has no raw-name prefix: " + shortId);
|
||||
String descriptor = shortId.substring(rawName.length());
|
||||
List<String> bodyAbsenceMarkers = new ArrayList<>();
|
||||
if (method.getAccessFlags().isNative()) bodyAbsenceMarkers.add("native_method");
|
||||
if (method.getAccessFlags().isAbstract()) bodyAbsenceMarkers.add("abstract_method");
|
||||
String signature = name + "(" + method.getArgTypes().stream()
|
||||
.map(Object::toString).collect(Collectors.joining(", "))
|
||||
+ "): " + method.getReturnType().toString();
|
||||
return new MethodSnapshot(name, rawName, shortId, List.copyOf(bodyAbsenceMarkers), Map.of(
|
||||
"name", name, "raw_name", rawName, "signature", signature,
|
||||
"dex_descriptor", descriptor,
|
||||
"is_constructor", method.isConstructor(), "def_pos", 0));
|
||||
}).toList();
|
||||
List<FieldNode> orderedFields = new ArrayList<>(node.getFields());
|
||||
orderedFields.sort(Comparator.comparing(FieldNode::getAlias));
|
||||
List<Map<String, Object>> fields = new ArrayList<>();
|
||||
List<Map<String, Object>> valuedFields = new ArrayList<>();
|
||||
boolean anyValue = false;
|
||||
for (FieldNode field : orderedFields) {
|
||||
// Raw DEX identity for mapping lookups; the display type can carry generics.
|
||||
Map<String, Object> entry = Map.of("name", field.getAlias(),
|
||||
"raw_name", field.getFieldInfo().getName(),
|
||||
"type", field.getType().toString(),
|
||||
"dex_type", TypeGen.signature(field.getFieldInfo().getType()), "def_pos", 0);
|
||||
fields.add(entry);
|
||||
Map<String, Object> value = dexStaticValue(field);
|
||||
if (value == null) valuedFields.add(entry);
|
||||
else {
|
||||
anyValue = true;
|
||||
Map<String, Object> valued = new LinkedHashMap<>(entry);
|
||||
valued.put("dex_static_value", value);
|
||||
valuedFields.add(Collections.unmodifiableMap(valued));
|
||||
List<MethodNode> rawMethods = node.getMethods();
|
||||
List<MethodSnapshot> methods;
|
||||
List<Map<String, Object>> methodSummaries;
|
||||
if (rawMethods.isEmpty()) {
|
||||
methods = List.of();
|
||||
methodSummaries = List.of();
|
||||
} else {
|
||||
List<MethodNode> ordered = new ArrayList<>(rawMethods);
|
||||
if (ordered.size() > 1) ordered.sort(Comparator.comparing(MethodNode::getAlias));
|
||||
methods = new ArrayList<>(ordered.size());
|
||||
methodSummaries = new ArrayList<>(ordered.size());
|
||||
String prevName = null;
|
||||
int overloadIndex = 0;
|
||||
for (MethodNode method : ordered) {
|
||||
String name = method.getAlias();
|
||||
overloadIndex = name.equals(prevName) ? overloadIndex + 1 : 0;
|
||||
prevName = name;
|
||||
String shortId = method.getMethodInfo().getShortId();
|
||||
String rawName = method.getMethodInfo().getName();
|
||||
if (!shortId.startsWith(rawName + "("))
|
||||
throw new IllegalStateException("JADX method ID has no raw-name prefix: " + shortId);
|
||||
String descriptor = shortId.substring(rawName.length());
|
||||
boolean isNative = method.getAccessFlags().isNative();
|
||||
boolean isAbstract = method.getAccessFlags().isAbstract();
|
||||
List<String> bodyAbsenceMarkers;
|
||||
if (isNative && isAbstract) bodyAbsenceMarkers = List.of("native_method", "abstract_method");
|
||||
else if (isNative) bodyAbsenceMarkers = List.of("native_method");
|
||||
else if (isAbstract) bodyAbsenceMarkers = List.of("abstract_method");
|
||||
else bodyAbsenceMarkers = List.of();
|
||||
List<ArgType> argTypes = method.getArgTypes();
|
||||
String signature;
|
||||
if (argTypes.isEmpty()) {
|
||||
signature = name + "(): " + method.getReturnType().toString();
|
||||
} else {
|
||||
StringBuilder sigBuilder = new StringBuilder(name.length() + 32);
|
||||
sigBuilder.append(name).append('(');
|
||||
for (int i = 0; i < argTypes.size(); i++) {
|
||||
if (i > 0) sigBuilder.append(", ");
|
||||
sigBuilder.append(argTypes.get(i).toString());
|
||||
}
|
||||
sigBuilder.append("): ").append(method.getReturnType().toString());
|
||||
signature = sigBuilder.toString();
|
||||
}
|
||||
Map<String, Object> methodSummary = Map.of(
|
||||
"name", name, "raw_name", rawName, "signature", signature,
|
||||
"dex_descriptor", descriptor,
|
||||
"is_constructor", method.isConstructor(), "def_pos", 0);
|
||||
methods.add(new MethodSnapshot(method, name, rawName, shortId, overloadIndex,
|
||||
bodyAbsenceMarkers, methodSummary));
|
||||
methodSummaries.add(methodSummary);
|
||||
}
|
||||
methods = Collections.unmodifiableList(methods);
|
||||
methodSummaries = Collections.unmodifiableList(methodSummaries);
|
||||
}
|
||||
List<FieldNode> rawFields = node.getFields();
|
||||
List<Map<String, Object>> fields;
|
||||
List<Map<String, Object>> valuedFieldsList = null;
|
||||
if (rawFields.isEmpty()) {
|
||||
fields = List.of();
|
||||
} else {
|
||||
List<FieldNode> orderedFields = new ArrayList<>(rawFields);
|
||||
if (orderedFields.size() > 1) orderedFields.sort(Comparator.comparing(FieldNode::getAlias));
|
||||
fields = new ArrayList<>(orderedFields.size());
|
||||
for (int i = 0; i < orderedFields.size(); i++) {
|
||||
FieldNode field = orderedFields.get(i);
|
||||
// Raw DEX identity for mapping lookups; the display type can carry generics.
|
||||
Map<String, Object> entry = Map.of("name", field.getAlias(),
|
||||
"raw_name", field.getFieldInfo().getName(),
|
||||
"type", field.getType().toString(),
|
||||
"dex_type", TypeGen.signature(field.getFieldInfo().getType()), "def_pos", 0);
|
||||
fields.add(entry);
|
||||
Map<String, Object> value = dexStaticValue(field);
|
||||
if (value != null) {
|
||||
if (valuedFieldsList == null) {
|
||||
valuedFieldsList = new ArrayList<>(orderedFields.size());
|
||||
for (int j = 0; j < i; j++) valuedFieldsList.add(fields.get(j));
|
||||
}
|
||||
Map<String, Object> valued = new LinkedHashMap<>(entry);
|
||||
valued.put("dex_static_value", value);
|
||||
valuedFieldsList.add(Collections.unmodifiableMap(valued));
|
||||
} else if (valuedFieldsList != null) {
|
||||
valuedFieldsList.add(entry);
|
||||
}
|
||||
}
|
||||
fields = Collections.unmodifiableList(fields);
|
||||
}
|
||||
List<ClassNode> rawInners = node.getInnerClasses();
|
||||
List<String> inner;
|
||||
List<String> innerRaw;
|
||||
if (rawInners.isEmpty()) {
|
||||
inner = List.of();
|
||||
innerRaw = List.of();
|
||||
} else {
|
||||
List<String> innerList = new ArrayList<>(rawInners.size());
|
||||
List<String> innerRawList = new ArrayList<>(rawInners.size());
|
||||
for (ClassNode innerNode : rawInners) {
|
||||
innerList.add(innerNode.getFullName());
|
||||
innerRawList.add(innerNode.getRawName());
|
||||
}
|
||||
inner = Collections.unmodifiableList(innerList);
|
||||
innerRaw = Collections.unmodifiableList(innerRawList);
|
||||
}
|
||||
List<String> inner = node.getInnerClasses().stream().map(ClassNode::getFullName).toList();
|
||||
List<String> innerRaw = node.getInnerClasses().stream().map(ClassNode::getRawName).toList();
|
||||
Map<String, Object> summary = Map.of(
|
||||
"full_name", cls.getFullName(), "raw_name", cls.getRawName(), "name", cls.getName(),
|
||||
"method_count", methods.size(), "field_count", fields.size(),
|
||||
"inner_class_count", inner.size(), "inner_classes", inner, "inner_class_raw_names", innerRaw,
|
||||
"methods", methods.stream().map(MethodSnapshot::summary).toList(), "fields", List.copyOf(fields));
|
||||
"methods", methodSummaries, "fields", fields);
|
||||
// DEX static values are opt-in, so method and reference lookups keep the member-only reply.
|
||||
Map<String, Object> summaryWithValues = summary;
|
||||
if (anyValue) {
|
||||
if (valuedFieldsList != null) {
|
||||
Map<String, Object> copy = new LinkedHashMap<>(summary);
|
||||
copy.put("fields", List.copyOf(valuedFields));
|
||||
copy.put("fields", Collections.unmodifiableList(valuedFieldsList));
|
||||
summaryWithValues = Collections.unmodifiableMap(copy);
|
||||
}
|
||||
ClassSnapshot snapshot = new ClassSnapshot(cls, methods, summary, summaryWithValues);
|
||||
index.computeIfAbsent(cls.getFullName(), ignored -> new ArrayList<>()).add(snapshot);
|
||||
orderedList.add(snapshot);
|
||||
index.computeIfAbsent(cls.getFullName(), ignored -> new ArrayList<>(1)).add(snapshot);
|
||||
// Keep the binary identity supplied by JADX; '$' can also be a literal
|
||||
// name character, so replacing separators would invent lookup aliases.
|
||||
if (!cls.getRawName().equals(cls.getFullName()))
|
||||
index.computeIfAbsent(cls.getRawName(), ignored -> new ArrayList<>()).add(snapshot);
|
||||
index.computeIfAbsent(cls.getRawName(), ignored -> new ArrayList<>(1)).add(snapshot);
|
||||
}
|
||||
if (orderedList.size() > 1)
|
||||
orderedList.sort(Comparator.comparing(source -> source.node().getRawName()));
|
||||
}
|
||||
classes = Collections.unmodifiableMap(index);
|
||||
orderedClasses = Collections.unmodifiableList(orderedList);
|
||||
indexedSession = current;
|
||||
}
|
||||
}
|
||||
@@ -676,8 +771,9 @@ class ReaJadxBridge {
|
||||
}
|
||||
|
||||
private JavaMethod method(ClassSnapshot cls, MethodSnapshot selected) {
|
||||
JavaMethod result = cls.node().searchMethodByShortId(selected.shortId());
|
||||
if (result == null) throw new IllegalArgumentException("Method identity no longer available: " + selected.shortId());
|
||||
JavaNode resolved = cls.node().getClassNode().root().getDecompiler().getJavaNodeByRef(selected.methodNode());
|
||||
if (!(resolved instanceof JavaMethod result))
|
||||
throw new IllegalArgumentException("Method identity no longer available: " + selected.shortId());
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -750,12 +846,62 @@ class ReaJadxBridge {
|
||||
private static int escapedJsonBytes(Object value) {
|
||||
return JSON.toJson(JSON.toJson(value)).getBytes(StandardCharsets.UTF_8).length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Exact UTF-8 byte length of a string's characters after Gson htmlSafe=true
|
||||
* serialization wrapped inside an outer Gson JSON string (excluding quotes).
|
||||
*/
|
||||
static long doubleEscapedStringBytes(String text) {
|
||||
long bytes = 0;
|
||||
int length = text.length();
|
||||
for (int i = 0; i < length; i++) {
|
||||
char c = text.charAt(i);
|
||||
if (c < 0x80) {
|
||||
if (c == '"' || c == '\\') bytes += 4;
|
||||
else if (c == '\b' || c == '\t' || c == '\n' || c == '\f' || c == '\r') bytes += 3;
|
||||
else if (c < 0x20 || c == '<' || c == '>' || c == '&' || c == '=' || c == '\'') bytes += 7;
|
||||
else bytes += 1;
|
||||
} else if (c < 0x800) {
|
||||
bytes += 2;
|
||||
} else if (c == '\u2028' || c == '\u2029') {
|
||||
bytes += 7;
|
||||
} else if (Character.isHighSurrogate(c) && i + 1 < length && Character.isLowSurrogate(text.charAt(i + 1))) {
|
||||
bytes += 4;
|
||||
i++;
|
||||
} else if (Character.isSurrogate(c)) {
|
||||
bytes += 1;
|
||||
} else {
|
||||
bytes += 3;
|
||||
}
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
private static int intDigits(int value) {
|
||||
if (value < 0) return value == Integer.MIN_VALUE ? 11 : 1 + intDigits(-value);
|
||||
if (value < 10) return 1;
|
||||
if (value < 100) return 2;
|
||||
if (value < 1000) return 3;
|
||||
if (value < 10000) return 4;
|
||||
if (value < 100000) return 5;
|
||||
if (value < 1000000) return 6;
|
||||
if (value < 10000000) return 7;
|
||||
if (value < 100000000) return 8;
|
||||
if (value < 1000000000) return 9;
|
||||
return 10;
|
||||
}
|
||||
|
||||
private static final class InvokeBudget {
|
||||
long remaining;
|
||||
InvokeBudget(long remaining) { this.remaining = Math.max(0, remaining); }
|
||||
boolean fitsText(long characters) {
|
||||
return remaining >= 256 && characters <= (remaining - 256) / 12;
|
||||
}
|
||||
boolean admitBytes(long bytes) {
|
||||
if (bytes > remaining) return false;
|
||||
remaining -= bytes;
|
||||
return true;
|
||||
}
|
||||
boolean admit(Map<String, Object> site) {
|
||||
// Check a conservative two-layer escape bound before serialization.
|
||||
long bound = 256;
|
||||
@@ -774,6 +920,15 @@ class ReaJadxBridge {
|
||||
void accept(MethodInfo target, int offset, int index, Opcode opcode);
|
||||
}
|
||||
|
||||
private static final boolean[] INVOKE_OPCODES;
|
||||
static {
|
||||
Opcode[] values = Opcode.values();
|
||||
INVOKE_OPCODES = new boolean[values.length];
|
||||
for (Opcode opcode : values) {
|
||||
if (opcode.name().startsWith("INVOKE_")) INVOKE_OPCODES[opcode.ordinal()] = true;
|
||||
}
|
||||
}
|
||||
|
||||
/** Decode raw invoke identity once at the shared bridge boundary, without generating source. */
|
||||
private static void visitInvokes(MethodNode node, InvokeVisitor visitor) {
|
||||
checkNativeInterrupted();
|
||||
@@ -781,12 +936,10 @@ class ReaJadxBridge {
|
||||
if (code == null) return;
|
||||
code.visitInstructions(insn -> {
|
||||
checkNativeInterrupted();
|
||||
insn.decode();
|
||||
if (insn.getIndexType() != InsnIndexType.METHOD_REF) return;
|
||||
Opcode opcode = insn.getOpcode();
|
||||
if (!opcode.name().startsWith("INVOKE_")) return;
|
||||
if (!INVOKE_OPCODES[opcode.ordinal()] || insn.getIndexType() != InsnIndexType.METHOD_REF) return;
|
||||
insn.decode();
|
||||
IMethodRef ref = insn.getIndexAsMethod();
|
||||
ref.load();
|
||||
visitor.accept(MethodInfo.fromRef(node.root(), ref), insn.getOffset(), insn.getIndex(), opcode);
|
||||
});
|
||||
}
|
||||
@@ -797,43 +950,41 @@ class ReaJadxBridge {
|
||||
}
|
||||
|
||||
private static void visitDirectInvokes(MethodNode node, MethodInfo target, InvokeVisitor visitor) {
|
||||
String targetRawFullId = target.getRawFullId();
|
||||
visitInvokes(node, (referenced, offset, index, opcode) -> {
|
||||
if (referenced.getRawFullId().equals(target.getRawFullId()))
|
||||
if (referenced.getRawFullId().equals(targetRawFullId))
|
||||
visitor.accept(referenced, offset, index, opcode);
|
||||
});
|
||||
}
|
||||
|
||||
private static boolean referencesMethod(MethodNode node, MethodInfo target) {
|
||||
boolean[] found = {false};
|
||||
visitDirectInvokes(node, target, (referenced, offset, index, opcode) -> found[0] = true);
|
||||
return found[0];
|
||||
}
|
||||
|
||||
private static DirectInvokes directInvokes(MethodNode node, MethodInfo target, InvokeBudget budget) {
|
||||
if (node.getCodeReader() == null) return null;
|
||||
List<Map<String, Object>> sites = new ArrayList<>();
|
||||
boolean[] exhaustive = {true};
|
||||
String dexEntry = node.getInputFileName();
|
||||
String sourceRawMethodId = node.getMethodInfo().getRawFullId();
|
||||
// 5 ASCII keys/quotes/colons (96) + 3 value quote pairs (12) + braces/commas (6) + 1 separator = 115.
|
||||
long fixedBytes = 115L + doubleEscapedStringBytes(dexEntry) + doubleEscapedStringBytes(sourceRawMethodId);
|
||||
visitDirectInvokes(node, target, (referenced, offset, index, opcode) -> {
|
||||
Map<String, Object> site = Map.of(
|
||||
"dex_entry", node.getInputFileName(),
|
||||
"source_raw_method_id", node.getMethodInfo().getRawFullId(),
|
||||
"dex_code_unit_offset", offset,
|
||||
"dex_method_index", index,
|
||||
"opcode", opcode.name());
|
||||
if (budget.admit(site)) sites.add(site);
|
||||
else exhaustive[0] = false;
|
||||
String opcodeName = opcode.name();
|
||||
long siteBytes = fixedBytes + opcodeName.length() + intDigits(offset) + intDigits(index);
|
||||
if (budget.admitBytes(siteBytes)) {
|
||||
sites.add(Map.of(
|
||||
"dex_entry", dexEntry,
|
||||
"source_raw_method_id", sourceRawMethodId,
|
||||
"dex_code_unit_offset", offset,
|
||||
"dex_method_index", index,
|
||||
"opcode", opcodeName));
|
||||
} else {
|
||||
exhaustive[0] = false;
|
||||
}
|
||||
});
|
||||
return new DirectInvokes(sites, exhaustive[0]);
|
||||
}
|
||||
|
||||
private List<ClassSnapshot> sourceClasses() {
|
||||
indexClasses();
|
||||
Set<ClassSnapshot> seen = Collections.newSetFromMap(new IdentityHashMap<>());
|
||||
List<ClassSnapshot> result = new ArrayList<>();
|
||||
for (List<ClassSnapshot> group : classes.values())
|
||||
for (ClassSnapshot source : group) if (seen.add(source)) result.add(source);
|
||||
result.sort(Comparator.comparing(source -> source.node().getRawName()));
|
||||
return result;
|
||||
return orderedClasses;
|
||||
}
|
||||
|
||||
private static long displayTypeCharacters(ArgType type) {
|
||||
@@ -848,15 +999,26 @@ class ReaJadxBridge {
|
||||
String name = info.getName();
|
||||
long signatureCharacters = name.length() + 4L + displayTypeCharacters(info.getReturnType())
|
||||
+ 2L * Math.max(0, info.getArgsCount() - 1);
|
||||
for (ArgType type : info.getArgumentsTypes()) signatureCharacters += displayTypeCharacters(type);
|
||||
List<ArgType> argTypes = info.getArgumentsTypes();
|
||||
for (ArgType type : argTypes) signatureCharacters += displayTypeCharacters(type);
|
||||
long descriptorCharacters = info.getShortId().length() - (long) name.length();
|
||||
// Use parsed type facts and the existing short-id length before copying/joining strings.
|
||||
if (!budget.fitsText(2L * name.length() + descriptorCharacters + signatureCharacters))
|
||||
throw new ReferenceLimit("method_inventory");
|
||||
String descriptor = info.getShortId().substring(name.length());
|
||||
String signature = name + "(" + info.getArgumentsTypes().stream()
|
||||
.map(Object::toString).collect(Collectors.joining(", "))
|
||||
+ "): " + info.getReturnType();
|
||||
String signature;
|
||||
if (argTypes.isEmpty()) {
|
||||
signature = name + "(): " + info.getReturnType();
|
||||
} else {
|
||||
StringBuilder sigBuilder = new StringBuilder((int) Math.min(signatureCharacters, 4096L));
|
||||
sigBuilder.append(name).append('(');
|
||||
for (int i = 0; i < argTypes.size(); i++) {
|
||||
if (i > 0) sigBuilder.append(", ");
|
||||
sigBuilder.append(argTypes.get(i).toString());
|
||||
}
|
||||
sigBuilder.append("): ").append(info.getReturnType());
|
||||
signature = sigBuilder.toString();
|
||||
}
|
||||
Map<String, Object> summary = Map.of("name", name, "raw_name", name, "signature", signature,
|
||||
"dex_descriptor", descriptor, "is_constructor", info.isConstructor(), "def_pos", 0);
|
||||
if (!budget.admit(summary)) throw new ReferenceLimit("method_inventory");
|
||||
@@ -874,16 +1036,47 @@ class ReaJadxBridge {
|
||||
// Retain only the latest bounded selection, never results from a replaced APK/session.
|
||||
externalInventory = null;
|
||||
SortedMap<String, ExternalMethod> methods = new TreeMap<>();
|
||||
Map<String, List<ExternalCallerTarget>> callersByShortId = new HashMap<>();
|
||||
int indexedCallerEntries = 0;
|
||||
boolean[] observedClass = {false};
|
||||
InvokeBudget budget = new InvokeBudget(MAX_EXTERNAL_XREF_BYTES
|
||||
- 4096L - 12L * (className.length() + (long) methodName.length()));
|
||||
final class MethodScanState {
|
||||
String firstShortId;
|
||||
Set<String> extraShortIds;
|
||||
boolean callersIndexed = true;
|
||||
int indexedEntries = 0;
|
||||
}
|
||||
MethodScanState scanState = new MethodScanState();
|
||||
for (ClassSnapshot source : sourceClasses()) {
|
||||
for (MethodSnapshot selected : source.methods()) {
|
||||
visitInvokes(method(source, selected).getMethodNode(), (info, offset, index, opcode) -> {
|
||||
scanState.firstShortId = null;
|
||||
if (scanState.extraShortIds != null) scanState.extraShortIds.clear();
|
||||
visitInvokes(selected.methodNode(), (info, offset, index, opcode) -> {
|
||||
if (!info.getDeclClass().getRawName().equals(className)) return;
|
||||
observedClass[0] = true;
|
||||
if (!info.getName().equals(methodName) || methods.containsKey(info.getShortId())) return;
|
||||
methods.put(info.getShortId(), new ExternalMethod(info, externalMethodSummary(info, budget)));
|
||||
if (!info.getName().equals(methodName)) return;
|
||||
String shortId = info.getShortId();
|
||||
if (!methods.containsKey(shortId))
|
||||
methods.put(shortId, new ExternalMethod(info, externalMethodSummary(info, budget)));
|
||||
if (!scanState.callersIndexed) return;
|
||||
boolean recordCaller = false;
|
||||
if (scanState.firstShortId == null) {
|
||||
scanState.firstShortId = shortId;
|
||||
recordCaller = true;
|
||||
} else if (!scanState.firstShortId.equals(shortId)) {
|
||||
if (scanState.extraShortIds == null) scanState.extraShortIds = new HashSet<>();
|
||||
recordCaller = scanState.extraShortIds.add(shortId);
|
||||
}
|
||||
if (!recordCaller) return;
|
||||
if (scanState.indexedEntries >= maxExternalCallerIndexEntries) {
|
||||
scanState.callersIndexed = false;
|
||||
callersByShortId.clear();
|
||||
return;
|
||||
}
|
||||
scanState.indexedEntries++;
|
||||
callersByShortId.computeIfAbsent(shortId, ignored -> new ArrayList<>())
|
||||
.add(new ExternalCallerTarget(source, selected));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -892,7 +1085,8 @@ class ReaJadxBridge {
|
||||
if (methods.isEmpty()) throw new InputFailure("method_name",
|
||||
"No direct DEX invoke references " + className + "." + methodName);
|
||||
List<ExternalMethod> result = List.copyOf(methods.values());
|
||||
externalInventory = new ExternalInventory(current, className, methodName, result);
|
||||
externalInventory = new ExternalInventory(current, className, methodName, result,
|
||||
scanState.callersIndexed ? Collections.unmodifiableMap(callersByShortId) : null);
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -905,26 +1099,37 @@ class ReaJadxBridge {
|
||||
|
||||
private record ExternalCaller(MethodNode node, Map<String, Object> row) {}
|
||||
|
||||
private void appendExternalCaller(ClassSnapshot source, MethodSnapshot candidate,
|
||||
InvokeBudget budget, List<ExternalCaller> callers) {
|
||||
String className = String.valueOf(source.summary().get("full_name"));
|
||||
if (classes.get(className).size() != 1)
|
||||
throw new IllegalArgumentException("External caller has an ambiguous APK class identity: " + className);
|
||||
Map<String, Object> row = new LinkedHashMap<>(Map.of(
|
||||
"kind", "method", "name", candidate.name(), "full_name", className + "." + candidate.name(),
|
||||
"containing_class", className, "top_class", source.node().getTopParentClass().getFullName(),
|
||||
"def_pos", 0, "source_selector", Map.of("class_name", className,
|
||||
"method_name", candidate.name(), "overload_index", candidate.overloadIndex()),
|
||||
"direct_invokes", List.of(), "direct_invokes_exhaustive", false));
|
||||
if (!budget.admit(row)) throw new ReferenceLimit("caller_inventory");
|
||||
callers.add(new ExternalCaller(candidate.methodNode(), row));
|
||||
}
|
||||
|
||||
/** Reserve the complete using-node inventory before optional instruction positions. */
|
||||
private List<ExternalCaller> externalCallers(MethodInfo target, InvokeBudget budget) {
|
||||
private List<ExternalCaller> externalCallers(ExternalInventory inventory, MethodInfo target, InvokeBudget budget) {
|
||||
Map<String, List<ExternalCallerTarget>> indexedCallers = inventory.callersByShortId();
|
||||
if (indexedCallers != null) {
|
||||
List<ExternalCallerTarget> targets = indexedCallers.getOrDefault(target.getShortId(), List.of());
|
||||
List<ExternalCaller> callers = new ArrayList<>(targets.size());
|
||||
for (ExternalCallerTarget callerTarget : targets)
|
||||
appendExternalCaller(callerTarget.owner(), callerTarget.method(), budget, callers);
|
||||
return List.copyOf(callers);
|
||||
}
|
||||
List<ExternalCaller> callers = new ArrayList<>();
|
||||
for (ClassSnapshot source : sourceClasses()) {
|
||||
String className = String.valueOf(source.summary().get("full_name"));
|
||||
Map<String, Integer> overloads = new HashMap<>();
|
||||
for (MethodSnapshot candidate : source.methods()) {
|
||||
int overload = overloads.merge(candidate.name(), 1, Integer::sum) - 1;
|
||||
MethodNode node = method(source, candidate).getMethodNode();
|
||||
if (!referencesMethod(node, target)) continue;
|
||||
if (classes.get(className).size() != 1)
|
||||
throw new IllegalArgumentException("External caller has an ambiguous APK class identity: " + className);
|
||||
Map<String, Object> row = new LinkedHashMap<>(Map.of(
|
||||
"kind", "method", "name", candidate.name(), "full_name", className + "." + candidate.name(),
|
||||
"containing_class", className, "top_class", source.node().getTopParentClass().getFullName(),
|
||||
"def_pos", 0, "source_selector", Map.of("class_name", className,
|
||||
"method_name", candidate.name(), "overload_index", overload),
|
||||
"direct_invokes", List.of(), "direct_invokes_exhaustive", false));
|
||||
if (!budget.admit(row)) throw new ReferenceLimit("caller_inventory");
|
||||
callers.add(new ExternalCaller(node, row));
|
||||
boolean[] invokes = {false};
|
||||
visitDirectInvokes(candidate.methodNode(), target, (referenced, offset, index, opcode) -> invokes[0] = true);
|
||||
if (invokes[0]) appendExternalCaller(source, candidate, budget, callers);
|
||||
}
|
||||
}
|
||||
return List.copyOf(callers);
|
||||
@@ -941,7 +1146,7 @@ class ReaJadxBridge {
|
||||
Map<String, Object> selected = method.summary();
|
||||
InvokeBudget budget = new InvokeBudget(MAX_EXTERNAL_XREF_BYTES
|
||||
- 4096L - escapedJsonBytes(selected));
|
||||
List<ExternalCaller> callers = externalCallers(target, budget);
|
||||
List<ExternalCaller> callers = externalCallers(externalInventory, target, budget);
|
||||
List<Map<String, Object>> items = new ArrayList<>();
|
||||
for (ExternalCaller caller : callers) {
|
||||
DirectInvokes invokes = directInvokes(caller.node(), target, budget);
|
||||
|
||||
@@ -316,7 +316,8 @@ const searchClasses = async (
|
||||
page.items.length > page.next_offset - offset ||
|
||||
(request.input.query === "" &&
|
||||
page.items.length !== page.next_offset - offset) ||
|
||||
page.items.some((name) => !name.includes(request.input.query))
|
||||
(request.input.query !== "" &&
|
||||
page.items.some((name) => !name.includes(request.input.query)))
|
||||
)
|
||||
throw new AnalysisOutputError(
|
||||
request.operation,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { z } from "zod";
|
||||
import { AnalysisOutputError } from "../domain/analysisErrorCore.js";
|
||||
import { parseJsonWithDuplicatePolicy } from "../domain/jsonDuplicateMember.js";
|
||||
import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
|
||||
import { ownedJsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
|
||||
import type { AndroidOperation } from "../domain/android/androidAnalysis.js";
|
||||
import {
|
||||
androidMethodSelectorSchema,
|
||||
@@ -92,7 +92,7 @@ const jadxClassPageSchema = z
|
||||
limit: count,
|
||||
items: z.array(z.string()),
|
||||
})
|
||||
.catchall(jsonValueSchema);
|
||||
.catchall(ownedJsonValueSchema);
|
||||
export type JadxClassPage = z.infer<typeof jadxClassPageSchema>;
|
||||
|
||||
/** Validate a decoded page without dropping observed JSON members such as __proto__. */
|
||||
@@ -211,11 +211,11 @@ const toolResponse = z
|
||||
content: z.tuple([
|
||||
z
|
||||
.object({ type: z.literal("text"), text: z.string() })
|
||||
.catchall(jsonValueSchema),
|
||||
.catchall(ownedJsonValueSchema),
|
||||
]),
|
||||
isError: z.boolean().exactOptional(),
|
||||
})
|
||||
.catchall(jsonValueSchema);
|
||||
.catchall(ownedJsonValueSchema);
|
||||
|
||||
/** Parse the upstream text-only envelope, preserving errors at the producing boundary. */
|
||||
export const parseJadxEnvelope = (
|
||||
@@ -236,7 +236,7 @@ export const parseJadxEnvelope = (
|
||||
export const parseJadxJson = (
|
||||
text: string,
|
||||
operation: AndroidOperation,
|
||||
): z.infer<typeof jsonValueSchema> => {
|
||||
): z.infer<typeof ownedJsonValueSchema> => {
|
||||
const decoded = parseJsonWithDuplicatePolicy(text, "reject");
|
||||
if (!decoded.ok) {
|
||||
if (decoded.duplicate !== undefined)
|
||||
@@ -251,7 +251,7 @@ export const parseJadxJson = (
|
||||
);
|
||||
}
|
||||
try {
|
||||
return jsonValueSchema.parse(decoded.value);
|
||||
return ownedJsonValueSchema.parse(decoded.value);
|
||||
} catch (cause) {
|
||||
throw new AnalysisOutputError(
|
||||
operation,
|
||||
|
||||
@@ -19,8 +19,8 @@ import {
|
||||
} from "../domain/analysisErrorCore.js";
|
||||
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
|
||||
import {
|
||||
jsonObjectSchema,
|
||||
jsonValueSchema,
|
||||
ownedJsonObjectSchema,
|
||||
ownedJsonValueSchema,
|
||||
type JsonValue,
|
||||
} from "../domain/jsonValue.js";
|
||||
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
|
||||
@@ -73,6 +73,7 @@ export class JadxSession {
|
||||
version: "1",
|
||||
});
|
||||
#loaded: ReturnType<typeof jadxLoadSchema.parse> | undefined;
|
||||
#runtime: ReturnType<typeof jadxRuntimeSchema.parse> | undefined;
|
||||
#connected = false;
|
||||
#partialContext:
|
||||
| {
|
||||
@@ -178,9 +179,9 @@ export class JadxSession {
|
||||
`Expected ${expected.name} ${expected.version}; server reported ${server?.name ?? "unknown"} ${server?.version ?? "unknown"}.`,
|
||||
);
|
||||
const tools = this.#tools(request, target, signal, timeoutMs);
|
||||
const runtime = jadxRuntimeSchema.parse(
|
||||
await tools.json("rea_jvm_status", {}),
|
||||
);
|
||||
const runtime =
|
||||
this.#runtime ??
|
||||
jadxRuntimeSchema.parse(await tools.json("rea_jvm_status", {}));
|
||||
this.#engineVersion = runtime.engine_reported_version;
|
||||
if (runtime.engine_reported_version !== JADX_RELEASE.version)
|
||||
throw new AnalysisCapabilityUnavailableError(
|
||||
@@ -188,6 +189,7 @@ export class JadxSession {
|
||||
request.operation,
|
||||
`Expected engine ${JADX_RELEASE.version}; JAR reported ${runtime.engine_reported_version}.`,
|
||||
);
|
||||
this.#runtime = runtime;
|
||||
const loaded =
|
||||
request.operation === "inspect_android_jni_bindings"
|
||||
? undefined
|
||||
@@ -281,7 +283,7 @@ export class JadxSession {
|
||||
},
|
||||
}),
|
||||
});
|
||||
const raw = jsonObjectSchema.parse({
|
||||
const raw = ownedJsonObjectSchema.parse({
|
||||
server,
|
||||
bridge_sha256: context.bridgeHash,
|
||||
jar_sha256: jarHash,
|
||||
@@ -381,7 +383,7 @@ export class JadxSession {
|
||||
{ name, arguments: input },
|
||||
{ timeout: timeoutMs, signal },
|
||||
);
|
||||
const observedResponse = jsonValueSchema.parse(response);
|
||||
const observedResponse = ownedJsonValueSchema.parse(response);
|
||||
const call = { operation: name, input, response: observedResponse };
|
||||
const observation: JadxCallObservation = { complete: call };
|
||||
this.#observedCalls.push(observation);
|
||||
|
||||
@@ -3,7 +3,12 @@ import { localPathStringSchema } from "../domain/localPath.js";
|
||||
import type { AsarHeaderAdmission } from "../config/asarHeaderAdmission.js";
|
||||
import { artifactIntegrityDetails } from "../domain/artifactIntegrity.js";
|
||||
import { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import { constants, createWriteStream, type Stats } from "node:fs";
|
||||
import {
|
||||
assertStableRegularFileIdentity,
|
||||
RegularFileChangedError,
|
||||
type StableRegularFileDescriptor,
|
||||
} from "../filesystem/RegularFile.js";
|
||||
import { constants, type Stats } from "node:fs";
|
||||
import {
|
||||
lstat,
|
||||
mkdtemp,
|
||||
@@ -15,8 +20,7 @@ import {
|
||||
import { tmpdir } from "node:os";
|
||||
import { createHash } from "node:crypto";
|
||||
import { isAbsolute, join, relative, sep } from "node:path";
|
||||
import { Readable, Transform } from "node:stream";
|
||||
import { pipeline } from "node:stream/promises";
|
||||
import { Readable } from "node:stream";
|
||||
|
||||
import {
|
||||
ArtifactEntryContentUnavailable,
|
||||
@@ -32,7 +36,10 @@ import {
|
||||
readAsarHeader,
|
||||
type AsarHeaderExtents,
|
||||
} from "../resources/index.js";
|
||||
import { closeAsarHandle, readValidatedAsarEntry } from "./AsarEntryStream.js";
|
||||
import {
|
||||
readValidatedAsarEntry,
|
||||
readValidatedAsarRange,
|
||||
} from "./AsarEntryStream.js";
|
||||
import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js";
|
||||
import type { FileHandleChunkStream } from "../filesystem/readFileHandleChunks.js";
|
||||
import {
|
||||
@@ -42,6 +49,8 @@ import {
|
||||
} from "./AsarFailure.js";
|
||||
import { readAsarListing, type AsarListedEntry } from "./AsarListing.js";
|
||||
|
||||
const SNAPSHOT_CHUNK_BYTES = 256 * 1024;
|
||||
|
||||
/**
|
||||
* Electron ASAR reader with strict header decoding and range-streamed member reads.
|
||||
*
|
||||
@@ -55,7 +64,15 @@ export class AsarArtifactReader implements ArtifactReader {
|
||||
#selectedCanonicalSource: string | undefined;
|
||||
readonly #entries = new Map<string, AsarEntryState>();
|
||||
readonly #ownedHandles = new Map<SharedAsarFileHandle, OwnedAsarHandle>();
|
||||
#snapshot: { readonly path: string; readonly sha256: string } | undefined;
|
||||
#snapshot:
|
||||
| {
|
||||
readonly path: string;
|
||||
readonly sha256: string;
|
||||
readonly bytes: number;
|
||||
}
|
||||
| undefined;
|
||||
#snapshotHandle: SharedAsarFileHandle | undefined;
|
||||
#snapshotStatsChecked = false;
|
||||
#snapshotRoot: string | undefined;
|
||||
#snapshotOperation: Promise<void> = Promise.resolve();
|
||||
#snapshotGeneration = 0;
|
||||
@@ -153,10 +170,7 @@ export class AsarArtifactReader implements ArtifactReader {
|
||||
}
|
||||
|
||||
async #admitHeader(snapshotPath: string, signal?: AbortSignal) {
|
||||
const headerHandle = await this.#openOwned(
|
||||
snapshotPath,
|
||||
constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,
|
||||
);
|
||||
const headerHandle = await this.#ensureSnapshotHandle(signal);
|
||||
let admission:
|
||||
| {
|
||||
readonly ok: true;
|
||||
@@ -181,17 +195,18 @@ export class AsarArtifactReader implements ArtifactReader {
|
||||
} catch (cause: unknown) {
|
||||
admission = { ok: false, cause };
|
||||
}
|
||||
try {
|
||||
await this.#closeOwnedHandle(headerHandle);
|
||||
} catch (cleanupCause: unknown) {
|
||||
if (!admission.ok)
|
||||
if (!admission.ok) {
|
||||
try {
|
||||
await this.#closeOwnedHandle(headerHandle);
|
||||
} catch (cleanupCause: unknown) {
|
||||
throw ArtifactReaderFailure.withCleanup(
|
||||
admission.cause,
|
||||
ArtifactReaderFailure.cleanupObservation(cleanupCause, snapshotPath),
|
||||
);
|
||||
throw cleanupCause;
|
||||
}
|
||||
throw admission.cause;
|
||||
}
|
||||
if (!admission.ok) throw admission.cause;
|
||||
this.#snapshotStatsChecked = true;
|
||||
return admission.value;
|
||||
}
|
||||
|
||||
@@ -266,43 +281,37 @@ export class AsarArtifactReader implements ArtifactReader {
|
||||
`ASAR entry range is outside its container: ${producedEntry.path}`,
|
||||
);
|
||||
const snapshotPath = this.#snapshotPath();
|
||||
if (facts.size === 0) return Readable.from([]);
|
||||
let openedNew = false;
|
||||
let handle: SharedAsarFileHandle | undefined;
|
||||
try {
|
||||
const openedHandle = await this.#openOwned(
|
||||
snapshotPath,
|
||||
constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,
|
||||
);
|
||||
const needsOpen =
|
||||
this.#snapshotHandle === undefined ||
|
||||
!this.#ownedHandles.has(this.#snapshotHandle);
|
||||
const openedHandle = await this.#ensureSnapshotHandle(signal);
|
||||
openedNew = needsOpen;
|
||||
handle = openedHandle;
|
||||
const observed = await openedHandle.stat();
|
||||
assertAsarReadActive(signal);
|
||||
if (!observed.isFile() || observed.size !== archiveSize)
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
`ASAR container changed before read: ${producedEntry.path}`,
|
||||
{ integrityCheck: "container-identity" },
|
||||
);
|
||||
if (facts.size === 0) {
|
||||
handle = undefined;
|
||||
await closeAsarHandle(
|
||||
() => this.#closeOwnedHandle(openedHandle),
|
||||
signal,
|
||||
);
|
||||
return Readable.from([]);
|
||||
if (!this.#snapshotStatsChecked) {
|
||||
const observed = await openedHandle.stat();
|
||||
assertAsarReadActive(signal);
|
||||
if (!observed.isFile() || observed.size !== archiveSize)
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
`ASAR container changed before read: ${producedEntry.path}`,
|
||||
{ integrityCheck: "container-identity" },
|
||||
);
|
||||
this.#snapshotStatsChecked = true;
|
||||
}
|
||||
const source = this.#ownedReadStream(openedHandle, {
|
||||
const output = readValidatedAsarRange(
|
||||
openedHandle,
|
||||
start,
|
||||
end: start + facts.size - 1,
|
||||
signal,
|
||||
});
|
||||
handle = undefined;
|
||||
const output = readValidatedAsarEntry(
|
||||
source,
|
||||
facts.size,
|
||||
producedEntry.path,
|
||||
this.path,
|
||||
signal,
|
||||
);
|
||||
this.#setOwnedOutput(openedHandle, output);
|
||||
this.#trackOwnedStream(openedHandle, output);
|
||||
handle = undefined;
|
||||
return output;
|
||||
} catch (cause: unknown) {
|
||||
const failure = asarFailure(
|
||||
@@ -310,7 +319,7 @@ export class AsarArtifactReader implements ArtifactReader {
|
||||
`read ${producedEntry.path}`,
|
||||
cause,
|
||||
);
|
||||
if (handle !== undefined) {
|
||||
if (handle !== undefined && openedNew) {
|
||||
try {
|
||||
await this.#closeOwnedHandle(handle);
|
||||
} catch (cleanupCause: unknown) {
|
||||
@@ -331,6 +340,7 @@ export class AsarArtifactReader implements ArtifactReader {
|
||||
async prepareContainer(
|
||||
expectedSha256?: string,
|
||||
signal?: AbortSignal,
|
||||
expectedBytes?: number,
|
||||
): Promise<void> {
|
||||
await this.#withSnapshotOperation(async () => {
|
||||
assertAsarReadActive(signal);
|
||||
@@ -339,8 +349,9 @@ export class AsarArtifactReader implements ArtifactReader {
|
||||
await this.#closeSnapshot();
|
||||
if (this.#snapshot === undefined) await this.#captureSnapshot(signal);
|
||||
if (
|
||||
expectedSha256 !== undefined &&
|
||||
this.#snapshot?.sha256 !== expectedSha256
|
||||
(expectedSha256 !== undefined &&
|
||||
this.#snapshot?.sha256 !== expectedSha256) ||
|
||||
(expectedBytes !== undefined && this.#snapshot?.bytes !== expectedBytes)
|
||||
)
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
@@ -355,12 +366,8 @@ export class AsarArtifactReader implements ArtifactReader {
|
||||
await this.prepareContainer(undefined, signal);
|
||||
return this.#withSnapshotOperation(async () => {
|
||||
assertAsarReadActive(signal);
|
||||
const snapshotPath = this.#snapshotPath();
|
||||
const handle = await this.#openOwned(
|
||||
snapshotPath,
|
||||
constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,
|
||||
);
|
||||
return this.#ownedReadStream(handle, { signal });
|
||||
const handle = await this.#ensureSnapshotHandle(signal);
|
||||
return this.#ownedReadStream(handle, { signal, releaseOnClose: false });
|
||||
}, signal);
|
||||
}
|
||||
|
||||
@@ -370,46 +377,65 @@ export class AsarArtifactReader implements ArtifactReader {
|
||||
}
|
||||
|
||||
async #captureSnapshot(signal?: AbortSignal): Promise<void> {
|
||||
const admitted =
|
||||
this.options.openFile === undefined ? this.options.admitted : undefined;
|
||||
let inputHandle: SharedAsarFileHandle | undefined;
|
||||
let snapshotWriteHandle: FileHandle | undefined;
|
||||
let snapshotPath: string | undefined;
|
||||
try {
|
||||
this.#snapshotRoot = await mkdtemp(join(tmpdir(), "rea-asar-snapshot-"));
|
||||
const snapshotPath = join(this.#snapshotRoot, "container.asar");
|
||||
snapshotPath = join(this.#snapshotRoot, "container.asar");
|
||||
const hash = createHash("sha256");
|
||||
inputHandle = await this.#openOwned(
|
||||
this.path,
|
||||
constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,
|
||||
const readHandle =
|
||||
admitted !== undefined
|
||||
? admitted.handle
|
||||
: (inputHandle = await this.#openOwned(
|
||||
this.path,
|
||||
constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,
|
||||
));
|
||||
snapshotWriteHandle = await open(
|
||||
snapshotPath,
|
||||
constants.O_WRONLY |
|
||||
constants.O_CREAT |
|
||||
constants.O_EXCL |
|
||||
constants.O_NOFOLLOW,
|
||||
0o600,
|
||||
);
|
||||
const source = this.#ownedReadStream(inputHandle, {
|
||||
this.#adoptHandle(snapshotWriteHandle, snapshotPath);
|
||||
const bytes = await this.#copyToSnapshot(
|
||||
readHandle,
|
||||
snapshotWriteHandle,
|
||||
hash,
|
||||
admitted,
|
||||
signal,
|
||||
releaseOnClose: false,
|
||||
});
|
||||
const digesting = new Transform({
|
||||
transform(chunk: Buffer, _encoding, callback) {
|
||||
hash.update(chunk);
|
||||
callback(null, chunk);
|
||||
},
|
||||
});
|
||||
await pipeline(
|
||||
source,
|
||||
digesting,
|
||||
createWriteStream(snapshotPath, { flags: "wx", mode: 0o600 }),
|
||||
);
|
||||
const completedInput = inputHandle;
|
||||
inputHandle = undefined;
|
||||
await this.#closeOwnedHandle(completedInput);
|
||||
const completedWrite = snapshotWriteHandle;
|
||||
snapshotWriteHandle = undefined;
|
||||
await this.#closeOwnedHandle(completedWrite);
|
||||
if (inputHandle !== undefined) {
|
||||
const completedInput = inputHandle;
|
||||
inputHandle = undefined;
|
||||
await this.#closeOwnedHandle(completedInput);
|
||||
}
|
||||
assertAsarReadActive(signal);
|
||||
this.#snapshot = { path: snapshotPath, sha256: hash.digest("hex") };
|
||||
this.#snapshot = {
|
||||
path: snapshotPath,
|
||||
sha256: hash.digest("hex"),
|
||||
bytes,
|
||||
};
|
||||
} catch (cause: unknown) {
|
||||
let failure = asarFailure(this.path, "snapshot", cause);
|
||||
if (inputHandle !== undefined) {
|
||||
const failedInput = inputHandle;
|
||||
inputHandle = undefined;
|
||||
for (const [pending, label] of [
|
||||
[snapshotWriteHandle, snapshotPath ?? this.path] as const,
|
||||
[inputHandle, this.path] as const,
|
||||
]) {
|
||||
if (pending === undefined) continue;
|
||||
try {
|
||||
await this.#closeOwnedHandle(failedInput);
|
||||
await this.#closeOwnedHandle(pending);
|
||||
} catch (cleanupCause: unknown) {
|
||||
failure = ArtifactReaderFailure.withCleanup(
|
||||
failure,
|
||||
ArtifactReaderFailure.cleanupObservation(cleanupCause, this.path),
|
||||
ArtifactReaderFailure.cleanupObservation(cleanupCause, label),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -428,6 +454,71 @@ export class AsarArtifactReader implements ArtifactReader {
|
||||
}
|
||||
}
|
||||
|
||||
async #copyToSnapshot(
|
||||
readHandle: Pick<FileHandle, "read">,
|
||||
writeHandle: FileHandle,
|
||||
hash: ReturnType<typeof createHash>,
|
||||
admitted: StableRegularFileDescriptor | undefined,
|
||||
signal?: AbortSignal,
|
||||
): Promise<number> {
|
||||
const buffer = Buffer.allocUnsafe(SNAPSHOT_CHUNK_BYTES);
|
||||
let position = 0;
|
||||
const limit = admitted?.initial.size;
|
||||
for (;;) {
|
||||
assertAsarReadActive(signal);
|
||||
const toRead =
|
||||
limit === undefined
|
||||
? buffer.length
|
||||
: Math.min(buffer.length, limit - position + 1);
|
||||
if (toRead <= 0) break;
|
||||
const { bytesRead } = await readHandle.read(buffer, 0, toRead, position);
|
||||
if (limit !== undefined && position + bytesRead > limit)
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
`ASAR container changed before interpretation: ${this.path}`,
|
||||
{ integrityCheck: "container-identity" },
|
||||
);
|
||||
assertAsarReadActive(signal);
|
||||
if (bytesRead === 0) break;
|
||||
const chunk =
|
||||
bytesRead === buffer.length ? buffer : buffer.subarray(0, bytesRead);
|
||||
hash.update(chunk);
|
||||
await writeHandleAll(writeHandle, chunk);
|
||||
position += bytesRead;
|
||||
}
|
||||
if (admitted !== undefined) {
|
||||
if (position !== admitted.initial.size)
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
`ASAR container changed before interpretation: ${this.path}`,
|
||||
{ integrityCheck: "container-identity" },
|
||||
);
|
||||
try {
|
||||
await assertStableRegularFileIdentity(
|
||||
admitted.handle,
|
||||
this.path,
|
||||
admitted.initial,
|
||||
{
|
||||
symlinks: "reject",
|
||||
...(signal === undefined ? {} : { signal }),
|
||||
},
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
if (cause instanceof RegularFileChangedError)
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
`ASAR container changed before interpretation: ${this.path}`,
|
||||
{
|
||||
cause: cause.cause ?? cause,
|
||||
integrityCheck: "container-identity",
|
||||
},
|
||||
);
|
||||
throw cause;
|
||||
}
|
||||
}
|
||||
return position;
|
||||
}
|
||||
|
||||
async #closeSnapshot(): Promise<void> {
|
||||
await this.#closeOwnedHandles();
|
||||
const root = this.#snapshotRoot;
|
||||
@@ -444,6 +535,8 @@ export class AsarArtifactReader implements ArtifactReader {
|
||||
}
|
||||
if (root === undefined || this.#snapshotRoot === undefined) {
|
||||
this.#snapshot = undefined;
|
||||
this.#snapshotHandle = undefined;
|
||||
this.#snapshotStatsChecked = false;
|
||||
this.#resetArchiveState();
|
||||
this.#entries.clear();
|
||||
}
|
||||
@@ -572,7 +665,7 @@ export class AsarArtifactReader implements ArtifactReader {
|
||||
this.path,
|
||||
signal,
|
||||
);
|
||||
this.#setOwnedOutput(openedHandle, output);
|
||||
this.#trackOwnedStream(openedHandle, output);
|
||||
return output;
|
||||
} catch (cause: unknown) {
|
||||
let failure = asarUnpackedEntryFailure(this.path, entry, cause);
|
||||
@@ -593,11 +686,45 @@ export class AsarArtifactReader implements ArtifactReader {
|
||||
}
|
||||
}
|
||||
|
||||
async #ensureSnapshotHandle(
|
||||
signal?: AbortSignal,
|
||||
): Promise<SharedAsarFileHandle> {
|
||||
assertAsarReadActive(signal);
|
||||
if (
|
||||
this.#snapshotHandle !== undefined &&
|
||||
this.#ownedHandles.has(this.#snapshotHandle)
|
||||
) {
|
||||
return this.#snapshotHandle;
|
||||
}
|
||||
const snapshotPath = this.#snapshotPath();
|
||||
const handle = await this.#openOwned(
|
||||
snapshotPath,
|
||||
constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,
|
||||
);
|
||||
try {
|
||||
assertAsarReadActive(signal);
|
||||
} catch (cause: unknown) {
|
||||
try {
|
||||
await this.#closeOwnedHandle(handle);
|
||||
} catch (cleanupCause: unknown) {
|
||||
throw ArtifactReaderFailure.withCleanup(
|
||||
asarFailure(this.path, "read", cause),
|
||||
ArtifactReaderFailure.cleanupObservation(cleanupCause, snapshotPath),
|
||||
);
|
||||
}
|
||||
throw cause;
|
||||
}
|
||||
this.#snapshotHandle = handle;
|
||||
this.#snapshotStatsChecked = false;
|
||||
return handle;
|
||||
}
|
||||
|
||||
async #closeOwnedHandle(handle: SharedAsarFileHandle): Promise<void> {
|
||||
const owned = this.#ownedHandles.get(handle);
|
||||
if (owned === undefined) return;
|
||||
owned.output?.destroy();
|
||||
owned.source?.destroy();
|
||||
for (const stream of [...owned.streams]) {
|
||||
if (!stream.destroyed) stream.destroy();
|
||||
}
|
||||
try {
|
||||
await owned.owner.close();
|
||||
} catch (cause: unknown) {
|
||||
@@ -607,11 +734,15 @@ export class AsarArtifactReader implements ArtifactReader {
|
||||
);
|
||||
}
|
||||
this.#ownedHandles.delete(handle);
|
||||
if (this.#snapshotHandle === handle) {
|
||||
this.#snapshotHandle = undefined;
|
||||
this.#snapshotStatsChecked = false;
|
||||
}
|
||||
}
|
||||
|
||||
async #closeOwnedHandles(): Promise<void> {
|
||||
let failure: ArtifactReaderFailure | undefined;
|
||||
for (const [handle, owned] of this.#ownedHandles) {
|
||||
for (const [handle, owned] of [...this.#ownedHandles]) {
|
||||
try {
|
||||
await this.#closeOwnedHandle(handle);
|
||||
} catch (cause: unknown) {
|
||||
@@ -634,6 +765,7 @@ export class AsarArtifactReader implements ArtifactReader {
|
||||
this.#ownedHandles.set(handle, {
|
||||
path,
|
||||
owner: new OwnedFileHandle(handle),
|
||||
streams: new Set(),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -648,13 +780,7 @@ export class AsarArtifactReader implements ArtifactReader {
|
||||
): FileHandleChunkStream {
|
||||
const { releaseOnClose, ...readOptions } = options;
|
||||
const source = readArtifactFileChunks(handle, readOptions);
|
||||
const owned = this.#ownedHandles.get(handle);
|
||||
if (owned === undefined)
|
||||
throw new ArtifactReaderFailure("integrity", "ASAR handle has no owner", {
|
||||
integrityCheck: "reader-ownership",
|
||||
});
|
||||
owned.source = source;
|
||||
owned.output = source;
|
||||
this.#trackOwnedStream(handle, source);
|
||||
if (releaseOnClose !== false)
|
||||
source.once("close", () => {
|
||||
void this.#closeOwnedHandle(handle).catch(() => undefined);
|
||||
@@ -662,9 +788,16 @@ export class AsarArtifactReader implements ArtifactReader {
|
||||
return source;
|
||||
}
|
||||
|
||||
#setOwnedOutput(handle: SharedAsarFileHandle, output: Readable): void {
|
||||
#trackOwnedStream(handle: SharedAsarFileHandle, stream: Readable): void {
|
||||
const owned = this.#ownedHandles.get(handle);
|
||||
if (owned !== undefined) owned.output = output;
|
||||
if (owned === undefined)
|
||||
throw new ArtifactReaderFailure("integrity", "ASAR handle has no owner", {
|
||||
integrityCheck: "reader-ownership",
|
||||
});
|
||||
owned.streams.add(stream);
|
||||
stream.once("close", () => {
|
||||
owned.streams.delete(stream);
|
||||
});
|
||||
}
|
||||
|
||||
#resetArchiveState(): void {
|
||||
@@ -686,19 +819,40 @@ type OpenAsarFile = (
|
||||
type OwnedAsarHandle = {
|
||||
readonly path: string;
|
||||
readonly owner: OwnedFileHandle<SharedAsarFileHandle>;
|
||||
source?: Readable;
|
||||
output?: Readable;
|
||||
readonly streams: Set<Readable>;
|
||||
};
|
||||
export type AsarArtifactReaderOptions = {
|
||||
/** Header/index admission resolved by the caller's composition root; default otherwise. */
|
||||
readonly headerAdmission?: AsarHeaderAdmission;
|
||||
/** Companion selected by the caller archive spelling, independently of packed identity. */
|
||||
readonly selectedPath?: string;
|
||||
/** Pre-opened source descriptor admitted during classification to avoid re-opening. */
|
||||
readonly admitted?: StableRegularFileDescriptor;
|
||||
readonly openFile?: OpenAsarFile;
|
||||
readonly openUnpackedFile?: OpenAsarFile;
|
||||
readonly removeSnapshot?: (path: string) => Promise<void>;
|
||||
};
|
||||
|
||||
const writeHandleAll = async (
|
||||
handle: FileHandle,
|
||||
chunk: Uint8Array,
|
||||
): Promise<void> => {
|
||||
let offset = 0;
|
||||
while (offset < chunk.length) {
|
||||
const { bytesWritten } = await handle.write(
|
||||
chunk,
|
||||
offset,
|
||||
chunk.length - offset,
|
||||
);
|
||||
if (bytesWritten <= 0)
|
||||
throw new ArtifactReaderFailure(
|
||||
"io",
|
||||
"Short write while capturing ASAR snapshot",
|
||||
);
|
||||
offset += bytesWritten;
|
||||
}
|
||||
};
|
||||
|
||||
const defaultRemoveSnapshot = (path: string): Promise<void> =>
|
||||
rm(path, { recursive: true, force: true });
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { FileHandle } from "node:fs/promises";
|
||||
import type { FileHandleChunkStream } from "../filesystem/readFileHandleChunks.js";
|
||||
import { Readable } from "node:stream";
|
||||
|
||||
@@ -8,6 +9,109 @@ import {
|
||||
asarFailure,
|
||||
} from "./AsarFailure.js";
|
||||
|
||||
const ASAR_READ_CHUNK_BYTES = 256 * 1024;
|
||||
|
||||
/** Stream one bounded packed ASAR member range via positional preads on an open handle. */
|
||||
export const readValidatedAsarRange = (
|
||||
handle: Pick<FileHandle, "read">,
|
||||
start: number,
|
||||
expectedBytes: number,
|
||||
entryPath: string,
|
||||
archivePath: string,
|
||||
signal?: AbortSignal,
|
||||
): Readable => {
|
||||
let position = start;
|
||||
let remaining = expectedBytes;
|
||||
let readState: "idle" | "pending" | "failed" = "idle";
|
||||
let reading = false;
|
||||
let ended = false;
|
||||
const output = new Readable({
|
||||
read() {
|
||||
if (reading || ended || output.destroyed) return;
|
||||
reading = true;
|
||||
void pump().finally(() => {
|
||||
reading = false;
|
||||
});
|
||||
},
|
||||
});
|
||||
const fail = (cause: unknown): void => {
|
||||
ended = true;
|
||||
output.destroy(asarFailure(archivePath, `read ${entryPath}`, cause));
|
||||
};
|
||||
const pump = async (): Promise<void> => {
|
||||
while (remaining > 0 && !ended && !output.destroyed) {
|
||||
if (signal?.aborted) {
|
||||
fail(asarCancellationFailure(signal.reason));
|
||||
return;
|
||||
}
|
||||
const length = Math.min(ASAR_READ_CHUNK_BYTES, remaining);
|
||||
const buffer = Buffer.allocUnsafe(length);
|
||||
readState = "pending";
|
||||
let bytesRead: number;
|
||||
try {
|
||||
({ bytesRead } = await handle.read(buffer, 0, length, position));
|
||||
readState = "idle";
|
||||
} catch (cause: unknown) {
|
||||
// Keep physical read errors primary even if cancellation arrives in flight.
|
||||
readState = "failed";
|
||||
if (output.destroyed) return;
|
||||
fail(cause);
|
||||
return;
|
||||
}
|
||||
if (output.destroyed) return;
|
||||
if (bytesRead <= 0 || bytesRead > length) {
|
||||
fail(
|
||||
new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
`ASAR entry size disagrees with its header: ${entryPath}`,
|
||||
{ integrityCheck: "declared-size" },
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
position += bytesRead;
|
||||
remaining -= bytesRead;
|
||||
const chunk =
|
||||
bytesRead === buffer.length ? buffer : buffer.subarray(0, bytesRead);
|
||||
if (signal?.aborted) {
|
||||
fail(asarCancellationFailure(signal.reason));
|
||||
return;
|
||||
}
|
||||
const wantMore = output.push(chunk);
|
||||
if (output.destroyed) return;
|
||||
if (remaining === 0) {
|
||||
if (signal?.aborted) {
|
||||
fail(asarCancellationFailure(signal.reason));
|
||||
return;
|
||||
}
|
||||
ended = true;
|
||||
output.push(null);
|
||||
return;
|
||||
}
|
||||
if (signal?.aborted) {
|
||||
fail(asarCancellationFailure(signal.reason));
|
||||
return;
|
||||
}
|
||||
if (!wantMore) break;
|
||||
}
|
||||
};
|
||||
// Cancellation can precede the caller's first read while it prepares output.
|
||||
output.on("error", () => undefined);
|
||||
const onAbort = (): void => {
|
||||
if (readState === "idle" && !output.destroyed && !output.readableEnded) {
|
||||
ended = true;
|
||||
output.destroy(asarCancellationFailure(signal!.reason));
|
||||
}
|
||||
};
|
||||
signal?.addEventListener("abort", onAbort, { once: true });
|
||||
output.once("close", () => {
|
||||
ended = true;
|
||||
signal?.removeEventListener("abort", onAbort);
|
||||
});
|
||||
if (signal?.aborted) onAbort();
|
||||
return output;
|
||||
};
|
||||
|
||||
/** Close an ASAR file handle before honoring cancellation of an empty member. */
|
||||
export const closeAsarHandle = async (
|
||||
close: () => Promise<void>,
|
||||
|
||||
@@ -275,17 +275,21 @@ const NON_ZIP_FORMATS = {
|
||||
}),
|
||||
pkg: container("pkg", { absentInventory: "platform" }),
|
||||
asar: container("asar", {
|
||||
retainClassifiedSource: true,
|
||||
extractable: true,
|
||||
absentInventory: "unavailable",
|
||||
createReader: (path, options) =>
|
||||
new AsarArtifactReader(path, {
|
||||
createReader: (path, options) => {
|
||||
const admitted = sourceOf(options);
|
||||
return new AsarArtifactReader(path, {
|
||||
...(options.asarHeaderAdmission === undefined
|
||||
? {}
|
||||
: { headerAdmission: options.asarHeaderAdmission }),
|
||||
...(options.selectedPath === undefined
|
||||
? {}
|
||||
: { selectedPath: options.selectedPath }),
|
||||
}),
|
||||
...(admitted === undefined ? {} : { admitted }),
|
||||
});
|
||||
},
|
||||
}),
|
||||
ines: container("ines", {
|
||||
roleContainer: true,
|
||||
|
||||
@@ -284,6 +284,7 @@ const scanCanonical = async (
|
||||
rootSource !== undefined &&
|
||||
(isZipPackageFormat(rootFormat) ||
|
||||
rootFormat === "ines" ||
|
||||
rootFormat === "asar" ||
|
||||
(readerAdmission !== undefined && "kind" in readerAdmission))
|
||||
? "transfer"
|
||||
: "release",
|
||||
|
||||
@@ -54,6 +54,7 @@ interface ReadContext {
|
||||
readonly signal: AbortSignal | undefined;
|
||||
readonly asarHeaderAdmission: AsarHeaderAdmission | undefined;
|
||||
readonly selectedPaths: ReadonlyMap<string, number> | undefined;
|
||||
readonly verifiedAsarReaders: ReadonlySet<AsarArtifactReader>;
|
||||
textBytes: number;
|
||||
invalidUtf8: number;
|
||||
}
|
||||
@@ -114,6 +115,7 @@ export const readJavaScriptArtifactFiles = async (
|
||||
undefined,
|
||||
issues,
|
||||
);
|
||||
const verifiedAsarReaders = new Set<AsarArtifactReader>();
|
||||
if (reader instanceof AsarArtifactReader) {
|
||||
const root = snapshot.nodes.find(
|
||||
({ artifact_id }) => artifact_id === snapshot.manifest.root_artifact_id,
|
||||
@@ -124,11 +126,8 @@ export const readJavaScriptArtifactFiles = async (
|
||||
"Root artifact node is missing",
|
||||
{ integrityCheck: "inventory-node" },
|
||||
);
|
||||
await verifyEntryBytes(
|
||||
await reader.openContainer(signal),
|
||||
{ path: ".", sha256: root.sha256, bytes: root.size },
|
||||
signal,
|
||||
);
|
||||
await reader.prepareContainer(root.sha256, signal, root.size);
|
||||
verifiedAsarReaders.add(reader);
|
||||
}
|
||||
if (inventory.ambiguousPath !== undefined)
|
||||
throw new ArtifactReaderFailure(
|
||||
@@ -159,6 +158,7 @@ export const readJavaScriptArtifactFiles = async (
|
||||
signal,
|
||||
asarHeaderAdmission,
|
||||
selectedPaths,
|
||||
verifiedAsarReaders,
|
||||
textBytes: 0,
|
||||
invalidUtf8: 0,
|
||||
};
|
||||
@@ -285,13 +285,19 @@ const visitReader = async (
|
||||
: { headerAdmission: context.asarHeaderAdmission },
|
||||
);
|
||||
ownedReaders.push({ reader: nested, path });
|
||||
await nested.prepareContainer(
|
||||
inventory.sha256,
|
||||
context.signal,
|
||||
inventory.bytes,
|
||||
);
|
||||
// Safe to mutate local Set initialized in readJavaScriptArtifactFiles.
|
||||
(context.verifiedAsarReaders as Set<AsarArtifactReader>).add(nested);
|
||||
stack.push({
|
||||
reader: nested,
|
||||
prefix: path,
|
||||
containerSha256: inventory.sha256,
|
||||
iterator: nested.entries(context.signal)[Symbol.asyncIterator](),
|
||||
});
|
||||
await nested.prepareContainer(inventory.sha256, context.signal);
|
||||
continue;
|
||||
}
|
||||
const expected = context.expected.get(path);
|
||||
@@ -362,19 +368,11 @@ const readText = async (
|
||||
) {
|
||||
// Keep the inventory/acquisition identity check without allocating or
|
||||
// decoding an unrelated source's text.
|
||||
await verifyEntryBytes(
|
||||
await input.reader.open(input.entry, context.signal),
|
||||
input.expected,
|
||||
context.signal,
|
||||
);
|
||||
await verifyUnselectedOrBinaryEntry(context, input);
|
||||
return { included: false, reason: "outside-analysis-scope" };
|
||||
}
|
||||
if (input.expected.kind === "native-addon") {
|
||||
await verifyEntryBytes(
|
||||
await input.reader.open(input.entry, context.signal),
|
||||
input.expected,
|
||||
context.signal,
|
||||
);
|
||||
await verifyUnselectedOrBinaryEntry(context, input);
|
||||
return { included: false, reason: "not-applicable" };
|
||||
}
|
||||
const bytes = await readAll(
|
||||
@@ -406,6 +404,31 @@ const readText = async (
|
||||
}
|
||||
};
|
||||
|
||||
const verifyUnselectedOrBinaryEntry = async (
|
||||
context: ReadContext,
|
||||
input: ReadTextInput,
|
||||
): Promise<void> => {
|
||||
abortIfNeeded(context.signal);
|
||||
if (
|
||||
input.reader instanceof AsarArtifactReader &&
|
||||
context.verifiedAsarReaders.has(input.reader) &&
|
||||
!input.entry.unpacked
|
||||
) {
|
||||
if (input.entry.declaredSize !== input.expected.bytes)
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
`Artifact entry changed after inventory: ${input.expected.path}`,
|
||||
{ integrityCheck: "member-identity" },
|
||||
);
|
||||
return;
|
||||
}
|
||||
await verifyEntryBytes(
|
||||
await input.reader.open(input.entry, context.signal),
|
||||
input.expected,
|
||||
context.signal,
|
||||
);
|
||||
};
|
||||
|
||||
const verifyEntryBytes = async (
|
||||
stream: Readable,
|
||||
expected: Pick<ExpectedFile, "path" | "sha256" | "bytes">,
|
||||
@@ -667,6 +690,9 @@ const readAll = async (
|
||||
bytes += chunk.length;
|
||||
chunks.push(chunk);
|
||||
}
|
||||
if (chunks.length === 0) return Buffer.alloc(0);
|
||||
const first = chunks[0];
|
||||
if (chunks.length === 1 && first !== undefined) return first;
|
||||
return Buffer.concat(chunks, bytes);
|
||||
};
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
writeFile,
|
||||
} from "node:fs/promises";
|
||||
import { dirname, join } from "node:path";
|
||||
import { buffer } from "node:stream/consumers";
|
||||
|
||||
import { createPackage } from "@electron/asar";
|
||||
import { describe, expect, it } from "vitest";
|
||||
@@ -155,7 +156,7 @@ describe("ASAR reader cleanup", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("closes a member handle adopted while reader shutdown is queued", async () => {
|
||||
it("closes a snapshot handle adopted while reader shutdown is queued", async () => {
|
||||
const { archive } = await createArchive();
|
||||
let pauseMemberOpen = false;
|
||||
const memberOpen = phaseGate();
|
||||
@@ -168,13 +169,13 @@ describe("ASAR reader cleanup", () => {
|
||||
},
|
||||
});
|
||||
|
||||
let opening: ReturnType<typeof reader.open> | undefined;
|
||||
let opening: ReturnType<typeof reader.openContainer> | undefined;
|
||||
let closing: ReturnType<typeof reader.close> | undefined;
|
||||
await withVerifierCleanup(async () => {
|
||||
const entry = await packedMember(reader);
|
||||
await reader.prepareContainer();
|
||||
pauseMemberOpen = true;
|
||||
opening = reader.open(entry);
|
||||
await memberOpen.reached(opening, "member open");
|
||||
opening = reader.openContainer();
|
||||
await memberOpen.reached(opening, "snapshot handle open");
|
||||
closing = reader.close();
|
||||
memberOpen.release();
|
||||
const output = await opening;
|
||||
@@ -199,7 +200,7 @@ describe("ASAR reader cleanup", () => {
|
||||
});
|
||||
|
||||
describe("ASAR preparation cleanup", () => {
|
||||
it("retains a zero-byte member handle when its first close fails", async () => {
|
||||
it("retains the snapshot handle after reading a zero-byte member when close fails", async () => {
|
||||
const { archive } = await createArchive("");
|
||||
let failNextClose = false;
|
||||
const { reader, opened } = createTrackedReader(archive, {
|
||||
@@ -213,14 +214,17 @@ describe("ASAR preparation cleanup", () => {
|
||||
});
|
||||
try {
|
||||
const entry = await packedMember(reader);
|
||||
expect((await buffer(await reader.open(entry))).toString("utf8")).toBe(
|
||||
"",
|
||||
);
|
||||
const handle = latestHandle(opened);
|
||||
failNextClose = true;
|
||||
await expect(reader.open(entry)).rejects.toMatchObject({
|
||||
await expect(reader.close()).rejects.toMatchObject({
|
||||
cleanup: {
|
||||
reason: "empty member close denied",
|
||||
resources: [expect.any(String)],
|
||||
resources: [handle.path],
|
||||
},
|
||||
});
|
||||
const handle = latestHandle(opened);
|
||||
expectDescriptorOpen(handle.fd);
|
||||
expect((await lstat(dirname(handle.path))).isDirectory()).toBe(true);
|
||||
await reader.close();
|
||||
@@ -301,12 +305,15 @@ it.each(["snapshot", "member"])(
|
||||
);
|
||||
let active = stage === "snapshot";
|
||||
const { reader, opened } = createTrackedReader(archive, {
|
||||
beforeAdoption: async (_path, handle) => {
|
||||
if (active)
|
||||
handle.read = (async () => {
|
||||
beforeAdoption: async (path, handle) => {
|
||||
const originalRead = handle.read;
|
||||
handle.read = (async (...args: readonly unknown[]) => {
|
||||
if (active && (stage === "snapshot" || path !== archive)) {
|
||||
controller.abort(null);
|
||||
throw failure;
|
||||
}) as FileHandle["read"];
|
||||
}
|
||||
return Reflect.apply(originalRead, handle, args);
|
||||
}) as FileHandle["read"];
|
||||
},
|
||||
});
|
||||
try {
|
||||
|
||||
@@ -20,6 +20,7 @@ import { AsarArtifactReader } from "../../../src/artifacts/AsarArtifactReader.js
|
||||
import {
|
||||
closeAsarHandle,
|
||||
readValidatedAsarEntry,
|
||||
readValidatedAsarRange,
|
||||
} from "../../../src/artifacts/AsarEntryStream.js";
|
||||
import { hashReadable } from "../../../src/artifacts/ArtifactHash.js";
|
||||
import { ARTIFACT_CLASSIFICATION_PREFIX_BYTES } from "../../../src/artifacts/ArtifactClassificationProbe.js";
|
||||
@@ -112,13 +113,17 @@ const createPackedFixture = async () => {
|
||||
|
||||
describe("ASAR entry streaming", () => {
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"closes a packed member handle when its unopened output stream is destroyed",
|
||||
"reuses one snapshot descriptor across container and packed member streams until reader close",
|
||||
async () => {
|
||||
const archive = await createPackedFixture();
|
||||
let snapshotPath: string | undefined;
|
||||
let snapshotOpens = 0;
|
||||
const reader = new AsarArtifactReader(archive, {
|
||||
openFile: async (path, flags) => {
|
||||
if (path !== archive) snapshotPath = path;
|
||||
if (path !== archive) {
|
||||
snapshotPath = path;
|
||||
snapshotOpens += 1;
|
||||
}
|
||||
return openFile(path, flags);
|
||||
},
|
||||
});
|
||||
@@ -130,22 +135,34 @@ describe("ASAR entry streaming", () => {
|
||||
}
|
||||
const entry = entries.find(({ path }) => path === "small.js");
|
||||
if (entry === undefined) throw new Error("Expected packed ASAR member");
|
||||
const snapshot = await reader.openContainer();
|
||||
if (snapshotPath === undefined)
|
||||
throw new Error("Expected snapshot acquisition");
|
||||
const identity = await lstat(snapshotPath);
|
||||
expect(snapshotOpens).toBe(1);
|
||||
expect(await matchingDescriptorCount(identity)).toBe(1);
|
||||
|
||||
const snapshot = await reader.openContainer();
|
||||
await buffer(snapshot);
|
||||
const probe = await openFile(snapshotPath, "r");
|
||||
expect(await matchingDescriptorCount(identity)).toBeGreaterThan(0);
|
||||
await probe.close();
|
||||
expect(await matchingDescriptorCount(identity)).toBe(0);
|
||||
expect(snapshotOpens).toBe(1);
|
||||
expect(await matchingDescriptorCount(identity)).toBe(1);
|
||||
|
||||
const output = await reader.open(entry);
|
||||
expect(await matchingDescriptorCount(identity)).toBeGreaterThan(0);
|
||||
expect(snapshotOpens).toBe(1);
|
||||
expect(await matchingDescriptorCount(identity)).toBe(1);
|
||||
const closed = new Promise<void>((resolve) =>
|
||||
output.once("close", resolve),
|
||||
);
|
||||
output.destroy();
|
||||
await closed;
|
||||
expect(output.destroyed).toBe(true);
|
||||
expect(await matchingDescriptorCount(identity)).toBe(1);
|
||||
|
||||
const second = await reader.open(entry);
|
||||
expect((await buffer(second)).toString("utf8")).toBe(packedContents);
|
||||
expect(snapshotOpens).toBe(1);
|
||||
expect(await matchingDescriptorCount(identity)).toBe(1);
|
||||
|
||||
await reader.close();
|
||||
await waitForNoMatchingDescriptor(identity);
|
||||
} finally {
|
||||
await reader.close();
|
||||
@@ -153,34 +170,31 @@ describe("ASAR entry streaming", () => {
|
||||
},
|
||||
);
|
||||
|
||||
it("closes an acquired packed member handle before returning cancellation", async () => {
|
||||
it("closes an acquired snapshot handle before returning cancellation", async () => {
|
||||
const archive = await createPackedFixture();
|
||||
const cancellation = new Error("cancel at member acquisition");
|
||||
const cancellation = new Error("cancel at snapshot handle acquisition");
|
||||
let controller: AbortController | undefined;
|
||||
let memberHandle: FileHandle | undefined;
|
||||
let snapshotHandle: FileHandle | undefined;
|
||||
const reader = new AsarArtifactReader(archive, {
|
||||
openFile: async (path, flags) => {
|
||||
const handle = await openFile(path, flags);
|
||||
if (controller !== undefined) {
|
||||
memberHandle = handle;
|
||||
if (path !== archive && controller !== undefined) {
|
||||
snapshotHandle = handle;
|
||||
controller.abort(cancellation);
|
||||
}
|
||||
return handle;
|
||||
},
|
||||
});
|
||||
try {
|
||||
const entries = [];
|
||||
for await (const entry of reader.entries()) entries.push(entry);
|
||||
const entry = entries.find(({ path }) => path === "small.js");
|
||||
if (entry === undefined) throw new Error("Expected packed ASAR member");
|
||||
await reader.prepareContainer();
|
||||
controller = new AbortController();
|
||||
await expect(reader.open(entry, controller.signal)).rejects.toMatchObject(
|
||||
{
|
||||
reason: "cancelled",
|
||||
cause: cancellation,
|
||||
},
|
||||
);
|
||||
expect(memberHandle?.fd).toBe(-1);
|
||||
await expect(
|
||||
reader.openContainer(controller.signal),
|
||||
).rejects.toMatchObject({
|
||||
reason: "cancelled",
|
||||
cause: cancellation,
|
||||
});
|
||||
expect(snapshotHandle?.fd).toBe(-1);
|
||||
} finally {
|
||||
await reader.close();
|
||||
}
|
||||
@@ -214,6 +228,57 @@ describe("ASAR entry streaming", () => {
|
||||
);
|
||||
});
|
||||
|
||||
describe("ASAR range streaming", () => {
|
||||
it("propagates cancellation during an in-flight range read even under stream backpressure", async () => {
|
||||
const controller = new AbortController();
|
||||
const cancellation = new Error("abort during paused chunk");
|
||||
const chunkBytes = 256 * 1024;
|
||||
let readCalls = 0;
|
||||
const read = (async (target: Buffer, offset: number, length: number) => {
|
||||
readCalls += 1;
|
||||
controller.abort(cancellation);
|
||||
target.fill(0x61, offset, offset + length);
|
||||
return { bytesRead: length, buffer: target };
|
||||
}) as FileHandle["read"];
|
||||
const output = readValidatedAsarRange(
|
||||
{ read },
|
||||
0,
|
||||
chunkBytes * 2,
|
||||
"large.bin",
|
||||
"/fixture/archive.asar",
|
||||
controller.signal,
|
||||
);
|
||||
const failed = new Promise<Error>((resolve) =>
|
||||
output.once("error", resolve),
|
||||
);
|
||||
output.pause();
|
||||
output.read(0);
|
||||
await expect(failed).resolves.toMatchObject({
|
||||
reason: "cancelled",
|
||||
cause: cancellation,
|
||||
});
|
||||
expect(readCalls).toBe(1);
|
||||
});
|
||||
|
||||
it("rejects out-of-bounds range reads with declared-size integrity failure", async () => {
|
||||
const read = (async (target: Buffer, _offset: number, length: number) => ({
|
||||
bytesRead: length + 1,
|
||||
buffer: target,
|
||||
})) as FileHandle["read"];
|
||||
const output = readValidatedAsarRange(
|
||||
{ read },
|
||||
0,
|
||||
16,
|
||||
"overread.bin",
|
||||
"/fixture/archive.asar",
|
||||
);
|
||||
await expect(buffer(output)).rejects.toMatchObject({
|
||||
reason: "integrity",
|
||||
integrityCheck: "declared-size",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("ASAR entry producer identity", () => {
|
||||
it.each([false, true] as const)(
|
||||
"rejects a copied entry with a changed unpacked flag for unpacked=%s",
|
||||
|
||||
@@ -2,8 +2,8 @@ import { lstat, mkdir, rm, writeFile } from "node:fs/promises";
|
||||
import { createHash } from "node:crypto";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { createPackage } from "@electron/asar";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { createPackage, createPackageWithOptions } from "@electron/asar";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { scanArtifactInventory } from "../../fixtures/artifactInventory.js";
|
||||
import { readJavaScriptArtifactFiles } from "../../support/javascriptApplicationScope.js";
|
||||
@@ -343,3 +343,160 @@ it.each(["file-first", "link-first"] as const)(
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
const createSelectiveAsarFixture = async () => {
|
||||
const root = await createTestTempDirectory("rea-asar-source-paths-");
|
||||
const source = join(root, "source");
|
||||
const archive = join(root, "app.asar");
|
||||
await mkdir(source);
|
||||
const largeBody = `export const payload = "${"x".repeat(300 * 1024)}";\n`;
|
||||
await writeFile(join(source, "main.js"), "export const main = 1;\n");
|
||||
await writeFile(join(source, "unselected.js"), "export const unused = 2;\n");
|
||||
await writeFile(join(source, "small.js"), "");
|
||||
await writeFile(join(source, "large.js"), largeBody);
|
||||
await writeFile(
|
||||
join(source, "addon.node"),
|
||||
Buffer.from([0xcf, 0xfa, 0xed, 0xfe, 1]),
|
||||
);
|
||||
await createPackageWithOptions(source, archive, { unpack: "addon.node" });
|
||||
return { source, archive, largeBody };
|
||||
};
|
||||
|
||||
describe("JavaScript ASAR source_paths verification", () => {
|
||||
it("skips opening unselected packed entries while reading selected files and verifying unpacked binaries", async () => {
|
||||
const { archive, largeBody } = await createSelectiveAsarFixture();
|
||||
const snapshot = await scanArtifactInventory(archive);
|
||||
const reader = new AsarArtifactReader(archive);
|
||||
const openSpy = vi.spyOn(reader, "open");
|
||||
try {
|
||||
const result = await readJavaScriptArtifactFiles(
|
||||
reader,
|
||||
snapshot,
|
||||
undefined,
|
||||
["main.js", "large.js", "small.js"],
|
||||
);
|
||||
const openedPaths = openSpy.mock.calls.map(([entry]) => entry.path);
|
||||
expect(openedPaths).not.toContain("unselected.js");
|
||||
expect(openedPaths).toEqual(
|
||||
expect.arrayContaining([
|
||||
"main.js",
|
||||
"large.js",
|
||||
"small.js",
|
||||
"addon.node",
|
||||
]),
|
||||
);
|
||||
expect(result.files.find(({ path }) => path === "main.js")?.text).toEqual(
|
||||
{
|
||||
included: true,
|
||||
value: "export const main = 1;\n",
|
||||
},
|
||||
);
|
||||
expect(
|
||||
result.files.find(({ path }) => path === "small.js")?.text,
|
||||
).toEqual({
|
||||
included: true,
|
||||
value: "",
|
||||
});
|
||||
expect(
|
||||
result.files.find(({ path }) => path === "large.js")?.text,
|
||||
).toEqual({
|
||||
included: true,
|
||||
value: largeBody,
|
||||
});
|
||||
expect(
|
||||
result.files.find(({ path }) => path === "unselected.js")?.text,
|
||||
).toEqual({
|
||||
included: false,
|
||||
reason: "outside-analysis-scope",
|
||||
});
|
||||
expect(
|
||||
result.files.find(({ path }) => path === "addon.node")?.text,
|
||||
).toEqual({
|
||||
included: false,
|
||||
reason: "outside-analysis-scope",
|
||||
});
|
||||
expect(result.source_selection).toEqual({
|
||||
requested_paths: ["main.js", "large.js", "small.js"],
|
||||
unselected_files: 2,
|
||||
});
|
||||
} finally {
|
||||
openSpy.mockRestore();
|
||||
await reader.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects same-size packed archive replacement even when only main.js is selected", async () => {
|
||||
const { source, archive } = await createSelectiveAsarFixture();
|
||||
const snapshot = await scanArtifactInventory(archive);
|
||||
const original = await lstat(archive);
|
||||
await writeFile(
|
||||
join(source, "unselected.js"),
|
||||
"export const unused = 3;\n",
|
||||
);
|
||||
await createPackageWithOptions(source, archive, { unpack: "addon.node" });
|
||||
expect((await lstat(archive)).size).toBe(original.size);
|
||||
|
||||
const reader = new AsarArtifactReader(archive);
|
||||
try {
|
||||
await expect(
|
||||
readJavaScriptArtifactFiles(reader, snapshot, undefined, ["main.js"]),
|
||||
).rejects.toMatchObject({ reason: "integrity" });
|
||||
} finally {
|
||||
await reader.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects unselected packed entry size mismatch against inventory under source_paths", async () => {
|
||||
const { archive } = await createSelectiveAsarFixture();
|
||||
const snapshot = await scanArtifactInventory(archive);
|
||||
const unselectedOccurrence = snapshot.occurrences.find(
|
||||
({ logical_path }) => logical_path === "unselected.js",
|
||||
);
|
||||
if (
|
||||
unselectedOccurrence === undefined ||
|
||||
unselectedOccurrence.artifact_id === null
|
||||
)
|
||||
throw new Error("Expected unselected.js occurrence in snapshot");
|
||||
const tamperedSnapshot = {
|
||||
...snapshot,
|
||||
nodes: snapshot.nodes.map((node) =>
|
||||
node.artifact_id === unselectedOccurrence.artifact_id
|
||||
? { ...node, size: node.size + 1 }
|
||||
: node,
|
||||
),
|
||||
};
|
||||
const reader = new AsarArtifactReader(archive);
|
||||
try {
|
||||
await expect(
|
||||
readJavaScriptArtifactFiles(reader, tamperedSnapshot, undefined, [
|
||||
"main.js",
|
||||
]),
|
||||
).rejects.toMatchObject({
|
||||
reason: "integrity",
|
||||
integrityCheck: "member-identity",
|
||||
});
|
||||
} finally {
|
||||
await reader.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects mutated unpacked companion bytes even when only packed main.js is selected", async () => {
|
||||
const { archive } = await createSelectiveAsarFixture();
|
||||
const snapshot = await scanArtifactInventory(archive);
|
||||
await writeFile(
|
||||
join(`${archive}.unpacked`, "addon.node"),
|
||||
Buffer.from([0xcf, 0xfa, 0xed, 0xfe, 2]),
|
||||
);
|
||||
const reader = new AsarArtifactReader(archive);
|
||||
try {
|
||||
await expect(
|
||||
readJavaScriptArtifactFiles(reader, snapshot, undefined, ["main.js"]),
|
||||
).rejects.toMatchObject({
|
||||
reason: "integrity",
|
||||
integrityCheck: "member-identity",
|
||||
});
|
||||
} finally {
|
||||
await reader.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -19,6 +19,7 @@ import { fileURLToPath } from "node:url";
|
||||
import { parseBinaryTarget } from "../../../src/application/BinaryTargetResolver.js";
|
||||
import { AndroidAnalysisService } from "../../../src/application/android/AndroidAnalysisService.js";
|
||||
import { JadxProvider } from "../../../src/android/JadxProvider.js";
|
||||
import { JADX_RELEASE } from "../../../src/android/JadxRelease.js";
|
||||
import { JadxSession } from "../../../src/android/JadxSession.js";
|
||||
import { androidResultSchemas } from "../../../src/domain/android/androidAnalysis.js";
|
||||
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
|
||||
@@ -397,10 +398,7 @@ it("reuses immutable engine state while keeping each Evidence observation separa
|
||||
expect(JSON.stringify(first.value)).toBe(preserved);
|
||||
expect(second.value.raw_result).toMatchObject({
|
||||
loaded: { class_count: 401 },
|
||||
calls: [
|
||||
expect.objectContaining({ operation: "rea_jvm_status" }),
|
||||
expect.objectContaining({ operation: "get_class_summary" }),
|
||||
],
|
||||
calls: [expect.objectContaining({ operation: "get_class_summary" })],
|
||||
});
|
||||
expect(
|
||||
androidResultSchemas.inspect_android_class.parse(
|
||||
@@ -411,6 +409,119 @@ it("reuses immutable engine state while keeping each Evidence observation separa
|
||||
await verifyCleanup(launches);
|
||||
});
|
||||
|
||||
it("does not cache failed or wrong-version rea_jvm_status and preserves engine_version on warm failures", async () => {
|
||||
const { apk } = await setup();
|
||||
const target = await parseBinaryTarget(apk);
|
||||
if (!target.ok) throw target.error;
|
||||
const fixturePath = fileURLToPath(
|
||||
new URL("../../fixtures/android/jadx-mcp.mjs", import.meta.url),
|
||||
);
|
||||
const startSession = async (mode: string) => {
|
||||
const workspace = await createTestTempDirectory("rea-jadx-runtime-cache-");
|
||||
return new JadxSession(
|
||||
{
|
||||
command: process.execPath,
|
||||
arguments: [],
|
||||
cwd: workspace,
|
||||
hostEnvironment: process.env,
|
||||
signal: new AbortController().signal,
|
||||
},
|
||||
(options) =>
|
||||
spawnOwnedProviderProcess({
|
||||
...options,
|
||||
command: process.execPath,
|
||||
arguments: [fixturePath],
|
||||
expectedCommand: process.execPath,
|
||||
env: { ...options.env, REA_FAKE_JADX_MODE: mode },
|
||||
}),
|
||||
);
|
||||
};
|
||||
const baseContext = {
|
||||
target: target.value,
|
||||
snapshot: apk,
|
||||
jarHash: "0".repeat(64),
|
||||
bridgeHash: "0".repeat(64),
|
||||
bridgeIdentity: packagedJadxBridgeIdentity(),
|
||||
signal: new AbortController().signal,
|
||||
timeoutMs: 10_000,
|
||||
resources: new ArtifactResourceScope(),
|
||||
deadline: new AbortController().signal,
|
||||
};
|
||||
|
||||
const wrongVersion = await startSession("engine-version");
|
||||
onTestFinished(() => wrongVersion.close());
|
||||
try {
|
||||
for (let attempt = 0; attempt < 2; attempt += 1) {
|
||||
await expect(
|
||||
wrongVersion.execute({
|
||||
...baseContext,
|
||||
request: {
|
||||
operation: "inspect_android_package",
|
||||
input: { path: apk },
|
||||
},
|
||||
}),
|
||||
).rejects.toMatchObject({ _tag: "AnalysisCapabilityUnavailableError" });
|
||||
expect(wrongVersion.partialObservation()).toMatchObject({
|
||||
provider_facts: { engine_version: "0.7.0" },
|
||||
calls: [expect.objectContaining({ operation: "rea_jvm_status" })],
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
await wrongVersion.close();
|
||||
}
|
||||
|
||||
const healthy = await startSession("normal");
|
||||
onTestFinished(() => healthy.close());
|
||||
try {
|
||||
await healthy.execute({
|
||||
...baseContext,
|
||||
request: { operation: "inspect_android_package", input: { path: apk } },
|
||||
});
|
||||
await expect(
|
||||
healthy.execute({
|
||||
...baseContext,
|
||||
request: {
|
||||
operation: "inspect_android_class",
|
||||
input: { path: apk, class_name: "fixture.Missing" },
|
||||
},
|
||||
}),
|
||||
).rejects.toMatchObject({ _tag: "AnalysisInputError" });
|
||||
expect(healthy.partialObservation()).toMatchObject({
|
||||
provider_facts: { engine_version: JADX_RELEASE.version },
|
||||
calls: [expect.objectContaining({ operation: "get_class_summary" })],
|
||||
});
|
||||
} finally {
|
||||
await healthy.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("re-queries rea_jvm_status when JadxProvider replaces a session", async () => {
|
||||
const { service, apk, launches, provider, environment } = await setup();
|
||||
const cold = await service.execute("inspect_android_package", { path: apk });
|
||||
if (!cold.ok) throw cold.error;
|
||||
expect(cold.value.raw_result).toMatchObject({
|
||||
calls: expect.arrayContaining([
|
||||
expect.objectContaining({ operation: "rea_jvm_status" }),
|
||||
]) as unknown,
|
||||
});
|
||||
environment.JAVA_TOOL_OPTIONS = "-Xmx8g";
|
||||
const replaced = await service.execute("inspect_android_class", {
|
||||
path: apk,
|
||||
class_name: "fixture.Target",
|
||||
});
|
||||
if (!replaced.ok) throw replaced.error;
|
||||
expect(launches).toHaveLength(2);
|
||||
expect(replaced.value.raw_result).toMatchObject({
|
||||
calls: expect.arrayContaining([
|
||||
expect.objectContaining({ operation: "rea_jvm_status" }),
|
||||
expect.objectContaining({ operation: "load_apk" }),
|
||||
expect.objectContaining({ operation: "get_class_summary" }),
|
||||
]) as unknown,
|
||||
});
|
||||
await provider.close();
|
||||
await verifyCleanup(launches);
|
||||
});
|
||||
|
||||
it("bounds output per operation without repeating prerequisite probes for a retained session", async () => {
|
||||
const { service, apk, launches, provider, javaProbeCount } =
|
||||
await setup("large-manifest");
|
||||
|
||||
@@ -258,7 +258,100 @@ public class ReaJadxExternalReferencesRegression {
|
||||
System.out.println("EXTERNAL_SITE_BUDGET_PASS callers=11 partial_sites=true bounded=true replay=true");
|
||||
}
|
||||
|
||||
private static void verifyDoubleEscapedStringBytes() {
|
||||
Gson gson = new Gson();
|
||||
String[] samples = {
|
||||
"",
|
||||
"classes.dex",
|
||||
"<init>",
|
||||
"\"quoted\"\\slash",
|
||||
"\b\t\n\f\r\u0000\u001f",
|
||||
"<>&='",
|
||||
"\u2028\u2029",
|
||||
"日本語",
|
||||
"😀",
|
||||
"a\uD800b",
|
||||
"a\uDC00b",
|
||||
"fixture.Caller.notify(Ljava/lang/String;ILandroid/app/Notification;)V"
|
||||
};
|
||||
for (String sample : samples) {
|
||||
long expected = gson.toJson(gson.toJson(sample)).getBytes(StandardCharsets.UTF_8).length - 6L;
|
||||
long actual = ReaJadxBridge.doubleEscapedStringBytes(sample);
|
||||
require(actual == expected,
|
||||
"doubleEscapedStringBytes mismatch for " + gson.toJson(sample)
|
||||
+ ": expected=" + expected + " actual=" + actual);
|
||||
}
|
||||
}
|
||||
|
||||
private static void verifyIntermediateExternalQuery(SessionHolder holder, SessionConfig config,
|
||||
Constructor<?> constructor, Method handle, Path output) throws Exception {
|
||||
Path source = output.resolve("MultiExternalTarget.smali");
|
||||
Files.writeString(source,
|
||||
".class public Lfixture/MultiExternalTarget;\n.super Ljava/lang/Object;\n"
|
||||
+ ".method public static useBoth(Landroid/app/NotificationManager;Landroid/app/Notification;Ljava/lang/StringBuilder;Ljava/lang/String;)V\n"
|
||||
+ ".registers 5\n"
|
||||
+ "const/4 v0, 0x1\n"
|
||||
+ "invoke-virtual {p0, v0, p1}, Landroid/app/NotificationManager;->notify(ILandroid/app/Notification;)V\n"
|
||||
+ "invoke-virtual {p2, p3}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;\n"
|
||||
+ "return-void\n.end method\n",
|
||||
StandardCharsets.UTF_8);
|
||||
Path dex = output.resolve("external-intermediate.dex");
|
||||
assemble(dex, List.of(source));
|
||||
Path multiApk = apk(output, "external-intermediate.apk", List.of(dex));
|
||||
BuildersKt.runBlocking(EmptyCoroutineContext.INSTANCE,
|
||||
(scope, continuation) -> holder.unload(continuation));
|
||||
BuildersKt.runBlocking(EmptyCoroutineContext.INSTANCE,
|
||||
(scope, continuation) -> holder.load(multiApk.toString(), config, continuation));
|
||||
Object bridge = constructor.newInstance(holder);
|
||||
JsonObject notifySummary = args(API, "notify", null);
|
||||
notifySummary.addProperty("reference_target", true);
|
||||
JsonObject sbSummary = args("java.lang.StringBuilder", "append", null);
|
||||
sbSummary.addProperty("reference_target", true);
|
||||
require(call(handle, bridge, "get_class_summary", notifySummary)
|
||||
.get("observed_method_count").getAsInt() == 1, "Lost notify prototype");
|
||||
require(call(handle, bridge, "get_class_summary", sbSummary)
|
||||
.get("observed_method_count").getAsInt() == 1, "Lost StringBuilder.append prototype");
|
||||
JsonObject notifyXrefs = call(handle, bridge, "get_xrefs_to_method", external(0));
|
||||
require(notifyXrefs.get("target").getAsString().equals(API + ".notify")
|
||||
&& notifyXrefs.get("count").getAsInt() == 1
|
||||
&& notifyXrefs.getAsJsonArray("items").get(0).getAsJsonObject()
|
||||
.get("containing_class").getAsString().equals("fixture.MultiExternalTarget"),
|
||||
"Intermediate external query corrupted get_xrefs_to_method for notify");
|
||||
JsonObject sbArgs = args("java.lang.StringBuilder", "append", 0);
|
||||
sbArgs.addProperty("reference_target", true);
|
||||
JsonObject sbXrefs = call(handle, bridge, "get_xrefs_to_method", sbArgs);
|
||||
require(sbXrefs.get("target").getAsString().equals("java.lang.StringBuilder.append")
|
||||
&& sbXrefs.get("count").getAsInt() == 1,
|
||||
"StringBuilder.append xrefs lost after notify query");
|
||||
}
|
||||
|
||||
private static void verifyBoundedCallerIndexFallback(SessionHolder holder, SessionConfig config,
|
||||
Constructor<?> constructor, Method handle, Path apk) throws Exception {
|
||||
BuildersKt.runBlocking(EmptyCoroutineContext.INSTANCE,
|
||||
(scope, continuation) -> holder.unload(continuation));
|
||||
BuildersKt.runBlocking(EmptyCoroutineContext.INSTANCE,
|
||||
(scope, continuation) -> holder.load(apk.toString(), config, continuation));
|
||||
Object bridge = constructor.newInstance(holder);
|
||||
Field cap = bridge.getClass().getDeclaredField("maxExternalCallerIndexEntries");
|
||||
cap.setAccessible(true);
|
||||
cap.setInt(bridge, 1);
|
||||
JsonObject summary = call(handle, bridge, "get_class_summary", external(null));
|
||||
require(summary.get("observed_method_count").getAsInt() == 2,
|
||||
"Bounded caller cap dropped prototype summaries");
|
||||
Field invField = bridge.getClass().getDeclaredField("externalInventory");
|
||||
invField.setAccessible(true);
|
||||
Object inventory = invField.get(bridge);
|
||||
Method callersAccessor = inventory.getClass().getDeclaredMethod("callersByShortId");
|
||||
callersAccessor.setAccessible(true);
|
||||
require(callersAccessor.invoke(inventory) == null,
|
||||
"Caller index stayed allocated after exceeding maxExternalCallerIndexEntries");
|
||||
JsonObject references = call(handle, bridge, "get_xrefs_to_method", external(0));
|
||||
require(references.get("count").getAsInt() == 3,
|
||||
"Scan fallback missed callers after dropping oversized caller index");
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
verifyDoubleEscapedStringBytes();
|
||||
Path output = Path.of(args[1]);
|
||||
List<Path> fixtures = fixtures(Path.of(args[0]), output);
|
||||
largeFixture(output);
|
||||
@@ -274,6 +367,8 @@ public class ReaJadxExternalReferencesRegression {
|
||||
try {
|
||||
verify(holder, config, constructor, handle, fixtures.get(0), "classes.dex");
|
||||
verify(holder, config, constructor, handle, fixtures.get(1), "classes2.dex");
|
||||
verifyIntermediateExternalQuery(holder, config, constructor, handle, output);
|
||||
verifyBoundedCallerIndexFallback(holder, config, constructor, handle, fixtures.get(0));
|
||||
verifySiteBudget(holder, config, constructor, handle, siteHeavy);
|
||||
verifyPrototypeLimit(holder, config, constructor, handle, oversizedPrototype);
|
||||
System.out.println("EXTERNAL_REFERENCE_REGRESSION_PASS prototypes=2 using_nodes=3 sites=4 overloaded_callers=true nested=true multidex=true no_source=true post_codegen=true");
|
||||
|
||||
@@ -1132,10 +1132,73 @@ public class ReaJadxMetadataRegression {
|
||||
verifyInitializers(holder, config, constructor, handle, initializerApk);
|
||||
verifyDirectInvokes(holder, config, constructor, handle,
|
||||
Path.of(args[3]), Path.of(args[2]));
|
||||
verifyLargeOverloadedClass(holder, config, constructor, handle, Path.of(args[2]));
|
||||
verifyRootManifests(holder, config, constructor, handle, Path.of(args[2]));
|
||||
} finally {
|
||||
BuildersKt.runBlocking(EmptyCoroutineContext.INSTANCE,
|
||||
(scope, continuation) -> holder.unload(continuation));
|
||||
}
|
||||
}
|
||||
|
||||
private static void verifyLargeOverloadedClass(SessionHolder holder, SessionConfig config,
|
||||
Constructor<?> constructor, Method handle, Path output) throws Exception {
|
||||
Path source = output.resolve("LargeOverloaded.smali");
|
||||
StringBuilder text = new StringBuilder(".class public Lfixture/LargeOverloaded;\n.super Ljava/lang/Object;\n");
|
||||
for (int index = 0; index < 2495; index++) {
|
||||
text.append(".method public static m").append(index).append("()V\n.registers 0\nreturn-void\n.end method\n");
|
||||
}
|
||||
text.append(".method public static pick()I\n.registers 1\nconst/16 v0, 101\nreturn v0\n.end method\n")
|
||||
.append(".method public static pick(I)I\n.registers 1\nconst/16 v0, 102\nreturn v0\n.end method\n")
|
||||
.append(".method public static pick(Ljava/lang/String;)I\n.registers 1\nconst/16 v0, 103\nreturn v0\n.end method\n")
|
||||
.append(".method public static pick(II)I\n.registers 2\nconst/16 v0, 104\nreturn v0\n.end method\n")
|
||||
.append(".method public static pick(J)I\n.registers 2\nconst/16 v0, 105\nreturn v0\n.end method\n")
|
||||
.append(".method public static usePick(Ljava/lang/String;)I\n.registers 1\n"
|
||||
+ "invoke-static {p0}, Lfixture/LargeOverloaded;->pick(Ljava/lang/String;)I\n"
|
||||
+ "move-result v0\nreturn v0\n.end method\n");
|
||||
Files.writeString(source, text, StandardCharsets.UTF_8);
|
||||
Path dex = output.resolve("large-overloaded.dex");
|
||||
SmaliOptions options = new SmaliOptions();
|
||||
options.apiLevel = 28;
|
||||
options.jobs = 1;
|
||||
options.outputDexFile = dex.toString();
|
||||
require(Smali.assemble(options, List.of(source.toString())), "Large overloaded assembly failed");
|
||||
Path apk = output.resolve("large-overloaded.apk");
|
||||
try (ZipOutputStream zip = new ZipOutputStream(Files.newOutputStream(apk))) {
|
||||
zip.putNextEntry(new ZipEntry("classes.dex"));
|
||||
Files.copy(dex, zip);
|
||||
zip.closeEntry();
|
||||
}
|
||||
BuildersKt.runBlocking(EmptyCoroutineContext.INSTANCE,
|
||||
(scope, continuation) -> holder.unload(continuation));
|
||||
BuildersKt.runBlocking(EmptyCoroutineContext.INSTANCE,
|
||||
(scope, continuation) -> holder.load(apk.toString(), config, continuation));
|
||||
Object bridge = constructor.newInstance(holder);
|
||||
ClassNode node = holder.current().getClasses().get(0).getClassNode();
|
||||
require(node.getState() == ProcessState.NOT_LOADED, "Large class preload generated source");
|
||||
JsonObject summary = call(handle, bridge, "get_class_summary", arguments("fixture.LargeOverloaded"));
|
||||
require(summary.get("method_count").getAsInt() == 2501, "Wrong large method count");
|
||||
require(node.getState() == ProcessState.NOT_LOADED, "Large class summary generated source");
|
||||
String[] expectedDescriptors = { "()I", "(I)I", "(II)I", "(J)I", "(Ljava/lang/String;)I" };
|
||||
String[] expectedConstants = { "101", "102", "104", "105", "103" };
|
||||
for (int index = 0; index < expectedDescriptors.length; index++) {
|
||||
JsonObject req = arguments("fixture.LargeOverloaded");
|
||||
req.addProperty("method_name", "pick");
|
||||
req.addProperty("overload_index", index);
|
||||
JsonObject body = call(handle, bridge, "get_method_body", req);
|
||||
require(body.get("dex_descriptor").getAsString().equals(expectedDescriptors[index])
|
||||
&& body.get("overload_count").getAsInt() == 5
|
||||
&& body.get("body").getAsString().contains(expectedConstants[index]),
|
||||
"Overload resolution mismatch in 2500-method class at index " + index + ": " + body);
|
||||
}
|
||||
JsonObject lateReq = methodArguments("fixture.LargeOverloaded", "m2490");
|
||||
JsonObject lateBody = call(handle, bridge, "get_method_body", lateReq);
|
||||
require(lateBody.get("dex_descriptor").getAsString().equals("()V"), "Late method lookup failed");
|
||||
JsonObject xrefReq = arguments("fixture.LargeOverloaded");
|
||||
xrefReq.addProperty("method_name", "pick");
|
||||
xrefReq.addProperty("overload_index", 4);
|
||||
JsonObject xrefs = call(handle, bridge, "get_xrefs_to_method", xrefReq);
|
||||
require(xrefs.get("count").getAsInt() == 1
|
||||
&& xrefs.getAsJsonArray("items").get(0).getAsJsonObject().get("name").getAsString().equals("usePick"),
|
||||
"Overloaded xref resolution failed in 2500-method class: " + xrefs);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user