Log window: stream the hook's logs over IPC into an in-app Log panel

Add a shared log ring (common/coop/log_ring.hpp): a lossy multi-producer /
single-consumer ring named coop_log_<pid>. The hook logs from several threads,
so producers claim a slot with fetch_add and publish each record with a
release store of its sequence; the consumer reads in order and tolerates
losing the oldest lines if it falls a whole ring behind.

The DLL's logf() now formats once and pushes every line to the ring (the file
trace stays as an opt-in mirror); the worker attaches the ring right after IPC
connect so bring-up is captured. The host (IpcServer) creates the ring at
injection time and exposes drain_logs(); a new LogPanel pulls new lines each
frame into a bounded rolling buffer and renders them with auto-scroll, a
filter, and clear. Added to the View menu (and UiState.show_log).

Verified against Phantom Brave via coop_audio_probe, which now also creates the
ring and drains it: the full hook bring-up trace streamed over IPC. All four
tests pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-06-19 20:25:04 +02:00
parent 0935dccfc4
commit 9557b9ca69
15 changed files with 371 additions and 21 deletions

View File

@@ -125,6 +125,11 @@ Done:
control is disabled when input forwarding is off, and the Audio panel notes when control is disabled when input forwarding is off, and the Audio panel notes when
the render-hook is off (mirroring then uses loopback). Defaults to all-on so the render-hook is off (mirroring then uses loopback). Defaults to all-on so
behavior is unchanged unless you toggle something. behavior is unchanged unless you toggle something.
- **In-app Log window. ✅** The injected DLL streams its log lines to the host
over a shared log ring (`coop_log_<pid>`, a lossy multi-producer ring), and the
host shows them in a **Log** window with auto-scroll, a text filter, and clear.
Replaces tailing `%TEMP%\coop_hook.log` (which stays as an opt-in file mirror).
`coop_audio_probe` drains and prints the same stream headless.
Future work, roughly in priority order: Future work, roughly in priority order:

View File

@@ -0,0 +1,128 @@
// Shared-memory log channel: the injected hook (coop_hook.dll) streams its log
// lines to the host (coop_host.exe), which shows them in a Log window. Separate
// mapping from the input/status SharedBlock, named coop_log_<pid>.
//
// Lossy multi-producer / single-consumer ring: the hook logs from several threads
// (worker, audio render thread, window thread), so producers claim a slot with an
// atomic fetch_add and publish each record with a release store of its sequence;
// the host consumer reads in order and tolerates losing the oldest lines if it
// ever falls a whole ring behind (fine for diagnostics). POD + version-locked.
#pragma once
#include <atomic>
#include <cstdint>
#include <cstring>
#include <string>
namespace coop
{
// 'CLOG' little-endian.
inline constexpr std::uint32_t kLogRingMagic = 0x474F4C43u;
inline constexpr std::uint32_t kLogRingVersion = 1;
// Per-pid mapping name, mirroring the other channels: coop_log_<pid>.
inline constexpr wchar_t kLogRingPrefix[] = L"Local\\coop_log_";
inline constexpr std::uint32_t kLogMsgLen = 192; // chars per line (incl. NUL)
inline constexpr std::uint32_t kLogCapacity = 1024; // ring records
struct LogRecord
{
std::atomic<std::uint64_t> seq; // 0 = empty; else (global index + 1) once written
std::uint32_t pid;
std::uint32_t level; // reserved (0)
std::uint64_t millis; // producer timestamp (GetTickCount64)
char text[kLogMsgLen];
};
struct LogRing
{
std::uint32_t magic;
std::uint32_t version;
std::uint32_t capacity; // number of records
std::uint32_t msg_len; // kLogMsgLen (sanity)
std::atomic<std::uint64_t> write_index; // total records ever claimed (free-running)
std::uint8_t reserved[32];
// LogRecord records[capacity] follows immediately.
};
static_assert(std::atomic<std::uint64_t>::is_always_lock_free,
"log ring needs a lock-free 64-bit atomic for cross-process use");
inline constexpr std::size_t log_ring_total_size(std::uint32_t capacity)
{
return sizeof(LogRing) + static_cast<std::size_t>(capacity) * sizeof(LogRecord);
}
inline LogRecord* log_ring_records(LogRing* r)
{
return reinterpret_cast<LogRecord*>(reinterpret_cast<std::uint8_t*>(r) + sizeof(LogRing));
}
// Host: stamp a freshly created (zero-filled) mapping. Records start empty (seq 0).
inline void log_ring_init(LogRing& r, std::uint32_t capacity)
{
r.capacity = capacity;
r.msg_len = kLogMsgLen;
r.write_index.store(0, std::memory_order_relaxed);
std::memset(r.reserved, 0, sizeof(r.reserved));
r.version = kLogRingVersion;
r.magic = kLogRingMagic; // last
}
inline bool log_ring_valid(const LogRing& r)
{
return r.magic == kLogRingMagic && r.version == kLogRingVersion && r.capacity != 0 &&
r.msg_len == kLogMsgLen;
}
// Producer (hook): append a line. Multi-producer safe.
inline void log_ring_push(LogRing& r, std::uint32_t pid, std::uint64_t millis, const char* text)
{
const std::uint64_t idx = r.write_index.fetch_add(1, std::memory_order_acq_rel);
LogRecord& rec = log_ring_records(&r)[idx % r.capacity];
rec.pid = pid;
rec.level = 0;
rec.millis = millis;
std::strncpy(rec.text, text, kLogMsgLen - 1);
rec.text[kLogMsgLen - 1] = '\0';
rec.seq.store(idx + 1, std::memory_order_release); // publish: record is ready
}
// Consumer (host): emit each new record since `cursor` (advanced in place). Skips
// records lost to ring wrap; stops at an in-flight record and retries next call.
template <typename F>
inline void log_ring_drain(LogRing& r, std::uint64_t& cursor, F&& emit)
{
const std::uint64_t w = r.write_index.load(std::memory_order_acquire);
if (w <= cursor)
{
return;
}
const std::uint64_t lo = (w > r.capacity) ? (w - r.capacity) : 0;
std::uint64_t i = cursor < lo ? lo : cursor; // skip records already overwritten
LogRecord* recs = log_ring_records(&r);
for (; i < w; ++i)
{
LogRecord& rec = recs[i % r.capacity];
const std::uint64_t s = rec.seq.load(std::memory_order_acquire);
if (s == i + 1)
{
emit(rec); // ready
}
else if (s <= i)
{
break; // slot not written for this generation yet (in-flight); retry later
}
// s > i + 1: overwritten before we read it; skip (lost)
}
cursor = i;
}
inline std::wstring log_ring_name(unsigned long target_pid)
{
return std::wstring(kLogRingPrefix) + std::to_wstring(target_pid);
}
} // namespace coop

View File

@@ -1,12 +1,15 @@
#define _CRT_SECURE_NO_WARNINGS #define _CRT_SECURE_NO_WARNINGS
#include "debug_log.hpp" #include "debug_log.hpp"
#include <atomic>
#include <cstdarg> #include <cstdarg>
#include <cstdio> #include <cstdio>
#include <mutex> #include <mutex>
#include <windows.h> #include <windows.h>
#include "coop/log_ring.hpp"
namespace coop::hook namespace coop::hook
{ {
@@ -16,6 +19,7 @@ namespace
std::mutex g_log_mutex; std::mutex g_log_mutex;
FILE* g_log_file = nullptr; FILE* g_log_file = nullptr;
bool g_log_tried = false; bool g_log_tried = false;
std::atomic<coop::LogRing*> g_log_ring{nullptr};
// Logging is opt-in so an injected DLL doesn't write to disk in normal use. // Logging is opt-in so an injected DLL doesn't write to disk in normal use.
// Enable it by setting the COOP_HOOK_LOG environment variable for the target, or // Enable it by setting the COOP_HOOK_LOG environment variable for the target, or
@@ -60,27 +64,37 @@ FILE* log_file_locked()
} // namespace } // namespace
void logf(const char* fmt, ...) void set_log_ring(coop::LogRing* ring)
{ {
std::scoped_lock lock(g_log_mutex); g_log_ring.store(ring, std::memory_order_release);
FILE* f = log_file_locked();
if (f == nullptr)
{
return;
} }
SYSTEMTIME st; void logf(const char* fmt, ...)
GetLocalTime(&st); {
std::fprintf(f, "[%02u:%02u:%02u.%03u pid=%lu] ", st.wHour, st.wMinute, st.wSecond, st.wMilliseconds, // Format the line once.
GetCurrentProcessId()); char line[coop::kLogMsgLen];
va_list args; va_list args;
va_start(args, fmt); va_start(args, fmt);
std::vfprintf(f, fmt, args); std::vsnprintf(line, sizeof(line), fmt, args);
va_end(args); va_end(args);
std::fputc('\n', f); // Stream to the host's Log window over the shared ring (the primary sink).
if (coop::LogRing* ring = g_log_ring.load(std::memory_order_acquire))
{
coop::log_ring_push(*ring, GetCurrentProcessId(), GetTickCount64(), line);
}
// Also mirror to the file when the opt-in trace is enabled.
std::scoped_lock lock(g_log_mutex);
FILE* f = log_file_locked();
if (f != nullptr)
{
SYSTEMTIME st;
GetLocalTime(&st);
std::fprintf(f, "[%02u:%02u:%02u.%03u pid=%lu] %s\n", st.wHour, st.wMinute, st.wSecond,
st.wMilliseconds, GetCurrentProcessId(), line);
std::fflush(f); std::fflush(f);
} }
}
} // namespace coop::hook } // namespace coop::hook

View File

@@ -1,14 +1,21 @@
// Lightweight file logger for diagnosing the injected hook from inside a game. // Lightweight logger for the injected hook. We can't see stdout from an injected
// // DLL, so each line is (a) streamed to the host over the shared log ring for the
// We can't see stdout from an injected DLL, so route diagnostics to a file in // in-app Log window, and (b) optionally written to %TEMP%\coop_hook.log (opt-in;
// %TEMP%\coop_hook.log. Thread-safe, opened lazily, append-only. Intended for // see debug_log.cpp). Thread-safe; cheap enough to leave compiled in.
// development / bring-up; cheap enough to leave compiled in.
#pragma once #pragma once
namespace coop
{
struct LogRing;
}
namespace coop::hook namespace coop::hook
{ {
// Append a printf-style line to %TEMP%\coop_hook.log (prefixed with pid + time). // Append a printf-style line to the log ring (if attached) and the file (if on).
void logf(const char* fmt, ...); void logf(const char* fmt, ...);
// Attach/detach the host's shared log ring so lines stream to the Log window.
void set_log_ring(coop::LogRing* ring);
} // namespace coop::hook } // namespace coop::hook

View File

@@ -14,6 +14,7 @@
#include "audio_hook.hpp" #include "audio_hook.hpp"
#include "coop/audio_ring.hpp" #include "coop/audio_ring.hpp"
#include "coop/log_ring.hpp"
#include "coop/shared_memory.hpp" #include "coop/shared_memory.hpp"
#include "debug_log.hpp" #include "debug_log.hpp"
#include "focus_spoof.hpp" #include "focus_spoof.hpp"
@@ -27,6 +28,7 @@ namespace
coop::hook::IpcClient g_ipc; coop::hook::IpcClient g_ipc;
std::atomic<bool> g_running{true}; std::atomic<bool> g_running{true};
coop::SharedMemory g_audio_shm; // the host's audio ring, opened when present coop::SharedMemory g_audio_shm; // the host's audio ring, opened when present
coop::SharedMemory g_log_shm; // the host's log ring, opened when present
DWORD WINAPI worker_thread(LPVOID) DWORD WINAPI worker_thread(LPVOID)
{ {
@@ -38,6 +40,24 @@ DWORD WINAPI worker_thread(LPVOID)
coop::hook::logf("worker_thread: IPC connect FAILED (no host mapping); exiting"); coop::hook::logf("worker_thread: IPC connect FAILED (no host mapping); exiting");
return 0; return 0;
} }
// Attach the host's log ring first so the rest of bring-up streams to the Log
// window. The host creates it at injection time; it's normally already there.
{
const std::wstring log_name = coop::log_ring_name(GetCurrentProcessId());
if (g_log_shm.open(log_name, coop::log_ring_total_size(coop::kLogCapacity)))
{
auto* lr = g_log_shm.as<coop::LogRing>();
if (coop::log_ring_valid(*lr))
{
coop::hook::set_log_ring(lr);
}
else
{
g_log_shm.reset();
}
}
}
coop::hook::logf("worker_thread: IPC connected"); coop::hook::logf("worker_thread: IPC connected");
// The audio render-hook instantiates a COM enumerator on this thread. // The audio render-hook instantiates a COM enumerator on this thread.
@@ -161,6 +181,7 @@ BOOL APIENTRY DllMain(HMODULE module, DWORD reason, LPVOID reserved)
if (reserved == nullptr) if (reserved == nullptr)
{ {
g_running.store(false, std::memory_order_relaxed); g_running.store(false, std::memory_order_relaxed);
coop::hook::set_log_ring(nullptr);
coop::hook::remove_focus_spoof(); coop::hook::remove_focus_spoof();
coop::hook::remove_xinput_hooks(); coop::hook::remove_xinput_hooks();
coop::hook::remove_audio_hooks(); coop::hook::remove_audio_hooks();

View File

@@ -6,6 +6,7 @@ add_executable(coop_host WIN32
src/injection_panel.cpp src/injection_panel.cpp
src/capture_panel.cpp src/capture_panel.cpp
src/audio_panel.cpp src/audio_panel.cpp
src/log_panel.cpp
src/ui/app_chrome.cpp src/ui/app_chrome.cpp
src/input/xinput_source.cpp src/input/xinput_source.cpp
src/inject/process_list.cpp src/inject/process_list.cpp

View File

@@ -42,6 +42,13 @@ public:
return server_.hook_status(); return server_.hook_status();
} }
// Drain log lines the hook streamed (for the Log window). No-op if not active.
template <typename F>
void drain_logs(F&& emit)
{
server_.drain_logs(std::forward<F>(emit));
}
private: private:
void refresh_processes(); void refresh_processes();
void inject_selected(); void inject_selected();

View File

@@ -22,6 +22,15 @@ bool IpcServer::start(unsigned long target_pid)
block_ = block; block_ = block;
target_pid_ = target_pid; target_pid_ = target_pid;
// Log ring: the injected hook opens this and streams its log lines back for the
// Log window. Best-effort -- the rest of the tool works without it.
if (log_shm_.create(log_ring_name(target_pid), log_ring_total_size(kLogCapacity)))
{
log_ring_ = log_shm_.as<LogRing>();
log_ring_init(*log_ring_, kLogCapacity);
log_cursor_ = 0;
}
return true; return true;
} }
@@ -96,6 +105,9 @@ void IpcServer::stop()
block_ = nullptr; block_ = nullptr;
} }
shm_.reset(); shm_.reset();
log_ring_ = nullptr;
log_shm_.reset();
log_cursor_ = 0;
target_pid_ = 0; target_pid_ = 0;
} }

View File

@@ -5,6 +5,7 @@
#include <array> #include <array>
#include <cstdint> #include <cstdint>
#include "coop/log_ring.hpp"
#include "coop/protocol.hpp" #include "coop/protocol.hpp"
#include "coop/shared_memory.hpp" #include "coop/shared_memory.hpp"
#include "input/input_source.hpp" #include "input/input_source.hpp"
@@ -56,6 +57,17 @@ public:
// reconciles on its next tick. No-op if not started. // reconciles on its next tick. No-op if not started.
void set_subsystem_enabled(std::uint32_t subsystem, bool enabled); void set_subsystem_enabled(std::uint32_t subsystem, bool enabled);
// Drain new log lines streamed by the hook, calling `emit(const LogRecord&)`
// for each. No-op if not started. Header-only so the callback can stay generic.
template <typename F>
void drain_logs(F&& emit)
{
if (log_ring_ != nullptr)
{
log_ring_drain(*log_ring_, log_cursor_, emit);
}
}
[[nodiscard]] bool running() const [[nodiscard]] bool running() const
{ {
return block_ != nullptr; return block_ != nullptr;
@@ -69,6 +81,10 @@ private:
SharedMemory shm_; SharedMemory shm_;
SharedBlock* block_ = nullptr; SharedBlock* block_ = nullptr;
unsigned long target_pid_ = 0; unsigned long target_pid_ = 0;
SharedMemory log_shm_; // shared log ring (named coop_log_<pid>)
LogRing* log_ring_ = nullptr;
std::uint64_t log_cursor_ = 0; // consumer position into the log ring
}; };
} // namespace coop } // namespace coop

75
host/src/log_panel.cpp Normal file
View File

@@ -0,0 +1,75 @@
#include "log_panel.hpp"
#include <cstdio>
#include <cstring>
#include "imgui.h"
#include "injection_panel.hpp"
namespace coop
{
void LogPanel::add_line(const LogRecord& rec)
{
if (first_millis_ == 0)
{
first_millis_ = rec.millis;
}
const double secs = static_cast<double>(rec.millis - first_millis_) / 1000.0;
char buf[256];
std::snprintf(buf, sizeof(buf), "[%8.3f] %s", secs, rec.text);
lines_.emplace_back(buf);
while (lines_.size() > kMaxLines)
{
lines_.pop_front();
}
}
void LogPanel::pull(InjectionPanel& injection)
{
injection.drain_logs([this](const LogRecord& rec) { add_line(rec); });
}
void LogPanel::draw()
{
ImGui::SetNextWindowPos(ImVec2(24, 760), ImGuiCond_FirstUseEver);
ImGui::SetNextWindowSize(ImVec2(720, 240), ImGuiCond_FirstUseEver);
ImGui::Begin("Log");
if (ImGui::Button("Clear"))
{
lines_.clear();
first_millis_ = 0;
}
ImGui::SameLine();
ImGui::Checkbox("Auto-scroll", &autoscroll_);
ImGui::SameLine();
ImGui::SetNextItemWidth(-1.0f);
ImGui::InputTextWithHint("##logfilter", "filter...", filter_, sizeof(filter_));
ImGui::Separator();
if (ImGui::BeginChild("loglines", ImVec2(0, 0), ImGuiChildFlags_None, ImGuiWindowFlags_HorizontalScrollbar))
{
const bool has_filter = filter_[0] != '\0';
for (const std::string& line : lines_)
{
if (has_filter && line.find(filter_) == std::string::npos)
{
continue;
}
ImGui::TextUnformatted(line.c_str());
}
// Stick to the bottom while new lines arrive (unless the user scrolled up).
if (autoscroll_ && ImGui::GetScrollY() >= ImGui::GetScrollMaxY() - 1.0f)
{
ImGui::SetScrollHereY(1.0f);
}
}
ImGui::EndChild();
ImGui::End();
}
} // namespace coop

36
host/src/log_panel.hpp Normal file
View File

@@ -0,0 +1,36 @@
// Log window: shows the log lines the injected hook streams over the shared log
// ring (see coop/log_ring.hpp). Pull new lines each frame from the IPC server,
// keep a bounded rolling history, and render them with autoscroll + a filter.
#pragma once
#include <cstdint>
#include <deque>
#include <string>
#include "coop/log_ring.hpp"
namespace coop
{
class InjectionPanel;
class LogPanel
{
public:
// Pull any new lines the hook emitted (call once per frame before draw()).
void pull(InjectionPanel& injection);
void draw();
private:
void add_line(const LogRecord& rec);
std::deque<std::string> lines_;
char filter_[96] = {};
bool autoscroll_ = true;
std::uint64_t first_millis_ = 0; // hook clock at the first line, for relative timestamps
static constexpr std::size_t kMaxLines = 2000;
};
} // namespace coop

View File

@@ -20,6 +20,7 @@
#include "imgui_layer.hpp" #include "imgui_layer.hpp"
#include "injection_panel.hpp" #include "injection_panel.hpp"
#include "input/xinput_source.hpp" #include "input/xinput_source.hpp"
#include "log_panel.hpp"
#include "ui/app_chrome.hpp" #include "ui/app_chrome.hpp"
namespace namespace
@@ -68,6 +69,7 @@ int run()
coop::InjectionPanel injection; coop::InjectionPanel injection;
coop::AudioPanel audio; coop::AudioPanel audio;
coop::CapturePanel capture; coop::CapturePanel capture;
coop::LogPanel log;
if (!capture.init(window.device())) if (!capture.init(window.device()))
{ {
MessageBoxW(nullptr, L"Failed to initialize the video mirror.", L"CoopAllTheThings", MB_ICONERROR); MessageBoxW(nullptr, L"Failed to initialize the video mirror.", L"CoopAllTheThings", MB_ICONERROR);
@@ -91,6 +93,7 @@ int run()
imgui.begin_frame(); imgui.begin_frame();
stats.tick(ImGui::GetIO().DeltaTime * 1000.0f); stats.tick(ImGui::GetIO().DeltaTime * 1000.0f);
log.pull(injection); // drain hook log lines even while the Log window is hidden
if (ImGui::IsKeyPressed(ImGuiKey_F1, false)) if (ImGui::IsKeyPressed(ImGuiKey_F1, false))
{ {
@@ -120,6 +123,10 @@ int run()
{ {
capture.draw_ui(stats); capture.draw_ui(stats);
} }
if (ui.show_log)
{
log.draw();
}
} }
else else
{ {

View File

@@ -24,6 +24,7 @@ float draw_main_menu_bar(UiState& ui, const FrameStats& stats)
ImGui::MenuItem("Injection", nullptr, &ui.show_injection); ImGui::MenuItem("Injection", nullptr, &ui.show_injection);
ImGui::MenuItem("Video mirror", nullptr, &ui.show_video); ImGui::MenuItem("Video mirror", nullptr, &ui.show_video);
ImGui::MenuItem("Audio mirror", nullptr, &ui.show_audio); ImGui::MenuItem("Audio mirror", nullptr, &ui.show_audio);
ImGui::MenuItem("Log", nullptr, &ui.show_log);
ImGui::Separator(); ImGui::Separator();
ImGui::MenuItem("Debug details", nullptr, &ui.debug_details); ImGui::MenuItem("Debug details", nullptr, &ui.debug_details);
ImGui::EndMenu(); ImGui::EndMenu();

View File

@@ -18,6 +18,7 @@ struct UiState
bool show_injection = true; bool show_injection = true;
bool show_video = true; bool show_video = true;
bool show_audio = true; bool show_audio = true;
bool show_log = true;
bool debug_details = false; // off = general status; on = full diagnostics bool debug_details = false; // off = general status; on = full diagnostics
}; };

View File

@@ -20,6 +20,7 @@
#include <windows.h> #include <windows.h>
#include "coop/audio_ring.hpp" #include "coop/audio_ring.hpp"
#include "coop/log_ring.hpp"
#include "coop/protocol.hpp" #include "coop/protocol.hpp"
#include "coop/shared_memory.hpp" #include "coop/shared_memory.hpp"
@@ -124,6 +125,16 @@ int wmain(int argc, wchar_t** argv)
} }
block->magic = coop::kProtocolMagic; block->magic = coop::kProtocolMagic;
// Log ring (host's role): the hook opens this and streams its log lines back.
coop::SharedMemory log_shm;
coop::LogRing* log_ring = nullptr;
std::uint64_t log_cursor = 0;
if (log_shm.create(coop::log_ring_name(pid), coop::log_ring_total_size(coop::kLogCapacity)))
{
log_ring = log_shm.as<coop::LogRing>();
coop::log_ring_init(*log_ring, coop::kLogCapacity);
}
// Enable the hook's file trace (%TEMP%\coop_hook.log) for this debug session. // Enable the hook's file trace (%TEMP%\coop_hook.log) for this debug session.
{ {
wchar_t dir[MAX_PATH] = {}; wchar_t dir[MAX_PATH] = {};
@@ -259,6 +270,14 @@ int wmain(int argc, wchar_t** argv)
e.installed ? "ON " : "off", static_cast<unsigned long long>(e.calls)); e.installed ? "ON " : "off", static_cast<unsigned long long>(e.calls));
} }
// Drain the IPC log ring to verify the hook streams its logs to the host.
if (log_ring != nullptr)
{
std::printf("\nHook log (streamed over IPC):\n");
coop::log_ring_drain(*log_ring, log_cursor,
[](const coop::LogRecord& rec) { std::printf(" %s\n", rec.text); });
}
std::printf("\nDone. Leaving the hook loaded in the game.\n"); std::printf("\nDone. Leaving the hook loaded in the game.\n");
block->magic = 0; // invalidate so a late hook read won't trust stale data block->magic = 0; // invalidate so a late hook read won't trust stale data
return 0; return 0;