diff --git a/docs/gameinput.md b/docs/gameinput.md index 8353b02343..a942f01ee0 100644 --- a/docs/gameinput.md +++ b/docs/gameinput.md @@ -639,8 +639,10 @@ holds stays valid after it leaves the history. | nothing newer, or nothing older after the horizon | `GAMEINPUT_E_READING_NOT_FOUND` | After a pad is plugged back in, its last reading before the unplug leads to the reconnect snapshot, older ones are -`REFERENCE_READING_TOO_OLD`, and sequence numbers carry on. Timestamps are poll times, so a change shorter than one poll -(2 ms with the thread) is not seen. +`REFERENCE_READING_TOO_OLD`, and sequence numbers carry on. Each poll drains SDL's gamepad button and axis events. +For each connected pad, events with the same SDL timestamp form one sample. Intermediate samples reach the history +and reading or Guide callbacks, while the final reading uses the current pad snapshot. GameInput timestamps still +record when the shim polled. A short press is recoverable when the SDL backend reports its two edges with distinct timestamps. ### Device identity @@ -700,8 +702,8 @@ rests on a transcription rather than on a side-by-side compile. - `gameinput_test` (CTest, no controller): turns SDL's real backends off and drives the shim through `rt::shims::find` with SDL virtual joysticks, an Xbox-style pad with trigger motors, a DualSense (Sony `054c:0ce6`) and a pad without trigger motors. It checks enumeration and device callbacks, the button, stick, - trigger and UI-navigation mapping, reading callbacks and sequence numbers, the reading history (a tap read after - the fact, both directions, two pads interleaved and filtered by device, ageing out, held readings, unplug and + trigger and UI-navigation mapping, reading callbacks and sequence numbers, the reading history (a button and trigger + tapped between two shim polls, both directions, two pads interleaved and filtered by device, ageing out, held readings, unplug and replug), the guide button, motor and trigger rumble as SDL receives them, the DualSense effect bytes in each `LEONIDA_DS_TRIGGERS` mode, the lightbar, a dispatcher and its quota, async and blocking enumeration, unregistering, unplugging and replugging, and three identical pads @@ -751,7 +753,7 @@ These need the game executable or a test on hardware: built against one of those, the vtables need a second set. - **IIDs.** `QueryInterface` answers the v0 IIDs from the public header. - **Reading history.** Microsoft's [next reading](https://learn.microsoft.com/en-us/gaming/gdk/docs/reference/input/gameinput/interfaces/igameinput/methods/igameinput_getnextreading) - and [previous reading](https://learn.microsoft.com/en-us/gaming/gdk/docs/reference/input/gameinput/interfaces/igameinput/methods/igameinput_getpreviousreading) pages describe half a second of readings per device and failure when old readings leave the stream. The table above records the shim's HRESULT choices. Changes faster than the poll are not seen. + and [previous reading](https://learn.microsoft.com/en-us/gaming/gdk/docs/reference/input/gameinput/interfaces/igameinput/methods/igameinput_getpreviousreading) pages describe half a second of readings per device and failure when old readings leave the stream. The table above records the shim's HRESULT choices. `GetTemporalReading` returns `E_NOTIMPL` with a null reading on purpose: Microsoft's [reference page](https://learn.microsoft.com/en-us/gaming/gdk/docs/reference/input/gameinput/deprecated/interfaces/igameinput/methods/igameinput_gettemporalreading) says it "was never implemented in v0" and returns `E_NOTIMPL`, and v1 removed it. The v0 header (NuGet diff --git a/runtime/shims/gameinput.cpp b/runtime/shims/gameinput.cpp index b47b5a4fc1..15f2436544 100644 --- a/runtime/shims/gameinput.cpp +++ b/runtime/shims/gameinput.cpp @@ -997,8 +997,6 @@ bool deliver_within(uint64_t quota_us) { uint16_t to_u16(float v) { return static_cast(std::lround(std::clamp(v, 0.0f, 1.0f) * 65535.0f)); } -float axis(SDL_Gamepad* p, SDL_GamepadAxis a) { return std::max(-1.0f, SDL_GetGamepadAxis(p, a) / 32767.0f); } - float norm(float v, float max) { return std::clamp(v / max, -1.0f, 1.0f); } bool is_keyboard_pad(SDL_JoystickID jid); // with the keyboard pad below @@ -1077,10 +1075,23 @@ void apply_prompt_config() { leonida::input_family_name(g_tracker.active())); } -Snapshot read_pad(Device* d) { - SDL_Gamepad* p = d->pad; - Snapshot s; - auto down = [p](SDL_GamepadButton b) { return SDL_GetGamepadButton(p, b); }; +void set_pad_axis(Snapshot& s, SDL_GamepadAxis axis, Sint16 value) { + static constexpr float GameInputGamepadState::* kFields[] = { + &GameInputGamepadState::leftThumbstickX, &GameInputGamepadState::leftThumbstickY, + &GameInputGamepadState::rightThumbstickX, &GameInputGamepadState::rightThumbstickY, + &GameInputGamepadState::leftTrigger, &GameInputGamepadState::rightTrigger, + }; + static_assert(SDL_GAMEPAD_AXIS_COUNT == kAxisCount && SDL_GAMEPAD_AXIS_RIGHT_TRIGGER == kAxisCount - 1); + // GameInput sticks use +Y up; the controller-axis view puts stick rest at 0.5. Triggers use 0..1 in both views. + float v = std::max(-1.0f, value / 32767.0f); + if (axis == SDL_GAMEPAD_AXIS_LEFTY || axis == SDL_GAMEPAD_AXIS_RIGHTY) v = -v; + const bool trigger = axis >= SDL_GAMEPAD_AXIS_LEFT_TRIGGER; + if (trigger) v = std::max(0.0f, v); + s.gamepad.*kFields[axis] = v; + s.axes[axis] = trigger ? v : (v + 1) * 0.5f; +} + +void map_pad_buttons_and_navigation(Snapshot& s) { struct Map { SDL_GamepadButton sdl; uint32_t gi; }; static const Map kMap[] = { {SDL_GAMEPAD_BUTTON_START, GameInputGamepadMenu}, @@ -1098,30 +1109,25 @@ Snapshot read_pad(Device* d) { {SDL_GAMEPAD_BUTTON_LEFT_STICK, GameInputGamepadLeftThumbstick}, {SDL_GAMEPAD_BUTTON_RIGHT_STICK, GameInputGamepadRightThumbstick}, }; + s.gamepad.buttons = 0; for (const Map& m : kMap) - if (down(m.sdl)) s.gamepad.buttons |= m.gi; - // GameInput: sticks in -1..1 with +Y up, triggers in 0..1. SDL: +Y down, -32768..32767, triggers 0..32767. - s.gamepad.leftThumbstickX = axis(p, SDL_GAMEPAD_AXIS_LEFTX); - s.gamepad.leftThumbstickY = -axis(p, SDL_GAMEPAD_AXIS_LEFTY); - s.gamepad.rightThumbstickX = axis(p, SDL_GAMEPAD_AXIS_RIGHTX); - s.gamepad.rightThumbstickY = -axis(p, SDL_GAMEPAD_AXIS_RIGHTY); - s.gamepad.leftTrigger = std::max(0.0f, axis(p, SDL_GAMEPAD_AXIS_LEFT_TRIGGER)); - s.gamepad.rightTrigger = std::max(0.0f, axis(p, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER)); - - // Controller axes, 0..1 with 0.5 at rest for the sticks (VERIFY: the raw-axis convention of a GameInput gamepad). - s.axes[0] = (s.gamepad.leftThumbstickX + 1) * 0.5f; - s.axes[1] = (s.gamepad.leftThumbstickY + 1) * 0.5f; - s.axes[2] = (s.gamepad.rightThumbstickX + 1) * 0.5f; - s.axes[3] = (s.gamepad.rightThumbstickY + 1) * 0.5f; - s.axes[4] = s.gamepad.leftTrigger; - s.axes[5] = s.gamepad.rightTrigger; - for (uint32_t i = 0; i < kButtonCount; ++i) s.buttons[i] = down(static_cast(i)); - s.guide = down(SDL_GAMEPAD_BUTTON_GUIDE); - - // Motion, normalised against the maxima motionInfo reports (the ABI's fraction convention). Sensors were enabled - // when the pad was opened; a pad whose sensor read fails just reports no motion this poll. SDL answers reads - // with zeros before the device's first sample arrives, and gravity makes a real accelerometer never read - // exactly zero, so all-zero accel means "no sample yet" and the reading carries no motion at all. + if (s.buttons[m.sdl]) s.gamepad.buttons |= m.gi; + s.guide = s.buttons[SDL_GAMEPAD_BUTTON_GUIDE]; + + s.ui = rt::gameinput::script::ui_navigation(s.gamepad); +} + +Snapshot read_pad(Device* d) { + SDL_Gamepad* p = d->pad; + Snapshot s; + for (uint32_t i = 0; i < kAxisCount; ++i) { + const auto axis = static_cast(i); + set_pad_axis(s, axis, SDL_GetGamepadAxis(p, axis)); + } + for (uint32_t i = 0; i < kButtonCount; ++i) s.buttons[i] = SDL_GetGamepadButton(p, static_cast(i)); + map_pad_buttons_and_navigation(s); + + // SDL supplies zeros before the first sensor sample. Use nonzero acceleration to detect the first sample. if (d->has_motion) { float accel[3], gyro[3]; if (SDL_GetGamepadSensorData(p, SDL_SENSOR_ACCEL, accel, 3) && @@ -1134,16 +1140,13 @@ Snapshot read_pad(Device* d) { s.motion.angularVelocityX = norm(gyro[0], kMaxAngularVelocity); s.motion.angularVelocityY = norm(gyro[1], kMaxAngularVelocity); s.motion.angularVelocityZ = norm(gyro[2], kMaxAngularVelocity); - // SDL's gamepad API has no compass and the shim synthesises no orientation, so those stay zero and - // unknown rather than a made-up value. + // SDL supplies neither compass nor orientation data. s.motion.accelerometerAccuracy = GameInputMotionAccuracyHigh; s.motion.gyroscopeAccuracy = GameInputMotionAccuracyHigh; s.motion.magnetometerAccuracy = GameInputMotionAccuracyUnknown; s.motion.orientationAccuracy = GameInputMotionAccuracyUnknown; } } - - s.ui = rt::gameinput::script::ui_navigation(s.gamepad); return s; } @@ -2058,13 +2061,15 @@ bool init_sdl() { #ifdef SDL_HINT_JOYSTICK_GAMEINPUT SDL_SetHint(SDL_HINT_JOYSTICK_GAMEINPUT, "0"); #endif - SDL_SetGamepadEventsEnabled(false); // the shim reads state directly; nothing drains an event queue if (!SDL_InitSubSystem(SDL_INIT_GAMEPAD)) { std::fprintf(stderr, "[rt] gameinput: SDL gamepad init failed: %s; no controllers\n", SDL_GetError()); s.sdl_failed = true; return false; } SDL_SetGamepadEventsEnabled(false); + SDL_SetEventEnabled(SDL_EVENT_GAMEPAD_AXIS_MOTION, true); + SDL_SetEventEnabled(SDL_EVENT_GAMEPAD_BUTTON_DOWN, true); + SDL_SetEventEnabled(SDL_EVENT_GAMEPAD_BUTTON_UP, true); s.sdl_ready = true; const int v = SDL_GetVersion(); std::fprintf(stderr, "[rt] gameinput: SDL %d.%d.%d gamepads\n", SDL_VERSIONNUM_MAJOR(v), SDL_VERSIONNUM_MINOR(v), @@ -2072,6 +2077,72 @@ bool init_sdl() { return true; } +std::vector take_pad_events() { + // SDL translates joystick events into gamepad events synchronously. Drain the underlying joystick queue + // as well so this headless input loop cannot fill SDL's queue with events it has already handled. + SDL_FlushEvents(SDL_EVENT_JOYSTICK_AXIS_MOTION, SDL_EVENT_JOYSTICK_UPDATE_COMPLETE); + SDL_FlushEvents(SDL_EVENT_GAMEPAD_ADDED, SDL_EVENT_GAMEPAD_STEAM_HANDLE_UPDATED); + constexpr auto first = SDL_EVENT_GAMEPAD_AXIS_MOTION; + constexpr auto last = SDL_EVENT_GAMEPAD_BUTTON_UP; + const int count = SDL_PeepEvents(nullptr, 0, SDL_PEEKEVENT, first, last); + if (count <= 0) return {}; + std::vector events(count); + const int taken = SDL_PeepEvents(events.data(), count, SDL_GETEVENT, first, last); + events.resize(std::max(taken, 0)); + return events; +} + +void publish_pad_sample(Device* d, const Snapshot& snap, uint64_t now, bool motion_tick = false) { + const bool guide_changed = d->last_snap.guide != snap.guide; + const bool changed = !(d->last_snap == snap); + // Every press is logged in LEONIDA_INPUT_SCRIPT's own form (name@seconds), so a session played by hand can + // be replayed unattended: join the logged items with commas. The right stick's vertical throws (what scrolls + // a page) are logged as rsup/rsdown. LEONIDA_INPUT_LOG=0 turns the lines off. + { + static const bool log_presses = env("LEONIDA_INPUT_LOG") != "0"; + static const ULONGLONG log_origin = GetTickCount64(); + if (log_presses) + rt::gameinput::script::log_presses(snap.gamepad.buttons & ~d->last_snap.gamepad.buttons, + d->last_snap.gamepad.rightThumbstickY, snap.gamepad.rightThumbstickY, + (GetTickCount64() - log_origin) / 1000.0, d->name.c_str()); + } + d->last_snap = snap; + // The first observation of a newly opened pad is a baseline, even if a button is held. + if (const leonida::InputEdge edge = g_tracker.observe(d->id, d->family, sample_of(snap), now); + edge != leonida::InputEdge::None) { + publish_active(); + if (!g_tracker.forced()) + std::fprintf(stderr, "[rt] gameinput: input in use: %s (%s, %s)\n", + leonida::input_family_name(d->family), d->name.c_str(), leonida::input_edge_name(edge)); + } + if (!changed && !motion_tick) return; + std::lock_guard lock(g().mu); + queue_event({CbType::Reading, d, push_reading(d, snap, now), now, 0, 0, false, 0}); + if (guide_changed) queue_event({CbType::Guide, d, nullptr, now, 0, 0, snap.guide, 0}); +} + +void replay_pad_events(Device* d, const std::vector& events, uint64_t now) { + std::optional pending; + Uint64 timestamp = 0; + for (const SDL_Event& e : events) { + const bool axis = e.type == SDL_EVENT_GAMEPAD_AXIS_MOTION; + const SDL_JoystickID id = axis ? e.gaxis.which : e.gbutton.which; + const uint32_t index = axis ? e.gaxis.axis : e.gbutton.button; + if (id != d->id || index >= (axis ? kAxisCount : kButtonCount)) continue; + + if (!pending) { + pending = d->last_snap; + } else if (timestamp != e.common.timestamp) { + map_pad_buttons_and_navigation(*pending); + publish_pad_sample(d, *pending, now); + } + timestamp = e.common.timestamp; + if (axis) set_pad_axis(*pending, static_cast(index), e.gaxis.value); + else pending->buttons[index] = e.gbutton.down; + } + // The final group is represented by the fresh snapshot, which also picks up motion and raw HID state. +} + void poll_once() { State& s = g(); std::lock_guard pl(s.poll_mu); @@ -2080,6 +2151,7 @@ void poll_once() { update_keyboard_pad(); SDL_UpdateGamepads(); const uint64_t now = now_us(); + const auto events = take_pad_events(); int count = 0; SDL_JoystickID* ids = SDL_GetGamepads(&count); @@ -2098,6 +2170,11 @@ void poll_once() { for (Device* d : connected) if (std::find(present.begin(), present.end(), d->id) == present.end() || !SDL_GamepadConnected(d->pad)) close_pad(d, now); + size_t previously_open; + { + std::lock_guard lock(s.mu); + previously_open = s.connected.size(); + } for (SDL_JoystickID jid : present) { bool known = false; { @@ -2111,44 +2188,15 @@ void poll_once() { std::lock_guard lock(s.mu); connected = s.connected; } - for (Device* d : connected) { + for (size_t i = 0; i < connected.size(); ++i) { + Device* d = connected[i]; + const uint64_t last_reading_us = d->last_reading_us; + if (i < previously_open) replay_pad_events(d, events, now); Snapshot snap = read_pad(d); read_raw(d, &snap); - const bool guide_changed = d->last_snap.guide != snap.guide; - const bool changed = !(d->last_snap == snap); - // Every press is logged in LEONIDA_INPUT_SCRIPT's own form (name@seconds), so a session played by hand can - // be replayed unattended: join the logged items with commas. The right stick's vertical throws (what scrolls - // a page) are logged as rsup/rsdown. LEONIDA_INPUT_LOG=0 turns the lines off. - { - static const bool log_presses = env("LEONIDA_INPUT_LOG") != "0"; - static const ULONGLONG log_origin = GetTickCount64(); - if (log_presses) - rt::gameinput::script::log_presses(snap.gamepad.buttons & ~d->last_snap.gamepad.buttons, - d->last_snap.gamepad.rightThumbstickY, snap.gamepad.rightThumbstickY, - (GetTickCount64() - log_origin) / 1000.0, d->name.c_str()); - } - d->last_snap = snap; - // A newly opened pad's first sample here is its baseline (active_input.h), so connecting a pad with a button - // held changes nothing. - if (const leonida::InputEdge edge = g_tracker.observe(d->id, d->family, sample_of(snap), now); - edge != leonida::InputEdge::None) { - publish_active(); - if (!g_tracker.forced()) - std::fprintf(stderr, "[rt] gameinput: input in use: %s (%s, %s)\n", - leonida::input_family_name(d->family), d->name.c_str(), leonida::input_edge_name(edge)); - } - // A pad with sensors streams readings at ~125 Hz even when nothing else changes, so motion the title reads - // between its frames is never stuck at the last button event; pads without sensors only read on change, as - // before. push_reading stamps last_reading_us, so the cadence follows the actual history. - const bool motion_tick = snap.has_motion && now - d->last_reading_us >= kMotionReadingUs; - if (changed || motion_tick) { - std::lock_guard lock(s.mu); - queue_event({CbType::Reading, d, push_reading(d, snap, now), now, 0, 0, false, 0}); - } - if (guide_changed) { - std::lock_guard lock(s.mu); - queue_event({CbType::Guide, d, nullptr, now, 0, 0, snap.guide, 0}); - } + // A pad with sensors still streams readings at ~125 Hz when the controls stay idle. + const bool motion_tick = snap.has_motion && now - last_reading_us >= kMotionReadingUs; + publish_pad_sample(d, snap, now, motion_tick); refresh_battery(d, now); apply_output(d, now); } diff --git a/runtime/test/gameinput_test.cpp b/runtime/test/gameinput_test.cpp index 89d2537f5c..a155fee5a2 100644 --- a/runtime/test/gameinput_test.cpp +++ b/runtime/test/gameinput_test.cpp @@ -1742,6 +1742,47 @@ void test_haptic_motors(IGameInput* input) { dev->Release(); } +void test_buffered_gamepad_input(IGameInput* input) { + Pad pad; + attach(pad, "Leonida buffered input pad", 0x045E, 0x0B12, true); + rt::gameinput::poll(); + IGameInputReading* idle = current(input, nullptr); + IGameInputDevice* dev = device_of(idle); + + GameInputCallbackToken token = 0; + const int callbacks_before = g_reading_events; + check(dev && input->RegisterReadingCallback(dev, GameInputKindGamepad, 0.0f, nullptr, on_reading, &token) == S_OK, + "buffered input: register a reading callback for the virtual pad"); + + // SDL sees two hardware samples before the shim's next poll. Both end states are neutral again. + SDL_SetJoystickVirtualButton(pad.js, SDL_GAMEPAD_BUTTON_SOUTH, true); + SDL_SetJoystickVirtualAxis(pad.js, SDL_GAMEPAD_AXIS_LEFT_TRIGGER, 32767); + SDL_UpdateGamepads(); + SDL_SetJoystickVirtualButton(pad.js, SDL_GAMEPAD_BUTTON_SOUTH, false); + SDL_SetJoystickVirtualAxis(pad.js, SDL_GAMEPAD_AXIS_LEFT_TRIGGER, -32768); + rt::gameinput::poll(); + + HRESULT end = S_OK; + auto readings = walk(input, idle, dev, true, 8, &end); + GameInputGamepadState pressed{}, released{}; + check(readings.size() == 2 && end == GAMEINPUT_E_READING_NOT_FOUND && + readings[0]->GetGamepadState(&pressed) && pressed.buttons == GameInputGamepadA && + approx(pressed.leftTrigger, 1.0f) && readings[1]->GetGamepadState(&released) && + released.buttons == 0 && approx(released.leftTrigger, 0.0f), + "buffered input: history delivers both the short A/trigger press and its release"); + IGameInputReading* latest = current(input, dev); + check(latest && readings.size() == 2 && latest == readings.back() && + g_reading_events - callbacks_before == 2, + "buffered input: two callbacks fire and the current reading stays released"); + + if (token) input->UnregisterCallback(token, 0); + if (latest) latest->Release(); + release_all(readings); + if (idle) idle->Release(); + detach(pad); + rt::gameinput::poll(); +} + } // namespace // A pad plugged in after the title started, with the title holding a dispatcher (RT-GAMEINPUT-LATE-PAD). The title @@ -2444,6 +2485,7 @@ int main(int argc, char** argv) { test_haptic_motors(input); test_raw_hid(input); test_raw_report_during_reconnect(input); + test_buffered_gamepad_input(input); test_late_pad_behind_dispatcher(input); input->Release(); 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())