diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp index d441605057..28a091d7fd 100644 --- a/runtime/src/pe_loader.cpp +++ b/runtime/src/pe_loader.cpp @@ -1769,7 +1769,7 @@ Module& Loader::map_image(const std::filesystem::path& path, const std::string& for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++sec) { if (sec->VirtualAddress < oh.SizeOfHeaders) throw std::runtime_error(m->name + ": section " + std::to_string(i) + " overlaps the headers"); - uint32_t n = std::min(sec->SizeOfRawData, sec->Misc.VirtualSize ? sec->Misc.VirtualSize : sec->SizeOfRawData); + uint32_t n = section_file_bytes(sec->Misc.VirtualSize, sec->SizeOfRawData); if (!n) continue; if (sec->PointerToRawData > file.size() || n > file.size() - sec->PointerToRawData) throw std::runtime_error(m->name + ": section " + std::to_string(i) + " reads past the end of the file"); @@ -2026,20 +2026,14 @@ void Loader::parse_exports(Module& m) { // Follows a forwarder string to the module and export it names. Bundled modules are searched first, with or without // the extension, because a forwarder may point at another mapped module; system DLLs go through LoadLibraryEx, whose // own GetProcAddress already follows its forwarders. Errors are "not found": the caller decides what to bind. -void* Loader::resolve_forwarder(const std::string& spec, Binding& binding, int depth) { +void* Loader::resolve_forwarder(const std::string& spec, Binding& binding, int depth, bool* compat_miss) { if (depth >= 8) return nullptr; // a longer chain is a loop between modules, not a re-export auto dot = spec.rfind('.'); if (dot == std::string::npos || dot == 0 || dot + 1 >= spec.size()) return nullptr; const std::string module = spec.substr(0, dot), symbol = spec.substr(dot + 1); - // A forwarder can name a module the loader shims. Shims take precedence over a bundled or host copy, exactly as - // they do for a direct import in resolve(); without this, a forwarded xmem or d3d12_xs call becomes a failure thunk. std::string shim_key = lower(module); if (shim_key.size() < 4 || shim_key.compare(shim_key.size() - 4, 4, ".dll") != 0) shim_key += ".dll"; - if (void* p = shims::find(shim_key, symbol)) { - binding = Binding::Shim; - return p; - } const bool by_ordinal = symbol.size() > 1 && symbol[0] == '#'; uint32_t ordinal = 0; @@ -2051,6 +2045,32 @@ void* Loader::resolve_forwarder(const std::string& spec, Binding& binding, int d } } + // A drop-in DLL in LEONIDA_COMPAT_DIR owns all of its exports, forwarded ones too, as it does for a direct import + // in resolve(): one module is never served half by a shim or a bundled copy and half by the drop-in. Its file is + // looked up as the bundled module is below: the name as given when it has an extension of its own + // ("winspool.drv"), then with ".dll". + std::vector compat_names; + if (module.find('.') != std::string::npos) compat_names.push_back(module); + if (module.size() < 4 || lower(module).compare(module.size() - 4, 4, ".dll") != 0) compat_names.push_back(module + ".dll"); + for (const std::string& compat_dll : compat_names) { + void* p = nullptr; + if (!resolve_compat(lower(compat_dll), compat_dll, symbol, static_cast(ordinal), by_ordinal, p)) + continue; + if (!p) { + if (compat_miss) *compat_miss = true; + return nullptr; + } + binding = Binding::Host; + return p; + } + + // A forwarder can name a module the loader shims. Shims take precedence over a bundled or host copy, exactly as + // they do for a direct import in resolve(); without this, a forwarded xmem or d3d12_xs call becomes a failure thunk. + if (void* p = shims::find(shim_key, symbol)) { + binding = Binding::Shim; + return p; + } + // shim_key, not the bare module name: forwarder strings usually leave out ".dll" ("MSVCP140.?foo"), and the host // CRT copies are named with it, so a forwarded CRT symbol must skip the bundled Xbox build as a direct import does. const std::filesystem::path candidates[] = {game_dir_ / module, game_dir_ / (module + ".dll")}; @@ -2063,7 +2083,7 @@ void* Loader::resolve_forwarder(const std::string& spec, Binding& binding, int d return it->second; } if (auto it = dep.forwarders.find(symbol); it != dep.forwarders.end()) - return resolve_forwarder(it->second, binding, depth + 1); + return resolve_forwarder(it->second, binding, depth + 1, compat_miss); return nullptr; // the bundled module exists and does not export it; don't look for a host namesake } @@ -2224,10 +2244,17 @@ void* Loader::resolve(Module& m, const std::string& dll, const std::string& name } if (auto it = dep.forwarders.find(sym); it != dep.forwarders.end()) { Binding binding = Binding::Unimplemented; - if (void* p = resolve_forwarder(it->second, binding, 0)) { + bool compat_miss = false; + if (void* p = resolve_forwarder(it->second, binding, 0, &compat_miss)) { m.imports.push_back({dll, sym, binding}); return p; } + // The forwarded module is a LEONIDA_COMPAT_DIR drop-in without this export: a failure thunk, as for a + // direct import, not a System32 namesake of the forwarding module. + if (compat_miss) { + m.imports.push_back({dll, sym, Binding::Unimplemented}); + return shims::make_unimplemented_thunk(dll, sym); + } } } // Host Windows: system DLLs and API sets. LOAD_LIBRARY_SEARCH_SYSTEM32 keeps the game folder out of the search. @@ -2327,7 +2354,8 @@ void Loader::protect_sections(Module& m) { const IMAGE_SECTION_HEADER* cs = IMAGE_FIRST_SECTION(nt); for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++cs) { if (!(cs->Characteristics & IMAGE_SCN_MEM_EXECUTE) || cs->VirtualAddress >= m.size) continue; - const uint64_t size = std::min(std::min(cs->Misc.VirtualSize, cs->SizeOfRawData), + // The bytes map_image copied from the file; a virtual size of 0 is the raw size, not an empty section. + const uint64_t size = std::min(section_file_bytes(cs->Misc.VirtualSize, cs->SizeOfRawData), m.size - cs->VirtualAddress); if (size) code.push_back({m.base + cs->VirtualAddress, static_cast(size)}); } diff --git a/runtime/src/pe_loader.h b/runtime/src/pe_loader.h index 31be1a9d36..1ba8144537 100644 --- a/runtime/src/pe_loader.h +++ b/runtime/src/pe_loader.h @@ -20,6 +20,12 @@ enum class Binding { Shim, Host, Module, Unimplemented }; // No module TLS index has been assigned (matches TLS_OUT_OF_INDEXES without pulling into this header). inline constexpr uint32_t kNoTlsIndex = 0xFFFFFFFFu; +// The bytes of a section that come from the file: its raw data, cut to its virtual size. A virtual size of 0 means the +// raw size (the PE rule map_image follows), so such a section is not empty. +inline constexpr uint32_t section_file_bytes(uint32_t virtual_size, uint32_t raw_size) { + return raw_size < virtual_size || !virtual_size ? raw_size : virtual_size; +} + struct ImportRecord { std::string dll; std::string name; // "#123" for ordinals @@ -167,7 +173,9 @@ class Loader { // its own, as another compat DLL's dependency), else loaded by Windows when `load`. Null with `error` (a Windows // error code) when Windows refused the file, or when it is not loaded and `load` is false. Caller holds mutex_. void* compat_handle(const std::filesystem::path& file, bool load, uint32_t& error); - void* resolve_forwarder(const std::string& spec, Binding& binding, int depth); + // `compat_miss`, when given, is set when a LEONIDA_COMPAT_DIR module owns the forwarded name and lacks the + // export: the caller then binds a failure thunk, as for a direct import, instead of looking further. + void* resolve_forwarder(const std::string& spec, Binding& binding, int depth, bool* compat_miss = nullptr); void parse_exports(Module& m); void protect_sections(Module& m); void register_unwind(Module& m); diff --git a/runtime/test/loader_test.cpp b/runtime/test/loader_test.cpp index aa2dce9d49..8df87ca3c8 100644 --- a/runtime/test/loader_test.cpp +++ b/runtime/test/loader_test.cpp @@ -1493,6 +1493,13 @@ rt::ImportRecord bind_with_compat(const std::filesystem::path& compat, const cha return m.imports[0]; } +// A section's file bytes: its raw data cut to its virtual size, where a virtual size of 0 is the raw size (map_image, +// and the CLZERO scan in protect_sections, which skipped such a section). +static_assert(rt::section_file_bytes(0x100, 0x200) == 0x100); +static_assert(rt::section_file_bytes(0x300, 0x200) == 0x200); +static_assert(rt::section_file_bytes(0, 0x200) == 0x200); +static_assert(rt::section_file_bytes(0x100, 0) == 0); + void test_compat_modules() { const std::filesystem::path compat = g_dir / "compat"; std::filesystem::create_directories(compat); @@ -1524,6 +1531,59 @@ void test_compat_modules() { else if (!bound || bound == reinterpret_cast(&test_shim_function)) failed(what, "F reached the shim"); else pass(what); } + { + // A bundled module's export forwarded into a compat DLL binds to the drop-in, as a direct import does. + const char* what = "LEONIDA_COMPAT_DIR also owns a forwarded export: it binds to the drop-in DLL"; + write_image_as(make_forwarder_image("testcompat.Answer", 0x1C0000000), "fwd_compat.dll"); + auto r = bind_with_compat(compat, "fwd_compat.dll", "fwd", bound); + HMODULE h = GetModuleHandleW(dll_path.c_str()); + auto expected = h ? reinterpret_cast(GetProcAddress(h, "Answer")) : nullptr; + if (r.binding != rt::Binding::Host) failed(what, "the forwarded import was not bound as Host"); + else if (!expected || bound != expected) failed(what, "the IAT does not hold the drop-in's export"); + else if (reinterpret_cast(bound)() != 42) failed(what, "the export did not return 42"); + else pass(what); + } + { + const char* what = "a forwarder into a compat DLL that lacks the symbol is unimplemented, not shimmed"; + write_image_as(make_forwarder_image("testshim.F", 0x1D0000000), "fwd_shim.dll"); + auto r = bind_with_compat(compat, "fwd_shim.dll", "fwd", bound); + if (r.binding != rt::Binding::Unimplemented) failed(what, "F was not left unimplemented"); + else if (!bound || bound == reinterpret_cast(&test_shim_function)) failed(what, "F reached the shim"); + else pass(what); + const char* plain = "without LEONIDA_COMPAT_DIR the same forwarder binds to the shim"; + r = bind_with_compat({}, "fwd_shim.dll", "fwd", bound); + if (r.binding != rt::Binding::Shim || bound != reinterpret_cast(&test_shim_function)) + failed(plain, "F did not bind to the test shim"); + else pass(plain); + } + { + // A forwarding module named like a System32 DLL, whose forwarded export the compat DLL lacks: the import + // gets a failure thunk, as a direct import of the compat DLL would, not the System32 namesake's export. + const char* what = "a compat DLL's missing forwarded export is not taken from a System32 namesake"; + auto img = make_forwarder_image("testcompat.Missing", 0x1E0000000); + std::memcpy(img.data() + 0x380, "GetFileVersionInfoSizeA", 24); + const auto bundled = write_image_as(img, "version.dll"); + auto r = bind_with_compat(compat, "version.dll", "GetFileVersionInfoSizeA", bound); + if (r.binding != rt::Binding::Unimplemented) failed(what, "the import was bound"); + else if (bound == host_symbol("version.dll", "GetFileVersionInfoSizeA") && bound) + failed(what, "the import is the System32 export"); + else pass(what); + std::error_code ec; + std::filesystem::remove(bundled, ec); + } + { + // A forwarder naming a module with its own extension: the compat file is that name, not name + ".dll". + const char* what = "a forwarder to a compat module with its own extension finds that file"; + write_image_as(make_os_dll(0x1F0000000), "compat/testcompat.drv"); + write_image_as(make_forwarder_image("testcompat.drv.Answer", 0x1C8000000), "fwd_drv.dll"); + auto r = bind_with_compat(compat, "fwd_drv.dll", "fwd", bound); + HMODULE h = GetModuleHandleW((compat / "testcompat.drv").c_str()); + auto expected = h ? reinterpret_cast(GetProcAddress(h, "Answer")) : nullptr; + if (r.binding != rt::Binding::Host) failed(what, "the forwarded import was not bound as Host"); + else if (!expected || bound != expected) failed(what, "the IAT does not hold testcompat.drv's export"); + else if (reinterpret_cast(bound)() != 42) failed(what, "the export did not return 42"); + else pass(what); + } { const char* what = "a DLL that is not in the compat folder still binds to its shim"; std::filesystem::path empty = g_dir / "compat_empty"; @@ -1570,7 +1630,7 @@ void test_compat_modules() { failed("LEONIDA_COMPAT_DIR", e.what()); } // Loaders keep compat DLLs for the process lifetime; drop the references so the work folder can be removed. - for (const auto& p : {dll_path, compat / "testshim.dll"}) + for (const auto& p : {dll_path, compat / "testshim.dll", compat / "testcompat.drv"}) while (HMODULE h = GetModuleHandleW(p.c_str())) FreeLibrary(h); } diff --git a/tests/test_bcpack_tool.py b/tests/test_bcpack_tool.py index 8f89216efc..4662fbdd89 100644 --- a/tests/test_bcpack_tool.py +++ b/tests/test_bcpack_tool.py @@ -5,12 +5,15 @@ """ from __future__ import annotations +import errno import io +import json import os import struct import sys import tempfile import unittest +from unittest import mock ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TOOLS = os.path.join(ROOT, "tools") @@ -61,6 +64,16 @@ def test_profile_stream_synthetic(self) -> None: self.assertGreaterEqual(h["unique_symbols"], 1) self.assertGreater(len(h["top_symbols"]), 0) + def test_profile_stream_decodes_lanes_once(self) -> None: + with mock.patch.object( + bcpack_tool.bcpack, "decode_lanes", wraps=bcpack_tool.bcpack.decode_lanes + ) as spy: + prof = bcpack_tool.profile_stream( + self.compressed_stream, codec=1, out_size=len(self.original_blocks) + ) + self.assertEqual(spy.call_count, 1) + self.assertEqual(len(prof["histograms"]), 12) + def test_decode_file_synthetic(self) -> None: with tempfile.TemporaryDirectory() as tmp_dir: in_file = os.path.join(tmp_dir, "test.bcpack") @@ -128,6 +141,136 @@ def test_decode_refuses_hardlink_output(self) -> None: with open(in_file, "rb") as f: self.assertEqual(f.read(), self.compressed_stream) + def test_decode_refuses_history_file_output(self) -> None: + with tempfile.TemporaryDirectory() as tmp_dir: + in_file = os.path.join(tmp_dir, "sample.bcpack") + hist_file = os.path.join(tmp_dir, "hist.json") + hist_body = json.dumps({"bc1": {"confirmed": {}}}) + with open(in_file, "wb") as f: + f.write(self.compressed_stream) + with open(hist_file, "w", encoding="utf-8", newline="\n") as f: + f.write(hist_body) + with self.assertRaises(ValueError) as ctx: + bcpack_tool.decode_file( + in_file, hist_file, codec=1, out_size=len(self.original_blocks), history=hist_file + ) + self.assertIn(hist_file, str(ctx.exception)) + with open(hist_file, "r", encoding="utf-8") as f: + self.assertEqual(f.read(), hist_body) + + def test_decode_refuses_symlink_to_history_file(self) -> None: + with tempfile.TemporaryDirectory() as tmp_dir: + in_file = os.path.join(tmp_dir, "sample.bcpack") + hist_file = os.path.join(tmp_dir, "hist.json") + link_file = os.path.join(tmp_dir, "hist_link.json") + hist_body = json.dumps({"bc1": {"confirmed": {}}}) + with open(in_file, "wb") as f: + f.write(self.compressed_stream) + with open(hist_file, "w", encoding="utf-8", newline="\n") as f: + f.write(hist_body) + try: + os.symlink(hist_file, link_file) + except (OSError, NotImplementedError, AttributeError) as e: + self.skipTest(f"symlinks unavailable: {e}") + with self.assertRaises(ValueError) as ctx: + bcpack_tool.decode_file( + in_file, link_file, codec=1, out_size=len(self.original_blocks), history=hist_file + ) + self.assertIn(link_file, str(ctx.exception)) + with open(hist_file, "r", encoding="utf-8") as f: + self.assertEqual(f.read(), hist_body) + + def test_decode_refuses_history_dir_codec_file_output(self) -> None: + with tempfile.TemporaryDirectory() as tmp_dir: + in_file = os.path.join(tmp_dir, "sample.bcpack") + hist_dir = os.path.join(tmp_dir, "hist_dir") + os.makedirs(hist_dir) + hist_file = os.path.join(hist_dir, "bc1.json") + hist_body = json.dumps({"codec": "bc1", "confirmed": {}}) + with open(in_file, "wb") as f: + f.write(self.compressed_stream) + with open(hist_file, "w", encoding="utf-8", newline="\n") as f: + f.write(hist_body) + with self.assertRaises(ValueError) as ctx: + bcpack_tool.decode_file( + in_file, hist_file, codec=1, out_size=len(self.original_blocks), history=hist_dir + ) + self.assertIn(hist_file, str(ctx.exception)) + with open(hist_file, "r", encoding="utf-8") as f: + self.assertEqual(f.read(), hist_body) + + def test_decode_allows_dict_history_api(self) -> None: + with tempfile.TemporaryDirectory() as tmp_dir: + in_file = os.path.join(tmp_dir, "sample.bcpack") + out_file = os.path.join(tmp_dir, "sample.raw") + with open(in_file, "wb") as f: + f.write(self.compressed_stream) + written = bcpack_tool.decode_file( + in_file, + out_file, + codec=1, + out_size=len(self.original_blocks), + history={"bc1": {"confirmed": {}}}, + ) + self.assertEqual(written, len(self.original_blocks)) + with open(out_file, "rb") as f: + self.assertEqual(f.read(), self.original_blocks) + + def test_decode_atomic_write_preserves_existing_output_on_error(self) -> None: + with tempfile.TemporaryDirectory() as tmp_dir: + in_file = os.path.join(tmp_dir, "sample.bcpack") + out_file = os.path.join(tmp_dir, "out.raw") + with open(in_file, "wb") as f: + f.write(self.compressed_stream) + with open(out_file, "wb") as f: + f.write(b"EXISTING_BYTES") + with mock.patch.object(bcpack_tool.os, "replace", side_effect=OSError("simulated replace failure")): + with self.assertRaises(OSError): + bcpack_tool.decode_file( + in_file, out_file, codec=1, out_size=len(self.original_blocks) + ) + with open(out_file, "rb") as f: + self.assertEqual(f.read(), b"EXISTING_BYTES") + leftovers = [name for name in os.listdir(tmp_dir) if name.startswith(".bcpack_tool-")] + self.assertEqual(leftovers, []) + + def test_decode_preserves_output_symlink(self) -> None: + with tempfile.TemporaryDirectory() as tmp_dir: + in_file = os.path.join(tmp_dir, "sample.bcpack") + real_out = os.path.join(tmp_dir, "target.raw") + link_out = os.path.join(tmp_dir, "link.raw") + with open(in_file, "wb") as f: + f.write(self.compressed_stream) + try: + os.symlink(real_out, link_out) + except (OSError, NotImplementedError, AttributeError) as e: + self.skipTest(f"symlinks unavailable: {e}") + written = bcpack_tool.decode_file( + in_file, link_out, codec=1, out_size=len(self.original_blocks) + ) + self.assertEqual(written, len(self.original_blocks)) + self.assertTrue(os.path.islink(link_out)) + with open(real_out, "rb") as f: + self.assertEqual(f.read(), self.original_blocks) + + def test_decode_refuses_symlink_loop(self) -> None: + with tempfile.TemporaryDirectory() as tmp_dir: + in_file = os.path.join(tmp_dir, "sample.bcpack") + loop_a = os.path.join(tmp_dir, "loop_a.raw") + loop_b = os.path.join(tmp_dir, "loop_b.raw") + with open(in_file, "wb") as f: + f.write(self.compressed_stream) + try: + os.symlink(loop_b, loop_a) + os.symlink(loop_a, loop_b) + except (OSError, NotImplementedError, AttributeError) as e: + self.skipTest(f"symlinks unavailable: {e}") + with self.assertRaises(OSError) as ctx: + bcpack_tool.decode_file( + in_file, loop_a, codec=1, out_size=len(self.original_blocks) + ) + self.assertEqual(ctx.exception.errno, errno.ELOOP) + def test_cli_subcommands(self) -> None: with tempfile.TemporaryDirectory() as tmp_dir: in_file = os.path.join(tmp_dir, "sample.bcpack") @@ -288,6 +431,43 @@ def test_malformed_history_json(self) -> None: self._assert_one_error_line(rc, err, "hist.json") self.assertFalse(os.path.exists(out_file)) + def test_malformed_history_dir_with_trailing_slash_attributes_file(self) -> None: + with tempfile.TemporaryDirectory() as tmp_dir: + in_file = os.path.join(tmp_dir, "sample.bcpack") + with open(in_file, "wb") as f: + f.write(self.compressed_stream) + hist_dir = os.path.join(tmp_dir, "hist_dir") + os.makedirs(hist_dir) + with open(os.path.join(hist_dir, "bc1.json"), "w", encoding="utf-8", newline="\n") as f: + f.write("{not json") + out_file = os.path.join(tmp_dir, "out.raw") + rc, err, _ = self._cli( + ["decode", in_file, out_file, "--codec", "1", "--size", "32", + "--history", hist_dir + os.sep], + tmp_dir, "decode_hist_dir", + ) + self._assert_one_error_line(rc, err, "bc1.json") + self.assertIn("hist_dir", err) + self.assertFalse(os.path.exists(out_file)) + + def test_cli_unsupported_codec_exits_2_without_traceback(self) -> None: + with tempfile.TemporaryDirectory() as tmp_dir: + in_file = os.path.join(tmp_dir, "sample.bcpack") + out_file = os.path.join(tmp_dir, "out.raw") + with open(in_file, "wb") as f: + f.write(self.compressed_stream) + with mock.patch.object( + bcpack_tool.bcpack, + "decode_with_info", + side_effect=bcpack_tool.bcpack.BcpackUnsupportedCodec("codec unsupported"), + ): + rc, err, _ = self._cli( + ["decode", in_file, out_file, "--codec", "1", "--size", "32"], + tmp_dir, "decode_unsupported", + ) + self._assert_one_error_line(rc, err, "codec unsupported") + self.assertFalse(os.path.exists(out_file)) + def test_decode_same_input_output_cli_exits_2(self) -> None: with tempfile.TemporaryDirectory() as tmp_dir: in_file = os.path.join(tmp_dir, "same.bcpack") diff --git a/tools/bcpack_tool.py b/tools/bcpack_tool.py index d127250c41..785dac80fc 100644 --- a/tools/bcpack_tool.py +++ b/tools/bcpack_tool.py @@ -11,17 +11,21 @@ from __future__ import annotations import argparse +from contextlib import suppress +import errno import json import os import sys +import tempfile sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import bcpack +from file_mode import published_mode from report_paths import same_report_path -def inspect_stream(raw: bytes, codec: int, out_size: int) -> dict: - """Analyze stream structure, compression ratio and per-lane statistics.""" +def _inspect_decoded_lanes(raw: bytes, codec: int, out_size: int) -> tuple[dict, list[list[int]]]: + """Decode lanes once and build the inspection report alongside the decoded lanes.""" if codec not in bcpack.ALL_CODECS: raise ValueError(f"unsupported BCPack codec id: {codec}") @@ -61,7 +65,7 @@ def inspect_stream(raw: bytes, codec: int, out_size: int) -> dict: trailing_bytes = len(raw) - used ratio = round(len(raw) / out_size, 4) if out_size else 0.0 - return { + info = { "codec": bcpack.CODEC_NAMES[codec], "codec_id": codec, "compressed_bytes": len(raw), @@ -73,12 +77,18 @@ def inspect_stream(raw: bytes, codec: int, out_size: int) -> dict: "total_symbols": total_symbols, "lanes": lane_reports, } + return info, lanes + + +def inspect_stream(raw: bytes, codec: int, out_size: int) -> dict: + """Analyze stream structure, compression ratio and per-lane statistics.""" + info, _ = _inspect_decoded_lanes(raw, codec, out_size) + return info def profile_stream(raw: bytes, codec: int, out_size: int) -> dict: """Generate symbol frequency distribution profile across all lanes.""" - info = inspect_stream(raw, codec, out_size) - lanes, _ = bcpack.decode_lanes(raw, codec, out_size) + info, lanes = _inspect_decoded_lanes(raw, codec, out_size) histograms = [] for idx, lane in enumerate(lanes): @@ -96,6 +106,57 @@ def profile_stream(raw: bytes, codec: int, out_size: int) -> dict: return info +def _history_paths(history: object, codec: int) -> tuple[str | None, list[str]]: + """Return `(display_path, protected_paths)` for an on-disk `history` argument, or `(None, [])`.""" + if history is None or isinstance(history, dict): + return None, [] + hist_path = os.fsdecode(os.fspath(history)) + protected = [hist_path] + display = os.path.normpath(hist_path) + if os.path.isdir(hist_path): + codec_name = bcpack.CODEC_NAMES.get(codec) + if codec_name is not None: + candidate = os.path.join(display, f"{codec_name.lower()}.json") + if os.path.exists(candidate): + protected.append(candidate) + if os.path.isfile(candidate): + display = candidate + return display, protected + + +def _write_output_atomic(destination: str, data: bytes) -> None: + """Publish decoded bytes to `destination` without truncating an existing file on error.""" + parent = os.path.dirname(os.path.abspath(destination)) + if parent: + os.makedirs(parent, exist_ok=True) + + # Special non-regular files (e.g. /dev/null or NUL) cannot be replaced by rename. + if os.path.exists(destination) and not os.path.isfile(destination): + with open(destination, "wb") as f: + f.write(data) + return + + staged = None + try: + with tempfile.NamedTemporaryFile( + mode="wb", + dir=parent or ".", + prefix=".bcpack_tool-", + suffix=".tmp", + delete=False, + ) as f: + staged = f.name + f.write(data) + os.chmod(staged, published_mode(destination)) + os.replace(staged, destination) + staged = None + finally: + if staged is not None: + with suppress(OSError): + os.chmod(staged, 0o600) + os.unlink(staged) + + def decode_file( in_path: str, out_path: str, @@ -111,6 +172,20 @@ def decode_file( f"refusing to overwrite it" ) + hist_label, hist_protected = _history_paths(history, codec) + for target in hist_protected: + if same_report_path(target, out_path): + raise ValueError( + f"output path '{out_path}' names the history path '{target}'; " + f"refusing to overwrite it" + ) + + destination = os.path.realpath(out_path) + if os.path.islink(destination): + raise OSError(errno.ELOOP, os.strerror(errno.ELOOP), out_path) + if os.path.isdir(destination): + raise IsADirectoryError(errno.EISDIR, os.strerror(errno.EISDIR), out_path) + with open(in_path, "rb") as f: raw = f.read() @@ -123,16 +198,13 @@ def decode_file( except ValueError as e: # json.JSONDecodeError from a --history file carries no filename; attribute it, # but do not double-prefix messages that already name the history path. - if history is not None and os.path.basename(str(history)) not in str(e): - raise ValueError(f"{history}: {e}") from e + if hist_label is not None: + base = os.path.basename(os.path.normpath(hist_label)) + if not base or base not in str(e): + raise ValueError(f"{hist_label}: {e}") from e raise - parent = os.path.dirname(os.path.abspath(out_path)) - if parent: - os.makedirs(parent, exist_ok=True) - - with open(out_path, "wb") as f: - f.write(data) + _write_output_atomic(destination, data) return len(data) @@ -220,7 +292,7 @@ def main(argv: list[str] | None = None) -> int: src = args.in_file if args.command == "decode" else args.file try: return _run(args) - except (ValueError, OSError) as e: + except (ValueError, OSError, bcpack.BcpackUnsupportedCodec) as e: print(f"ERROR: {src}: {e}", file=sys.stderr) return 2 @@ -267,5 +339,8 @@ def _run(args: argparse.Namespace) -> int: return 1 if __name__ == "__main__": - sys.stdout.reconfigure(errors="replace") + try: + sys.stdout.reconfigure(errors="replace") + except (AttributeError, ValueError, OSError): + pass sys.exit(main())