Free fork of NotProton: Windows Steam games in Mac Steam, on CodeWeavers' Wine and Apple's Game Porting Toolkit
Swift apple-silicond3dmetaldxmtdxvkgame-porting-toolkitgptkmac-gamingmacosmetalfxrosetta-2steamsteam-playwinewinecx
Improves Icon Parser logic, improves tests, fixes bugs in resolver
NotProtonNota26167c5e08c
diff --git a/.github/workflows/app.yml b/.github/workflows/app.ymlindex 4638579..4b78d4d 100644--- a/.github/workflows/app.yml+++ b/.github/workflows/app.yml@@ -95,6 +95,7 @@ jobs:run: |make -s sigcheckmake -s webpatch-fixtures+ make -s peicon-fixturesmake -s panel-behaviormake -s spawn-envmake -s compatcheckdiff --git a/Makefile b/Makefileindex 6e9436e..8b58f7f 100644--- a/Makefile+++ b/Makefile@@ -56,7 +56,7 @@ OBJS := $(patsubst %.c,$(OUT_DIR)/%.o,$(SRCS))DEPS := $(OBJS:.o=.d).PHONY: all clean rebuild dobby deploy dylib-install sigcheck app-payload app app-zip \- anchorcheck sigdb-fixtures webpatch-fixtures panel-behavior app-tests \+ anchorcheck sigdb-fixtures webpatch-fixtures peicon-fixtures panel-behavior app-tests \tests-list overlay-shim overlay-shim-install overlay-shim-tests \overlay-shim-bench iconmaker icon \appinfo helpers-install ntdll-resolve bridge runcheck compatcheck \@@ -163,6 +163,25 @@ sigdb-fixtures:if [ $$fail -ne 0 ]; then exit 1; fi; \echo "==> $$n sigdb fixtures: none crashed, each exited as $(SIGDB_FIXTURES)/EXPECTED records"+PEICON_CHECK := $(OUT_DIR)/peicon-check++$(PEICON_CHECK): dylib/tests/peicon-check.c dylib/util/peicon.c dylib/util/peicon.h+ @mkdir -p $(dir $@)+ $(CC) -arch $(ARCH) -mmacosx-version-min=$(MIN_VER) -std=c17 -g -O1 \+ -Wall -Wextra -Wno-unused-parameter -Idylib \+ -o $@ dylib/tests/peicon-check.c dylib/util/peicon.c++peicon-fixtures:+ @if [ ! -f dylib/tests/peicon-check.c ]; then \+ $(call SKIP,peicon-fixtures,dylib/tests/peicon-check.c); exit 0; fi; \+ $(MAKE) -s $(PEICON_CHECK) || exit 1; \+ tmp=$$(mktemp -d); \+ $(PEICON_CHECK) "$$tmp"; rc=$$?; \+ rm -rf "$$tmp"; \+ if [ $$rc -eq 9 ]; then \+ echo "peicon-check ran out of time, so a hostile resource tree is unbounded"; fi; \+ exit $$rc+GATECHECK := $(OUT_DIR)/gatecheckWEBPATCH_FIXTURES := dylib/tests/webpatch-fixtures@@ -354,8 +373,10 @@ iconmaker: $(ICONMAKER)$(ICONMAKER): helpers/iconmaker.swift dylib/util/peicon.c dylib/util/peicon.h@mkdir -p $(OUT_DIR)- $(CC) -c -O2 -Wall -Wextra -o $(OUT_DIR)/peicon-host.o dylib/util/peicon.c- swiftc -O -framework AppKit -import-objc-header dylib/util/peicon.h \+ $(CC) -c -arch $(ARCH) -mmacosx-version-min=$(MIN_VER) -std=c17 -O2 \+ -Wall -Wextra -o $(OUT_DIR)/peicon-host.o dylib/util/peicon.c+ swiftc -O -target $(ARCH)-apple-macos$(MIN_VER) \+ -framework AppKit -import-objc-header dylib/util/peicon.h \-o $@ helpers/iconmaker.swift $(OUT_DIR)/peicon-host.o@echo "==> Built $@"@@ -365,7 +386,7 @@ appinfo: $(APPINFO)$(APPINFO): helpers/appinfo.swift@mkdir -p $(OUT_DIR)- swiftc -O -o $@ $<+ swiftc -O -target $(ARCH)-apple-macos$(MIN_VER) -o $@ $<@echo "==> Built $@"helpers-install: $(ICONMAKER) $(APPINFO)diff --git a/app/Sources/NotProtonApp/SystemStatus.swift b/app/Sources/NotProtonApp/SystemStatus.swiftindex 133bf37..e8b46e3 100644--- a/app/Sources/NotProtonApp/SystemStatus.swift+++ b/app/Sources/NotProtonApp/SystemStatus.swift@@ -18,15 +18,16 @@ struct StatusSnapshot: Sendable {var steamRunning: Boolvar updateBlocked: Boolvar crossOver: [CrossOverInstall]- var crossOverLicense: CrossOverLicense.Status?+ var crossOverLicense: [String: CrossOverLicense.Status] = [:]var runner: RunnerStatevar payload: PayloadStatevar installedRunners: [RunnerBuild] = []static func capture(bundledVersion: String) -> StatusSnapshot {let installs = CrossOverSource.discover()- let license = installs.first(where: \.isUsable).map {- CrossOverLicense.check(crossOverRoot: $0.crossOverRoot)+ var licenses: [String: CrossOverLicense.Status] = [:]+ for install in installs where install.isUsable {+ licenses[install.id] = CrossOverLicense.check(crossOverRoot: install.crossOverRoot)}let runner = RunnerStore.state()@@ -36,7 +37,7 @@ struct StatusSnapshot: Sendable {steamRunning: SteamBundle.isRunning,updateBlocked: UpdateBlock.isPresent(),crossOver: installs,- crossOverLicense: license,+ crossOverLicense: licenses,runner: runner,payload: PayloadInspector.inspect(build: runner.buildIdentifier.flatMap(SupportedRunners.build(id:))@@ -57,7 +58,10 @@ final class SystemStatus {private(set) var failure: String?private(set) var failureRemedy: Remedy?- var isBusy: Bool { activity != nil }+ private var runInFlight = false+ private var checkingLicense = false++ var isBusy: Bool { activity != nil || runInFlight || checkingLicense }var isIdle: Bool { !isBusy && !isRefreshing }enum Confirmation: Identifiable, Hashable {@@ -124,6 +128,16 @@ final class SystemStatus {snapshot?.crossOver.filter(\.isUsable) ?? []}+ var crossOverRowsOfferSetUp: Bool {+ let usable = usableCrossOvers+ guard usable.count > 1 else { return false }+ let installed = snapshot?.installedRunners ?? []+ return usable.contains { install in+ if case .supported(let build) = install.support { return !installed.contains(build) }+ return false+ }+ }+// The install a repair of the current tool copies from: the one it was cloned// from when that is still around, so a recopy does not swap Rosetta for FEX.var setupSource: CrossOverInstall? {@@ -139,7 +153,7 @@ final class SystemStatus {let status = await Task.detached(priority: .userInitiated) {CrossOverLicense.check(crossOverRoot: install.crossOverRoot)}.value- snapshot?.crossOverLicense = status+ snapshot?.crossOverLicense[install.id] = statusreturn status}@@ -159,6 +173,9 @@ final class SystemStatus {}func requestInstall() async {+ guard isIdle else { return }+ checkingLicense = true+ defer { checkingLicense = false }if let question = Self.activationQuestion(.install,licensed: await checkLicense()?.licensed,@@ -173,6 +190,9 @@ final class SystemStatus {func requestCompatibilityTool(from chosen: CrossOverInstall? = nil, replacingExisting: Bool = false) async {+ guard isIdle else { return }+ checkingLicense = true+ defer { checkingLicense = false }let install = chosen ?? setupSourceif let question = Self.activationQuestion(.compatibilityTool,@@ -186,6 +206,7 @@ final class SystemStatus {}func switchRunner(to build: RunnerBuild) async {+ guard isIdle else { return }guard build.id != snapshot?.runner.buildIdentifier else { return }await perform(from: RunnerSetup.Phase.staging.label) { progress inlet result = try await Task.detached(priority: .userInitiated) {@@ -240,6 +261,13 @@ final class SystemStatus {from first: String,_ body: (_ progress: @escaping @Sendable (String) -> Void) async throws -> String?) async {+ guard !runInFlight else {+ AppLog.note("run refused: '\(first)' overlaps a run already in flight")+ return+ }+ runInFlight = true+ defer { runInFlight = false }+clearFailure()outcome = nillet run = beginRun(first)diff --git a/app/Sources/NotProtonApp/Views/StatusView.swift b/app/Sources/NotProtonApp/Views/StatusView.swiftindex 6445157..a9abf89 100644--- a/app/Sources/NotProtonApp/Views/StatusView.swift+++ b/app/Sources/NotProtonApp/Views/StatusView.swift@@ -406,7 +406,7 @@ struct StatusView: View {StatusRow(title: install.name,value: "Build \(build.displayVersion)",- tone: snapshot.crossOverLicense?.licensed == true ? .ok : .warning,+ tone: snapshot.crossOverLicense[install.id]?.licensed == true ? .ok : .warning,detail: install.bundle.path(percentEncoded: false),action: installs.count > 1? setUpAction(for: install, build: build, snapshot: snapshot)@@ -515,7 +515,7 @@ struct StatusView: View {value: "Not set up.",tone: .neutral,// Each copy of CrossOver above has its own button when there are several.- action: status.usableCrossOvers.count > 1 ? nil : runnerAction()+ action: status.crossOverRowsOfferSetUp ? nil : runnerAction())case .cloned(let build, let supported):let satisfied = supported && !patchedMissingdiff --git a/app/Tests/NotProtonAppTests/RunnerSwitchTests.swift b/app/Tests/NotProtonAppTests/RunnerSwitchTests.swiftindex 182a39e..0503277 100644--- a/app/Tests/NotProtonAppTests/RunnerSwitchTests.swift+++ b/app/Tests/NotProtonAppTests/RunnerSwitchTests.swift@@ -215,7 +215,7 @@ struct SetupSourceTests {steamRunning: false,updateBlocked: false,crossOver: installs,- crossOverLicense: nil,+ crossOverLicense: [:],runner: runner,payload: PayloadInspector.inspect(bridge: FileManager.default.temporaryDirectory))diff --git a/app/Tests/NotProtonAppTests/SystemStatusTests.swift b/app/Tests/NotProtonAppTests/SystemStatusTests.swiftindex 42dae6e..1757fae 100644--- a/app/Tests/NotProtonAppTests/SystemStatusTests.swift+++ b/app/Tests/NotProtonAppTests/SystemStatusTests.swift@@ -345,7 +345,7 @@ struct LicenseFreshnessTests {steamRunning: false,updateBlocked: false,crossOver: install.map { [$0] } ?? [],- crossOverLicense: license,+ crossOverLicense: install.flatMap { i in license.map { [i.id: $0] } } ?? [:],runner: .none,payload: PayloadInspector.inspect(bridge: bridge))@@ -375,7 +375,7 @@ struct LicenseFreshnessTests {#expect(!fresh.licensed, "the cached verdict was handed back instead of a new one")#expect(- status.snapshot?.crossOverLicense?.licensed == false,+ status.snapshot?.crossOverLicense[install.id]?.licensed == false,"the dialog would still report the verdict the check replaced")}diff --git a/dylib/core/macho.c b/dylib/core/macho.cindex 96029b1..e511c18 100644--- a/dylib/core/macho.c+++ b/dylib/core/macho.c@@ -74,21 +74,27 @@ static const uint8_t *fn_starts_table(const struct mach_header_64 *mh,uint32_t remaining = mh->ncmds;const struct linkedit_data_command *fs = NULL;- uint64_t le_vmaddr = 0, le_fileoff = 0;+ uint64_t le_vmaddr = 0, le_fileoff = 0, le_filesize = 0;int have_le = 0;+ const uint8_t *lc_end = cursor + mh->sizeofcmds;+while (remaining--) {+ if ((size_t)(lc_end - cursor) < sizeof(struct load_command)) return NULL;const struct load_command *lc = (const struct load_command *)cursor;- if (lc->cmdsize < sizeof(*lc)) return NULL;+ if (lc->cmdsize < sizeof(*lc) || lc->cmdsize > (size_t)(lc_end - cursor))+ return NULL;if (lc->cmd == LC_FUNCTION_STARTS && lc->cmdsize >= sizeof(*fs)) {fs = (const struct linkedit_data_command *)cursor;- } else if (lc->cmd == LC_SEGMENT_64) {+ } else if (lc->cmd == LC_SEGMENT_64 &&+ lc->cmdsize >= sizeof(struct segment_command_64)) {const struct segment_command_64 *sc = (const struct segment_command_64 *)cursor;if (strncmp(sc->segname, SEG_LINKEDIT, sizeof(sc->segname)) == 0) {- le_vmaddr = sc->vmaddr;- le_fileoff = sc->fileoff;- have_le = 1;+ le_vmaddr = sc->vmaddr;+ le_fileoff = sc->fileoff;+ le_filesize = sc->filesize;+ have_le = 1;}}cursor += lc->cmdsize;@@ -97,9 +103,11 @@ static const uint8_t *fn_starts_table(const struct mach_header_64 *mh,if (!fs || !have_le || !fs->datasize) return NULL;if (fs->dataoff < le_fileoff) return NULL;+ uint64_t rel = (uint64_t)fs->dataoff - le_fileoff;+ if (rel > le_filesize || (uint64_t)fs->datasize > le_filesize - rel) return NULL;+*out_size = fs->datasize;- return (const uint8_t *)(uintptr_t)(le_vmaddr + (fs->dataoff - le_fileoff)- + (uint64_t)slide);+ return (const uint8_t *)(uintptr_t)(le_vmaddr + rel + (uint64_t)slide);}int np_function_bounds(const struct mach_header_64 *mh, intptr_t slide,diff --git a/dylib/hooks/hook_icon.c b/dylib/hooks/hook_icon.cindex a0ab8a8..c6eac1c 100644--- a/dylib/hooks/hook_icon.c+++ b/dylib/hooks/hook_icon.c@@ -44,13 +44,10 @@ static size_t g_cache_len;static long g_cache_mtime;static long long g_cache_size;-static int runtime_ready(void) {- static int checked;- static int ok;-- if (checked) return ok;- checked = 1;+static pthread_once_t g_runtime_once = PTHREAD_ONCE_INIT;+static int g_runtime_ok;+static void runtime_init(void) {np_get_class = (void *(*)(const char *))dlsym(RTLD_DEFAULT, "objc_getClass");np_sel = (void *(*)(const char *))dlsym(RTLD_DEFAULT, "sel_registerName");g_msg_send = dlsym(RTLD_DEFAULT, "objc_msgSend");@@ -61,10 +58,14 @@ static int runtime_ready(void) {void **rgb = (void **)dlsym(RTLD_DEFAULT, "NSDeviceRGBColorSpace");if (rgb) g_device_rgb = *rgb;- ok = np_get_class && np_sel && g_msg_send && np_release &&- np_pool_push && np_pool_pop && g_device_rgb;- if (!ok) NP_WARN("icon: AppKit runtime unavailable, leaving icons to Steam");- return ok;+ g_runtime_ok = np_get_class && np_sel && g_msg_send && np_release &&+ np_pool_push && np_pool_pop && g_device_rgb;+ if (!g_runtime_ok) NP_WARN("icon: AppKit runtime unavailable, leaving icons to Steam");+}++static int runtime_ready(void) {+ pthread_once(&g_runtime_once, runtime_init);+ return g_runtime_ok;}static void *ico_copy_for_path(const char *path, size_t *out_len) {diff --git a/dylib/resolver/resolver.c b/dylib/resolver/resolver.cindex 02fde0e..0962643 100644--- a/dylib/resolver/resolver.c+++ b/dylib/resolver/resolver.c@@ -42,9 +42,13 @@ static void push(np_resolve_result_t *r, const char *name, uintptr_t addr) {r->items[r->used++] = (np_resolved_t){ .name = name, .site = addr };}+static int usable_code_address(const char *name, uintptr_t addr,+ uintptr_t text, size_t text_sz);+// Single-signature resolution-static uintptr_t scan_aob(np_sig_entry_t *sig, uintptr_t text, size_t text_sz) {- if (!sig->aob_hex[0]) return 0;+uintptr_t np_aob_site(const np_sig_entry_t *sig, uintptr_t text, size_t text_sz) {+ if (!sig || !sig->aob_hex[0]) return 0;+ if (text_sz < sizeof(uint32_t)) return 0;np_byte_pattern_t pat;if (np_compile_pattern(sig->aob_hex, &pat) != 0) {@@ -56,15 +60,66 @@ static uintptr_t scan_aob(np_sig_entry_t *sig, uintptr_t text, size_t text_sz) {np_release_pattern(&pat);if (!hit) return 0;- return hit + (intptr_t)sig->match_offset;+ uintptr_t site = hit - (uintptr_t)(intptr_t)sig->match_offset;+ if (!usable_code_address(sig->name, site, text, text_sz))+ return 0;+ return site;+}++static int anchor_targets_function_entry(np_match_kind_t kind) {+ switch (kind) {+ case NP_MATCH_STRING:+ case NP_MATCH_VTABLE_SLOT:+ case NP_MATCH_CALL_TARGET:+ return 1;+ case NP_MATCH_NONE:+ case NP_MATCH_INSN_AFTER_STRING:+ case NP_MATCH_INSN_PAIR_IN_FN:+ case NP_MATCH_AOB:+ return 0;+ }+ return 0;+}++static int aob_site_plausible(const np_sig_entry_t *sig,+ const struct mach_header_64 *mh, intptr_t slide,+ uintptr_t addr) {+ uintptr_t start = 0, end = 0;+ int bounded = np_function_bounds(mh, slide, addr, &start, &end) == 0;++ if (!anchor_targets_function_entry(sig->anchor.kind)) {+ if (!bounded)+ NP_WARN("resolver: '%s' byte pattern site 0x%lx is not inside any known "+ "function; rejecting", sig->name, (unsigned long)addr);+ return bounded;+ }++ if (bounded) {+ if (start != addr) {+ NP_WARN("resolver: '%s' byte pattern hit 0x%lx is inside 0x%lx, not a "+ "function start; rejecting", sig->name, (unsigned long)addr,+ (unsigned long)start);+ return 0;+ }+ return 1;+ }+ if (!np_looks_like_prologue(addr)) {+ NP_WARN("resolver: '%s' byte pattern hit 0x%lx has no function bounds and "+ "does not open with a prologue; rejecting", sig->name,+ (unsigned long)addr);+ return 0;+ }+ return 1;}static uintptr_t try_anchor(np_sig_entry_t *sig,const struct mach_header_64 *mh, intptr_t slide,uintptr_t text, size_t text_sz) {if (sig->anchor.kind == NP_MATCH_AOB) {- uintptr_t addr = scan_aob(sig, text, text_sz);- if (addr) NP_LOG("resolver: '%s' -> 0x%lx [aob]", sig->name, (unsigned long)addr);+ uintptr_t addr = np_aob_site(sig, text, text_sz);+ if (!addr) return 0;+ if (!aob_site_plausible(sig, mh, slide, addr)) return 0;+ NP_LOG("resolver: '%s' -> 0x%lx [aob]", sig->name, (unsigned long)addr);return addr;}@@ -72,18 +127,11 @@ static uintptr_t try_anchor(np_sig_entry_t *sig,if (sig->anchor.kind != NP_MATCH_NONE)addr = np_locate_anchor(mh, slide, text, text_sz, &sig->anchor);- uintptr_t alt = scan_aob(sig, text, text_sz);+ uintptr_t alt = np_aob_site(sig, text, text_sz);if (!addr) {if (!alt) return 0;-- uintptr_t start = 0, end = 0;- if (np_function_bounds(mh, slide, alt, &start, &end) == 0 && start != alt) {- NP_WARN("resolver: '%s' byte pattern hit 0x%lx is inside 0x%lx, not a "- "function start; rejecting", sig->name, (unsigned long)alt,- (unsigned long)start);- return 0;- }+ if (!aob_site_plausible(sig, mh, slide, alt)) return 0;NP_LOG("resolver: '%s' -> 0x%lx [aob, anchor did not resolve]",sig->name, (unsigned long)alt);diff --git a/dylib/resolver/resolver.h b/dylib/resolver/resolver.hindex def7b22..a249f7d 100644--- a/dylib/resolver/resolver.h+++ b/dylib/resolver/resolver.h@@ -21,6 +21,8 @@ typedef struct {// True when the 32-bit value at `addr` looks like a common AArch64 prologue.int np_looks_like_prologue(uintptr_t addr);+uintptr_t np_aob_site(const np_sig_entry_t *sig, uintptr_t text, size_t text_sz);+// Resolve the signatures in `sigdb` that name `module` against the live image at// `mh`+`slide`. Entries belonging to another image are left out of `out`.int np_resolve_signatures(const struct mach_header_64 *mh, intptr_t slide,diff --git a/dylib/resolver/sigdb.c b/dylib/resolver/sigdb.cindex aeeefaf..78abf3a 100644--- a/dylib/resolver/sigdb.c+++ b/dylib/resolver/sigdb.c@@ -208,8 +208,15 @@ int np_load_profile(const char *path, np_sigdb_t *out) {if ((v = cJSON_GetObjectItem(elem, "deprecated")))e->deprecated = cJSON_IsTrue(v);- if ((v = cJSON_GetObjectItem(elem, "match_offset")))- e->match_offset = (int32_t)v->valueint;+ if ((v = cJSON_GetObjectItem(elem, "match_offset"))) {+ if (cJSON_IsNumber(v)) {+ e->match_offset = (int32_t)v->valueint;+ } else {+ NP_WARN("sigdb: '%s' has a non-numeric match_offset; dropping "+ "its byte pattern", e->name);+ e->aob_hex[0] = '\0';+ }+ }load_anchor(elem, &e->anchor);diff --git a/dylib/tests/anchorcheck.c b/dylib/tests/anchorcheck.cindex d823873..305e33c 100644--- a/dylib/tests/anchorcheck.c+++ b/dylib/tests/anchorcheck.c@@ -97,20 +97,7 @@ static int load_image(const char *module) {// pattern was recorded from.static uintptr_t resolve_by_aob(np_sig_entry_t *sig,uintptr_t text, size_t text_sz) {- if (!sig->aob_hex[0]) return 0;-- np_byte_pattern_t pat;- if (np_compile_pattern(sig->aob_hex, &pat) != 0) return 0;- uintptr_t addr = np_scan_sole_match(text, text_sz, &pat);- np_release_pattern(&pat);- if (!addr) return 0;-- if (sig->match_offset) {- uintptr_t adj = addr - (uintptr_t)sig->match_offset;- if (adj < text || adj >= text + text_sz) return 0;- addr = adj;- }- return addr;+ return np_aob_site(sig, text, text_sz);}static const char *kind_name(np_match_kind_t k) {@@ -269,6 +256,52 @@ static int check_db(dbcheck_t *db) {return 0;}+static int check_aob_fallback(const char *path) {+ np_sigdb_t db = {0};+ if (np_load_profile(path, &db) != 0) {+ fprintf(stderr, "cannot reload sigdb '%s'\n", path);+ return 1;+ }+ for (int i = 0; i < db.sig_count; i++) {+ db.signatures[i].anchor.str[0] = '\001';+ db.signatures[i].anchor.str[1] = '\0';+ db.signatures[i].anchor.va = 0;+ }++ int bad = 0, checked = 0;+ printf("byte-pattern fallback with every anchor forced to miss\n");+ for (int m = 0; m < g_image_count; m++) {+ np_resolve_result_t res = {0};+ np_resolve_signatures(g_images[m].mh, g_images[m].slide, &db,+ g_images[m].module, &res);++ for (int i = 0; i < db.sig_count; i++) {+ np_sig_entry_t *sig = &db.signatures[i];+ if (strcmp(sig->module, g_images[m].module) != 0) continue;+ if (!sig->aob_hex[0] || !sig->func_addr_this_build) continue;++ uintptr_t got = np_lookup_address(&res, sig->name);+ uintptr_t want = sig->func_addr_this_build + (uintptr_t)g_images[m].slide;+ checked++;+ if (!got) {+ printf(" %-56s recorded=0x%-9lx PATTERN DID NOT RESOLVE\n",+ sig->name, (unsigned long)sig->func_addr_this_build);+ bad++;+ } else if (got != want) {+ printf(" %-56s aob=0x%-9lx recorded=0x%-9lx WRONG ADDRESS\n",+ sig->name, (unsigned long)(got - (uintptr_t)g_images[m].slide),+ (unsigned long)sig->func_addr_this_build);+ bad++;+ }+ }+ np_free_resolution(&res);+ }+ printf(" %d signatures with a pattern and a recorded address, %d wrong\n\n",+ checked, bad);+ np_free_profile(&db);+ return bad;+}+// The database whose recorded addresses the anchors actually landed on describes// the running client. Nothing in the app bundle reports the client build, so it// has to be recognised rather than read.@@ -295,9 +328,9 @@ static int report_db(const dbcheck_t *db, int is_live) {if (r->kind == NP_MATCH_NONE) { verdict = "NO ANCHOR"; bad++; }else if (!r->anchor) { verdict = (r->has_pattern && r->aob)- ? "anchor failed, aob resolves"- : "UNRESOLVED";- if (!(r->has_pattern && r->aob)) bad++; }+ ? "ANCHOR FAILED (aob resolves)"+ : "ANCHOR FAILED";+ if (is_live) bad++; }else if (!is_live) { verdict = (r->has_pattern && r->aob && r->aob != r->anchor)? "stale pattern hit elsewhere": "resolved"; }@@ -375,8 +408,13 @@ int main(int argc, char **argv) {return 2;}dbs[i].loaded = 1;- for (int j = 0; j < dbs[i].sigdb.sig_count; j++)- if (load_image(dbs[i].sigdb.signatures[j].module) != 0) return 3;+ for (int j = 0; j < dbs[i].sigdb.sig_count; j++) {+ const char *mod = dbs[i].sigdb.signatures[j].module;+ if (load_image(mod) == 0) continue;+ fprintf(stderr, "sigdb '%s' names module '%s', which will not load\n",+ dbs[i].path, mod);+ return strcmp(mod, NP_MODULE_DEFAULT) == 0 ? 3 : 2;+ }}for (int i = 0; i < n; i++) {if (check_db(&dbs[i]) != 0) return 2;@@ -395,6 +433,7 @@ int main(int argc, char **argv) {} else {const image_t *sc = image_for(NP_MODULE_DEFAULT);bad += run_rtti(sc->mh, sc->slide, sc->text, sc->text_sz, dbs[live].build);+ bad += check_aob_fallback(dbs[live].path);}for (int i = 0; i < n; i++) {diff --git a/dylib/tests/peicon-check.c b/dylib/tests/peicon-check.cnew file mode 100644index 0000000..2910867--- /dev/null+++ b/dylib/tests/peicon-check.c@@ -0,0 +1,292 @@+#include "../util/peicon.h"++#include <signal.h>+#include <stdint.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <unistd.h>++#define PEO 0x80u+#define OPT_SIZE 240u+#define SECT_OFF (PEO + 24u + OPT_SIZE)+#define RSRC_OFF 0x400u+#define RSRC_RVA 0x1000u+#define BUDGET_SECS 20+#define MAX_ICO (32u * 1024u * 1024u)++static const char *g_case = "startup";++static void on_alarm(int sig) {+ (void)sig;+ static const char msg[] = " did not finish within the time budget\n";+ write(2, "peicon-check: ", 14);+ write(2, g_case, strlen(g_case));+ write(2, msg, sizeof(msg) - 1);+ _exit(9);+}++static void put16(uint8_t *p, unsigned v) {+ p[0] = (uint8_t)(v & 0xFF);+ p[1] = (uint8_t)((v >> 8) & 0xFF);+}++static void put32(uint8_t *p, uint32_t v) {+ p[0] = (uint8_t)(v & 0xFF);+ p[1] = (uint8_t)((v >> 8) & 0xFF);+ p[2] = (uint8_t)((v >> 16) & 0xFF);+ p[3] = (uint8_t)((v >> 24) & 0xFF);+}++static uint8_t *pe_alloc(size_t rsrc_size, size_t *out_total) {+ size_t total = RSRC_OFF + rsrc_size;+ uint8_t *img = calloc(1, total);+ if (!img) return NULL;++ img[0] = 'M';+ img[1] = 'Z';+ put32(img + 0x3C, PEO);++ uint8_t *pe = img + PEO;+ pe[0] = 'P';+ pe[1] = 'E';+ put16(pe + 6, 1);+ put16(pe + 20, OPT_SIZE);+ put16(pe + 24, 0x20B);+ put32(pe + 24 + 108, 16);+ put32(pe + 24 + 112 + 16, RSRC_RVA);++ uint8_t *sect = img + SECT_OFF;+ memcpy(sect, ".rsrc", 5);+ put32(sect + 8, (uint32_t)rsrc_size);+ put32(sect + 12, RSRC_RVA);+ put32(sect + 16, (uint32_t)rsrc_size);+ put32(sect + 20, RSRC_OFF);++ *out_total = total;+ return img;+}++static void dir_header(uint8_t *node, unsigned named, unsigned ids) {+ put16(node + 12, named);+ put16(node + 14, ids);+}++static void dir_entry(uint8_t *node, unsigned slot, uint32_t name, uint32_t off,+ int is_subdir) {+ uint8_t *e = node + 16 + (size_t)slot * 8;+ put32(e, name);+ put32(e + 4, is_subdir ? (off | 0x80000000u) : off);+}++static void data_entry(uint8_t *at, uint32_t rva, uint32_t size) {+ put32(at, rva);+ put32(at + 4, size);+}++static int write_file(const char *path, const uint8_t *buf, size_t len) {+ FILE *f = fopen(path, "wb");+ if (!f) return -1;+ size_t wrote = fwrite(buf, 1, len, f);+ if (fclose(f) != 0 || wrote != len) return -1;+ return 0;+}++static uint8_t *build_selfref(size_t *out_total) {+ unsigned entries = 131070;+ size_t rsrc = 16 + (size_t)entries * 8;+ uint8_t *img = pe_alloc(rsrc, out_total);+ if (!img) return NULL;++ uint8_t *root = img + RSRC_OFF;+ dir_header(root, 65535, 65535);+ for (unsigned i = 0; i < entries; i++)+ dir_entry(root, i, 0, 0, 1);++ return img;+}++#define B_ROOT 0x000u+#define B_T3 0x020u+#define B_T3ID 0x038u+#define B_T14 0x050u+#define B_T14ID 0x068u+#define B_LICON 0x080u+#define B_LGROUP 0x090u+#define B_GROUP 0x100u++static uint8_t *build_group(unsigned count, uint32_t icon_size, size_t *out_total) {+ size_t group_bytes = 6 + (size_t)count * 14;+ size_t icon_at = (B_GROUP + group_bytes + 0xFFF) & ~(size_t)0xFFF;+ size_t rsrc = icon_at + icon_size;++ uint8_t *img = pe_alloc(rsrc, out_total);+ if (!img) return NULL;++ uint8_t *base = img + RSRC_OFF;++ dir_header(base + B_ROOT, 0, 2);+ dir_entry(base + B_ROOT, 0, 3, B_T3, 1);+ dir_entry(base + B_ROOT, 1, 14, B_T14, 1);++ dir_header(base + B_T3, 0, 1);+ dir_entry(base + B_T3, 0, 1, B_T3ID, 1);+ dir_header(base + B_T3ID, 0, 1);+ dir_entry(base + B_T3ID, 0, 0, B_LICON, 0);++ dir_header(base + B_T14, 0, 1);+ dir_entry(base + B_T14, 0, 1, B_T14ID, 1);+ dir_header(base + B_T14ID, 0, 1);+ dir_entry(base + B_T14ID, 0, 0, B_LGROUP, 0);++ data_entry(base + B_LICON, (uint32_t)(RSRC_RVA + icon_at), icon_size);+ data_entry(base + B_LGROUP, (uint32_t)(RSRC_RVA + B_GROUP), (uint32_t)group_bytes);++ uint8_t *group = base + B_GROUP;+ put16(group + 2, 1);+ put16(group + 4, count);+ for (unsigned i = 0; i < count; i++) {+ uint8_t *e = group + 6 + (size_t)i * 14;+ e[0] = 32;+ e[1] = 32;+ e[2] = 0;+ put16(e + 4, 1);+ put16(e + 6, 32);+ put32(e + 8, icon_size);+ put16(e + 12, 1);+ }++ memset(base + icon_at, 0xA5, icon_size);+ return img;+}++static int fails;++static void fail(const char *what) {+ printf(" FAIL %s: %s\n", g_case, what);+ fails++;+}++static void expect_null(const char *dir, const char *name, const uint8_t *img,+ size_t len) {+ char path[1024];+ snprintf(path, sizeof(path), "%s/%s", dir, name);+ g_case = name;+ if (write_file(path, img, len) != 0) { fail("could not write fixture"); return; }++ size_t out = 12345;+ void *ico = np_pe_icon_ico(path, &out);+ if (ico) {+ fail("expected no icon");+ free(ico);+ return;+ }+ printf(" ok %s: refused\n", name);+}++static void expect_bounded(const char *dir, const char *name, const uint8_t *img,+ size_t len) {+ char path[1024];+ snprintf(path, sizeof(path), "%s/%s", dir, name);+ g_case = name;+ if (write_file(path, img, len) != 0) { fail("could not write fixture"); return; }++ size_t out = 0;+ void *ico = np_pe_icon_ico(path, &out);+ if (!ico) { fail("expected an icon"); return; }+ if (out > MAX_ICO) {+ fail("icon exceeds the output ceiling");+ printf(" produced %zu bytes, ceiling is %u\n", out, MAX_ICO);+ free(ico);+ return;+ }+ printf(" ok %s: %zu bytes, within the ceiling\n", name, out);+ free(ico);+}++static void expect_valid_ico(const char *dir, const char *name, const uint8_t *img,+ size_t len, uint32_t icon_size) {+ char path[1024];+ snprintf(path, sizeof(path), "%s/%s", dir, name);+ g_case = name;+ if (write_file(path, img, len) != 0) { fail("could not write fixture"); return; }++ size_t out = 0;+ uint8_t *ico = np_pe_icon_ico(path, &out);+ if (!ico) { fail("expected an icon"); return; }++ if (out < 22) { fail("icon is too short to hold one entry"); free(ico); return; }+ if (ico[0] || ico[1]) fail("reserved field is not zero");+ if (ico[2] != 1 || ico[3] != 0) fail("type is not 1");++ unsigned n = (unsigned)ico[4] | ((unsigned)ico[5] << 8);+ if (n != 1) fail("expected exactly one image");++ if (n == 1) {+ const uint8_t *r = ico + 6;+ uint32_t size = (uint32_t)r[8] | ((uint32_t)r[9] << 8) |+ ((uint32_t)r[10] << 16) | ((uint32_t)r[11] << 24);+ uint32_t at = (uint32_t)r[12] | ((uint32_t)r[13] << 8) |+ ((uint32_t)r[14] << 16) | ((uint32_t)r[15] << 24);+ if (size != icon_size) fail("entry size does not match the resource");+ if ((size_t)at + size > out) fail("entry points outside the buffer");+ if (at == 22 && size == icon_size && ico[at] != 0xA5)+ fail("payload was not copied");+ }++ if (!fails) printf(" ok %s: %zu bytes, one well formed entry\n", name, out);+ free(ico);+}++int main(int argc, char **argv) {+ char dir[1024];+ if (argc > 1) {+ snprintf(dir, sizeof(dir), "%s", argv[1]);+ } else {+ const char *tmp = getenv("TMPDIR");+ snprintf(dir, sizeof(dir), "%speicon-check.XXXXXX",+ tmp && *tmp ? tmp : "/var/tmp/");+ if (!mkdtemp(dir)) { perror("mkdtemp"); return 2; }+ }++ signal(SIGALRM, on_alarm);+ alarm(BUDGET_SECS);++ printf("==> peicon fixtures\n");++ size_t len = 0;+ uint8_t *img = build_selfref(&len);+ if (!img) { fprintf(stderr, "peicon-check: out of memory\n"); return 2; }+ expect_null(dir, "selfref.exe", img, len);+ free(img);++ img = build_group(65535, 65536, &len);+ if (!img) { fprintf(stderr, "peicon-check: out of memory\n"); return 2; }+ expect_bounded(dir, "manyentries.exe", img, len);+ free(img);++ img = build_group(1024, 65536, &len);+ if (!img) { fprintf(stderr, "peicon-check: out of memory\n"); return 2; }+ expect_bounded(dir, "repeated.exe", img, len);+ free(img);++ img = build_group(1, 64, &len);+ if (!img) { fprintf(stderr, "peicon-check: out of memory\n"); return 2; }+ expect_valid_ico(dir, "good.exe", img, len, 64);+ size_t half = len / 2;+ expect_null(dir, "truncated.exe", img, half);+ free(img);++ uint8_t junk[0x200];+ memset(junk, 0xAA, sizeof(junk));+ expect_null(dir, "notpe.exe", junk, sizeof(junk));++ alarm(0);++ if (fails) {+ printf("==> %d peicon fixture check(s) failed\n", fails);+ return 1;+ }+ printf("==> peicon fixtures: hostile resources bounded, valid icon intact\n");+ return 0;+}diff --git a/dylib/util/peicon.c b/dylib/util/peicon.cindex 7f37611..aa1e146 100644--- a/dylib/util/peicon.c+++ b/dylib/util/peicon.c@@ -13,6 +13,10 @@#define NP_PE_MAX_LEAVES 4096#define NP_PE_MAX_IMAGE (16 * 1024 * 1024)#define NP_PE_MAX_DEPTH 3+#define NP_PE_MAX_ENTRIES 512+#define NP_PE_MAX_VISITS 65536+#define NP_PE_MAX_ICO (32 * 1024 * 1024)+#define NP_PE_MAX_ICO_IMGS 64#define NP_RT_ICON 3#define NP_RT_GROUP_ICON 14@@ -38,6 +42,7 @@ typedef struct {int nsects;np_leaf_t *leaves;int nleaves;+ uint32_t visits;} np_pe_t;static int rd_u8(const np_pe_t *pe, size_t off, uint8_t *out) {@@ -94,7 +99,12 @@ static void walk(np_pe_t *pe, size_t base, size_t node, int depth,if (!rd_u16(pe, node + 12, &named) || !rd_u16(pe, node + 14, &ids)) return;int total = (int)named + (int)ids;+ if (total > NP_PE_MAX_ENTRIES) total = NP_PE_MAX_ENTRIES;+for (int i = 0; i < total; i++) {+ if (pe->visits == 0) return;+ pe->visits--;+size_t entry = node + 16 + (size_t)i * 8;uint32_t name_field, off_field;if (!rd_u32(pe, entry, &name_field) || !rd_u32(pe, entry + 4, &off_field)) return;@@ -161,8 +171,10 @@ static void *build_ico(np_pe_t *pe, uint32_t rsrc_rva, size_t *out_len) {uint16_t count;if (!rva_to_off(pe, group->rva, &group_at)) return NULL;if (group->size < 6) return NULL;+ if (pe->n < group->size || group_at > pe->n - group->size) return NULL;if (!rd_u16(pe, group_at + 4, &count) || count == 0) return NULL;if (group->size < 6 + (uint32_t)count * 14) return NULL;+ if (count > NP_PE_MAX_ICO_IMGS) count = NP_PE_MAX_ICO_IMGS;const np_leaf_t **picked = calloc(count, sizeof(*picked));uint8_t *records = calloc(count, 16);@@ -190,6 +202,13 @@ static void *build_ico(np_pe_t *pe, uint32_t rsrc_rva, size_t *out_len) {if (!rva_to_off(pe, img->rva, &at)) continue;if (pe->n < img->size || at > pe->n - img->size) continue;+ int seen = 0;+ for (int j = 0; j < written; j++) {+ if (picked[j] == img) { seen = 1; break; }+ }+ if (seen) continue;+ if (img->size > NP_PE_MAX_ICO - payload) break;+uint8_t *r = records + (size_t)written * 16;r[0] = w;r[1] = h;@@ -245,6 +264,7 @@ static void *icon_from_map(const uint8_t *map, size_t len, size_t *out_len) {memset(&pe, 0, sizeof(pe));pe.p = map;pe.n = len;+ pe.visits = NP_PE_MAX_VISITS;uint16_t mz;uint32_t peo32, sig;diff --git a/helpers/iconmaker.swift b/helpers/iconmaker.swiftindex b694b64..061f9e8 100644--- a/helpers/iconmaker.swift+++ b/helpers/iconmaker.swift@@ -18,7 +18,7 @@ private func loadImage(_ path: String) -> NSImage? {var length = 0if let raw = np_pe_icon_ico(path, &length) {let ico = Data(bytesNoCopy: raw, count: length, deallocator: .free)- if !ico.isEmpty, let image = NSImage(data: ico) {+ if !ico.isEmpty, let image = NSImage(data: ico), hasArea(image) {FileHandle.standardError.write(Data("iconmaker: using icon from PE resources\n".utf8))return image}@@ -26,7 +26,12 @@ private func loadImage(_ path: String) -> NSImage? {return NSImage(contentsOfFile: path)}-guard let srcImage = loadImage(inputPath) else {+private func hasArea(_ image: NSImage) -> Bool {+ image.size.width > 0 && image.size.height > 0+ && image.size.width.isFinite && image.size.height.isFinite+}++guard let srcImage = loadImage(inputPath), hasArea(srcImage) else {fputs("iconmaker: cannot read \(inputPath)\n", stderr)exit(1)}