diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..044bc74 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,135 @@ +name: Build + +# Tags publish a release; pushes and PRs just prove it still builds. That +# second half is the point: the Windows build broke three different ways the +# first time anyone tried it (a compiler ICE in a dependency, POSIX-only file +# I/O, and library ordering), none of which a Linux-only workflow would show. +on: + push: + branches: [master] + tags: ['v*'] + pull_request: + branches: [master] + workflow_dispatch: + +jobs: + build-linux: + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - name: Checkout (with submodules) + uses: actions/checkout@v4 + with: + submodules: recursive + + - name: Install build dependencies + run: | + sudo apt-get update -qq + sudo apt-get install -y --no-install-recommends \ + build-essential pkg-config libunicorn-dev libsdl2-dev + + - name: Build + run: make -j"$(nproc)" + + - name: Smoke test + # No display and no sound card on a runner, so this only checks the + # binary starts, reads its ini and rejects a missing payload. That is + # enough to catch a bad link or a missing shared library. + env: + RCM_EMU_NO_AUDIO: "1" + run: | + test -x rcm_emu || { echo "rcm_emu missing"; exit 1; } + ./rcm_emu /nonexistent.bin 2>&1 | tee out.txt || true + grep -q "RCM Payload Emulator" out.txt \ + || { echo "banner missing - binary did not start"; exit 1; } + + - name: Upload artifact + uses: actions/upload-artifact@v4 + with: + name: rcm_emu-linux + path: rcm_emu + if-no-files-found: error + + - name: Attach to release + if: startsWith(github.ref, 'refs/tags/v') + uses: softprops/action-gh-release@v2 + with: + files: rcm_emu + fail_on_unmatched_files: true + generate_release_notes: true + + build-windows: + # Cross-compiled from Linux rather than built on a Windows runner: neither + # dependency has a MinGW package (SDL2 ships a devel tarball, unicorn has + # to be compiled), so the toolchain has to be assembled either way - and + # doing it in the container means CI and a local `make windows` are the + # same build. + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - name: Checkout (with submodules) + uses: actions/checkout@v4 + with: + submodules: recursive + + - name: Set up Buildx + uses: docker/setup-buildx-action@v3 + + - name: Build the cross-compile image + # Cached between runs: compiling unicorn for Windows is the slow part + # and it only changes when the Dockerfile pins a new version. + uses: docker/build-push-action@v6 + with: + context: . + file: Dockerfile.windows + tags: rcm_emu_win:latest + load: true + cache-from: type=gha + cache-to: type=gha,mode=max + + - name: Cross-compile rcm_emu.exe + run: | + docker run --rm -v "$PWD:/work" rcm_emu_win + test -s rcm_emu.exe || { echo "rcm_emu.exe missing"; exit 1; } + file rcm_emu.exe | grep -q "PE32+" \ + || { echo "not a Windows executable"; exit 1; } + + - name: Upload artifact + uses: actions/upload-artifact@v4 + with: + name: rcm_emu-windows + path: rcm_emu.exe + if-no-files-found: error + + - name: Attach to release + if: startsWith(github.ref, 'refs/tags/v') + uses: softprops/action-gh-release@v2 + with: + files: rcm_emu.exe + fail_on_unmatched_files: true + generate_release_notes: true + + smoke-windows: + # The cross-build only proves it links. This proves the .exe actually + # starts on a real Windows machine - the static link, the SDL entry point + # and the unicorn init are all things that can pass the linker and still + # fail at runtime. + needs: build-windows + runs-on: windows-latest + steps: + - name: Download the exe + uses: actions/download-artifact@v4 + with: + name: rcm_emu-windows + + - name: Run it + env: + RCM_EMU_NO_AUDIO: "1" + shell: bash + run: | + ./rcm_emu.exe /nonexistent.bin 2>&1 | tee out.txt || true + grep -q "RCM Payload Emulator" out.txt \ + || { echo "banner missing - the exe did not start on Windows"; exit 1; } + echo "rcm_emu.exe starts on a clean Windows runner" diff --git a/.gitignore b/.gitignore index 4bdca22..3d8cec6 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ # Build artifacts rcm_emu +rcm_emu.exe *.o *.d @@ -11,6 +12,8 @@ out.log out*.txt emu_run*.log emu_capture*.txt +win_run.log +last_audio*.wav # User data — never commit dumps or keys *.img diff --git a/Dockerfile.windows b/Dockerfile.windows new file mode 100644 index 0000000..280ce4a --- /dev/null +++ b/Dockerfile.windows @@ -0,0 +1,52 @@ +# Windows cross-build for the emulator. +# +# There is no MinGW package for either dependency, so both are built or +# unpacked into the cross sysroot here: SDL2 ships an official MinGW devel +# tarball, and Unicorn is compiled from source with the same toolchain. +# Doing it in a container keeps the host free of a second toolchain and makes +# the CI job and a local build the same thing. +FROM ubuntu:24.04 + +ARG SDL2_VERSION=2.30.9 +ARG UNICORN_VERSION=2.1.1 +ENV DEBIAN_FRONTEND=noninteractive + +RUN apt-get update && apt-get install -y --no-install-recommends \ + g++-mingw-w64-x86-64 gcc-mingw-w64-x86-64 \ + build-essential cmake make git pkg-config \ + wget ca-certificates xz-utils \ + && rm -rf /var/lib/apt/lists/* + +ENV MINGW_PREFIX=/usr/x86_64-w64-mingw32 + +# SDL2: unpack the official MinGW devel tree into the cross sysroot. +RUN wget -q https://github.com/libsdl-org/SDL/releases/download/release-${SDL2_VERSION}/SDL2-devel-${SDL2_VERSION}-mingw.tar.gz \ + && tar xf SDL2-devel-${SDL2_VERSION}-mingw.tar.gz \ + && cp -r SDL2-${SDL2_VERSION}/x86_64-w64-mingw32/* ${MINGW_PREFIX}/ \ + && rm -rf SDL2-${SDL2_VERSION}* + +# Unicorn: no prebuilt Windows package, so cross-compile it. Static, so the +# emulator .exe does not need a unicorn DLL beside it. +# +# Built at -O1, not -O2: mingw GCC 13 hits an internal compiler error +# (segfault) on qemu/softmmu/memory.c at -O2. -O1 compiles it, and unicorn is +# not the bottleneck here - the MMIO hooks are. +RUN git clone --depth 1 --branch ${UNICORN_VERSION} \ + https://github.com/unicorn-engine/unicorn.git /tmp/unicorn \ + && cmake -S /tmp/unicorn -B /tmp/unicorn/build \ + -DCMAKE_SYSTEM_NAME=Windows \ + -DCMAKE_C_COMPILER=x86_64-w64-mingw32-gcc \ + -DCMAKE_CXX_COMPILER=x86_64-w64-mingw32-g++ \ + -DCMAKE_RC_COMPILER=x86_64-w64-mingw32-windres \ + -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \ + -DCMAKE_BUILD_TYPE=Release \ + -DCMAKE_C_FLAGS_RELEASE="-O1" \ + -DCMAKE_CXX_FLAGS_RELEASE="-O1" \ + -DBUILD_SHARED_LIBS=OFF \ + -DUNICORN_ARCH="arm;aarch64" \ + && cmake --build /tmp/unicorn/build -j"$(nproc)" \ + && cmake --install /tmp/unicorn/build \ + && rm -rf /tmp/unicorn + +WORKDIR /work +CMD ["sh", "-c", "git config --global --add safe.directory /work; git submodule update --init --recursive && make windows -j$(nproc)"] diff --git a/Makefile b/Makefile index 56edfaf..6cf2044 100644 --- a/Makefile +++ b/Makefile @@ -37,10 +37,43 @@ ifneq ($(SDL2_CFLAGS),) LIBS = -lunicorn $(SDL2_LIBS) -lpthread endif -.PHONY: all clean +# ---- Windows cross-build --------------------------------------------------- +# +# `make windows` builds rcm_emu.exe with the MinGW toolchain. Both deps come +# from the cross sysroot the container prepares (see Dockerfile.windows): +# SDL2 from its official MinGW devel tree, unicorn built from source. +# +# Statically linked on purpose. A .exe that needs libstdc++, libgcc, winpthread +# and SDL2.dll beside it is not something anyone wants to download from a +# release page, and SDL2 is linked static here too so there is exactly one +# file to ship. +# +# SDL on Windows renames main to SDL_main and supplies its own entry point, so +# the link order -lmingw32 -lSDL2main -lSDL2 matters and SDL2main must come +# before SDL2. The trailing Windows libraries are what static SDL2 and unicorn +# pull in: without them the link fails on missing WinMM / OLE / socket symbols. +WIN_CXX = x86_64-w64-mingw32-g++ +WIN_OUT = rcm_emu.exe +WIN_OBJS = $(SRCS:.cpp=.win.o) +WIN_CXXFLAGS = -Wall -g -O2 -std=c++17 -MMD -MP -I. -I$(IMGUI_DIR) -I$(IMGUI_DIR)/backends -I/usr/x86_64-w64-mingw32/include/SDL2 -DSDL_MAIN_HANDLED +WIN_LIBS = -lmingw32 -lSDL2main -lSDL2 -lunicorn -lpthread -lwinmm -limm32 -lole32 -loleaut32 -lversion -lsetupapi -lcfgmgr32 -lgdi32 -lrpcrt4 -lws2_32 -luuid -lshell32 -ladvapi32 -luser32 +WIN_LDFLAGS = -static -static-libgcc -static-libstdc++ + +.PHONY: all clean windows all: $(OUTPUT) +windows: $(WIN_OUT) + +$(WIN_OUT): $(WIN_OBJS) + $(WIN_CXX) $(WIN_LDFLAGS) -o $@ $^ $(WIN_LIBS) + @echo " built $@ ($$(stat -c%s $@) bytes)" + +%.win.o: %.cpp + $(WIN_CXX) $(WIN_CXXFLAGS) -c -o $@ $< + +-include $(WIN_OBJS:.o=.d) + $(OUTPUT): $(OBJS) $(CXX) $(LDFLAGS) -o $@ $^ $(LIBS) @@ -52,4 +85,4 @@ $(OUTPUT): $(OBJS) -include $(OBJS:.o=.d) clean: - rm -f $(OUTPUT) $(OBJS) $(OBJS:.o=.d) + rm -f $(OUTPUT) $(OBJS) $(OBJS:.o=.d) \n $(WIN_OUT) $(WIN_OBJS) $(WIN_OBJS:.o=.d) diff --git a/README.md b/README.md index 91da9be..1b928a8 100644 --- a/README.md +++ b/README.md @@ -119,6 +119,21 @@ green: ![PIN recovery demo](img/pin_recovery_demo.png) +### Build (Windows) + +Cross-compiled from Linux in a container, because neither dependency has a +MinGW package: SDL2 ships a devel tarball and unicorn has to be compiled. + +```sh +docker build -f Dockerfile.windows -t rcm_emu_win . +docker run --rm -v "$PWD:/work" rcm_emu_win # produces rcm_emu.exe +``` + +The result is statically linked - one `rcm_emu.exe` with no DLLs beside it. +Audio goes to WASAPI on Windows and ALSA/PulseAudio on Linux; SDL picks the +backend, so nothing in the emulator cares which. `RCM_EMU_NO_AUDIO=1` skips +playback entirely, which is what CI uses since a runner has no sound device. + ## Live hardware tweaks Press `M` in the main window to open a second window that exposes the values diff --git a/t210/mmio.cpp b/t210/mmio.cpp index e66d5c8..caa7417 100644 --- a/t210/mmio.cpp +++ b/t210/mmio.cpp @@ -9,11 +9,33 @@ #include #include #include +#include #include #include #include #include #include +#include + +// pread/pwrite are POSIX and MinGW does not have them, so the SD/eMMC image +// access below would not compile for Windows. Seek-then-read is equivalent +// here: the emulated storage is touched only from the CPU thread, so the +// atomicity real pread() buys against a shared file offset is not in play. +// Kept next to the includes rather than in a header because these four call +// sites are the only users in the tree. +#ifdef _WIN32 +#include +static inline ssize_t pread(int fd, void *buf, size_t n, long long off) { + if (_lseeki64(fd, off, SEEK_SET) < 0) + return -1; + return _read(fd, buf, (unsigned int)n); +} +static inline ssize_t pwrite(int fd, const void *buf, size_t n, long long off) { + if (_lseeki64(fd, off, SEEK_SET) < 0) + return -1; + return _write(fd, buf, (unsigned int)n); +} +#endif #define BIT(n) (1U << (n)) @@ -2930,12 +2952,152 @@ static uint32_t admaif_read(EmuState *state, uint64_t addr) { } } +// Captured PIO audio. Every word the payload pushes into the FIFO is a whole +// stereo frame - low 16 bits left, high 16 bits right, per the CIF's UNPACK16 +// - so the capture is already interleaved PCM and needs only a header. +// +// This exists because "the probe reached its verdict" and "the console made +// the right noise" are different claims, and only one of them can be checked +// by reading registers. Writing the samples out means the tone an emulated +// run produces can actually be listened to, and measured, the same way a +// line-in capture of the real console is. +static std::vector audio_pcm; +static bool audio_pcm_full = false; + +// 4 M frames is ~3 minutes at this rate: far more than any test tone, and +// bounded so a runaway payload cannot eat memory. +static const size_t AUDIO_PCM_MAX_FRAMES = 4u * 1024u * 1024u; + +// Playback on the host sound card. +// +// The take is played AFTER it is complete, not streamed while it is produced. +// That is deliberate. The emulator does not generate samples anywhere near a +// steady rate - a phrase arrives in a burst, then generation stalls entirely +// while the payload talks to the codec over I2C between phrases - so a live +// stream underruns wherever the producer falls behind the sound card, which +// is heard as flicker. Queueing the finished buffer in one go removes the +// producer from the timing path completely: SDL has every sample before the +// first one is played, so it cannot run dry. +// +// The cost is latency - the melody is heard once the payload has finished +// writing it - which for a test tone is a fair trade for hearing it cleanly. +// +// An absent or unusable device (headless CI, no sound server) is not an +// error: playback is skipped and the WAV is still written, so a run never +// fails for want of speakers. +static SDL_AudioDeviceID audio_dev = 0; + +static uint32_t audio_rate_hz(void) { + uint32_t timing = mmio_regs.count(I2S_BASE + 0xA4) + ? (mmio_regs[I2S_BASE + 0xA4] & 0x7FFu) : 31u; + uint32_t frame = 2u * (timing + 1u); + return frame ? (1500000u / frame) : 23437u; +} + +static void audio_play_take(void) { + if (audio_pcm.empty() || getenv("RCM_EMU_NO_AUDIO")) + return; + + if (SDL_InitSubSystem(SDL_INIT_AUDIO) < 0) { + printf("[audio] no audio subsystem (%s) - WAV only\n", SDL_GetError()); + return; + } + + SDL_AudioSpec want{}, have{}; + want.freq = (int)audio_rate_hz(); + want.format = AUDIO_S16SYS; + want.channels = 2; + want.samples = 4096; + want.callback = nullptr; // queue-driven, no callback + + // No ALLOW_ANY_CHANGE: SDL_QueueAudio does not convert, so a device opened + // at a different rate or format would replay the take at the wrong pitch. + // Better to fail and keep the WAV than to play something misleading. + audio_dev = SDL_OpenAudioDevice(nullptr, 0, &want, &have, 0); + if (!audio_dev) { + printf("[audio] no device (%s) - WAV only\n", SDL_GetError()); + return; + } + + SDL_QueueAudio(audio_dev, audio_pcm.data(), + (Uint32)(audio_pcm.size() * sizeof(int16_t))); + SDL_PauseAudioDevice(audio_dev, 0); + printf("[audio] playing %.2f s on the host at %d Hz stereo\n", + (double)(audio_pcm.size() / 2) / (double)have.freq, have.freq); + fflush(stdout); + + // Wait it out, bounded, so the run cannot hang on a stuck device. + int guard = (int)(audio_pcm.size() / 2 / (size_t)have.freq) * 20 + 200; + while (guard-- > 0 && SDL_GetQueuedAudioSize(audio_dev) > 0) + SDL_Delay(50); + + SDL_CloseAudioDevice(audio_dev); + audio_dev = 0; +} + + +static void audio_write_wav(void) { + if (audio_pcm.empty()) + return; + + // The frame length the payload programmed decides the rate: I2S_TIMING + // holds the per-channel bit count minus one, so a frame is 2 x (cnt + 1) + // bit clocks and fs = bclk / that. hwtest drives BCLK at PLLA_OUT0 / 80 = + // 1.5 MHz, which with its TIMING of 31 gives 23437.5 Hz - the real rate, + // and the one its note table is computed against. Falling back to a + // nominal 48 kHz would replay the melody at twice the intended pitch. + uint32_t timing = mmio_regs.count(I2S_BASE + 0xA4) + ? (mmio_regs[I2S_BASE + 0xA4] & 0x7FFu) : 31u; + uint32_t frame = 2u * (timing + 1u); + uint32_t rate = frame ? (1500000u / frame) : 23437u; + + const char *path = "last_audio.wav"; + FILE *f = fopen(path, "wb"); + if (!f) { + printf("[audio] could not open %s\n", path); + return; + } + + uint32_t data_bytes = (uint32_t)(audio_pcm.size() * sizeof(int16_t)); + uint32_t byte_rate = rate * 2u * 2u; // stereo, 16-bit + auto u32 = [&](uint32_t v) { fwrite(&v, 4, 1, f); }; + auto u16 = [&](uint16_t v) { fwrite(&v, 2, 1, f); }; + + fwrite("RIFF", 1, 4, f); u32(36 + data_bytes); fwrite("WAVE", 1, 4, f); + fwrite("fmt ", 1, 4, f); u32(16); u16(1); u16(2); + u32(rate); u32(byte_rate); u16(4); u16(16); + fwrite("data", 1, 4, f); u32(data_bytes); + fwrite(audio_pcm.data(), 1, data_bytes, f); + fclose(f); + + printf("[audio] wrote %s: %zu frames, %u Hz stereo%s\n", path, + audio_pcm.size() / 2, rate, + audio_pcm_full ? " (truncated)" : ""); + fflush(stdout); + audio_play_take(); // buffer is complete: safe to play it straight + audio_pcm.clear(); + audio_pcm_full = false; +} + static void admaif_write(EmuState *state, uint64_t addr, uint32_t val) { (void)state; - (void)val; uint32_t offset = (uint32_t)(addr - ADMAIF_BASE); if (offset == 0x32C) { - // Sample sink. Deliberately does nothing and logs nothing. + // One packed word = one stereo frame. Record it rather than dropping it. + if (audio_pcm.size() / 2 < AUDIO_PCM_MAX_FRAMES) { + audio_pcm.push_back((int16_t)(val & 0xFFFF)); // left + audio_pcm.push_back((int16_t)((val >> 16) & 0xFFFF)); // right + } else { + audio_pcm_full = true; + } + return; + } + if (offset == 0x300 && val == 0) { + // TX channel disabled: the payload has finished feeding the port, so the + // take is complete. Write it out and play it. Doing this here rather + // than at exit means a run killed on its time budget still produces + // both the file and the sound. + audio_write_wav(); return; } // Everything else is left in mmio_regs by the write hook.