37 tok/s from Qwen3-Next-80B (48 GB) on a 32 GB laptop, 24 without drafts vs 2.8 for llama.cpp; reading 62 vs 16 tok/s. Faster than llama.cpp on all 13 models compared in Q4_K_M. LLMs bigger than your RAM, pure C, CPU or GPU.
C avx2ccpu-inferenceggufinference-enginelinuxllmlocal-llmmixture-of-expertsmoenvmequantizationqwen3simdspeculative-decodingvulkan
Release 2026-10-12: Janas on Windows - the same sources built for Windows 10 and 11 x86-64, as fast as on Linux on the development laptop
camauri0b0142b4ca17
diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex e5fc477..3b72f69 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -4,7 +4,9 @@# The binary package of Janas for Linux x86-64: built on Ubuntu 22.04, so# that it runs with the C library of Ubuntu 22.04, Debian 12 and later;# tested; packed as janas-linux-x86_64.tar.gz with the SHA-256 of every-# file. A tag v* publishes it as that tag's release (the name never+# file. The one for Windows x86-64 is built from the same sources with+# MinGW-w64 on Linux, tested on a Windows machine of GitHub's and packed as+# janas-windows-x86_64.zip, attached to the same release. A tag v* publishes it as that tag's release (the name never# changes, so releases/latest/download/janas-linux-x86_64.tar.gz is always# the newest); run by hand, it only builds the package and keeps it as an# artifact of the run. The shaders' compiler and the Vulkan headers are@@ -116,7 +118,137 @@ jobs:gh release create "$GITHUB_REF_NAME" \"$PACKAGE.tar.gz" "$PACKAGE.tar.gz.sha256" \--title "Janas $GITHUB_REF_NAME" \- --notes "Janas for Linux x86-64 (Ubuntu 22.04, Debian 12 and later). Unpack it and start: ./janas-get list, then ./janas-chat <model>. What changed: ChangeLog.md. The SHA-256 of every file: SHA256SUMS in the package."+ --notes "Janas for Linux x86-64 (Ubuntu 22.04, Debian 12 and later): janas-linux-x86_64.tar.gz; for Windows 10 and 11 x86-64: janas-windows-x86_64.zip. Unpack it and start: janas-get list, then janas-chat <model>. What changed: ChangeLog.md. The SHA-256 of every file: SHA256SUMS in the package."++ # Windows x86-64: the same sources built with MinGW-w64 on Linux (a+ # newer Ubuntu: the C library does not matter for Windows, the MinGW+ # headers do), then tested on Windows, then packed.+ windows-build:+ runs-on: ubuntu-24.04+ steps:+ - uses: actions/checkout@v7++ - name: MinGW-w64, the shaders' compiler and the Vulkan headers+ run: |+ set -euo pipefail+ sudo apt-get update -q+ sudo apt-get install -y -q gcc-mingw-w64-x86-64 binutils-mingw-w64-x86-64+ mkdir -p "$RUNNER_TEMP/khronos"+ cd "$RUNNER_TEMP/khronos"+ curl -fsSL -o glslang.tar.gz \+ "https://github.com/KhronosGroup/glslang/releases/download/$GLSLANG_VERSION/glslang-$GLSLANG_VERSION-linux-x86_64-release.tar.gz"+ echo "$GLSLANG_SHA256 glslang.tar.gz" | sha256sum -c -+ mkdir glslang && tar xzf glslang.tar.gz -C glslang+ echo "$RUNNER_TEMP/khronos/glslang/bin" >> "$GITHUB_PATH"+ git clone -q --depth 1 --branch "$VULKAN_HEADERS_TAG" \+ https://github.com/KhronosGroup/Vulkan-Headers.git+ test "$(git -C Vulkan-Headers rev-parse HEAD)" = "$VULKAN_HEADERS_COMMIT"+ echo "CPATH=$RUNNER_TEMP/khronos/Vulkan-Headers/include" >> "$GITHUB_ENV"++ - name: Build+ run: |+ set -euo pipefail+ x86_64-w64-mingw32-gcc --version | head -1+ JANAS_OS=windows ./build.sh release build 2>&1 | tee build.log+ if grep -q "building without GPU support" build.log; then+ echo "the build left the GPU out"; exit 1+ fi+ # nothing but Windows's own DLLs+ for f in bin/x86_64-windows/*.exe bin/x86_64-windows/*.dll; do+ x86_64-w64-mingw32-objdump -p "$f" | grep "DLL Name" |+ grep -v -i -E 'kernel32|msvcrt|ws2_32|bcrypt|crypt32|powrprof|advapi32|iphlpapi|ole32|wevtapi|wlanapi|shell32|psapi|user32' &&+ { echo "$f needs a DLL Windows does not have"; exit 1; } || true+ done++ - uses: actions/upload-artifact@v7+ with:+ name: windows-bin+ path: bin/x86_64-windows/++ windows-test:+ needs: windows-build+ runs-on: windows-latest+ steps:+ - uses: actions/checkout@v7++ - uses: actions/download-artifact@v7+ with:+ name: windows-bin+ path: bin/x86_64-windows++ - name: Test+ shell: pwsh+ run: |+ $failed = @()+ foreach ($t in Get-ChildItem bin\x86_64-windows\test_*.exe) {+ Write-Host "RUN $($t.Name)"+ & $t.FullName+ if ($LASTEXITCODE -ne 0) { $failed += $t.Name }+ }+ if ($failed.Count -gt 0) { Write-Host "failed: $failed"; exit 1 }++ windows-package:+ needs: [linux-x86_64, windows-build, windows-test]+ runs-on: ubuntu-24.04+ env:+ WPACKAGE: janas-windows-x86_64+ steps:+ - uses: actions/checkout@v7++ - uses: actions/download-artifact@v7+ with:+ name: windows-bin+ path: bin/x86_64-windows++ - name: Pack+ run: |+ set -euo pipefail+ B=bin/x86_64-windows+ P="$WPACKAGE/janas"+ mkdir -p "$P/services" "$P/lib" "$P/include/janas" "$P/docs"+ for f in janas-chat janas-server janas-get janas-bench janas-mcp \+ gguf2jns jns_planes hf2jns_mtp jns_check; do+ install -m 755 "$B/$f.exe" "$P/"+ done+ for s in src/services/*/; do+ s=$(basename "$s")+ [ "$s" = common ] && continue+ install -m 755 "$B/janas-$s.exe" "$P/services/"+ install -m 644 "src/services/$s/README.md" "$P/services/janas-$s.md"+ done+ sed -E 's#\(([a-z]+)/README\.md\)#(janas-\1.md)#g' \+ src/services/README.md > "$P/services/README.md"+ install -m 755 "$B/libjanas_llm.dll" "$B/libjanas_mcp.dll" "$P/lib/"+ install -m 644 "$B/libjanas_llm.dll.a" "$B/libjanas_mcp.dll.a" "$P/lib/"+ install -m 644 include/janas/* "$P/include/janas/"+ install -m 644 docs/*.md "$P/docs/"+ install -m 644 dist/README-windows.md "$P/README.md"+ install -m 644 LICENSE ChangeLog.md MODELS.md "$P/"+ if find "$P" -type f \( -name '*.sh' -o -name '*.py' -o -name '*.bat' \) | grep -q .; then+ echo "a script in the package"; exit 1+ fi+ (cd "$P" && find . -type f ! -name SHA256SUMS -print0 | sort -z |+ xargs -0 sha256sum > SHA256SUMS)+ (cd "$WPACKAGE" && zip -q -r -X "../$WPACKAGE.zip" janas)+ sha256sum "$WPACKAGE.zip" > "$WPACKAGE.zip.sha256"+ cat "$WPACKAGE.zip.sha256"++ - name: Keep the package (run by hand)+ if: github.event_name == 'workflow_dispatch'+ uses: actions/upload-artifact@v7+ with:+ name: ${{ env.WPACKAGE }}+ path: |+ ${{ env.WPACKAGE }}.zip+ ${{ env.WPACKAGE }}.zip.sha256++ - name: Add it to the release (a tag)+ if: startsWith(github.ref, 'refs/tags/v')+ env:+ GH_TOKEN: ${{ github.token }}+ run: |+ gh release upload "$GITHUB_REF_NAME" \+ "$WPACKAGE.zip" "$WPACKAGE.zip.sha256"# The wiki, made from the same pages as the repository: README.md becomes# Home, each docs/*.md a page named after its title. It is never editeddiff --git a/ChangeLog.md b/ChangeLog.mdindex b2092c0..0d6d4b1 100644--- a/ChangeLog.md+++ b/ChangeLog.md@@ -2,6 +2,13 @@> Curated, user-facing summary of completed work, newest first.+## [2026-10-12] - Janas on Windows++- **The same sources build for Windows x86-64**, with MinGW-w64 from Linux (`JANAS_OS=windows ./build.sh`): every program, the two libraries as DLLs, Janas's services (janas-system with Windows's own calls), the GPU through Vulkan; nothing needed but Windows's own DLLs. Run on Windows 11 (build 26300) on the development laptop on 12 October 2026: all 31 tests pass, and with the same files and commands as on Linux it writes as fast (Qwen3-4B 25.6 tok/s against 27, Qwen3-30B-A3B 34.2 against 32) and reads a prompt of 1,024 tokens as fast with the mixture (Qwen3-30B-A3B 132 against 135) and 1.8 times as fast with the dense model (Qwen3-4B 346 against 193), whose whole blocks go to the GPU, there through Intel's own driver.+- **What differs between the systems has one place each**: the reading of the experts (unbuffered overlapped reads on Windows, io_uring on Linux), the CPU's cores, the programs started (a job object holds what an MCP server starts in turn), sockets, the chat's terminal, time zones (Windows's ICU), the folders (`%LOCALAPPDATA%\janas`, `%APPDATA%\janas`).+- **The cores on Windows**: the low-power efficiency cores are told from the others by the level-3 cache they do not share; the clocks Windows reports had kept them and left out the eight ordinary efficiency cores.+- **Fixed on the way, on Linux too**: `libjanas_mcp.so` lacked functions it called, now an error when it is linked (`--no-undefined`); janas-system's list of errors could come in a different order when two came in the same second.+## [2026-10-11] - A binary package, and the models already converted- **The documentation in pages, and a wiki.** The README keeps the speeds, the tables and the machine they were measured on; the rest is in `docs/` (what works, getting a model, the chat, the library, serving the model, the tools, your hardware), and the README's old sections point there, so the links already given still work. Each release writes the project's wiki from the same pages, so the two never part.diff --git a/INSTALL.md b/INSTALL.mdindex 7d737e6..e0a8ddf 100644--- a/INSTALL.md+++ b/INSTALL.md@@ -4,7 +4,7 @@ Janas-LLM runs large mixture-of-experts language models on ordinary computers: t## Requirements-- **Linux on x86-64.** Windows is not supported yet.+- **Linux on x86-64**, or **Windows 10 (1903 or later) and 11 on x86-64**: the binary package of each release, or a build made on Linux with MinGW-w64 (below).- **CPU:** any x86-64 runs it; AVX2 with FMA and F16C (Intel since 2013, AMD since 2015) is needed for good speed, and AVX-VNNI is used when present.- **Memory:** at least 16 GB; 32 GB or more for large models (Qwen3-Next-80B-A3B: about 2 GB of resident weights, plus as much expert cache as the memory allows).- **Disk:** the model on an **NVMe SSD** (the experts are read directly from it while generating).@@ -32,6 +32,18 @@ Then, in the source directory:Everything goes to `bin/x86_64-linux/`: `janas-chat`, `janas-server`, `janas-mcp`, `janas-bench`, the libraries `libjanas_llm.so` (C API in `include/janas/llm.h`) and `libjanas_mcp.so` (the MCP client, `include/janas/mcp.h`) and the conversion tools. Without `glslangValidator` the build still succeeds, without GPU support. `./build.sh release test` also runs the tests, and `./build.sh --help` lists the other variants — a debug build, and the three sanitizers `asan`, `ubsan` and `tsan` — with what each one catches.++### For Windows++On Linux, with MinGW-w64 (`sudo apt install gcc-mingw-w64-x86-64` on Debian or Ubuntu), the same sources build for Windows x86-64:++```sh+JANAS_OS=windows ./build.sh # into bin/x86_64-windows/: .exe, the two .dll+JANAS_OS=windows ./build.sh release test # the tests, under Wine+```++The GPU's support comes in when `glslangValidator` and the Vulkan headers are there, as for Linux. The programs need nothing but Windows's own DLLs. On Windows what Janas keeps goes to `%LOCALAPPDATA%\janas` (the models, what it learns about the machine) and `%APPDATA%\janas` (the settings, the MCP servers).+## Preparing a modelJanas reads its own file format (`.jns`), converted from a GGUF file. Supported now: **Qwen3.5 and Qwen3.6** (`qwen35moe`, e.g. Qwen3.6-35B-A3B), **Qwen3-Next** (`qwen3next`, e.g. Qwen3-Next-80B-A3B-Instruct and Qwen3-Coder-Next) and **Qwen3 MoE** (`qwen3moe`, e.g. Qwen3-30B-A3B), in the Q4_K, Q5_K, Q6_K and Q8_0 formats (so the usual **Q4_K_M** files).diff --git a/README.md b/README.mdindex fed3d70..ed42aac 100644--- a/README.md+++ b/README.md@@ -1,6 +1,6 @@# Janas-[]() []() [](https://www.linkedin.com/in/maurizio-cammalleri-80a89a11/) [](https://cammalleri.substack.com/)+[]() []() [](https://www.linkedin.com/in/maurizio-cammalleri-80a89a11/) [](https://cammalleri.substack.com/)**37 tok/s from Qwen3-Next-80B (a 48 GB model) on a laptop with 32 GB of memory, 24 without drafts, where llama.cpp manages 2.8; reading a prompt, 62 tok/s against 16.** Janas-LLM was faster than llama.cpp on every model compared on the same laptop (Debian 13 Linux, Intel Core Ultra 9 185H, its integrated Arc GPU, 32 GB, an NVMe SSD; 9-11 October 2026; the whole machine [below](#the-machine-it-grew-on)):@@ -40,6 +40,8 @@ tar xf janas-linux-x86_64.tar.gz && cd janas./janas-chat # the models it knows: pick one, it is downloaded and checked```+**Or on Windows** 10 (1903 or later) and 11, x86-64: download [janas-windows-x86_64.zip](https://github.com/prabanta-dev/janas/releases/latest/download/janas-windows-x86_64.zip), unpack it, and in a terminal in its `janas` folder run `.\janas-chat`. On the same laptop under Windows 11 (12 October 2026) Janas-LLM wrote as fast as on Linux (Qwen3-4B 25.6 tok/s, Qwen3-30B-A3B 34.2) and read a prompt as fast with the mixture (Qwen3-30B-A3B 132 tok/s) and 1.8 times as fast with the dense model (Qwen3-4B 346 tok/s against 193), whose whole blocks go to the GPU, through Intel's own Windows driver there.+The models come already converted from [Hugging Face](https://huggingface.co/prabanta-dev); building from the sources: [Getting started](#getting-started).```@@ -81,6 +83,8 @@ Everything in this repository was written and measured on:- **32 GB** of DDR5 RAM- **1 TB NVMe SSD** (about 5.7 GB/s reading)+The Windows build was run on the same laptop under Windows 11 (build 26300), with Intel's own graphics driver: its tests pass there, and how fast it was is under **Or on Windows**, above.+Everything the engine does is chosen from what it measures, so another machine will make other choices — that part is meant to travel. What has never been tried is the rest: other CPUs (especially without AVX-VNNI, or AMD), discrete GPUs, slower disks, more or less memory. **If you run it somewhere else, the report from `janas-bench` is the single most useful thing you can send back** (see [Helping it run on more hardware](docs/hardware.md#helping-it-run-on-more-hardware)).## What works nowdiff --git a/build.sh b/build.shindex 091a111..e18bd75 100755--- a/build.sh+++ b/build.sh@@ -68,6 +68,10 @@ EnvironmentAR the archiver, ar by default (gcc-ar for -flto)JANAS_CFLAGS flags added to the variant, to try a compiler out:JANAS_CFLAGS="-O3 -flto" ./build.sh+ JANAS_OS windows: the same sources for Windows x86-64, with+ MinGW-w64 (x86_64-w64-mingw32-gcc), into+ bin/x86_64-windows/ (.exe, .dll); release and debug only.+ The tests run under Wine when the build is not on WindowsBefore a commit: ./build.sh release test and at least asan; tsan toowhen concurrent code was touched.@@ -90,10 +94,29 @@ esacVARIANT="${1:-release}"ACTION="${2:-build}"+JANAS_OS="${JANAS_OS:-}"+EXE=""+if [ "$JANAS_OS" = windows ]; then+ CC="${CC:-x86_64-w64-mingw32-gcc}"+ AR="${AR:-x86_64-w64-mingw32-ar}"+ EXE=".exe"+ case "$VARIANT" in+ release | debug) ;;+ *)+ echo "build.sh: $VARIANT is not available for Windows" \+ "(release and debug are)" >&2+ exit 2+ ;;+ esac+elif [ -n "$JANAS_OS" ]; then+ echo "build.sh: unknown JANAS_OS: $JANAS_OS (windows is known)" >&2+ exit 2+fiCC="${CC:-gcc}"CPU="$(uname -m)"OS="$(uname -s | tr '[:upper:]' '[:lower:]')"+[ "$JANAS_OS" = windows ] && OS=windowsOBJ="lib/$CPU-$OS-$VARIANT"BIN="bin/$CPU-$OS"SUFFIX=""@@ -102,8 +125,18 @@ SUFFIX=""# _GNU_SOURCE for every file, empty as the files that define it write it:# the C library of Ubuntu 22.04 (the binary package's) declares memmem,# strcasestr and the like only with it, where a newer one does by default-CFLAGS=(-std=gnu11 -D_GNU_SOURCE= -Wall -Wextra -Werror -pthread -fPIC -fvisibility=hidden- -Isrc -Iinclude)+CFLAGS=(-std=gnu11 -D_GNU_SOURCE= -Wall -Wextra -Werror -pthread -Isrc -Iinclude)+if [ "$OS" = windows ]; then+ # Windows 10 and later; printf with the C99 formats (%zu, %lld); what+ # MinGW's C library lacks, in one header every file starts with+ # files over 2 GiB (off_t and st_size of 64 bits); the headers that+ # stand in for POSIX's (src/common/win/)+ CFLAGS+=(-D_WIN32_WINNT=0x0A00 -D__USE_MINGW_ANSI_STDIO=1+ -D_FILE_OFFSET_BITS=64 -Isrc/common/win+ -include src/common/win_compat.h)+else+ CFLAGS+=(-fPIC -fvisibility=hidden)+ficase "$VARIANT" inrelease) CFLAGS+=(-O2 -DNDEBUG) ;;debug) CFLAGS+=(-O0 -g) ;;@@ -131,6 +164,12 @@ build | test | clean | clean-build | clean-test) ;;;;esacLDLIBS=(-lm)+# Windows: the system's sockets, random numbers, network interfaces and+# processes; the C runtime and the threads of MinGW linked in, so that a+# program needs no DLL beyond Windows's own+WIN_LIBS=(-lws2_32 -lbcrypt -liphlpapi -lpsapi -lshell32 -lole32 -lwevtapi+ -lwlanapi -ladvapi32 -lpowrprof -lcrypt32)+[ "$OS" = windows ] && LDLIBS+=("${WIN_LIBS[@]}")# Extra flags, for trying a compiler out: JANAS_CFLAGS="-O3 -flto" ./build.sh.# Nothing is added when it is unset, which is how the released build is made.# Link-time optimization needs an archiver that reads its objects, hence AR.@@ -140,6 +179,8 @@ if [ -n "${JANAS_CFLAGS:-}" ]; thenLDLIBS+=($JANAS_CFLAGS)fiAR="${AR:-ar}"+LDSTATIC=()+[ "$OS" = windows ] && LDSTATIC=(-static)# the version in reports (janas-bench)VERSION="$(git describe --always --dirty 2>/dev/null || echo unknown)"CFLAGS+=(-DJANAS_VERSION="\"$VERSION\"")@@ -186,9 +227,21 @@ mkdir -p "$OBJ" "$BIN"SPV="$OBJ/spv"mkdir -p "$SPV"GPU_MISSING=""+VK_INC=()+if [ "$OS" = windows ] && [ -d /usr/include/vulkan ] &&+ ! echo '#include <vulkan/vulkan.h>' | "$CC" -E -x c - >/dev/null 2>&1; then+ # the Vulkan headers are the same for every system: the host's, alone+ # in a directory of their own (never /usr/include, which is Linux's)+ mkdir -p "$OBJ/vkinc"+ for d in vulkan vk_video; do+ [ -d "/usr/include/$d" ] && ln -sfn "/usr/include/$d" "$OBJ/vkinc/$d"+ done+ VK_INC=(-I"$OBJ/vkinc")+ CFLAGS+=("${VK_INC[@]}")+ficommand -v glslangValidator >/dev/null 2>&1 ||GPU_MISSING="glslangValidator (glslang-tools, glslang)"-echo '#include <vulkan/vulkan.h>' | "$CC" -E -x c - >/dev/null 2>&1 ||+echo '#include <vulkan/vulkan.h>' | "$CC" "${VK_INC[@]}" -E -x c - >/dev/null 2>&1 ||GPU_MISSING="${GPU_MISSING:+$GPU_MISSING and }the Vulkan headers (libvulkan-dev, vulkan-headers)"[ -z "$GPU_MISSING" ] ||echo "note: building without GPU support: $GPU_MISSING not found"@@ -246,8 +299,15 @@ objname() { echo "$OBJ/$(echo "${1#src/}" | tr '/' '_' | sed 's/\.c$/.o/')"; }# the flags it needs and without Janas's warnings, in an archive of their# own: they go into the programs that use them, never into libjanas_llm.TP_CFLAGS=()+skip=0for f in "${CFLAGS[@]}"; do- case "$f" in -Wall | -Wextra | -Werror) ;; *) TP_CFLAGS+=("$f") ;; esac+ # nor Janas's stand-ins for POSIX on Windows: theirs are their own+ if [ $skip = 1 ]; then skip=0; continue; fi+ case "$f" in+ -Wall | -Wextra | -Werror | -Isrc/common/win) ;;+ -include) skip=1 ;;+ *) TP_CFLAGS+=("$f") ;;+ esacdoneTP_CFLAGS+=(-w)tp_flags()@@ -255,6 +315,8 @@ tp_flags()local d="src/third_party/$1"case "$1" inlibmicrohttpd)+ # Windows has a configuration of its own (see its origin.md)+ [ "$OS" = windows ] && echo "-I$d/w32"echo "-D_GNU_SOURCE -DHAVE_CONFIG_H -I$d -I$d/src/include" \"-I$d/src/microhttpd" ;;mbedtls)@@ -327,7 +389,8 @@ while IFS= read -r src; do# warnings are not Janas's to fix[ "$src" = src/common/mcp_tls.c ] && extra=("${MBEDTLS_INC[@]/#-I/-isystem}")compile "$src" "$obj" "${CFLAGS[@]}" "${extra[@]}"-done < <(find src -name '*.c' ! -name main.c ! -path 'src/third_party/*' | sort)+done < <(find src -name '*.c' ! -name main.c ! -name win_start.c \+ ! -path 'src/third_party/*' | sort)rm -f "$OBJ/libjanas.a""$AR" rcs "$OBJ/libjanas.a" "${objs[@]}"if [ "$VARIANT" = release ]; then@@ -342,29 +405,61 @@ if [ "$VARIANT" = release ]; then*/common_hf_*.o) ;; # for the tools, with libjanas.a only# what the services share (src/services/common/): theirs only*/services_*.o) ;;- # the JSON reader and the strict reading of words: both- */llm_json.o | */common_words.o) mcp_objs+=("$o") llm_objs+=("$o") ;;+ # the JSON reader and the strict reading of words, the sockets and+ # the programs started, what Windows lacks of POSIX: both+ */llm_json.o | */common_words.o | */common_sock.o | */common_proc.o | \+ */common_proc_win.o | */common_win_compat.o | */common_win_posix.o)+ mcp_objs+=("$o") llm_objs+=("$o") ;;*) llm_objs+=("$o") ;;esacdone- echo "LD $BIN/libjanas_llm.so"- "$CC" -shared -pthread "${llm_objs[@]}" "${LDLIBS[@]}" \- -o "$BIN/libjanas_llm.so"- echo "LD $BIN/libjanas_mcp.so"- # with Mbed TLS from the archive of the libraries of others- "$CC" -shared -pthread "${mcp_objs[@]}" "$OBJ/libjanas_third.a" \- "${LDLIBS[@]}" -o "$BIN/libjanas_mcp.so"+ if [ "$OS" = windows ]; then+ # a DLL and its import library (libjanas_llm.dll.a) for MinGW+ for l in llm mcp; do+ if [ $l = llm ]; then lo=("${llm_objs[@]}"); else+ lo=("${mcp_objs[@]}" "$OBJ/libjanas_third.a"); fi+ echo "LD $BIN/libjanas_$l.dll"+ "$CC" -shared -pthread "${LDSTATIC[@]}" "${lo[@]}" "${LDLIBS[@]}" \+ -Wl,--out-implib,"$BIN/libjanas_$l.dll.a" \+ -o "$BIN/libjanas_$l.dll"+ done+ else+ # --no-undefined: a function a library needs and does not have is+ # an error here, not when a program first calls it+ echo "LD $BIN/libjanas_llm.so"+ "$CC" -shared -pthread -Wl,--no-undefined "${llm_objs[@]}" \+ "${LDLIBS[@]}" -o "$BIN/libjanas_llm.so"+ echo "LD $BIN/libjanas_mcp.so"+ # with Mbed TLS from the archive of the libraries of others+ "$CC" -shared -pthread -Wl,--no-undefined "${mcp_objs[@]}" \+ "$OBJ/libjanas_third.a" "${LDLIBS[@]}" -o "$BIN/libjanas_mcp.so"+ fifiTHIRD=()[ -f "$OBJ/libjanas_third.a" ] && THIRD=("$OBJ/libjanas_third.a")+# Windows: every program starts with the console made ready for UTF-8 and+# colours (win_start.c), and carries the manifest that makes UTF-8 its+# code page (src/common/win/janas.manifest)+START=()+if [ "$OS" = windows ]; then+ compile src/common/win_start.c "$OBJ/win_start.o" "${CFLAGS[@]}"+ res="$OBJ/janas_res.o"+ if [ ! -f "$res" ] || [ src/common/win/janas.manifest -nt "$res" ] ||+ [ src/common/win/janas.rc -nt "$res" ]; then+ echo "RC src/common/win/janas.rc"+ "${WINDRES:-x86_64-w64-mingw32-windres}" -i src/common/win/janas.rc \+ -I src/common/win -O coff -o "$res"+ fi+ START=("$OBJ/win_start.o" "$res")+fi# test and benchmark programs, and the C toolsfor src in tests/*.c tools/*.c src/*/main.c src/services/*/main.c; do- exe="$BIN/$(basename "${src%.c}")$SUFFIX"+ exe="$BIN/$(basename "${src%.c}")$SUFFIX$EXE"own=()if [ "$(basename "$src")" = main.c ]; thendir=$(dirname "$src")- exe="$BIN/janas-$(basename "$dir")$SUFFIX"+ exe="$BIN/janas-$(basename "$dir")$SUFFIX$EXE"while IFS= read -r c; doobj=$(objname "$c")own+=("$obj")@@ -372,17 +467,24 @@ for src in tests/*.c tools/*.c src/*/main.c src/services/*/main.c; dodone < <(find "$dir" -maxdepth 1 -name '*.c' ! -name main.c | sort)fiecho "LD $exe"- "$CC" "${CFLAGS[@]}" "${TP_INC[@]}" "$src" "${own[@]}" "$OBJ/libjanas.a" \- "${THIRD[@]}" "${LDLIBS[@]}" -o "$exe"+ "$CC" "${CFLAGS[@]}" "${TP_INC[@]}" "$src" "${own[@]}" "${START[@]}" \+ "$OBJ/libjanas.a" "${THIRD[@]}" "${LDSTATIC[@]}" "${LDLIBS[@]}" -o "$exe"doneif [ "$ACTION" = test ]; thenstatus=0- for t in "$BIN"/test_*"$SUFFIX"; do+ # the variables of this script are not the engine's, which warns of+ # a JANAS_ it does not know; a Windows build made elsewhere runs its+ # tests under Wine+ RUN=(env -u JANAS_OS -u JANAS_CFLAGS)+ if [ "$OS" = windows ] && [ "$(uname -s)" = Linux ]; then+ RUN+=(WINEDEBUG=-all wine)+ fi+ for t in "$BIN"/test_*"$SUFFIX$EXE"; do# in release, skip the sanitizer builds (test_x-asan and the like)- [ -n "$SUFFIX" ] || [[ "$(basename "$t")" != *-* ]] || continue+ [ -n "$SUFFIX" ] || [[ "$(basename "$t" "$EXE")" != *-* ]] || continueecho "RUN $t"- "$t" || status=1+ "${RUN[@]}" "$t" || status=1doneexit $statusfidiff --git a/dist/README-windows.md b/dist/README-windows.mdnew file mode 100644index 0000000..192993a--- /dev/null+++ b/dist/README-windows.md@@ -0,0 +1,69 @@+# Janas for Windows x86-64++**Qwen3-Next-80B, a 48 GB model, on a laptop with 32 GB of memory: 37 tok/s with its own draft block, 24 without, where llama.cpp manages 2.8 on the same laptop.** Reading a prompt of 1,024 tokens: 62 tok/s against 16. Janas-LLM was faster than llama.cpp on every model compared on that laptop (Debian 13 Linux with kernel 6.12.107, Intel Core Ultra 9 185H, its integrated Arc GPU with Mesa 26.1.6, 32 GB of DDR5-5600 memory, an NVMe SSD), measured on 9-11 October 2026:++| Model | reading 1,024 tokens: Janas-LLM | llama.cpp | writing: Janas-LLM | llama.cpp |+|---|---:|---:|---:|---:|+| Qwen3-Next-80B-A3B (48.4 GB, more than the memory) | 62 tok/s | 16 tok/s | 24 tok/s | 2.8 tok/s |+| Qwen3-Coder-Next (48.4 GB, more than the memory) | 66 tok/s | 14 tok/s | 22 tok/s | 2.2 tok/s |+| Qwen3.6-35B-A3B | 104 tok/s | 79 tok/s | 19 tok/s | 12 tok/s |+| Qwen3-30B-A3B | 135 tok/s | 122 tok/s | 32 tok/s | 15 tok/s |+| Gemma-4-26B-A4B-it | 84 tok/s | 76 tok/s | 18 tok/s | 12 tok/s |+| Gemma-4-12B-it | 65 tok/s | 46 tok/s | 9.9 tok/s | 7.1 tok/s |+| Qwen3.5-9B | 111 tok/s | 78 tok/s | 14 tok/s | 8.7 tok/s |+| Gemma-4-E4B-it | 122 tok/s | 109 tok/s | 20 tok/s | 15 tok/s |+| Qwen3-4B | 193 tok/s | 164 tok/s | 27 tok/s | 18 tok/s |+| Gemma-4-E2B-it | 191 tok/s | 150 tok/s | 38 tok/s | 19 tok/s |+| Qwen3.5-2B | 441 tok/s | 323 tok/s | 52 tok/s | 28 tok/s |+| Qwen3.5-0.8B | 799 tok/s | 519 tok/s | 109 tok/s | 32 tok/s |+| Qwen3-0.6B | 939 tok/s | 670 tok/s | 130 tok/s | 45 tok/s |++The 3-bit Qwen3-30B of the catalog is the one exception: it reads a prompt slower than llama.cpp (100 tok/s against 112), its Q3_K weights not on the GPU's fast prompt yet. On another machine the figures will be other ones: `janas-bench` measures yours (below). How they were taken, and everything else: <https://github.com/prabanta-dev/janas>.++Janas-LLM, the inference engine of Janas, runs large language models on ordinary computers, with or without a GPU, mixtures of experts larger than the memory among them: the weights stay on disk, the experts each token needs are read from the SSD and the ones that keep coming back stay in memory. It is written in C and needs nothing but the system's C library; a GPU is used through its Vulkan driver when there is one.++The figures above were measured on Linux. On the same laptop under Windows 11 (build 26300, 12 October 2026), this package wrote as fast (Qwen3-4B 25.6 tok/s, Qwen3-30B-A3B 34.2), read a prompt as fast with the mixture (Qwen3-30B-A3B 132 tok/s) and 1.8 times as fast with the dense model (Qwen3-4B 346 tok/s).++## Start++In a terminal (Windows Terminal, PowerShell or the Command Prompt), in the folder where the package was unpacked:++```+.\janas-get list+.\janas-get qwen3-4b+.\janas-chat qwen3-4b+```++The first says which models it knows, their size and the memory they want; the second downloads one, checked, into `%LOCALAPPDATA%\janas\models`; the third talks to it.++`.\janas-chat` with no model shows the list and downloads the one you choose, after asking. The models come already converted from Hugging Face ([prabanta-dev](https://huggingface.co/prabanta-dev)), each file checked against the fingerprints of `MODELS.md`.++## What is here++| | |+|---|---|+| `janas-chat` | a chat in the terminal: line editor, history, the reasoning shown apart, a context that slides instead of ending, the tools of MCP servers and of Janas's own services |+| `janas-server` | the model served over HTTP with an API that follows OpenAI's: chat completions (tools, JSON schemas), completions, responses, embeddings, and llama.cpp's route for filling in code in editors |+| `janas-get` | downloads a model of the catalog, checked; `--from-gguf` converts the original GGUF here instead |+| `janas-bench` | measures what this machine does with a model, every configuration the engine can use, and fills the profile it starts from next time |+| `janas-mcp` | the model as an MCP server for other clients (Claude Code, an editor): a question to it, the embedding of a text |+| `gguf2jns` | converts a GGUF file (Q4_K_M and the other types `MODELS.md` lists) to the `.jns` file Janas reads |+| `jns_planes` | cuts the experts of a converted mixture into bit planes, so that fewer bits can be read when the memory is short |+| `hf2jns_mtp` | makes a model's multi-token prediction block from its original checkpoint |+| `jns_check` | what a `.jns` file says about itself: architecture, sizes, types, licence |+| `services/` | Janas's services, which bring data of the world to a model: flights, weather, maps, prices, earthquakes, Wikipedia, GitHub, git, this computer. `janas-chat` starts them by itself; any other MCP client can use them. See `services/README.md` |+| `lib/`, `include/` | `libjanas_llm.dll` and `libjanas_mcp.dll`, their import libraries for MinGW (`.dll.a`), their C headers and FreeBASIC bindings, for programs of your own; the programs above do not need them |++## Needs++- Windows 10 (version 1903 or later) or Windows 11, on x86-64. Nothing to install: the programs use only what Windows has.+- An NVMe SSD for the models larger than the memory.+- A GPU is optional: one with a Vulkan driver (the drivers of Intel, AMD and NVIDIA include it) reads the prompts faster.++What Janas keeps goes to `%LOCALAPPDATA%\janas` (the models, what it learns about the machine) and `%APPDATA%\janas` (the settings, the MCP servers); the variables `JANAS_MODELS` and `XDG_DATA_HOME`, `XDG_CACHE_HOME`, `XDG_CONFIG_HOME` move them elsewhere.++It is an experiment, developed and measured on one Linux machine: an Intel CPU with AVX2 and AVX-VNNI. The Windows build is new and has run on that one machine only; the report of `janas-bench` is the most useful thing to send back (<https://github.com/prabanta-dev/janas/issues>).++## Licence++Janas is under the GNU General Public License, version 3 or later: `LICENSE`. The models are not part of it and keep their own licences: `MODELS.md`.diff --git a/docs/hardware.md b/docs/hardware.mdindex 60c7abf..4c06ce8 100644--- a/docs/hardware.md+++ b/docs/hardware.md@@ -42,8 +42,9 @@ The [hardware report form](https://github.com/prabanta-dev/janas/issues/new?temp2. **Discrete GPUs** (NVIDIA, AMD, Intel Arc). The GPU support is correct - bit for bit on a reply's tokens, and on a prompt as close to the references as the CPU - and it pays where it was measured: on the development laptop's integrated GPU, with the fast prompt, Qwen3-4B reads a prompt 2.6 times faster than without the GPU (85 to 220 tokens/s; before the fast prompt, 83 to 107), and on an RTX 5080 (issue #15) Qwen3-4B read 13% faster and, with the GPU on single tokens too, replied 11-16% faster. Every other card is unknown, and the fast prompt has not run on a discrete one yet (`JANAS_GPU_FAST_PROMPT=0` turns it off if it misbehaves). **Careful:** a GPU driver reset takes the desktop with it. Start with `janas-bench`, not with a long chat.3. **Machines with 16 GB or less.** The engine is supposed to trade quality for memory on its own — fewer bits per weight, light experts not in memory left out — and the thresholds for that were measured on 32 GB.4. **Slower disks.** Everything assumes an NVMe SSD; on a SATA disk the engine should still work and simply wait more, but nobody has watched it do so.-5. **Other models** of the supported families. A file that will not convert, or converts and then answers nonsense, is a useful bug.+5. **Windows on other machines.** The Windows build has run on one laptop, the development one (Windows 11, build 26300), where its tests pass and it is as fast as on Linux; `janas-bench`'s report from any other is welcome.+6. **Other models** of the supported families. A file that will not convert, or converts and then answers nonsense, is a useful bug.-**What not to bother with yet:** Windows and macOS (not supported), and models outside the Qwen3, Qwen3.5, Qwen3.6, Qwen3-Next and Gemma 4 families (they are refused with a message).+**What not to bother with yet:** macOS (not supported), and models outside the Qwen3, Qwen3.5, Qwen3.6, Qwen3-Next and Gemma 4 families (they are refused with a message).Patches are welcome too, but a measurement from a machine nobody here can buy is worth more than most patches.diff --git a/src/bench/main.c b/src/bench/main.cindex d5207f1..2a4c3b4 100644--- a/src/bench/main.c+++ b/src/bench/main.c@@ -89,7 +89,7 @@ static double now(void)static FILE *report;/* Printed to the terminal and to the report file. */-static void out(const char *fmt, ...) __attribute__((format(printf, 1, 2)));+static void out(const char *fmt, ...) __attribute__((format(gnu_printf, 1, 2)));static void out(const char *fmt, ...){va_list ap;diff --git a/src/chat/edit.h b/src/chat/edit.hindex 9de9cb7..958e333 100644--- a/src/chat/edit.h+++ b/src/chat/edit.h@@ -220,8 +220,7 @@ static int line_read(struct janas_term *t, const char *prompt, char *buf,for (;;) {unsigned char c;if (line_idle) {- struct pollfd pf = {STDIN_FILENO, POLLIN, 0};- int pr = poll(&pf, 1, 500);+ int pr = tty_wait(500);if (pr < 0 && errno == EINTR) { /* the window changed size */term_size(t);ed_draw(t, prompt, buf, len, pos, ed_command(cmds, buf, len));@@ -241,7 +240,7 @@ static int line_read(struct janas_term *t, const char *prompt, char *buf,}/* a key: read() below takes it */}- ssize_t r = read(STDIN_FILENO, &c, 1);+ int r = tty_byte(&c);if (r < 0 && errno == EINTR) { /* the window changed size */term_size(t);ed_draw(t, prompt, buf, len, pos, ed_command(cmds, buf, len));@@ -351,16 +350,15 @@ static int line_read(struct janas_term *t, const char *prompt, char *buf,* Home, but Ctrl-Home sends five, and what was left over used* to end up typed into the line.*/- struct pollfd pf = {STDIN_FILENO, POLLIN, 0};unsigned char lead = 0, final = 0;char par[16];int pn = 0;- if (poll(&pf, 1, 50) <= 0 || read(STDIN_FILENO, &lead, 1) != 1 ||+ if (tty_wait(50) <= 0 || tty_byte(&lead) != 1 ||(lead != '[' && lead != 'O'))continue;for (;;) {unsigned char b;- if (read(STDIN_FILENO, &b, 1) != 1)+ if (tty_byte(&b) != 1)break;if (b >= 0x40 && b <= 0x7e) {final = b;diff --git a/src/chat/main.c b/src/chat/main.cindex cfe7cbd..9a03980 100644--- a/src/chat/main.c+++ b/src/chat/main.c@@ -67,6 +67,12 @@ static void on_sigwinch(int sig)resized = 1;}+/* Windows has no SIGWINCH: the console tells (tty.c) */+static void on_resize(void)+{+ on_sigwinch(0);+}+/** The footer is made of parts, and a part that does not fit is left out* rather than cut off at the edge. A big font is a narrow window, and the@@ -230,6 +236,9 @@ static int footer_idle(void)static void on_sigint(int sig){(void)sig;+#ifdef _WIN32+ signal(SIGINT, on_sigint); /* its C runtime takes the handler back */+#endifinterrupted = 1;mcpc_cancel(); /* a tool running stops too */}@@ -569,7 +578,7 @@ static int32_t set_system(janas_llm_chat *c, const char *system)/* What the reading ahead says, where the user sees it: in theconversation, or on stderr when the output is a pipe. */static void prep_say(const char *colour, const char *fmt, ...)- __attribute__((format(printf, 2, 3)));+ __attribute__((format(gnu_printf, 2, 3)));static void prep_say(const char *colour, const char *fmt, ...){char text[512];@@ -1055,8 +1064,8 @@ static int ask_yes(const char *question)return 1;term_printf(&term, "%s [y/N] ", question);term_raw(&term, 1);- char k = 0;- if (read(STDIN_FILENO, &k, 1) < 0)+ unsigned char k = 0;+ if (tty_byte(&k) < 0)k = 0;term_raw(&term, 0);int yes = k == 'y' || k == 'Y';@@ -1250,8 +1259,8 @@ static int ask_key(const char *question){term_printf(&term, "%s ", question);term_raw(&term, 1);- char k = 0;- if (read(STDIN_FILENO, &k, 1) < 0)+ unsigned char k = 0;+ if (tty_byte(&k) < 0)k = 0;term_raw(&term, 0);if (k >= 'A' && k <= 'Z')@@ -1666,6 +1675,7 @@ int main(int argc, char **argv)return 2;}+ tty_setup();term_init(&term);if (!term.tty)markdown = 0; /* a pipe gets the marks: a script may want them */@@ -1826,12 +1836,18 @@ int main(int argc, char **argv)fprintf(stderr, "%s\n/help for the commands\n", desc);prep_start(c);+#ifdef _WIN32+ signal(SIGINT, on_sigint);+ tty_on_resize = on_resize;+#elsestruct sigaction sa = {.sa_handler = on_sigint};sigemptyset(&sa.sa_mask);sigaction(SIGINT, &sa, NULL); /* no SA_RESTART: getline returns */struct sigaction sw = {.sa_handler = on_sigwinch};sigemptyset(&sw.sa_mask); /* no SA_RESTART: the editor redraws itself */sigaction(SIGWINCH, &sw, NULL);+ (void)on_resize;+#endifchar *msg = NULL;size_t cap = 0;diff --git a/src/chat/mcp_chat.c b/src/chat/mcp_chat.cindex db39139..260e56d 100644--- a/src/chat/mcp_chat.c+++ b/src/chat/mcp_chat.c@@ -15,6 +15,7 @@#include "layout.h"#include "llm/json.h"+#include "common/sysinfo.h"/* An answer longer than this is cut: the context is the model's memory ofthe whole conversation, and a file listing can fill it at one go. */@@ -384,10 +385,8 @@ int mcpc_start_services(void)/* in services/ beside the program (the binary package), else besideit: bin/x86_64-linux/janas-chat-asan has janas-flights-asan there */char self[4096];- ssize_t n = readlink("/proc/self/exe", self, sizeof self - 1);- if (n <= 0)+ if (janas_exe_path(self, sizeof self) < 0)return 0;- self[n] = 0;char *base = strrchr(self, '/');if (!base)return 0;diff --git a/src/chat/models.c b/src/chat/models.cindex fc5c9d6..9bdc300 100644--- a/src/chat/models.c+++ b/src/chat/models.c@@ -6,17 +6,15 @@#define _GNU_SOURCE#include "models.h"-#include <spawn.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <sys/stat.h>-#include <sys/wait.h>#include <unistd.h>#include "janas/llm.h"--extern char **environ;+#include "common/proc.h"+#include "common/sysinfo.h"static int is_file(const char *path){@@ -93,25 +91,24 @@ static const struct janas_model_entry *nth(int k)static int fetch(const struct janas_model_entry *m, const char *dir){char self[4096], tool[4200];- ssize_t n = readlink("/proc/self/exe", self, sizeof(self) - 1);- if (n <= 0)+ if (janas_exe_path(self, sizeof self) < 0)return -1;- self[n] = 0;char *slash = strrchr(self, '/');if (!slash)return -1;*slash = 0;snprintf(tool, sizeof(tool), "%s/janas-get", self);- char *argv[] = {"janas-get", (char *)m->name, "--dir", (char *)dir, NULL};- pid_t pid;- if (posix_spawn(&pid, tool, NULL, NULL, argv, environ) != 0) {+ const char *argv[] = {tool, m->name, "--dir", dir, NULL};+ struct janas_proc pr;+ char err[256];+ if (janas_proc_start(&pr, argv, NULL, NULL, -1, -1, -1, 0, err,+ sizeof err) != 0) {fprintf(stderr, "janas-chat: cannot start %s\n", tool);return -1;}- int st = 0;- while (waitpid(pid, &st, 0) < 0)- ;- return WIFEXITED(st) && WEXITSTATUS(st) == 0 ? 0 : -1;+ int code = -1;+ janas_proc_wait(&pr, -1, &code);+ return code == 0 ? 0 : -1;}/*diff --git a/src/chat/term.h b/src/chat/term.hindex 9c8fb50..48cad11 100644--- a/src/chat/term.h+++ b/src/chat/term.h@@ -19,14 +19,13 @@#include <stdio.h>#include <stdlib.h>#include <string.h>-#include <poll.h>-#include <sys/ioctl.h>#include <stdarg.h>#include <stdint.h>-#include <termios.h>#include <wchar.h>#include <unistd.h>+#include "tty.h"+struct janas_term {int tty; /* stdin and stdout are both a terminal */int colour; /* and colours are welcome there */@@ -45,7 +44,6 @@ struct janas_term {/* how many times the screen has been cleared: the store's partialredraw (scroll.h) trusts what it drew only while this stays put */unsigned cleared;- struct termios saved;};/* Colours: empty strings when they are not wanted, so every use is one@@ -252,7 +250,7 @@ static void term_puts(struct janas_term *t, const char *s)term_write(t, s, strlen(s));}-__attribute__((format(printf, 2, 3))) static void+__attribute__((format(gnu_printf, 2, 3))) static voidterm_printf(struct janas_term *t, const char *fmt, ...){char small[1024], *buf = small;@@ -286,20 +284,19 @@ static void term_gap(struct janas_term *t)static void term_size(struct janas_term *t){- struct winsize ws;+ int rows, cols;t->rows = 24;t->cols = 80;- if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == 0 && ws.ws_row > 4 &&- ws.ws_col > 20) {- t->rows = ws.ws_row;- t->cols = ws.ws_col;+ if (tty_size(&rows, &cols) == 0 && rows > 4 && cols > 20) {+ t->rows = rows;+ t->cols = cols;}}static void term_init(struct janas_term *t){memset(t, 0, sizeof(*t));- t->tty = isatty(STDIN_FILENO) && isatty(STDOUT_FILENO);+ t->tty = tty_both();const char *no = getenv("NO_COLOR"), *term = getenv("TERM");t->colour = t->tty && !(no && *no) && !(term && !strcmp(term, "dumb"));/* the box the line is written in, and the status line under it */@@ -312,16 +309,7 @@ static void term_raw(struct janas_term *t, int on){if (!t->tty || t->raw == on)return;- if (on) {- if (tcgetattr(STDIN_FILENO, &t->saved) != 0)- return;- struct termios r = t->saved;- r.c_lflag &= (tcflag_t) ~(ICANON | ECHO);- r.c_cc[VMIN] = 1;- r.c_cc[VTIME] = 0;- if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &r) != 0)- return;- } else if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &t->saved) != 0)+ if (tty_raw(on) != 0)return;t->raw = on;}@@ -690,20 +678,19 @@ enum {static int term_key(void){unsigned char c;- if (read(STDIN_FILENO, &c, 1) != 1)+ if (tty_byte(&c) != 1)return TERM_KEY_ESC; /* the input ended: let the page close */if (c != 27)return c;- struct pollfd pf = {STDIN_FILENO, POLLIN, 0};unsigned char lead = 0, final = 0;char par[16];int pn = 0;- if (poll(&pf, 1, 50) <= 0 || read(STDIN_FILENO, &lead, 1) != 1 ||+ if (tty_wait(50) <= 0 || tty_byte(&lead) != 1 ||(lead != '[' && lead != 'O'))return TERM_KEY_ESC; /* nothing followed it: Escape itself */for (;;) { /* the parameters, then the byte that names it */unsigned char b;- if (read(STDIN_FILENO, &b, 1) != 1)+ if (tty_byte(&b) != 1)break;if (b >= 0x40 && b <= 0x7e) {final = b;diff --git a/src/chat/tty.c b/src/chat/tty.cnew file mode 100644index 0000000..79ec2f2--- /dev/null+++ b/src/chat/tty.c@@ -0,0 +1,237 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * tty.c - see tty.h.+ */+#include "tty.h"++#include <errno.h>+#include <poll.h>+#include <unistd.h>++void (*tty_on_resize)(void);++#ifdef _WIN32+#include <windows.h>+#include <io.h>++static HANDLE in_h, out_h;+static DWORD saved_in;+static int raw_on;+/* the UTF-8 bytes of a character read and not yet handed out */+static unsigned char queue[8];+static int q_at, q_n;++void tty_setup(void)+{+ in_h = GetStdHandle(STD_INPUT_HANDLE);+ out_h = GetStdHandle(STD_OUTPUT_HANDLE);+ DWORD m;+ SetConsoleOutputCP(CP_UTF8);+ SetConsoleCP(CP_UTF8);+ /* the escape sequences understood, and the wrap at the last column+ left pending as an xterm does, so that a full line does not take+ two */+ if (GetConsoleMode(out_h, &m))+ SetConsoleMode(out_h, m | ENABLE_VIRTUAL_TERMINAL_PROCESSING |+ DISABLE_NEWLINE_AUTO_RETURN);+ HANDLE err_h = GetStdHandle(STD_ERROR_HANDLE);+ if (GetConsoleMode(err_h, &m))+ SetConsoleMode(err_h, m | ENABLE_VIRTUAL_TERMINAL_PROCESSING);+}++static int is_console(HANDLE h)+{+ DWORD m;+ return GetConsoleMode(h, &m) != 0;+}++int tty_both(void)+{+ return is_console(GetStdHandle(STD_INPUT_HANDLE)) &&+ is_console(GetStdHandle(STD_OUTPUT_HANDLE));+}++int tty_size(int *rows, int *cols)+{+ CONSOLE_SCREEN_BUFFER_INFO i;+ if (!GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &i))+ return -1;+ *rows = i.srWindow.Bottom - i.srWindow.Top + 1;+ *cols = i.srWindow.Right - i.srWindow.Left + 1;+ return 0;+}++int tty_raw(int on)+{+ if (!in_h)+ tty_setup();+ if (on == raw_on)+ return 0;+ if (on) {+ if (!GetConsoleMode(in_h, &saved_in))+ return -1;+ /* keys one by one as an xterm sends them; Ctrl-C still the+ console's, which the C runtime turns into SIGINT */+ DWORD m = (saved_in & ~(DWORD)(ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT |+ ENABLE_QUICK_EDIT_MODE)) |+ ENABLE_VIRTUAL_TERMINAL_INPUT | ENABLE_PROCESSED_INPUT |+ ENABLE_WINDOW_INPUT | ENABLE_EXTENDED_FLAGS;+ if (!SetConsoleMode(in_h, m))+ return -1;+ } else if (!SetConsoleMode(in_h, saved_in))+ return -1;+ raw_on = on;+ return 0;+}++/* Takes out of the console's queue what gives no character (keys let go,+ Shift alone, the mouse, the focus); a change of size is reported. 1 when+ a character waits, 0 when nothing does, -1 when the window changed. */+static int console_pending(void)+{+ for (;;) {+ INPUT_RECORD r;+ DWORD n = 0;+ if (!PeekConsoleInputW(in_h, &r, 1, &n) || n == 0)+ return 0;+ if (r.EventType == KEY_EVENT && r.Event.KeyEvent.bKeyDown &&+ r.Event.KeyEvent.uChar.UnicodeChar)+ return 1;+ ReadConsoleInputW(in_h, &r, 1, &n);+ if (r.EventType == WINDOW_BUFFER_SIZE_EVENT) {+ if (tty_on_resize)+ tty_on_resize();+ return -1;+ }+ }+}++int tty_wait(int ms)+{+ if (!in_h)+ tty_setup();+ if (q_at < q_n)+ return 1;+ if (!is_console(in_h)) {+ struct pollfd pf = {.fd = 0, .events = POLLIN};+ return poll(&pf, 1, ms);+ }+ ULONGLONG end = GetTickCount64() + (ULONGLONG)(ms < 0 ? 0 : ms);+ for (;;) {+ int p = console_pending();+ if (p > 0)+ return 1;+ if (p < 0) {+ errno = EINTR;+ return -1;+ }+ ULONGLONG now = GetTickCount64();+ if (ms >= 0 && now >= end)+ return 0;+ DWORD left = ms < 0 ? INFINITE : (DWORD)(end - now);+ if (WaitForSingleObject(in_h, left) == WAIT_TIMEOUT)+ return 0;+ }+}++int tty_byte(unsigned char *c)+{+ if (!in_h)+ tty_setup();+ if (q_at < q_n) {+ *c = queue[q_at++];+ return 1;+ }+ if (!is_console(in_h)) {+ int r = _read(0, c, 1);+ return r < 0 ? -1 : r;+ }+ for (;;) {+ int p = tty_wait(-1);+ if (p < 0)+ return -1;+ wchar_t w[2];+ DWORD n = 0;+ if (!ReadConsoleW(in_h, w, 1, &n, NULL)) {+ errno = GetLastError() == ERROR_OPERATION_ABORTED ? EINTR : EIO;+ return -1;+ }+ if (n == 0)+ continue;+ int units = 1;+ /* a character beyond the first plane comes as two halves */+ if (w[0] >= 0xD800 && w[0] <= 0xDBFF &&+ ReadConsoleW(in_h, w + 1, 1, &n, NULL) && n == 1)+ units = 2;+ if (w[0] == 26 && !raw_on)+ return 0; /* Ctrl-Z: the end of the input, as Windows has it */+ int len = WideCharToMultiByte(CP_UTF8, 0, w, units, (char *)queue,+ sizeof queue, NULL, NULL);+ if (len <= 0)+ continue;+ q_at = 1;+ q_n = len;+ *c = queue[0];+ return 1;+ }+}++#else+#include <sys/ioctl.h>+#include <termios.h>++static struct termios saved;+static int raw_on;++void tty_setup(void)+{+}++int tty_both(void)+{+ return isatty(STDIN_FILENO) && isatty(STDOUT_FILENO);+}++int tty_size(int *rows, int *cols)+{+ struct winsize ws;+ if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) != 0)+ return -1;+ *rows = ws.ws_row;+ *cols = ws.ws_col;+ return 0;+}++int tty_raw(int on)+{+ if (on == raw_on)+ return 0;+ if (on) {+ if (tcgetattr(STDIN_FILENO, &saved) != 0)+ return -1;+ struct termios r = saved;+ r.c_lflag &= (tcflag_t) ~(ICANON | ECHO);+ r.c_cc[VMIN] = 1;+ r.c_cc[VTIME] = 0;+ if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &r) != 0)+ return -1;+ } else if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &saved) != 0)+ return -1;+ raw_on = on;+ return 0;+}++int tty_wait(int ms)+{+ struct pollfd pf = {STDIN_FILENO, POLLIN, 0};+ return poll(&pf, 1, ms);+}++int tty_byte(unsigned char *c)+{+ ssize_t r = read(STDIN_FILENO, c, 1);+ return r < 0 ? -1 : (int)r;+}++#endifdiff --git a/src/chat/tty.h b/src/chat/tty.hnew file mode 100644index 0000000..c4aa00d--- /dev/null+++ b/src/chat/tty.h@@ -0,0 +1,39 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * tty.h - the terminal as the chat uses it: keys read one byte at a time,+ * the escape sequences of the arrows and the like as an xterm sends them,+ * UTF-8 both ways. POSIX: termios and the descriptors themselves. Windows:+ * the console in its virtual-terminal mode, read as UTF-16 and handed on+ * as UTF-8 (tty.c).+ */+#ifndef JANAS_CHAT_TTY_H+#define JANAS_CHAT_TTY_H++/* Once, at the start: on Windows the console made to take UTF-8 and the+ escape sequences; nothing elsewhere. */+void tty_setup(void);++/* Whether standard input and standard output are both a terminal. */+int tty_both(void);++/* The window's size; 0, or -1 when it is not known. */+int tty_size(int *rows, int *cols);++/* Raw mode (keys as they are pressed, no echo; Ctrl-C still a SIGINT) on+ or back to how it was. 0 or -1. */+int tty_raw(int on);++/* Waits up to ms (-1: as long as it takes) for a byte of input: 1 when+ there is one, 0 when none came, -1 with errno EINTR when a signal came+ or the window changed size (Windows: tty_on_resize is called first). */+int tty_wait(int ms);++/* One byte of input: 1, 0 at its end, -1 with errno (EINTR as above). */+int tty_byte(unsigned char *c);++/* Called on Windows when the console window changes size, where POSIX+ has SIGWINCH. */+extern void (*tty_on_resize)(void);++#endifdiff --git a/src/common/mcp_client.c b/src/common/mcp_client.cindex d6f05c7..da31021 100644--- a/src/common/mcp_client.c+++ b/src/common/mcp_client.c@@ -27,7 +27,6 @@#include <stdlib.h>#include <string.h>#include <sys/stat.h>-#include <sys/wait.h>#include <time.h>#include "common/mcp_config.h"@@ -712,9 +711,9 @@ static int ended(struct janas_mcp *m){if (m->http)return 0; /* each request is a connection of its own */- if (m->p.pid <= 0 || m->p.eof)+ if (!m->p.proc.id || m->p.eof)return 1;- return waitpid(m->p.pid, NULL, WNOHANG) == m->p.pid ? (m->p.pid = 0, 1) : 0;+ return janas_proc_wait(&m->p.proc, 0, NULL) == 1;}int32_t janas_mcp_tool_read_only(const janas_mcp *m, const char *name,diff --git a/src/common/mcp_client.h b/src/common/mcp_client.hindex 8c749db..8476452 100644--- a/src/common/mcp_client.h+++ b/src/common/mcp_client.h@@ -91,7 +91,7 @@ void janas_mcp_http_end(struct janas_mcp *m);/* Records the failure for janas_mcp_last_error; returns code. */int32_t janas_mcp_fail(int32_t code, const char *fmt, ...)- __attribute__((format(printf, 2, 3)));+ __attribute__((format(gnu_printf, 2, 3)));/* mcp_content.c: the tools of a tools/list page added to m (0, or -1 onmemory); the content of a tools/call result as text into m->result,diff --git a/src/common/mcp_http.c b/src/common/mcp_http.cindex ac677cb..069d4b3 100644--- a/src/common/mcp_http.c+++ b/src/common/mcp_http.c@@ -5,6 +5,7 @@*/#define _GNU_SOURCE /* strcasestr, getaddrinfo */#include "common/mcp_http.h"+#include "common/sock.h"#include <errno.h>#include <fcntl.h>@@ -321,7 +322,7 @@ static long io_read(struct janas_http *h, char *p, size_t n){if (h->tls)return janas_tls_read(h->tls, p, n);- long r = read(h->fd, p, n);+ long r = janas_sock_recv(h->fd, p, n);return r < 0 && (errno == EAGAIN || errno == EWOULDBLOCK) ? -2 : r;}@@ -330,7 +331,7 @@ static int send_all(struct janas_http *h, const char *p, size_t n, double end,{while (n > 0) {long w = h->tls ? janas_tls_write(h->tls, p, n)- : send(h->fd, p, n, MSG_NOSIGNAL);+ : janas_sock_send(h->fd, p, n);if (w > 0) {p += w;n -= (size_t)w;@@ -351,6 +352,7 @@ static int connect_to(const struct janas_url *u, double end,struct addrinfo hints = {.ai_family = AF_UNSPEC,.ai_socktype = SOCK_STREAM},*res = NULL;+ janas_sock_init();int e = getaddrinfo(u->host, u->port, &hints, &res);if (e != 0) {snprintf(err, err_len, "%s: %s", u->host, gai_strerror(e));@@ -358,21 +360,21 @@ static int connect_to(const struct janas_url *u, double end,}int fd = -1;for (struct addrinfo *a = res; a && fd < 0; a = a->ai_next) {- fd = socket(a->ai_family, a->ai_socktype | SOCK_CLOEXEC | SOCK_NONBLOCK,- a->ai_protocol);+ fd = janas_sock_open(a->ai_family, a->ai_socktype, a->ai_protocol);if (fd < 0)continue;if (connect(fd, a->ai_addr, a->ai_addrlen) == 0)break;- int ok = errno == EINPROGRESS && wait_fd(fd, POLLOUT, end, cancel) > 0;+ int ok =+ janas_sock_connecting() && wait_fd(fd, POLLOUT, end, cancel) > 0;int so = 0;socklen_t sl = sizeof(so);- if (ok && getsockopt(fd, SOL_SOCKET, SO_ERROR, &so, &sl) == 0 &&+ if (ok && getsockopt(fd, SOL_SOCKET, SO_ERROR, (void *)&so, &sl) == 0 &&so == 0)break;snprintf(err, err_len, "%s:%s: %s", u->host, u->port,ok ? strerror(so) : "cannot connect in time");- close(fd);+ janas_sock_close(fd);fd = -1;}freeaddrinfo(res);@@ -533,7 +535,7 @@ void janas_http_close(struct janas_http *h)janas_tls_close(h->tls);h->tls = NULL;if (h->fd >= 0)- close(h->fd);+ janas_sock_close(h->fd);h->fd = -1;free(h->buf);h->buf = NULL;diff --git a/src/common/mcp_stdio.c b/src/common/mcp_stdio.cindex cb4c536..7f2ec6c 100644--- a/src/common/mcp_stdio.c+++ b/src/common/mcp_stdio.c@@ -3,7 +3,6 @@/** mcp_stdio.c - an MCP server as a child process (see mcp_stdio.h).*/-#define _GNU_SOURCE /* pipe2 */#include "common/mcp_stdio.h"#include <errno.h>@@ -11,45 +10,14 @@#include <poll.h>#include <pthread.h>#include <signal.h>-#include <spawn.h>#include <stdio.h>#include <stdlib.h>#include <string.h>-#include <sys/wait.h>#include <time.h>#include <unistd.h>-extern char **environ;-#define LINE_MAX_BYTES ((size_t)64 << 20)-/* This process's environment with env laid over it: a KEY=VALUE of env- replaces the variable of the same name. */-static char **merge_env(char *const env[])-{- size_t n = 0, m = 0;- while (environ[n])- n++;- while (env && env[m])- m++;- char **out = calloc(n + m + 1, sizeof(*out));- if (!out)- return NULL;- size_t k = 0;- for (size_t i = 0; i < n; i++) {- const char *eq = strchr(environ[i], '=');- size_t key = eq ? (size_t)(eq - environ[i]) + 1 : strlen(environ[i]);- int replaced = 0;- for (size_t j = 0; j < m && !replaced; j++)- replaced = strncmp(env[j], environ[i], key) == 0;- if (!replaced)- out[k++] = environ[i];- }- for (size_t j = 0; j < m; j++)- out[k++] = env[j];- return out;-}-int janas_mcp_proc_start(struct janas_mcp_proc *p, char *const argv[],char *const env[], const char *log_path, char *err,size_t err_len)@@ -58,64 +26,32 @@ int janas_mcp_proc_start(struct janas_mcp_proc *p, char *const argv[],p->in = p->out = -1;int to[2] = {-1, -1}, from[2] = {-1, -1};int log = -1, rc = -1;- char **envp = NULL;- posix_spawn_file_actions_t fa;- posix_spawnattr_t at;- int have_fa = 0, have_at = 0;if (!argv || !argv[0] || !*argv[0]) {snprintf(err, err_len, "no command");return -1;}- if (pipe2(to, O_CLOEXEC) != 0 || pipe2(from, O_CLOEXEC) != 0) {+ if (janas_pipe(to) != 0 || janas_pipe(from) != 0) {snprintf(err, err_len, "pipe: %s", strerror(errno));goto out;}if (log_path)log = open(log_path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600);if (log < 0)- log = open("/dev/null", O_WRONLY | O_CLOEXEC);- envp = merge_env(env);- if (!envp || log < 0) {- snprintf(err, err_len, "out of memory or no /dev/null");+ log = janas_null_fd(1);+ if (log < 0) {+ snprintf(err, err_len, "no null device");goto out;}- have_fa = posix_spawn_file_actions_init(&fa) == 0;- have_at = posix_spawnattr_init(&at) == 0;- if (!have_fa || !have_at) {- snprintf(err, err_len, "out of memory");- goto out;- }- posix_spawn_file_actions_adddup2(&fa, to[0], 0);- posix_spawn_file_actions_adddup2(&fa, from[1], 1);- posix_spawn_file_actions_adddup2(&fa, log, 2);/* a group of its own, the signals as a new program has them */- sigset_t none, dflt;- sigemptyset(&none);- sigemptyset(&dflt);- sigaddset(&dflt, SIGPIPE);- sigaddset(&dflt, SIGINT);- posix_spawnattr_setpgroup(&at, 0);- posix_spawnattr_setsigmask(&at, &none);- posix_spawnattr_setsigdefault(&at, &dflt);- posix_spawnattr_setflags(&at, POSIX_SPAWN_SETPGROUP |- POSIX_SPAWN_SETSIGMASK |- POSIX_SPAWN_SETSIGDEF);- int e = posix_spawnp(&p->pid, argv[0], &fa, &at, argv, envp);- if (e != 0) {- p->pid = 0;- snprintf(err, err_len, "cannot start %s: %s", argv[0], strerror(e));+ if (janas_proc_start(&p->proc, (const char *const *)argv,+ (const char *const *)env, NULL, to[0], from[1], log,+ JANAS_PROC_GROUP, err, err_len) != 0)goto out;- }p->in = to[1];p->out = from[0];to[1] = from[0] = -1;rc = 0;out:- if (have_fa)- posix_spawn_file_actions_destroy(&fa);- if (have_at)- posix_spawnattr_destroy(&at);- free(envp);for (int i = 0; i < 2; i++) {if (to[i] >= 0)close(to[i]);@@ -134,6 +70,17 @@ int janas_mcp_proc_send(struct janas_mcp_proc *p, const char *s, size_t n){if (p->in < 0)return -1;+#ifdef _WIN32+ /* no signal there: a write to a pipe nobody reads only fails */+ while (n > 0) {+ int w = write(p->in, s, n > 0x40000000u ? 0x40000000u : (unsigned)n);+ if (w <= 0)+ return -1;+ s += w;+ n -= (size_t)w;+ }+ return 0;+#elsesigset_t pipe_set, old;sigemptyset(&pipe_set);sigaddset(&pipe_set, SIGPIPE);@@ -160,6 +107,7 @@ int janas_mcp_proc_send(struct janas_mcp_proc *p, const char *s, size_t n)}pthread_sigmask(SIG_SETMASK, &old, NULL);return rc;+#endif}static double now_ms(void)@@ -232,33 +180,19 @@ int janas_mcp_proc_line(struct janas_mcp_proc *p, int timeout_ms,}}-/* Waits up to ms for the process to end; 1 when it has. */-static int reap(pid_t pid, int ms)-{- for (int waited = 0;; waited += 10) {- pid_t r = waitpid(pid, NULL, WNOHANG);- if (r == pid || (r < 0 && errno == ECHILD))- return 1;- if (waited >= ms)- return 0;- struct timespec t = {0, 10 * 1000 * 1000};- nanosleep(&t, NULL);- }-}-void janas_mcp_proc_stop(struct janas_mcp_proc *p){if (p->in >= 0)close(p->in);p->in = -1;- if (p->pid > 0 && !reap(p->pid, 1000)) {- kill(-p->pid, SIGTERM);- if (!reap(p->pid, 2000)) {- kill(-p->pid, SIGKILL);- waitpid(p->pid, NULL, 0);+ if (p->proc.id && janas_proc_wait(&p->proc, 1000, NULL) == 0) {+ janas_proc_kill(&p->proc, 0);+ if (janas_proc_wait(&p->proc, 2000, NULL) == 0) {+ janas_proc_kill(&p->proc, 1);+ janas_proc_wait(&p->proc, -1, NULL);}}- p->pid = 0;+ memset(&p->proc, 0, sizeof p->proc);if (p->out >= 0)close(p->out);p->out = -1;diff --git a/src/common/mcp_stdio.h b/src/common/mcp_stdio.hindex 972ce4e..4aee3b3 100644--- a/src/common/mcp_stdio.h+++ b/src/common/mcp_stdio.h@@ -15,10 +15,11 @@#define JANAS_MCP_STDIO_H#include <stddef.h>-#include <sys/types.h>++#include "common/proc.h"struct janas_mcp_proc {- pid_t pid; /* 0: not running */+ struct janas_proc proc; /* id 0: not running */int in, out; /* its standard input (we write), output (we read) */char *buf; /* what was read and not yet taken as lines */size_t n, cap, start;@@ -41,7 +42,7 @@ int janas_mcp_proc_send(struct janas_mcp_proc *p, const char *s, size_t n);call): 1, or 0 when none came within timeout_ms (0: what has alreadyarrived), or -1 when the server has closed its output or wrote a linelonger than 64 MiB. The reading end may be any descriptor: a server- reads its own standard input with it, pid 0 and in -1. */+ reads its own standard input with it, proc cleared and in -1. */int janas_mcp_proc_line(struct janas_mcp_proc *p, int timeout_ms,const char **line, size_t *n);diff --git a/src/common/mcp_tls.c b/src/common/mcp_tls.cindex 611fc2b..b7a8653 100644--- a/src/common/mcp_tls.c+++ b/src/common/mcp_tls.c@@ -4,6 +4,7 @@* mcp_tls.c - TLS on Mbed TLS for the HTTP client of MCP (see mcp_tls.h).*/#include "common/mcp_tls.h"+#include "common/sock.h"#include <errno.h>#include <poll.h>@@ -39,6 +40,29 @@ static const char *const BUNDLES[] = {"/etc/ssl/cert.pem", /* Alpine, macOS */NULL};+#ifdef _WIN32+#include <windows.h>+#include <wincrypt.h>++/* Windows keeps no bundle: the authorities are the system's own store of+ trusted roots. 1 when one at least was read. */+static int load_system_roots(void)+{+ HCERTSTORE st = CertOpenSystemStoreA(0, "ROOT");+ if (!st)+ return 0;+ int n = 0;+ for (PCCERT_CONTEXT c = NULL;+ (c = CertEnumCertificatesInStore(st, c)) != NULL;)+ if (c->dwCertEncodingType == X509_ASN_ENCODING &&+ mbedtls_x509_crt_parse_der(&authorities, c->pbCertEncoded,+ c->cbCertEncoded) == 0)+ n++;+ CertCloseStore(st, 0);+ return n > 0;+}+#endif+/* Once: the crypto library, the authorities, the configuration shared byevery session. Called with the lock held. */static int set_up(void)@@ -59,6 +83,10 @@ static int set_up(void)loaded = mbedtls_x509_crt_parse_file(&authorities, file) >= 0;if (!loaded && dir && *dir)loaded = mbedtls_x509_crt_parse_path(&authorities, dir) >= 0;+#ifdef _WIN32+ if (!loaded)+ loaded = load_system_roots();+#endiffor (int i = 0; !loaded && BUNDLES[i]; i++)/* a bundle with a certificate it cannot read still loads the rest,and says how many it skipped with a positive number */@@ -84,7 +112,7 @@ static int set_up(void)static int bio_send(void *ctx, const unsigned char *p, size_t n){- ssize_t w = send(*(int *)ctx, p, n, MSG_NOSIGNAL);+ long w = janas_sock_send(*(int *)ctx, p, n);if (w >= 0)return (int)w;return errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR@@ -94,7 +122,7 @@ static int bio_send(void *ctx, const unsigned char *p, size_t n)static int bio_recv(void *ctx, unsigned char *p, size_t n){- ssize_t r = recv(*(int *)ctx, p, n, 0);+ long r = janas_sock_recv(*(int *)ctx, p, n);if (r >= 0)return (int)r;return errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTRdiff --git a/src/common/pool.c b/src/common/pool.cindex 4a729e7..1acb7c3 100644--- a/src/common/pool.c+++ b/src/common/pool.c@@ -123,14 +123,6 @@ struct worker_arg {int tid;};-int janas_pin_current_thread(int cpu)-{- cpu_set_t set;- CPU_ZERO(&set);- CPU_SET(cpu, &set);- return pthread_setaffinity_np(pthread_self(), sizeof(set), &set) ? -1 : 0;-}-static void *worker(void *v){struct worker_arg wa = *(struct worker_arg *)v;diff --git a/src/common/proc.c b/src/common/proc.cnew file mode 100644index 0000000..b857b3d--- /dev/null+++ b/src/common/proc.c@@ -0,0 +1,172 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * proc.c - see proc.h: POSIX, with posix_spawn. Windows: proc_win.c.+ */+#ifndef _WIN32+#define _GNU_SOURCE /* pipe2, posix_spawn_file_actions_addchdir_np */+#include "common/proc.h"++#include <errno.h>+#include <fcntl.h>+#include <signal.h>+#include <spawn.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <sys/stat.h>+#include <sys/wait.h>+#include <time.h>+#include <unistd.h>++extern char **environ;++/* This process's environment with env laid over it: a KEY=VALUE of env+ replaces the variable of the same name. */+static char **merge_env(const char *const env[])+{+ size_t n = 0, m = 0;+ while (environ[n])+ n++;+ while (env && env[m])+ m++;+ char **out = calloc(n + m + 1, sizeof(*out));+ if (!out)+ return NULL;+ size_t k = 0;+ for (size_t i = 0; i < n; i++) {+ const char *eq = strchr(environ[i], '=');+ size_t key = eq ? (size_t)(eq - environ[i]) + 1 : strlen(environ[i]);+ int replaced = 0;+ for (size_t j = 0; j < m && !replaced; j++)+ replaced = strncmp(env[j], environ[i], key) == 0;+ if (!replaced)+ out[k++] = environ[i];+ }+ for (size_t j = 0; j < m; j++)+ out[k++] = (char *)env[j];+ return out;+}++int janas_proc_start(struct janas_proc *p, const char *const argv[],+ const char *const env[], const char *dir, int fd_in,+ int fd_out, int fd_err, int flags, char *err,+ size_t err_len)+{+ memset(p, 0, sizeof(*p));+ if (!argv || !argv[0] || !*argv[0]) {+ snprintf(err, err_len, "no command");+ errno = EINVAL;+ return -1;+ }+ struct stat st;+ if (dir && (stat(dir, &st) != 0 || !S_ISDIR(st.st_mode))) {+ snprintf(err, err_len, "cannot enter %s", dir);+ errno = ENOTDIR;+ return -1;+ }+ char **envp = merge_env(env);+ posix_spawn_file_actions_t fa;+ posix_spawnattr_t at;+ int have_fa = posix_spawn_file_actions_init(&fa) == 0;+ int have_at = posix_spawnattr_init(&at) == 0;+ int rc = -1;+ if (!envp || !have_fa || !have_at) {+ snprintf(err, err_len, "out of memory");+ errno = ENOMEM;+ goto out;+ }+ if (fd_in >= 0)+ posix_spawn_file_actions_adddup2(&fa, fd_in, 0);+ if (fd_out >= 0)+ posix_spawn_file_actions_adddup2(&fa, fd_out, 1);+ if (fd_err >= 0)+ posix_spawn_file_actions_adddup2(&fa, fd_err, 2);+ if (dir)+ posix_spawn_file_actions_addchdir_np(&fa, dir);+ /* the signals as a new program has them */+ sigset_t none, dflt;+ sigemptyset(&none);+ sigemptyset(&dflt);+ sigaddset(&dflt, SIGPIPE);+ sigaddset(&dflt, SIGINT);+ posix_spawnattr_setsigmask(&at, &none);+ posix_spawnattr_setsigdefault(&at, &dflt);+ short f = POSIX_SPAWN_SETSIGMASK | POSIX_SPAWN_SETSIGDEF;+ if (flags & JANAS_PROC_DETACHED)+ f |= POSIX_SPAWN_SETSID; /* a session, and so a group, of its own */+ else if (flags & JANAS_PROC_GROUP) {+ posix_spawnattr_setpgroup(&at, 0);+ f |= POSIX_SPAWN_SETPGROUP;+ }+ posix_spawnattr_setflags(&at, f);+ pid_t pid;+ int e = posix_spawnp(&pid, argv[0], &fa, &at, (char *const *)argv, envp);+ if (e != 0) {+ snprintf(err, err_len, "cannot start %s: %s", argv[0], strerror(e));+ errno = e;+ goto out;+ }+ p->id = pid;+ p->pid = (unsigned long)pid;+ p->job = flags & (JANAS_PROC_GROUP | JANAS_PROC_DETACHED) ? 1 : 0;+ rc = 0;+out:+ if (have_fa)+ posix_spawn_file_actions_destroy(&fa);+ if (have_at)+ posix_spawnattr_destroy(&at);+ free(envp);+ return rc;+}++static int status_code(int st)+{+ return WIFEXITED(st) ? WEXITSTATUS(st) : -1;+}++int janas_proc_wait(struct janas_proc *p, int timeout_ms, int *code)+{+ if (p->id <= 0)+ return -1;+ pid_t pid = (pid_t)p->id;+ int st = 0;+ for (int waited = 0;; waited += 10) {+ pid_t r = waitpid(pid, &st, timeout_ms < 0 ? 0 : WNOHANG);+ if (r < 0 && errno == EINTR)+ continue;+ if (r == pid || (r < 0 && errno == ECHILD)) {+ if (code)+ *code = r == pid ? status_code(st) : -1;+ memset(p, 0, sizeof(*p));+ return 1;+ }+ if (r < 0)+ return -1;+ if (waited >= timeout_ms)+ return 0;+ struct timespec t = {0, 10 * 1000 * 1000};+ nanosleep(&t, NULL);+ }+}++void janas_proc_kill(struct janas_proc *p, int hard)+{+ if (p->id <= 0)+ return;+ pid_t pid = (pid_t)p->id;+ /* its group, which it leads, where it has one of its own */+ kill(p->job ? -pid : pid, hard ? SIGKILL : SIGTERM);+}++int janas_pipe(int fd[2])+{+ return pipe2(fd, O_CLOEXEC);+}++int janas_null_fd(int for_writing)+{+ return open("/dev/null", (for_writing ? O_WRONLY : O_RDONLY) | O_CLOEXEC);+}++#endif /* !_WIN32 */diff --git a/src/common/proc.h b/src/common/proc.hnew file mode 100644index 0000000..e176adc--- /dev/null+++ b/src/common/proc.h@@ -0,0 +1,62 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * proc.h - a program started by Janas: an MCP server, a service's git, a+ * tool beside the chat. POSIX: posix_spawn (proc.c); Windows: CreateProcess+ * with a job object that holds the program and what it starts in turn+ * (proc_win.c).+ */+#ifndef JANAS_COMMON_PROC_H+#define JANAS_COMMON_PROC_H++#include <stddef.h>+#include <stdint.h>++struct janas_proc {+ intptr_t id; /* 0: none. POSIX its pid, Windows its process's handle */+ intptr_t job; /* Windows: the job object; 0 elsewhere */+ unsigned long pid;+};++/* A group of its own: the terminal's Ctrl-C does not reach it, and+ janas_proc_kill reaches what it started in turn (npx starts node). */+#define JANAS_PROC_GROUP 1+/* No terminal at all: nothing can be asked of the user (setsid; on+ Windows no console). */+#define JANAS_PROC_DETACHED 2++/*+ * Starts argv[0] - a path, or a name looked for in PATH (on Windows a .cmd+ * or .bat too, through cmd.exe) - with argv, in dir (NULL: this one's),+ * with this process's environment and env laid over it (KEY=VALUE,+ * NULL-terminated; NULL: none). fd_in, fd_out and fd_err become its+ * standard input, output and error; -1 leaves it this process's.+ * 0, or -1 with the reason in err (errno ENOENT when the program is not+ * there).+ */+int janas_proc_start(struct janas_proc *p, const char *const argv[],+ const char *const env[], const char *dir, int fd_in,+ int fd_out, int fd_err, int flags, char *err,+ size_t err_len);++/*+ * Waits up to timeout_ms (-1: as long as it takes, 0: only looks) for it+ * to end: 1 when it has, with its exit status in *code (may be NULL; -1+ * when a signal ended it), 0 when it still runs, -1 on an error. Once it+ * has ended p is cleared.+ */+int janas_proc_wait(struct janas_proc *p, int timeout_ms, int *code);++/* Asks it and what it started to end (SIGTERM; Windows: Ctrl+Break to+ its group), or with hard ends them (SIGKILL; Windows: the job+ terminated). */+void janas_proc_kill(struct janas_proc *p, int hard);++/* A pipe, neither end passed on to programs started later. 0 or -1. */+int janas_pipe(int fd[2]);++/* A descriptor of the null device (/dev/null, NUL), for writing or for+ reading. */+int janas_null_fd(int for_writing);++#endifdiff --git a/src/common/proc_win.c b/src/common/proc_win.cnew file mode 100644index 0000000..986af1b--- /dev/null+++ b/src/common/proc_win.c@@ -0,0 +1,339 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * proc_win.c - see proc.h: Windows, with CreateProcess.+ *+ * The program gets exactly the three handles it is given and no other+ * (PROC_THREAD_ATTRIBUTE_HANDLE_LIST), and is started suspended inside a+ * job object, so that what it starts in turn is in the job too and goes+ * with it: TerminateJobObject is the kill of a process group. A job that+ * is closed takes its processes with it, as a group would not on POSIX:+ * nothing Janas starts outlives Janas.+ *+ * Windows has one command line, not a vector: the arguments are joined+ * and quoted as the C runtime of the program will split them again. A+ * .cmd or .bat (npx is npx.cmd) runs through cmd.exe.+ */+#ifdef _WIN32+#include "common/proc.h"++#include <windows.h>+#include <errno.h>+#include <fcntl.h>+#include <io.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>++/* A growing string. */+struct str {+ char *p;+ size_t n, cap;+ int oom;+};++static void put(struct str *s, const char *t, size_t n)+{+ if (s->oom)+ return;+ if (s->n + n + 2 > s->cap) {+ size_t cap = s->cap ? s->cap * 2 : 256;+ while (cap < s->n + n + 2)+ cap *= 2;+ char *p = realloc(s->p, cap);+ if (!p) {+ s->oom = 1;+ return;+ }+ s->p = p;+ s->cap = cap;+ }+ memcpy(s->p + s->n, t, n);+ s->n += n;+ s->p[s->n] = 0;+}++static void putc_(struct str *s, char c)+{+ put(s, &c, 1);+}++/* One argument quoted as CommandLineToArgvW and the C runtime read it:+ backslashes are literal except before a quote. */+static void quote(struct str *s, const char *a)+{+ if (*a && !strpbrk(a, " \t\n\v\"")) {+ put(s, a, strlen(a));+ return;+ }+ putc_(s, '"');+ for (const char *c = a;; c++) {+ size_t bs = 0;+ while (*c == '\\') {+ bs++;+ c++;+ }+ if (!*c) {+ for (size_t i = 0; i < bs * 2; i++)+ putc_(s, '\\');+ break;+ }+ if (*c == '"') {+ for (size_t i = 0; i < bs * 2 + 1; i++)+ putc_(s, '\\');+ putc_(s, '"');+ } else {+ for (size_t i = 0; i < bs; i++)+ putc_(s, '\\');+ putc_(s, *c);+ }+ }+ putc_(s, '"');+}++static int ends_with(const char *s, const char *tail)+{+ size_t n = strlen(s), t = strlen(tail);+ return n >= t && _stricmp(s + n - t, tail) == 0;+}++/* The program's file: a path as given (or with .exe), a name looked for+ in PATH as .exe, .cmd, .bat. 0, or -1. */+static int find_program(const char *name, char *out, size_t len)+{+ static const char *const ext[] = {".exe", ".cmd", ".bat"};+ if (strpbrk(name, "/\\:")) {+ DWORD a = GetFileAttributesA(name);+ if (a != INVALID_FILE_ATTRIBUTES && !(a & FILE_ATTRIBUTE_DIRECTORY)) {+ snprintf(out, len, "%s", name);+ return 0;+ }+ for (int i = 0; i < 3; i++) {+ snprintf(out, len, "%s%s", name, ext[i]);+ a = GetFileAttributesA(out);+ if (a != INVALID_FILE_ATTRIBUTES && !(a & FILE_ATTRIBUTE_DIRECTORY))+ return 0;+ }+ return -1;+ }+ for (int i = 0; i < 3; i++) {+ DWORD n = SearchPathA(NULL, name, ext[i], (DWORD)len, out, NULL);+ if (n > 0 && n < len)+ return 0;+ }+ return -1;+}++/* This process's environment with env laid over it, as a block of+ KEY=VALUE strings that ends with an empty one. Names are compared+ without case, as Windows does. */+static char *env_block(const char *const env[])+{+ struct str b = {0};+ char *cur = GetEnvironmentStringsA();+ if (!cur)+ return NULL;+ for (const char *e = cur; *e; e += strlen(e) + 1) {+ const char *eq = strchr(e + 1, '='); /* "=C:=C:\x" starts with = */+ size_t key = eq ? (size_t)(eq - e) + 1 : strlen(e);+ int replaced = 0;+ for (size_t j = 0; env[j] && !replaced; j++)+ replaced = _strnicmp(env[j], e, key) == 0;+ if (!replaced)+ put(&b, e, strlen(e) + 1);+ }+ FreeEnvironmentStringsA(cur);+ for (size_t j = 0; env[j]; j++)+ put(&b, env[j], strlen(env[j]) + 1);+ put(&b, "", 1);+ if (b.oom) {+ free(b.p);+ return NULL;+ }+ return b.p;+}++/* An inheritable copy of the handle behind fd, or of this process's own+ std handle when fd is -1; NULL when there is none. */+static HANDLE inheritable(int fd, DWORD std)+{+ HANDLE h = fd >= 0 ? (HANDLE)_get_osfhandle(fd) : GetStdHandle(std);+ HANDLE dup = NULL;+ if (h == INVALID_HANDLE_VALUE || h == NULL)+ return NULL;+ if (!DuplicateHandle(GetCurrentProcess(), h, GetCurrentProcess(), &dup, 0,+ TRUE, DUPLICATE_SAME_ACCESS))+ return NULL;+ return dup;+}++int janas_proc_start(struct janas_proc *p, const char *const argv[],+ const char *const env[], const char *dir, int fd_in,+ int fd_out, int fd_err, int flags, char *err,+ size_t err_len)+{+ memset(p, 0, sizeof(*p));+ if (!argv || !argv[0] || !*argv[0]) {+ snprintf(err, err_len, "no command");+ errno = EINVAL;+ return -1;+ }+ if (dir) {+ DWORD a = GetFileAttributesA(dir);+ if (a == INVALID_FILE_ATTRIBUTES || !(a & FILE_ATTRIBUTE_DIRECTORY)) {+ snprintf(err, err_len, "cannot enter %s", dir);+ errno = ENOTDIR;+ return -1;+ }+ }+ char prog[MAX_PATH * 2];+ if (find_program(argv[0], prog, sizeof prog) != 0) {+ snprintf(err, err_len, "cannot start %s: not found", argv[0]);+ errno = ENOENT;+ return -1;+ }+ int script = ends_with(prog, ".cmd") || ends_with(prog, ".bat");+ struct str cmd = {0};+ if (script) {+ /* cmd.exe /s /c "the whole line": its first and last quote go */+ put(&cmd, "cmd.exe /d /s /c \"", 18);+ quote(&cmd, prog);+ } else {+ quote(&cmd, prog);+ }+ for (size_t i = 1; argv[i]; i++) {+ putc_(&cmd, ' ');+ quote(&cmd, argv[i]);+ }+ if (script)+ putc_(&cmd, '"');+ char *envp = env ? env_block(env) : NULL;+ HANDLE std[3] = {inheritable(fd_in, STD_INPUT_HANDLE),+ inheritable(fd_out, STD_OUTPUT_HANDLE),+ inheritable(fd_err, STD_ERROR_HANDLE)};+ HANDLE list[3];+ DWORD n_list = 0;+ for (int i = 0; i < 3; i++)+ if (std[i])+ list[n_list++] = std[i];+ SIZE_T attr_len = 0;+ InitializeProcThreadAttributeList(NULL, 1, 0, &attr_len);+ LPPROC_THREAD_ATTRIBUTE_LIST attrs = malloc(attr_len);+ int rc = -1;+ HANDLE job = NULL;+ PROCESS_INFORMATION pi = {0};+ if (cmd.oom || (env && !envp) || !attrs ||+ !InitializeProcThreadAttributeList(attrs, 1, 0, &attr_len)) {+ snprintf(err, err_len, "out of memory");+ errno = ENOMEM;+ free(attrs);+ attrs = NULL;+ goto out;+ }+ if (n_list > 0)+ UpdateProcThreadAttribute(attrs, 0, PROC_THREAD_ATTRIBUTE_HANDLE_LIST,+ list, n_list * sizeof(HANDLE), NULL, NULL);+ STARTUPINFOEXA si = {.StartupInfo = {.cb = sizeof si,+ .dwFlags = STARTF_USESTDHANDLES,+ .hStdInput = std[0],+ .hStdOutput = std[1],+ .hStdError = std[2]},+ .lpAttributeList = attrs};+ DWORD how = CREATE_SUSPENDED | EXTENDED_STARTUPINFO_PRESENT;+ if (flags & JANAS_PROC_DETACHED)+ how |= CREATE_NO_WINDOW | CREATE_NEW_PROCESS_GROUP;+ else if (flags & JANAS_PROC_GROUP)+ how |= CREATE_NEW_PROCESS_GROUP;+ job = CreateJobObjectA(NULL, NULL);+ if (job) {+ JOBOBJECT_EXTENDED_LIMIT_INFORMATION li = {0};+ li.BasicLimitInformation.LimitFlags =+ JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;+ SetInformationJobObject(job, JobObjectExtendedLimitInformation, &li,+ sizeof li);+ }+ if (!CreateProcessA(NULL, cmd.p, NULL, NULL, TRUE, how, envp, dir,+ &si.StartupInfo, &pi)) {+ snprintf(err, err_len, "cannot start %s: error %lu", argv[0],+ (unsigned long)GetLastError());+ errno = ENOEXEC;+ goto out;+ }+ if (job && !AssignProcessToJobObject(job, pi.hProcess)) {+ CloseHandle(job); /* runs on its own: still a program that works */+ job = NULL;+ }+ ResumeThread(pi.hThread);+ CloseHandle(pi.hThread);+ p->id = (intptr_t)pi.hProcess;+ p->job = (intptr_t)job;+ p->pid = pi.dwProcessId;+ job = NULL;+ rc = 0;+out:+ if (attrs) {+ DeleteProcThreadAttributeList(attrs);+ free(attrs);+ }+ if (job)+ CloseHandle(job);+ for (int i = 0; i < 3; i++)+ if (std[i])+ CloseHandle(std[i]);+ free(envp);+ free(cmd.p);+ return rc;+}++static void clear(struct janas_proc *p)+{+ CloseHandle((HANDLE)p->id);+ if (p->job)+ CloseHandle((HANDLE)p->job);+ memset(p, 0, sizeof(*p));+}++int janas_proc_wait(struct janas_proc *p, int timeout_ms, int *code)+{+ if (!p->id)+ return -1;+ DWORD r = WaitForSingleObject(+ (HANDLE)p->id, timeout_ms < 0 ? INFINITE : (DWORD)timeout_ms);+ if (r == WAIT_TIMEOUT)+ return 0;+ if (r != WAIT_OBJECT_0)+ return -1;+ DWORD c = 0;+ GetExitCodeProcess((HANDLE)p->id, &c);+ if (code)+ *code = (int)c;+ clear(p);+ return 1;+}++void janas_proc_kill(struct janas_proc *p, int hard)+{+ if (!p->id)+ return;+ /* Ctrl+Break reaches a group that shares this console; a program+ without one, or one that does not end, is terminated */+ if (!hard && GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT, (DWORD)p->pid))+ return;+ if (p->job)+ TerminateJobObject((HANDLE)p->job, 1);+ else+ TerminateProcess((HANDLE)p->id, 1);+}++int janas_pipe(int fd[2])+{+ return _pipe(fd, 65536, _O_BINARY | _O_NOINHERIT);+}++int janas_null_fd(int for_writing)+{+ return _open("NUL", (for_writing ? _O_WRONLY : _O_RDONLY) | _O_BINARY |+ _O_NOINHERIT);+}++#endif /* _WIN32 */diff --git a/src/common/reopen.c b/src/common/reopen.cnew file mode 100644index 0000000..e908372--- /dev/null+++ b/src/common/reopen.c@@ -0,0 +1,44 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * reopen.c - see reopen.h. Linux: the file's entry in /proc/self/fd.+ * Windows: ReOpenFile on the descriptor's handle; a direct one is also+ * overlapped, for uring_win.c's reads that run while the caller computes.+ */+#define _GNU_SOURCE+#include "common/reopen.h"++#include <fcntl.h>+#include <stdio.h>+#include <unistd.h>++#ifdef _WIN32+#include <windows.h>++int janas_reopen_read(int fd, int direct)+{+ HANDLE h = (HANDLE)_get_osfhandle(fd);+ if (h == INVALID_HANDLE_VALUE)+ return -1;+ DWORD flags = direct ? FILE_FLAG_NO_BUFFERING | FILE_FLAG_OVERLAPPED : 0;+ HANDLE n = ReOpenFile(+ h, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,+ flags);+ if (n == INVALID_HANDLE_VALUE)+ return -1;+ int nfd = _open_osfhandle((intptr_t)n, _O_RDONLY | _O_BINARY);+ if (nfd < 0)+ CloseHandle(n);+ return nfd;+}++#else++int janas_reopen_read(int fd, int direct)+{+ char path[64];+ snprintf(path, sizeof(path), "/proc/self/fd/%d", fd);+ return open(path, O_RDONLY | (direct ? O_DIRECT : 0) | O_CLOEXEC);+}++#endifdiff --git a/src/common/reopen.h b/src/common/reopen.hnew file mode 100644index 0000000..43f3859--- /dev/null+++ b/src/common/reopen.h@@ -0,0 +1,16 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * reopen.h - a file opened again from a descriptor of it, for reading:+ * with direct I/O (O_DIRECT, Windows's unbuffered and overlapped reads) or+ * through the system's cache. The new descriptor is independent of the+ * old one (its own position, its own flags).+ */+#ifndef JANAS_COMMON_REOPEN_H+#define JANAS_COMMON_REOPEN_H++/* A new read-only descriptor of fd's file, or -1. Direct: the reads must+ be aligned as O_DIRECT's (offset, length and buffer). */+int janas_reopen_read(int fd, int direct);++#endifdiff --git a/src/common/sock.c b/src/common/sock.cnew file mode 100644index 0000000..05fa797--- /dev/null+++ b/src/common/sock.c@@ -0,0 +1,143 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * sock.c - see sock.h.+ */+#define _GNU_SOURCE+#include "common/sock.h"++#include <errno.h>+#include <sys/socket.h>+#include <unistd.h>++#ifdef _WIN32+#include <windows.h>++static INIT_ONCE started = INIT_ONCE_STATIC_INIT;++static BOOL CALLBACK start(PINIT_ONCE once, PVOID arg, PVOID *ctx)+{+ (void)once, (void)arg, (void)ctx;+ WSADATA d;+ WSAStartup(MAKEWORD(2, 2), &d);+ return TRUE;+}++void janas_sock_init(void)+{+ InitOnceExecuteOnce(&started, start, NULL, NULL);+}++/* Winsock's last error in errno, under POSIX's name. */+static void wsa_errno(void)+{+ switch (WSAGetLastError()) {+ case WSAEWOULDBLOCK:+ errno = EWOULDBLOCK;+ break;+ case WSAEINPROGRESS:+ errno = EINPROGRESS;+ break;+ case WSAEINTR:+ errno = EINTR;+ break;+ case WSAECONNRESET:+ errno = ECONNRESET;+ break;+ case WSAECONNREFUSED:+ errno = ECONNREFUSED;+ break;+ case WSAETIMEDOUT:+ errno = ETIMEDOUT;+ break;+ case WSAENOTCONN:+ errno = ENOTCONN;+ break;+ case WSAEHOSTUNREACH:+ errno = EHOSTUNREACH;+ break;+ case WSAENETUNREACH:+ errno = ENETUNREACH;+ break;+ default:+ errno = EIO;+ }+}++int janas_sock_open(int family, int type, int protocol)+{+ janas_sock_init();+ SOCKET s = WSASocketW(family, type, protocol, NULL, 0,+ WSA_FLAG_OVERLAPPED | WSA_FLAG_NO_HANDLE_INHERIT);+ if (s == INVALID_SOCKET) {+ wsa_errno();+ return -1;+ }+ u_long on = 1;+ ioctlsocket(s, FIONBIO, &on);+ return (int)s;+}++int janas_sock_connecting(void)+{+ int e = WSAGetLastError();+ return e == WSAEWOULDBLOCK || e == WSAEINPROGRESS;+}++long janas_sock_recv(int fd, void *p, size_t n)+{+ int r = recv((SOCKET)fd, p, n > 0x40000000u ? 0x40000000 : (int)n, 0);+ if (r == SOCKET_ERROR) {+ wsa_errno();+ return -1;+ }+ return r;+}++long janas_sock_send(int fd, const void *p, size_t n)+{+ int w = send((SOCKET)fd, p, n > 0x40000000u ? 0x40000000 : (int)n, 0);+ if (w == SOCKET_ERROR) {+ wsa_errno();+ return -1;+ }+ return w;+}++int janas_sock_close(int fd)+{+ return closesocket((SOCKET)fd) == 0 ? 0 : -1;+}++#else++void janas_sock_init(void)+{+}++int janas_sock_open(int family, int type, int protocol)+{+ return socket(family, type | SOCK_CLOEXEC | SOCK_NONBLOCK, protocol);+}++int janas_sock_connecting(void)+{+ return errno == EINPROGRESS;+}++long janas_sock_recv(int fd, void *p, size_t n)+{+ return read(fd, p, n);+}++long janas_sock_send(int fd, const void *p, size_t n)+{+ return send(fd, p, n, MSG_NOSIGNAL);+}++int janas_sock_close(int fd)+{+ return close(fd);+}++#endifdiff --git a/src/common/sock.h b/src/common/sock.hnew file mode 100644index 0000000..068e588--- /dev/null+++ b/src/common/sock.h@@ -0,0 +1,30 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * sock.h - the few things a TCP socket does differently on Windows: it is+ * not a file descriptor there (recv and send, not read and write; closed+ * with closesocket), its errors come from WSAGetLastError, and Winsock+ * must be started before any of it, name lookups included. These calls+ * leave the error in errno, with POSIX's names, on every system.+ */+#ifndef JANAS_COMMON_SOCK_H+#define JANAS_COMMON_SOCK_H++#include <stddef.h>++/* Winsock started, once (nothing elsewhere). Before getaddrinfo too. */+void janas_sock_init(void);++/* A socket that does not block and is not passed on to programs started+ later, or -1. */+int janas_sock_open(int family, int type, int protocol);++/* Whether the connect() that just failed is only under way (EINPROGRESS;+ Windows: WSAEWOULDBLOCK). */+int janas_sock_connecting(void);++long janas_sock_recv(int fd, void *p, size_t n);+long janas_sock_send(int fd, const void *p, size_t n);+int janas_sock_close(int fd);++#endifdiff --git a/src/common/stop.c b/src/common/stop.cnew file mode 100644index 0000000..c59f1ea--- /dev/null+++ b/src/common/stop.c@@ -0,0 +1,54 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * stop.c - see stop.h. POSIX: SIGINT and SIGTERM blocked in every thread+ * and taken with sigwait. Windows: the console's control handler, which+ * runs in a thread of its own, sets an event the waiting thread holds.+ */+#include "common/stop.h"++#ifdef _WIN32+#include <windows.h>++static HANDLE stop_event;++static BOOL WINAPI on_control(DWORD type)+{+ (void)type; /* Ctrl+C, Ctrl+Break, the window closed, a log-off */+ SetEvent(stop_event);+ return TRUE;+}++void janas_stop_prepare(void)+{+ stop_event = CreateEventA(NULL, TRUE, FALSE, NULL);+ SetConsoleCtrlHandler(on_control, TRUE);+}++void janas_stop_wait(void)+{+ WaitForSingleObject(stop_event, INFINITE);+}++#else+#include <pthread.h>+#include <signal.h>++static sigset_t stop_set;++void janas_stop_prepare(void)+{+ sigemptyset(&stop_set);+ sigaddset(&stop_set, SIGINT);+ sigaddset(&stop_set, SIGTERM);+ pthread_sigmask(SIG_BLOCK, &stop_set, NULL);+ signal(SIGPIPE, SIG_IGN);+}++void janas_stop_wait(void)+{+ int sig;+ sigwait(&stop_set, &sig);+}++#endifdiff --git a/src/common/stop.h b/src/common/stop.hnew file mode 100644index 0000000..bd3d1d1--- /dev/null+++ b/src/common/stop.h@@ -0,0 +1,20 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * stop.h - a program that runs until it is asked to stop: Ctrl+C, a+ * termination (SIGTERM), on Windows the console closed or the user+ * logging off. The request is awaited by one thread; the others never+ * see it.+ */+#ifndef JANAS_COMMON_STOP_H+#define JANAS_COMMON_STOP_H++/* Before any thread is made: the requests to stop held back from every+ thread but the one that awaits them; a write to a closed connection an+ error, not the end of the process (SIGPIPE ignored). */+void janas_stop_prepare(void);++/* Waits for a request to stop. */+void janas_stop_wait(void);++#endifdiff --git a/src/common/sysinfo.c b/src/common/sysinfo.cindex efd2154..cb77cdb 100644--- a/src/common/sysinfo.c+++ b/src/common/sysinfo.c@@ -1,17 +1,62 @@/* SPDX-License-Identifier: GPL-3.0-or-laterCopyright (C) 2026 Maurizio Cammalleri *//*- * sysinfo.c - see sysinfo.h. Linux: sysfs and procfs.+ * sysinfo.c - see sysinfo.h. The order of the CPUs, for every system; what+ * Linux tells of them, from sysfs and procfs. Windows: sysinfo_win.c.*/#define _GNU_SOURCE#include "sysinfo.h"+#include "pool.h"+#include "sysinfo_os.h"-#include <dirent.h>-#include <sched.h>#include <stdio.h>#include <stdlib.h>#include <string.h>+int janas_cpu_layout(const int *allowed, int n_allowed,+ struct janas_cpu_layout *l)+{+ int cand[JANAS_MAX_CPUS], nc = 0;+ if (allowed) {+ for (int i = 0; i < n_allowed && nc < JANAS_MAX_CPUS; i++)+ cand[nc++] = allowed[i];+ } else {+ nc = janas_os_allowed_cpus(cand, JANAS_MAX_CPUS);+ }+ if (nc <= 0)+ return -1;+ /* kind 0 performance, 1 efficiency, 2 low-power efficiency */+ int kind[JANAS_MAX_CPUS], leader[JANAS_MAX_CPUS];+ janas_os_cpu_kinds(cand, nc, kind, leader);+ l->n = l->n_p_cores = l->n_p_threads = 0;+ /* P leaders, P siblings, E leaders, E siblings */+ for (int pass = 0; pass < 4; pass++)+ for (int i = 0; i < nc; i++) {+ int k = pass < 2 ? 0 : 1, want_leader = pass % 2 == 0;+ if (kind[i] != k)+ continue;+ int first = 1;+ for (int j = 0; j < i && first; j++)+ first = !(kind[j] == k && leader[j] == leader[i]);+ if (first != want_leader)+ continue;+ l->cpus[l->n++] = cand[i];+ if (pass == 0)+ l->n_p_cores++;+ if (pass <= 1)+ l->n_p_threads++;+ }+ if (l->n == 0)+ return -1;+ return 0;+}++#ifndef _WIN32+#include <dirent.h>+#include <pthread.h>+#include <sched.h>+#include <unistd.h>+/* Reads a CPU list ("0-11,14") from a sysfs file. Returns the count. */static int read_cpu_list(const char *path, int *out, int max){@@ -43,15 +88,8 @@ int janas_cpu_split(int *compute, int *n_compute, int *io, int *n_io, int max)*n_io = read_cpu_list("/sys/devices/cpu_atom/cpus", io, max < 8 ? max : 8);if (*n_compute > 0 && *n_io > 0)return 1;- cpu_set_t set;- CPU_ZERO(&set);- if (sched_getaffinity(0, sizeof(set), &set) != 0)- return -1;- *n_compute = 0;- for (int c = 0; c < CPU_SETSIZE && *n_compute < max; c++)- if (CPU_ISSET(c, &set))- compute[(*n_compute)++] = c;- if (*n_compute == 0)+ *n_compute = janas_os_allowed_cpus(compute, max);+ if (*n_compute <= 0)return -1;*n_io = *n_compute < 8 ? *n_compute : 8;return 0;@@ -95,31 +133,27 @@ static int in_list(const int *list, int n, int cpu)return 0;}-int janas_cpu_layout(const int *allowed, int n_allowed,- struct janas_cpu_layout *l)+int janas_os_allowed_cpus(int *out, int max){- int cand[JANAS_MAX_CPUS], nc = 0;- if (allowed) {- for (int i = 0; i < n_allowed && nc < JANAS_MAX_CPUS; i++)- cand[nc++] = allowed[i];- } else {- cpu_set_t set;- CPU_ZERO(&set);- if (sched_getaffinity(0, sizeof(set), &set) != 0)- return -1;- for (int c = 0; c < CPU_SETSIZE && nc < JANAS_MAX_CPUS; c++)- if (CPU_ISSET(c, &set))- cand[nc++] = c;- }- if (nc == 0)+ cpu_set_t set;+ CPU_ZERO(&set);+ if (sched_getaffinity(0, sizeof(set), &set) != 0)return -1;+ int n = 0;+ for (int c = 0; c < CPU_SETSIZE && n < max; c++)+ if (CPU_ISSET(c, &set))+ out[n++] = c;+ return n;+}++void janas_os_cpu_kinds(const int *cand, int nc, int *kind, int *leader)+{/* hybrid processors list their core types */int pcores[JANAS_MAX_CPUS], ecores[JANAS_MAX_CPUS];int np =read_cpu_list("/sys/devices/cpu_core/cpus", pcores, JANAS_MAX_CPUS);int ne =read_cpu_list("/sys/devices/cpu_atom/cpus", ecores, JANAS_MAX_CPUS);- int kind[JANAS_MAX_CPUS], leader[JANAS_MAX_CPUS]; /* kind 0 P, 1 E, 2 LP */long efreq_max = 0, freq[JANAS_MAX_CPUS];for (int i = 0; i < nc; i++) {char path[128];@@ -142,27 +176,37 @@ int janas_cpu_layout(const int *allowed, int n_allowed,for (int i = 0; i < nc; i++)if (kind[i] == 1 && freq[i] > 0 && freq[i] < efreq_max * 85 / 100)kind[i] = 2;- l->n = l->n_p_cores = l->n_p_threads = 0;- /* P leaders, P siblings, E leaders, E siblings */- for (int pass = 0; pass < 4; pass++)- for (int i = 0; i < nc; i++) {- int k = pass < 2 ? 0 : 1, want_leader = pass % 2 == 0;- if (kind[i] != k)- continue;- int first = 1;- for (int j = 0; j < i && first; j++)- first = !(kind[j] == k && leader[j] == leader[i]);- if (first != want_leader)- continue;- l->cpus[l->n++] = cand[i];- if (pass == 0)- l->n_p_cores++;- if (pass <= 1)- l->n_p_threads++;- }- if (l->n == 0)+}++int janas_cpus_save(unsigned char save[JANAS_CPU_SAVE_BYTES])+{+ _Static_assert(sizeof(cpu_set_t) <= JANAS_CPU_SAVE_BYTES, "cpu set");+ return sched_getaffinity(0, sizeof(cpu_set_t), (cpu_set_t *)save) == 0 ? 0+ : -1;+}++void janas_cpus_restore(const unsigned char save[JANAS_CPU_SAVE_BYTES])+{+ sched_setaffinity(0, sizeof(cpu_set_t), (const cpu_set_t *)save);+}++int janas_pin_current_thread(int cpu)+{+ cpu_set_t set;+ CPU_ZERO(&set);+ CPU_SET(cpu, &set);+ return pthread_setaffinity_np(pthread_self(), sizeof(set), &set) ? -1 : 0;+}++int janas_exe_path(char *buf, size_t len)+{+ if (len == 0)return -1;- return 0;+ ssize_t n = readlink("/proc/self/exe", buf, len - 1);+ if (n <= 0)+ return -1;+ buf[n] = 0;+ return (int)n;}void janas_cpu_name(char *buf, size_t len)@@ -243,3 +287,5 @@ uint64_t janas_mem_total(void){return meminfo("MemTotal");}++#endif /* !_WIN32 */diff --git a/src/common/sysinfo.h b/src/common/sysinfo.hindex 376deb8..ac2dce2 100644--- a/src/common/sysinfo.h+++ b/src/common/sysinfo.h@@ -37,6 +37,14 @@ struct janas_cpu_layout {int janas_cpu_layout(const int *allowed, int n_allowed,struct janas_cpu_layout *l);+/* The calling thread's CPUs, saved to be given back to it later: a model+ pins the thread that opens it, for as long as it lives. 0 or -1. */+#define JANAS_CPU_SAVE_BYTES 128+int janas_cpus_save(unsigned char save[JANAS_CPU_SAVE_BYTES]);+void janas_cpus_restore(const unsigned char save[JANAS_CPU_SAVE_BYTES]);+/* The path of the running program, with / between its parts on every+ system. Its length, or -1. */+int janas_exe_path(char *buf, size_t len);/* The processor's name ("Intel(R) Core(TM) Ultra 9 185H"), or "". */void janas_cpu_name(char *buf, size_t len);diff --git a/src/common/sysinfo_os.h b/src/common/sysinfo_os.hnew file mode 100644index 0000000..1ef6a00--- /dev/null+++ b/src/common/sysinfo_os.h@@ -0,0 +1,18 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * sysinfo_os.h - what each system tells of its CPUs, for sysinfo.c:+ * Linux's in sysinfo.c, Windows's in sysinfo_win.c.+ */+#ifndef JANAS_COMMON_SYSINFO_OS_H+#define JANAS_COMMON_SYSINFO_OS_H++/* The CPUs the calling thread may use, at most max. The count, or -1. */+int janas_os_allowed_cpus(int *out, int max);++/* For each of the nc CPUs of cand: its kind (0 performance, 1 efficiency,+ 2 low-power efficiency) and the lowest CPU of its physical core. Every+ CPU a performance core of its own where nothing is known. */+void janas_os_cpu_kinds(const int *cand, int nc, int *kind, int *leader);++#endifdiff --git a/src/common/sysinfo_win.c b/src/common/sysinfo_win.cnew file mode 100644index 0000000..a182082--- /dev/null+++ b/src/common/sysinfo_win.c@@ -0,0 +1,292 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * sysinfo_win.c - see sysinfo.h and sysinfo_os.h: what Windows tells of the+ * machine. A CPU is numbered as Windows numbers its logical processors+ * within their group, the groups one after the other (64 a group).+ *+ * The kinds of core come from GetLogicalProcessorInformationEx: a hybrid+ * processor gives its cores efficiency classes, the performance cores the+ * highest. The low-power efficiency cores (Meteor Lake's, on a tile of+ * their own) are told apart by the level-3 cache they do not share with+ * the others. Not by the clock, as on Linux: on Windows 11 (build 26300)+ * the clocks Windows reports kept the two low-power cores of a Core Ultra+ * 9 185H and left out its eight ordinary efficiency cores (12 Oct 2026);+ * the clock is the fallback where Windows says nothing of the caches.+ */+#ifdef _WIN32+#include "sysinfo.h"+#include "pool.h"+#include "sysinfo_os.h"++#include <windows.h>+#include <cpuid.h>+#include <powrprof.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>++/* PROCESSOR_POWER_INFORMATION, which MinGW's headers lack */+struct power_info {+ ULONG number, max_mhz, current_mhz, mhz_limit, max_idle_state,+ current_idle_state;+};++/* The physical cores: each one's CPUs and efficiency class. */+struct core {+ int first, n_cpus, cls;+ int cpus[8];+};++static int cores_of(struct core *out, int max)+{+ DWORD len = 0;+ GetLogicalProcessorInformationEx(RelationProcessorCore, NULL, &len);+ if (GetLastError() != ERROR_INSUFFICIENT_BUFFER || len == 0)+ return -1;+ char *buf = malloc(len);+ if (!buf || !GetLogicalProcessorInformationEx(+ RelationProcessorCore,+ (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *)buf, &len)) {+ free(buf);+ return -1;+ }+ int n = 0;+ for (DWORD off = 0; off < len && n < max;) {+ SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *e =+ (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *)(buf + off);+ if (e->Relationship == RelationProcessorCore) {+ struct core *c = &out[n++];+ c->n_cpus = 0;+ c->first = -1;+ c->cls = e->Processor.EfficiencyClass;+ for (WORD g = 0; g < e->Processor.GroupCount; g++) {+ GROUP_AFFINITY *ga = &e->Processor.GroupMask[g];+ for (int b = 0; b < 64; b++)+ if ((ga->Mask >> b) & 1) {+ int cpu = ga->Group * 64 + b;+ if (c->n_cpus < 8)+ c->cpus[c->n_cpus++] = cpu;+ if (c->first < 0 || cpu < c->first)+ c->first = cpu;+ }+ }+ }+ off += e->Size;+ }+ free(buf);+ return n;+}++int janas_os_allowed_cpus(int *out, int max)+{+ GROUP_AFFINITY ga;+ if (!GetThreadGroupAffinity(GetCurrentThread(), &ga))+ return -1;+ int n = 0;+ for (int b = 0; b < 64 && n < max; b++)+ if ((ga.Mask >> b) & 1)+ out[n++] = ga.Group * 64 + b;+ return n;+}++/* The level-3 cache that serves the most CPUs, the one the performance+ and the ordinary efficiency cores share: Meteor Lake's low-power cores,+ on a tile of their own, are outside it. 1, or 0 when Windows says+ nothing of the caches. Its first group only (64 CPUs), as the old+ CACHE_RELATIONSHIP of MinGW's headers has it, and the new one starts. */+static int main_l3(GROUP_AFFINITY *out)+{+ DWORD len = 0;+ GetLogicalProcessorInformationEx(RelationCache, NULL, &len);+ if (GetLastError() != ERROR_INSUFFICIENT_BUFFER || len == 0)+ return 0;+ char *buf = malloc(len);+ if (!buf || !GetLogicalProcessorInformationEx(+ RelationCache,+ (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *)buf, &len)) {+ free(buf);+ return 0;+ }+ int best = 0;+ for (DWORD off = 0; off < len;) {+ SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *e =+ (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *)(buf + off);+ if (e->Relationship == RelationCache && e->Cache.Level == 3) {+ int cpus = __builtin_popcountll(+ (unsigned long long)e->Cache.GroupMask.Mask);+ if (cpus > best) {+ best = cpus;+ *out = e->Cache.GroupMask;+ }+ }+ off += e->Size;+ }+ free(buf);+ return best > 0;+}++/* Each CPU's top clock in MHz (0 where unknown), indexed by CPU. */+static void top_clocks(long *mhz, int max)+{+ memset(mhz, 0, sizeof(*mhz) * (size_t)max);+ int n = (int)GetActiveProcessorCount(ALL_PROCESSOR_GROUPS);+ if (n <= 0 || n > max)+ return;+ struct power_info *pi = calloc((size_t)n, sizeof *pi);+ if (pi && CallNtPowerInformation(ProcessorInformation, NULL, 0, pi,+ (ULONG)(sizeof *pi * (size_t)n)) == 0)+ for (int i = 0; i < n; i++)+ if ((int)pi[i].number < max)+ mhz[pi[i].number] = (long)pi[i].max_mhz;+ free(pi);+}++void janas_os_cpu_kinds(const int *cand, int nc, int *kind, int *leader)+{+ static struct core cores[JANAS_MAX_CPUS];+ int n = cores_of(cores, JANAS_MAX_CPUS);+ int top_cls = 0, bottom_cls = 255;+ for (int i = 0; i < n; i++) {+ if (cores[i].cls > top_cls)+ top_cls = cores[i].cls;+ if (cores[i].cls < bottom_cls)+ bottom_cls = cores[i].cls;+ }+ int hybrid = n > 0 && top_cls != bottom_cls;+ GROUP_AFFINITY l3;+ int have_l3 = main_l3(&l3);+ static long mhz[JANAS_MAX_CPUS];+ if (!have_l3)+ top_clocks(mhz, JANAS_MAX_CPUS);+ long efreq_max = 0;+ for (int i = 0; i < nc; i++) {+ kind[i] = 0;+ leader[i] = cand[i];+ for (int k = 0; k < n; k++)+ for (int j = 0; j < cores[k].n_cpus; j++)+ if (cores[k].cpus[j] == cand[i]) {+ leader[i] = cores[k].first;+ kind[i] = hybrid && cores[k].cls != top_cls ? 1 : 0;+ }+ /* the low-power ones: outside the L3 the others share */+ if (have_l3 && kind[i] == 1 &&+ (cand[i] / 64 != l3.Group || !((l3.Mask >> (cand[i] % 64)) & 1)))+ kind[i] = 2;+ long f = !have_l3 && cand[i] < JANAS_MAX_CPUS ? mhz[cand[i]] : 0;+ if (kind[i] == 1 && f > efreq_max)+ efreq_max = f;+ }+ /* without a word on the caches: the clock, as Linux has it */+ for (int i = 0; i < nc && !have_l3; i++) {+ long f = cand[i] < JANAS_MAX_CPUS ? mhz[cand[i]] : 0;+ if (kind[i] == 1 && f > 0 && f < efreq_max * 85 / 100)+ kind[i] = 2;+ }+}++int janas_cpu_split(int *compute, int *n_compute, int *io, int *n_io, int max)+{+ int cand[JANAS_MAX_CPUS];+ int nc = janas_os_allowed_cpus(cand, JANAS_MAX_CPUS);+ if (nc <= 0)+ return -1;+ int kind[JANAS_MAX_CPUS], leader[JANAS_MAX_CPUS];+ janas_os_cpu_kinds(cand, nc, kind, leader);+ /* as Linux's cpu_core and cpu_atom: the performance cores, the others */+ *n_compute = *n_io = 0;+ int max_io = max < 8 ? max : 8;+ for (int i = 0; i < nc; i++) {+ if (kind[i] == 0 && *n_compute < max)+ compute[(*n_compute)++] = cand[i];+ else if (kind[i] != 0 && *n_io < max_io)+ io[(*n_io)++] = cand[i];+ }+ if (*n_compute > 0 && *n_io > 0)+ return 1;+ *n_compute = 0;+ for (int i = 0; i < nc && *n_compute < max; i++)+ compute[(*n_compute)++] = cand[i];+ *n_io = *n_compute < 8 ? *n_compute : 8;+ return 0;+}++int janas_cpus_save(unsigned char save[JANAS_CPU_SAVE_BYTES])+{+ _Static_assert(sizeof(GROUP_AFFINITY) <= JANAS_CPU_SAVE_BYTES, "cpu set");+ return GetThreadGroupAffinity(GetCurrentThread(), (GROUP_AFFINITY *)save)+ ? 0+ : -1;+}++void janas_cpus_restore(const unsigned char save[JANAS_CPU_SAVE_BYTES])+{+ SetThreadGroupAffinity(GetCurrentThread(), (const GROUP_AFFINITY *)save,+ NULL);+}++int janas_pin_current_thread(int cpu)+{+ if (cpu < 0)+ return -1;+ GROUP_AFFINITY ga = {.Mask = (KAFFINITY)1 << (cpu % 64),+ .Group = (WORD)(cpu / 64)};+ return SetThreadGroupAffinity(GetCurrentThread(), &ga, NULL) ? 0 : -1;+}++int janas_exe_path(char *buf, size_t len)+{+ if (len == 0)+ return -1;+ DWORD n = GetModuleFileNameA(NULL, buf, (DWORD)len);+ if (n == 0 || n >= len)+ return -1;+ for (char *p = buf; *p; p++)+ if (*p == '\\')+ *p = '/';+ return (int)n;+}++void janas_cpu_name(char *buf, size_t len)+{+ /* the brand string, from the processor itself */+ unsigned r[12];+ buf[0] = 0;+ if (__get_cpuid_max(0x80000000, NULL) < 0x80000004)+ return;+ for (unsigned i = 0; i < 3; i++)+ __get_cpuid(0x80000002 + i, &r[i * 4], &r[i * 4 + 1], &r[i * 4 + 2],+ &r[i * 4 + 3]);+ char s[49];+ memcpy(s, r, 48);+ s[48] = 0;+ char *p = s;+ while (*p == ' ')+ p++;+ snprintf(buf, len, "%s", p);+}++int janas_on_mains(void)+{+ SYSTEM_POWER_STATUS ps;+ if (!GetSystemPowerStatus(&ps) || ps.ACLineStatus == 255)+ return -1;+ /* a desktop says "online" with no battery: as Linux's unknown */+ if (ps.BatteryFlag & 128)+ return -1;+ return ps.ACLineStatus == 1;+}++uint64_t janas_mem_available(void)+{+ MEMORYSTATUSEX m = {.dwLength = sizeof m};+ return GlobalMemoryStatusEx(&m) ? m.ullAvailPhys : 0;+}++uint64_t janas_mem_total(void)+{+ MEMORYSTATUSEX m = {.dwLength = sizeof m};+ return GlobalMemoryStatusEx(&m) ? m.ullTotalPhys : 0;+}++#endif /* _WIN32 */diff --git a/src/common/uring.c b/src/common/uring.cindex ec8cfa7..921b4d0 100644--- a/src/common/uring.c+++ b/src/common/uring.c@@ -26,7 +26,8 @@#endif#endif-#ifndef JANAS_HAVE_URING+/* Windows: uring_win.c, with overlapped reads */+#if !defined(JANAS_HAVE_URING) && !defined(_WIN32)struct janas_uring *janas_uring_create(unsigned entries){@@ -64,8 +65,7 @@ unsigned janas_uring_inflight(const struct janas_uring *u)return 0;}--#else+#elif defined(JANAS_HAVE_URING)#include <linux/io_uring.h>#include <sys/mman.h>@@ -316,5 +316,4 @@ unsigned janas_uring_inflight(const struct janas_uring *u)return u->pending;}-#endifdiff --git a/src/common/uring_win.c b/src/common/uring_win.cnew file mode 100644index 0000000..1265fb2--- /dev/null+++ b/src/common/uring_win.c@@ -0,0 +1,141 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * uring_win.c - uring.h on Windows, with overlapped reads: a read starts+ * as soon as it is queued (ReadFile on a handle opened for overlapped and+ * unbuffered I/O, reopen.c) and runs while the caller computes;+ * janas_uring_wait collects every one. As with io_uring, no thread is+ * woken to begin a read. A read that returns fewer bytes than asked is+ * started again for what is missing.+ */+#ifdef _WIN32+#include "common/uring.h"++#include <windows.h>+#include <io.h>+#include <stdlib.h>++struct request {+ OVERLAPPED o; /* the system's while the read runs: it must live here */+ HANDLE h;+ uint8_t *dst;+ uint64_t offset, bytes, done;+};++struct janas_uring {+ unsigned entries, n;+ int failed;+ struct request *req;+ HANDLE *events;+};++void janas_uring_destroy(struct janas_uring *u)+{+ if (!u)+ return;+ janas_uring_wait(u);+ for (unsigned i = 0; i < u->entries; i++)+ if (u->events[i])+ CloseHandle(u->events[i]);+ free(u->events);+ free(u->req);+ free(u);+}++struct janas_uring *janas_uring_create(unsigned entries)+{+ struct janas_uring *u = calloc(1, sizeof *u);+ if (!u || entries == 0) {+ free(u);+ return NULL;+ }+ u->entries = entries;+ u->req = calloc(entries, sizeof *u->req);+ u->events = calloc(entries, sizeof *u->events);+ if (!u->req || !u->events) {+ free(u->req);+ free(u->events);+ free(u);+ return NULL;+ }+ for (unsigned i = 0; i < entries; i++) {+ u->events[i] = CreateEventA(NULL, TRUE, FALSE, NULL);+ if (!u->events[i]) {+ janas_uring_destroy(u);+ return NULL;+ }+ }+ return u;+}++/* Starts (or starts again) the read of what request i still misses. */+static int start(struct janas_uring *u, unsigned i)+{+ struct request *r = &u->req[i];+ uint64_t at = r->offset + r->done, left = r->bytes - r->done;+ DWORD chunk = left > 0x40000000u ? 0x40000000u : (DWORD)left;+ ResetEvent(u->events[i]);+ r->o = (OVERLAPPED){.Offset = (DWORD)at,+ .OffsetHigh = (DWORD)(at >> 32),+ .hEvent = u->events[i]};+ if (ReadFile(r->h, r->dst + r->done, chunk, NULL, &r->o))+ return 0; /* done already: the result is collected as any other */+ return GetLastError() == ERROR_IO_PENDING ? 0 : -1;+}++int janas_uring_read(struct janas_uring *u, int fd, void *dst, uint64_t bytes,+ uint64_t offset)+{+ if (u->n == u->entries)+ return -1;+ HANDLE h = (HANDLE)_get_osfhandle(fd);+ if (h == INVALID_HANDLE_VALUE)+ return -1;+ unsigned i = u->n;+ u->req[i] =+ (struct request){.h = h, .dst = dst, .offset = offset, .bytes = bytes};+ if (bytes == 0)+ return 0;+ if (start(u, i) != 0)+ return -1;+ u->n++;+ return 0;+}++int janas_uring_submit(struct janas_uring *u)+{+ (void)u; /* each read began when it was queued */+ return 0;+}++int janas_uring_wait(struct janas_uring *u)+{+ for (unsigned i = 0; i < u->n; i++) {+ struct request *r = &u->req[i];+ for (;;) {+ DWORD got = 0;+ if (!GetOverlappedResult(r->h, &r->o, &got, TRUE) || got == 0) {+ u->failed = 1;+ break;+ }+ r->done += got;+ if (r->done >= r->bytes)+ break;+ if (start(u, i) != 0) {+ u->failed = 1;+ break;+ }+ }+ }+ int rc = u->failed ? -1 : 0;+ u->n = 0;+ u->failed = 0;+ return rc;+}++unsigned janas_uring_inflight(const struct janas_uring *u)+{+ return u->n;+}++#endif /* _WIN32 */diff --git a/src/common/win/arpa/inet.h b/src/common/win/arpa/inet.hnew file mode 100644index 0000000..9d56581--- /dev/null+++ b/src/common/win/arpa/inet.h@@ -0,0 +1,8 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/* arpa/inet.h for Windows (src/common/win/): Winsock's sockets. A socket is a+ SOCKET there, not a file descriptor: closesocket, recv and send. */+#ifndef JANAS_WIN_ARPA_INET_H+#define JANAS_WIN_ARPA_INET_H+#include "win_sockets.h"+#endifdiff --git a/src/common/win/dlfcn.h b/src/common/win/dlfcn.hnew file mode 100644index 0000000..d656995--- /dev/null+++ b/src/common/win/dlfcn.h@@ -0,0 +1,15 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/* dlfcn.h for Windows (src/common/win/): a DLL loaded and its functions+ found, through LoadLibrary and GetProcAddress (win_posix.c). */+#ifndef JANAS_WIN_DLFCN_H+#define JANAS_WIN_DLFCN_H+#define RTLD_LAZY 1+#define RTLD_NOW 2+#define RTLD_LOCAL 0+#define RTLD_GLOBAL 0x100+void *dlopen(const char *file, int mode);+void *dlsym(void *handle, const char *name);+int dlclose(void *handle);+char *dlerror(void);+#endifdiff --git a/src/common/win/janas.manifest b/src/common/win/janas.manifestnew file mode 100644index 0000000..2920ff7--- /dev/null+++ b/src/common/win/janas.manifest@@ -0,0 +1,17 @@+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>+<!-- Every program of Janas on Windows: for Windows 10 and 11, UTF-8 the+ code page of the narrow ("A") calls, as POSIX's are, and paths longer+ than 260 characters where the system allows them. -->+<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">+ <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">+ <application>+ <supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}"/>+ </application>+ </compatibility>+ <application xmlns="urn:schemas-microsoft-com:asm.v3">+ <windowsSettings>+ <activeCodePage xmlns="http://schemas.microsoft.com/SMI/2019/WindowsSettings">UTF-8</activeCodePage>+ <longPathAware xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">true</longPathAware>+ </windowsSettings>+ </application>+</assembly>diff --git a/src/common/win/janas.rc b/src/common/win/janas.rcnew file mode 100644index 0000000..4278c47--- /dev/null+++ b/src/common/win/janas.rc@@ -0,0 +1,4 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 Maurizio Cammalleri+// The manifest every program of Janas carries on Windows (janas.manifest).+1 24 "janas.manifest"diff --git a/src/common/win/netdb.h b/src/common/win/netdb.hnew file mode 100644index 0000000..2012834--- /dev/null+++ b/src/common/win/netdb.h@@ -0,0 +1,8 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/* netdb.h for Windows (src/common/win/): Winsock's sockets. A socket is a+ SOCKET there, not a file descriptor: closesocket, recv and send. */+#ifndef JANAS_WIN_NETDB_H+#define JANAS_WIN_NETDB_H+#include "win_sockets.h"+#endifdiff --git a/src/common/win/netinet/in.h b/src/common/win/netinet/in.hnew file mode 100644index 0000000..cb1e8ef--- /dev/null+++ b/src/common/win/netinet/in.h@@ -0,0 +1,8 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/* netinet/in.h for Windows (src/common/win/): Winsock's sockets. A socket is a+ SOCKET there, not a file descriptor: closesocket, recv and send. */+#ifndef JANAS_WIN_NETINET_IN_H+#define JANAS_WIN_NETINET_IN_H+#include "win_sockets.h"+#endifdiff --git a/src/common/win/netinet/tcp.h b/src/common/win/netinet/tcp.hnew file mode 100644index 0000000..cab5613--- /dev/null+++ b/src/common/win/netinet/tcp.h@@ -0,0 +1,8 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/* netinet/tcp.h for Windows (src/common/win/): Winsock's sockets. A socket is a+ SOCKET there, not a file descriptor: closesocket, recv and send. */+#ifndef JANAS_WIN_NETINET_TCP_H+#define JANAS_WIN_NETINET_TCP_H+#include "win_sockets.h"+#endifdiff --git a/src/common/win/poll.h b/src/common/win/poll.hnew file mode 100644index 0000000..b571969--- /dev/null+++ b/src/common/win/poll.h@@ -0,0 +1,7 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/* poll.h for Windows (src/common/win/): see win_sockets.h. */+#ifndef JANAS_WIN_POLL_H+#define JANAS_WIN_POLL_H+#include "win_sockets.h"+#endifdiff --git a/src/common/win/sys/mman.h b/src/common/win/sys/mman.hnew file mode 100644index 0000000..43f5133--- /dev/null+++ b/src/common/win/sys/mman.h@@ -0,0 +1,19 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/* sys/mman.h for Windows (src/common/win/): only the advice, which Windows+ has no use for; memory is mapped by code of its own there. */+#ifndef JANAS_WIN_SYS_MMAN_H+#define JANAS_WIN_SYS_MMAN_H+#include <stddef.h>+#define MADV_NORMAL 0+#define MADV_WILLNEED 3+#define MADV_DONTNEED 4+#define MADV_HUGEPAGE 14+static inline int madvise(void *addr, size_t len, int advice)+{+ (void)addr;+ (void)len;+ (void)advice;+ return 0;+}+#endifdiff --git a/src/common/win/sys/random.h b/src/common/win/sys/random.hnew file mode 100644index 0000000..bfed0e3--- /dev/null+++ b/src/common/win/sys/random.h@@ -0,0 +1,10 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/* sys/random.h for Windows (src/common/win/): the system's random bytes,+ from BCryptGenRandom (win_posix.c). */+#ifndef JANAS_WIN_SYS_RANDOM_H+#define JANAS_WIN_SYS_RANDOM_H+#include <stddef.h>+#include <sys/types.h>+ssize_t getrandom(void *buf, size_t n, unsigned flags);+#endifdiff --git a/src/common/win/sys/resource.h b/src/common/win/sys/resource.hnew file mode 100644index 0000000..e2d1422--- /dev/null+++ b/src/common/win/sys/resource.h@@ -0,0 +1,14 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/* sys/resource.h for Windows (src/common/win/): the process's times and+ its peak working set as getrusage's (win_posix.c). */+#ifndef JANAS_WIN_SYS_RESOURCE_H+#define JANAS_WIN_SYS_RESOURCE_H+#include <sys/time.h>+#define RUSAGE_SELF 0+struct rusage {+ struct timeval ru_utime, ru_stime;+ long ru_maxrss; /* KiB, as Linux's */+};+int getrusage(int who, struct rusage *u);+#endifdiff --git a/src/common/win/sys/socket.h b/src/common/win/sys/socket.hnew file mode 100644index 0000000..c2bd319--- /dev/null+++ b/src/common/win/sys/socket.h@@ -0,0 +1,8 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/* sys/socket.h for Windows (src/common/win/): Winsock's sockets. A socket is a+ SOCKET there, not a file descriptor: closesocket, recv and send. */+#ifndef JANAS_WIN_SYS_SOCKET_H+#define JANAS_WIN_SYS_SOCKET_H+#include "win_sockets.h"+#endifdiff --git a/src/common/win/sys/statvfs.h b/src/common/win/sys/statvfs.hnew file mode 100644index 0000000..49b2494--- /dev/null+++ b/src/common/win/sys/statvfs.h@@ -0,0 +1,12 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/* sys/statvfs.h for Windows (src/common/win/): a file system's room, from+ GetDiskFreeSpaceEx (win_posix.c). */+#ifndef JANAS_WIN_SYS_STATVFS_H+#define JANAS_WIN_SYS_STATVFS_H+struct statvfs {+ unsigned long long f_bsize, f_frsize, f_blocks, f_bfree, f_bavail;+};+int statvfs(const char *path, struct statvfs *s);+int fstatvfs(int fd, struct statvfs *s);+#endifdiff --git a/src/common/win/sys/utsname.h b/src/common/win/sys/utsname.hnew file mode 100644index 0000000..34bf2dc--- /dev/null+++ b/src/common/win/sys/utsname.h@@ -0,0 +1,11 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/* sys/utsname.h for Windows (src/common/win/): the system's name and+ version, from RtlGetVersion (win_posix.c). */+#ifndef JANAS_WIN_SYS_UTSNAME_H+#define JANAS_WIN_SYS_UTSNAME_H+struct utsname {+ char sysname[65], nodename[65], release[65], version[65], machine[65];+};+int uname(struct utsname *u);+#endifdiff --git a/src/common/win/win_sockets.h b/src/common/win/win_sockets.hnew file mode 100644index 0000000..2e2c5da--- /dev/null+++ b/src/common/win/win_sockets.h@@ -0,0 +1,36 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/* win_sockets.h (src/common/win/): Winsock under the names of POSIX's+ socket headers, and poll() over sockets, pipes and the console+ (win_posix.c). */+#ifndef JANAS_WIN_SOCKETS_H+#define JANAS_WIN_SOCKETS_H+#ifndef WIN32_LEAN_AND_MEAN+#define WIN32_LEAN_AND_MEAN+#endif+#ifndef NOMINMAX+#define NOMINMAX+#endif+#include <winsock2.h>+#include <ws2tcpip.h>+#ifndef MSG_NOSIGNAL+#define MSG_NOSIGNAL 0+#endif+#ifndef SHUT_RD+#define SHUT_RD SD_RECEIVE+#define SHUT_WR SD_SEND+#define SHUT_RDWR SD_BOTH+#endif+typedef unsigned long nfds_t;+/* POSIX's pollfd, with a descriptor that may be -1 (Winsock's has an+ unsigned SOCKET there: its own is WSAPOLLFD) */+struct janas_pollfd {+ int fd;+ short events, revents;+};+#define pollfd janas_pollfd+/* poll over CRT descriptors (pipes, the console, files) and sockets:+ a descriptor is taken for a socket when Winsock knows it as one */+int janas_poll(struct pollfd *fds, nfds_t n, int timeout_ms);+#define poll janas_poll+#endifdiff --git a/src/common/win_compat.c b/src/common/win_compat.cnew file mode 100644index 0000000..506571f--- /dev/null+++ b/src/common/win_compat.c@@ -0,0 +1,557 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * win_compat.c - the POSIX calls MinGW-w64 lacks, for Windows (see+ * win_compat.h). Nothing on other systems.+ */+#ifdef _WIN32+#define WIN32_LEAN_AND_MEAN+#include <windows.h>++#include <ctype.h>+#include <math.h>+#include <stdarg.h>++/* the CRT's own, under the names win_compat.h moved aside */+#undef open+#undef fopen+#undef rename+#undef pread+#undef pwrite+#undef realpath+#undef remove+#undef flock+#undef sysconf+#undef alarm+#undef setenv+#undef unsetenv+#undef getenv+#undef strcasestr+#undef memmem+#undef strndup+#undef aligned_alloc+#undef posix_memalign+#undef free+#undef getline+#undef mkdtemp+#undef open_memstream+#undef fflush+#undef fclose++char *janas_getenv(const char *name)+{+ char *v = getenv(name);+ if ((v && *v) || !name)+ return v;+ static const char *const map[][2] = {{"HOME", "USERPROFILE"},+ {"XDG_CONFIG_HOME", "APPDATA"},+ {"XDG_CACHE_HOME", "LOCALAPPDATA"},+ {"XDG_DATA_HOME", "LOCALAPPDATA"},+ {"TMPDIR", "TEMP"}};+ static char kept[5][MAX_PATH * 2];+ for (int i = 0; i < 5; i++) {+ if (strcmp(name, map[i][0]) != 0)+ continue;+ const char *w = getenv(map[i][1]);+ if (!w || !*w)+ return v;+ if (!kept[i][0]) {+ snprintf(kept[i], sizeof kept[i], "%s", w);+ for (char *c = kept[i]; *c; c++)+ if (*c == '\\')+ *c = '/';+ }+ return kept[i];+ }+ return v;+}++int janas_mkdir(const char *path)+{+ if (_mkdir(path) == 0)+ return 0;+ int e = errno;+ DWORD a = GetFileAttributesA(path);+ errno = a != INVALID_FILE_ATTRIBUTES && (a & FILE_ATTRIBUTE_DIRECTORY)+ ? EEXIST+ : e;+ return -1;+}++int janas_setenv(const char *name, const char *value, int overwrite)+{+ if (!name || !*name || strchr(name, '=')) {+ errno = EINVAL;+ return -1;+ }+ if (!overwrite && getenv(name))+ return 0;+ return _putenv_s(name, value ? value : "") == 0 ? 0 : -1;+}++int janas_unsetenv(const char *name)+{+ if (!name || !*name || strchr(name, '=')) {+ errno = EINVAL;+ return -1;+ }+ /* an empty value removes the variable */+ return _putenv_s(name, "") == 0 ? 0 : -1;+}++char *janas_strcasestr(const char *hay, const char *needle)+{+ size_t n = strlen(needle);+ if (n == 0)+ return (char *)hay;+ for (; *hay; hay++)+ if (_strnicmp(hay, needle, n) == 0)+ return (char *)hay;+ return NULL;+}++void *janas_memmem(const void *hay, size_t hay_len, const void *needle,+ size_t needle_len)+{+ const unsigned char *h = hay, *n = needle;+ if (needle_len == 0)+ return (void *)hay;+ if (hay_len < needle_len)+ return NULL;+ for (size_t i = 0; i + needle_len <= hay_len; i++)+ if (h[i] == n[0] && memcmp(h + i, n, needle_len) == 0)+ return (void *)(h + i);+ return NULL;+}++char *janas_strndup(const char *s, size_t n)+{+ size_t len = strnlen(s, n);+ char *d = malloc(len + 1);+ if (!d)+ return NULL;+ memcpy(d, s, len);+ d[len] = 0;+ return d;+}++int janas_open(const char *path, int flags, ...)+{+ int mode = 0;+ if (flags & O_CREAT) {+ va_list ap;+ va_start(ap, flags);+ mode = va_arg(ap, int);+ va_end(ap);+ }+ return _open(path, flags | _O_BINARY,+ mode ? (mode & 0200 ? _S_IREAD | _S_IWRITE : _S_IREAD) : 0);+}++FILE *janas_fopen(const char *path, const char *mode)+{+ char m[16];+ size_t n = strlen(mode);+ if (n + 2 > sizeof m || strchr(mode, 'b') || strchr(mode, 't'))+ return fopen(path, mode);+ /* the 'b' after the letter and any '+', before the extensions */+ size_t k = 1;+ while (k < n && mode[k] == '+')+ k++;+ memcpy(m, mode, k);+ m[k] = 'b';+ memcpy(m + k + 1, mode + k, n - k + 1);+ return fopen(path, m);+}++int janas_rename(const char *from, const char *to)+{+ if (MoveFileExA(from, to,+ MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED)) {+ return 0;+ }+ DWORD e = GetLastError();+ errno = e == ERROR_FILE_NOT_FOUND || e == ERROR_PATH_NOT_FOUND ? ENOENT+ : e == ERROR_ACCESS_DENIED ? EACCES+ : EIO;+ return -1;+}++/* A read at an offset through an OVERLAPPED structure, as POSIX's: the+ handle's position is left where it is not counted on. */+static ssize_t at_offset(int fd, void *buf, size_t n, int64_t off, int write)+{+ HANDLE h = (HANDLE)_get_osfhandle(fd);+ if (h == INVALID_HANDLE_VALUE) {+ errno = EBADF;+ return -1;+ }+ if (n > 0x7fffffffu)+ n = 0x7fffffffu;+ /* an event of the thread's own: on a handle opened for overlapped+ reads (reopen.c) the call may return before the read is done, and+ several threads may read through the same handle */+ static __thread HANDLE ev;+ if (!ev)+ ev = CreateEventA(NULL, TRUE, FALSE, NULL);+ OVERLAPPED o = {.Offset = (DWORD)(uint64_t)off,+ .OffsetHigh = (DWORD)((uint64_t)off >> 32),+ .hEvent = ev};+ DWORD got = 0;+ BOOL ok = write ? WriteFile(h, buf, (DWORD)n, &got, &o)+ : ReadFile(h, buf, (DWORD)n, &got, &o);+ if (!ok && GetLastError() == ERROR_IO_PENDING)+ ok = GetOverlappedResult(h, &o, &got, TRUE);+ if (!ok) {+ DWORD e = GetLastError();+ if (!write && e == ERROR_HANDLE_EOF)+ return 0;+ errno = EIO;+ return -1;+ }+ return (ssize_t)got;+}++ssize_t janas_pread(int fd, void *buf, size_t n, int64_t off)+{+ return at_offset(fd, buf, n, off, 0);+}++ssize_t janas_pwrite(int fd, const void *buf, size_t n, int64_t off)+{+ return at_offset(fd, (void *)buf, n, off, 1);+}++int janas_remove(const char *path)+{+ DWORD a = GetFileAttributesA(path);+ if (a != INVALID_FILE_ATTRIBUTES && (a & FILE_ATTRIBUTE_DIRECTORY))+ return _rmdir(path);+ return remove(path);+}++char *janas_realpath(const char *path, char *resolved)+{+ char *r = _fullpath(resolved, path, resolved ? MAX_PATH : 0);+ if (!r)+ return NULL;+ if (GetFileAttributesA(r) == INVALID_FILE_ATTRIBUTES) {+ if (!resolved)+ free(r);+ errno = ENOENT;+ return NULL;+ }+ return r;+}++int janas_flock(int fd, int op)+{+ HANDLE h = (HANDLE)_get_osfhandle(fd);+ if (h == INVALID_HANDLE_VALUE) {+ errno = EBADF;+ return -1;+ }+ OVERLAPPED o = {0};+ if (op & LOCK_UN)+ return UnlockFileEx(h, 0, MAXDWORD, MAXDWORD, &o) ? 0 : -1;+ DWORD f = (op & LOCK_EX) ? LOCKFILE_EXCLUSIVE_LOCK : 0;+ if (op & LOCK_NB)+ f |= LOCKFILE_FAIL_IMMEDIATELY;+ if (LockFileEx(h, f, 0, MAXDWORD, MAXDWORD, &o))+ return 0;+ errno = GetLastError() == ERROR_LOCK_VIOLATION ? EWOULDBLOCK : EIO;+ return -1;+}++long janas_sysconf(int name)+{+ SYSTEM_INFO si;+ GetSystemInfo(&si);+ switch (name) {+ case _SC_NPROCESSORS_ONLN:+ return (long)GetActiveProcessorCount(ALL_PROCESSOR_GROUPS);+ case _SC_PAGESIZE:+ return (long)si.dwPageSize;+ case _SC_PHYS_PAGES: {+ MEMORYSTATUSEX m = {.dwLength = sizeof m};+ if (!GlobalMemoryStatusEx(&m))+ return -1;+ /* in pages: a long holds 2^31 of them, 8 TiB of 4 KiB */+ return (long)(m.ullTotalPhys / si.dwPageSize);+ }+ }+ errno = EINVAL;+ return -1;+}++/* the tag before an aligned block: where malloc's block began, and that+ address mixed with a constant, so that the bytes before an ordinary+ block (the heap's own header) are not taken for one */+#define ALIGN_TAG 0x4a414e4153414c47ull+struct align_tag {+ void *base;+ uint64_t check;+};++void *janas_aligned_alloc(size_t align, size_t size)+{+ if (align < sizeof(void *) || (align & (align - 1))) {+ errno = EINVAL;+ return NULL;+ }+ size_t extra = align + sizeof(struct align_tag);+ if (size > SIZE_MAX - extra) {+ errno = ENOMEM;+ return NULL;+ }+ char *base = malloc(size + extra);+ if (!base)+ return NULL;+ uintptr_t a = ((uintptr_t)base + sizeof(struct align_tag) + align - 1) &+ ~(uintptr_t)(align - 1);+ struct align_tag *t = (struct align_tag *)a - 1;+ t->base = base;+ t->check = ALIGN_TAG ^ (uint64_t)a;+ return (void *)a;+}++int janas_posix_memalign(void **p, size_t align, size_t size)+{+ void *a = janas_aligned_alloc(align, size ? size : 1);+ if (!a)+ return errno;+ *p = a;+ return 0;+}++void janas_free(void *p)+{+ if (!p)+ return;+ struct align_tag *t = (struct align_tag *)p - 1;+ if (((uintptr_t)p & 15) == 0 &&+ t->check == (ALIGN_TAG ^ (uint64_t)(uintptr_t)p)) {+ void *base = t->base;+ t->check = 0;+ free(base);+ return;+ }+ free(p);+}++ssize_t janas_getline(char **line, size_t *cap, FILE *f)+{+ if (!line || !cap || !f) {+ errno = EINVAL;+ return -1;+ }+ size_t n = 0;+ int c;+ while ((c = getc(f)) != EOF) {+ if (n + 2 > *cap) {+ size_t nc = *cap ? *cap * 2 : 128;+ char *p = realloc(*line, nc);+ if (!p) {+ errno = ENOMEM;+ return -1;+ }+ *line = p;+ *cap = nc;+ }+ (*line)[n++] = (char)c;+ if (c == '\n')+ break;+ }+ if (n == 0)+ return -1;+ (*line)[n] = 0;+ return (ssize_t)n;+}++char *janas_mkdtemp(char *tmpl)+{+ size_t n = strlen(tmpl);+ if (n < 6 || strcmp(tmpl + n - 6, "XXXXXX") != 0) {+ errno = EINVAL;+ return NULL;+ }+ static const char abc[] = "abcdefghijklmnopqrstuvwxyz0123456789";+ for (int tries = 0; tries < 100; tries++) {+ unsigned v = (unsigned)GetTickCount() ^+ (unsigned)GetCurrentProcessId() * 2654435761u ^+ (unsigned)tries * 40503u;+ for (int i = 0; i < 6; i++) {+ tmpl[n - 6 + i] = abc[v % 36];+ v = v / 36 + (unsigned)i * 7919u;+ }+ if (_mkdir(tmpl) == 0)+ return tmpl;+ if (errno != EEXIST)+ return NULL;+ }+ return NULL;+}++/* the memory streams open, with where their content goes */+static struct memstream {+ FILE *f;+ char **ptr;+ size_t *size;+} memstreams[16];+static SRWLOCK memstreams_lock = SRWLOCK_INIT;++FILE *janas_open_memstream(char **ptr, size_t *size)+{+ char dir[MAX_PATH], path[MAX_PATH];+ if (!GetTempPathA(sizeof dir, dir) ||+ !GetTempFileNameA(dir, "jns", 0, path))+ return NULL;+ /* T: kept in memory where it can, D: deleted when closed */+ FILE *f = fopen(path, "w+bTD");+ if (!f)+ return NULL;+ AcquireSRWLockExclusive(&memstreams_lock);+ int slot = -1;+ for (int i = 0; i < 16 && slot < 0; i++)+ if (!memstreams[i].f)+ slot = i;+ if (slot >= 0)+ memstreams[slot] = (struct memstream){f, ptr, size};+ ReleaseSRWLockExclusive(&memstreams_lock);+ if (slot < 0) {+ fclose(f);+ errno = EMFILE;+ return NULL;+ }+ *ptr = NULL;+ *size = 0;+ return f;+}++/* The content written so far, into a buffer of its own for the caller. */+static int memstream_publish(struct memstream *m)+{+ if (fflush(m->f) != 0)+ return -1;+ long end = ftell(m->f);+ if (end < 0)+ return -1;+ char *b = malloc((size_t)end + 1);+ if (!b)+ return -1;+ rewind(m->f);+ size_t got = fread(b, 1, (size_t)end, m->f);+ b[got] = 0;+ fseek(m->f, end, SEEK_SET);+ free(*m->ptr);+ *m->ptr = b;+ *m->size = got;+ return 0;+}++static struct memstream *memstream_of(FILE *f)+{+ for (int i = 0; i < 16; i++)+ if (memstreams[i].f == f)+ return &memstreams[i];+ return NULL;+}++int janas_fflush(FILE *f)+{+ if (!f)+ return fflush(NULL);+ AcquireSRWLockExclusive(&memstreams_lock);+ struct memstream *m = memstream_of(f);+ int rc = m ? memstream_publish(m) : fflush(f);+ ReleaseSRWLockExclusive(&memstreams_lock);+ return rc;+}++int janas_fclose(FILE *f)+{+ AcquireSRWLockExclusive(&memstreams_lock);+ struct memstream *m = memstream_of(f);+ int rc = 0;+ if (m) {+ rc = memstream_publish(m);+ m->f = NULL;+ }+ ReleaseSRWLockExclusive(&memstreams_lock);+ return fclose(f) == 0 ? rc : EOF;+}++/*+ * fmaf as the C standard has it, x * y + z rounded once: MinGW's rounds+ * the sum to a double and then again to a float, and now and then lands+ * on the next float, where glibc's is exact. The kernels, built for FMA,+ * never call it (the instruction is inlined there); the scalar code does,+ * and must agree with them to the bit. Defined under the C library's own+ * name, it is the one every file links.+ */+__attribute__((target("fma"))) static float fmaf_fma(float x, float y, float z)+{+ return __builtin_fmaf(x, y, z); /* one vfmadd */+}++/* Without the instruction: the product is exact in a double (24 + 24+ bits), the sum rounded once to a double; a float rounded from that is+ wrong only when the double lies halfway between two floats and was+ itself rounded, and then the exact sum's side decides. */+static float fmaf_soft(float x, float y, float z)+{+ double xy = (double)x * y, r = xy + z;+ uint64_t u;+ memcpy(&u, &r, sizeof u);+ int e = (int)(u >> 52 & 0x7ff);+ if ((u & 0x1fffffff) != 0x10000000 || e == 0x7ff ||+ (r - xy == z && r - z == xy))+ return (float)r;+ /* the error of r, exactly (Knuth's two-sum), moves it off the tie:+ one step of the double toward the exact sum (a step up the bits+ is away from zero) */+ double bv = r - xy, av = r - bv;+ double err = (xy - av) + (z - bv);+ if (err != 0) {+ if ((err > 0) == (r > 0))+ u++;+ else+ u--;+ }+ memcpy(&r, &u, sizeof r);+ return (float)r;+}++float fmaf(float x, float y, float z)+{+ static int has_fma = -1;+ if (has_fma < 0) {+ __builtin_cpu_init();+ has_fma = __builtin_cpu_supports("fma") ? 1 : 0;+ }+ return has_fma ? fmaf_fma(x, y, z) : fmaf_soft(x, y, z);+}++static VOID CALLBACK alarm_fired(PVOID arg, BOOLEAN timer)+{+ (void)arg;+ (void)timer;+ static const char msg[] = "Alarm clock\n";+ _write(2, msg, sizeof msg - 1);+ _exit(142); /* 128 + SIGALRM, as a shell reports it */+}++unsigned janas_alarm(unsigned seconds)+{+ static HANDLE timer;+ if (timer) {+ DeleteTimerQueueTimer(NULL, timer, NULL);+ timer = NULL;+ }+ if (seconds)+ CreateTimerQueueTimer(&timer, NULL, alarm_fired, NULL, seconds * 1000u,+ 0, WT_EXECUTEONLYONCE);+ return 0;+}++#endif /* _WIN32 */diff --git a/src/common/win_compat.h b/src/common/win_compat.hnew file mode 100644index 0000000..50252d6--- /dev/null+++ b/src/common/win_compat.h@@ -0,0 +1,152 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * win_compat.h - what MinGW-w64's C library lacks of the POSIX one that+ * Janas is written against, for Windows builds only: build.sh makes every+ * file of Janas start with it (-include), never the libraries of others.+ *+ * It holds only what a POSIX call can be mapped to without changing what+ * the caller means: setenv, localtime_r, pread, mkdir with a mode, a rename+ * that replaces, memmem and the like. What differs in kind - processes,+ * sockets, the terminal, the CPU's topology - has code of its own for each+ * system. windows.h is not included here: its macros (near, far, small,+ * min, max...) would collide with ordinary names; win_compat.c includes it.+ *+ * Every file is opened in binary mode, as on POSIX: open() and fopen()+ * add the flag Windows needs, so that a byte read is the byte written.+ */+#ifndef JANAS_COMMON_WIN_COMPAT_H+#define JANAS_COMMON_WIN_COMPAT_H+#ifdef _WIN32++/* the thread-safe localtime_r and gmtime_r of MinGW's time.h */+#ifndef _POSIX_THREAD_SAFE_FUNCTIONS+#define _POSIX_THREAD_SAFE_FUNCTIONS 200112L+#endif++#include <direct.h>+#include <errno.h>+#include <fcntl.h>+#include <io.h>+#include <process.h>+#include <stdint.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <sys/stat.h>+#include <sys/types.h>+#include <time.h>+#include <unistd.h>++/* open(2)'s flags Windows has no use for, or names otherwise */+#ifndef O_CLOEXEC+#define O_CLOEXEC _O_NOINHERIT+#endif+#ifndef O_DIRECT+#define O_DIRECT 0+#endif+#ifndef O_NOFOLLOW+#define O_NOFOLLOW 0+#endif+#ifndef O_NONBLOCK+#define O_NONBLOCK 0+#endif++/* environment: HOME and XDG's directories answered with Windows's own+ when they are not set (HOME %USERPROFILE%, XDG_CONFIG_HOME %APPDATA%,+ XDG_CACHE_HOME and XDG_DATA_HOME %LOCALAPPDATA%, TMPDIR %TEMP%), with /+ between the parts: what Janas keeps goes to %LOCALAPPDATA%\janas and+ %APPDATA%\janas, and setting them still decides */+char *janas_getenv(const char *name);+#define getenv janas_getenv+int janas_setenv(const char *name, const char *value, int overwrite);+int janas_unsetenv(const char *name);+#define setenv janas_setenv+#define unsetenv janas_unsetenv++/* time: struct tm in UTC to time_t */+#define timegm _mkgmtime++/* strings */+char *janas_strcasestr(const char *hay, const char *needle);+void *janas_memmem(const void *hay, size_t hay_len, const void *needle,+ size_t needle_len);+char *janas_strndup(const char *s, size_t n);+#define strcasestr janas_strcasestr+#define memmem janas_memmem+#define strndup janas_strndup++/* files: binary always; a rename that replaces the target as POSIX's+ does; reads and writes at an offset; mkdir without a mode */+int janas_open(const char *path, int flags, ...);+FILE *janas_fopen(const char *path, const char *mode);+int janas_rename(const char *from, const char *to);+ssize_t janas_pread(int fd, void *buf, size_t n, int64_t off);+ssize_t janas_pwrite(int fd, const void *buf, size_t n, int64_t off);+char *janas_realpath(const char *path, char *resolved);+#define open janas_open+#define fopen janas_fopen+#define rename janas_rename+#define pread janas_pread+#define pwrite janas_pwrite+#define realpath janas_realpath+/* remove() takes an empty directory too, as POSIX's */+int janas_remove(const char *path);+#define remove janas_remove+/* EEXIST for whatever is already a directory, as POSIX's says it of "C:"+ and "C:/Users" too */+int janas_mkdir(const char *path);+#define mkdir(path, mode) janas_mkdir(path)++/* advisory locks on a whole file */+#define LOCK_SH 1+#define LOCK_EX 2+#define LOCK_NB 4+#define LOCK_UN 8+int janas_flock(int fd, int op);+#define flock janas_flock++/* the system's sizes */+#define _SC_NPROCESSORS_ONLN 84+#define _SC_PAGESIZE 30+#define _SC_PAGE_SIZE _SC_PAGESIZE+#define _SC_PHYS_PAGES 85+long janas_sysconf(int name);+#define sysconf janas_sysconf++/* Aligned memory that free() takes back, as POSIX's: MinGW's own+ (_aligned_malloc) wants _aligned_free, and code that frees aligned and+ ordinary blocks alike would have to know which is which. A block is+ malloc's, with a tag before the address returned that says where it+ began; free() looks for the tag (win_compat.c). */+void *janas_aligned_alloc(size_t align, size_t size);+int janas_posix_memalign(void **p, size_t align, size_t size);+void janas_free(void *p);+#define aligned_alloc janas_aligned_alloc+#define posix_memalign janas_posix_memalign+#define free janas_free++/* a line of any length, as POSIX's getline */+ssize_t janas_getline(char **line, size_t *cap, FILE *f);+#define getline janas_getline++/* a directory made under a name of its own (the template's XXXXXX) */+char *janas_mkdtemp(char *tmpl);+#define mkdtemp janas_mkdtemp++/* A stream written into memory: a temporary file the system deletes on+ closing, whose content fflush and fclose hand to *ptr and *size as+ glibc's open_memstream does (the buffer the caller frees). */+FILE *janas_open_memstream(char **ptr, size_t *size);+int janas_fflush(FILE *f);+int janas_fclose(FILE *f);+#define open_memstream janas_open_memstream+#define fflush janas_fflush+#define fclose janas_fclose++/* a watchdog for the tests: ends the process after seconds */+unsigned janas_alarm(unsigned seconds);+#define alarm janas_alarm++#endif /* _WIN32 */+#endifdiff --git a/src/common/win_posix.c b/src/common/win_posix.cnew file mode 100644index 0000000..9c230b9--- /dev/null+++ b/src/common/win_posix.c@@ -0,0 +1,276 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * win_posix.c - the functions behind the headers of src/common/win/, which+ * stand in for POSIX's on Windows: statvfs, getrusage, uname, getrandom,+ * dlopen, and poll over sockets, pipes and the console. Nothing on other+ * systems.+ */+#ifdef _WIN32+#include "win/dlfcn.h"+#include "win/sys/random.h"+#include "win/sys/resource.h"+#include "win/sys/statvfs.h"+#include "win/sys/utsname.h"+#include "win/win_sockets.h"++#include <windows.h>+#include <bcrypt.h>+#include <psapi.h>++#undef poll++static int volume_room(const char *path, struct statvfs *s)+{+ ULARGE_INTEGER avail, total, free_;+ if (!GetDiskFreeSpaceExA(path, &avail, &total, &free_)) {+ errno = ENOENT;+ return -1;+ }+ /* in bytes: a block of one */+ *s = (struct statvfs){.f_bsize = 1,+ .f_frsize = 1,+ .f_blocks = total.QuadPart,+ .f_bfree = free_.QuadPart,+ .f_bavail = avail.QuadPart};+ return 0;+}++int statvfs(const char *path, struct statvfs *s)+{+ return volume_room(path, s);+}++int fstatvfs(int fd, struct statvfs *s)+{+ HANDLE h = (HANDLE)_get_osfhandle(fd);+ char p[MAX_PATH + 8];+ DWORD n =+ h == INVALID_HANDLE_VALUE+ ? 0+ : GetFinalPathNameByHandleA(h, p, sizeof p, FILE_NAME_NORMALIZED);+ if (n == 0 || n >= sizeof p) {+ errno = EBADF;+ return -1;+ }+ /* \\?\C:\dir\file: the volume is the path's root */+ char root[MAX_PATH + 8];+ if (!GetVolumePathNameA(p, root, sizeof root)) {+ errno = EBADF;+ return -1;+ }+ return volume_room(root, s);+}++static struct timeval filetime_tv(FILETIME f)+{+ uint64_t t = ((uint64_t)f.dwHighDateTime << 32) | f.dwLowDateTime;+ t /= 10; /* 100 ns to us */+ return (struct timeval){.tv_sec = (long)(t / 1000000),+ .tv_usec = (long)(t % 1000000)};+}++int getrusage(int who, struct rusage *u)+{+ (void)who;+ FILETIME c, e, k, us;+ PROCESS_MEMORY_COUNTERS m = {.cb = sizeof m};+ memset(u, 0, sizeof *u);+ if (GetProcessTimes(GetCurrentProcess(), &c, &e, &k, &us)) {+ u->ru_utime = filetime_tv(us);+ u->ru_stime = filetime_tv(k);+ }+ if (GetProcessMemoryInfo(GetCurrentProcess(), &m, sizeof m))+ u->ru_maxrss = (long)(m.PeakWorkingSetSize / 1024);+ return 0;+}++int uname(struct utsname *u)+{+ memset(u, 0, sizeof *u);+ snprintf(u->sysname, sizeof u->sysname, "Windows");+ DWORD n = sizeof u->nodename;+ if (!GetComputerNameA(u->nodename, &n))+ snprintf(u->nodename, sizeof u->nodename, "?");+ /* the true version: GetVersionEx answers what the manifest says */+ RTL_OSVERSIONINFOW v = {.dwOSVersionInfoSize = sizeof v};+ typedef LONG(WINAPI * get_version)(RTL_OSVERSIONINFOW *);+ HMODULE nt = GetModuleHandleA("ntdll.dll");+ get_version gv =+ nt ? (get_version)(void (*)(void))GetProcAddress(nt, "RtlGetVersion")+ : NULL;+ if (gv && gv(&v) == 0) {+ snprintf(u->release, sizeof u->release, "%lu.%lu.%lu",+ (unsigned long)v.dwMajorVersion,+ (unsigned long)v.dwMinorVersion,+ (unsigned long)v.dwBuildNumber);+ snprintf(u->version, sizeof u->version, "build %lu",+ (unsigned long)v.dwBuildNumber);+ }+ SYSTEM_INFO si;+ GetNativeSystemInfo(&si);+ snprintf(u->machine, sizeof u->machine, "%s",+ si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64+ ? "x86_64"+ : si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_ARM64+ ? "aarch64"+ : "unknown");+ return 0;+}++ssize_t getrandom(void *buf, size_t n, unsigned flags)+{+ (void)flags;+ if (n > 0xffffffffu)+ n = 0xffffffffu;+ if (BCryptGenRandom(NULL, buf, (ULONG)n, BCRYPT_USE_SYSTEM_PREFERRED_RNG) !=+ 0) {+ errno = EIO;+ return -1;+ }+ return (ssize_t)n;+}++static char dl_error[160];+static int dl_failed;++static void dl_fail(const char *what)+{+ snprintf(dl_error, sizeof dl_error, "%s: error %lu", what,+ (unsigned long)GetLastError());+ dl_failed = 1;+}++void *dlopen(const char *file, int mode)+{+ (void)mode;+ HMODULE h = LoadLibraryA(file);+ if (!h)+ dl_fail(file);+ return (void *)h;+}++void *dlsym(void *handle, const char *name)+{+ FARPROC f = GetProcAddress((HMODULE)handle, name);+ if (!f)+ dl_fail(name);+ return (void *)(intptr_t)f;+}++int dlclose(void *handle)+{+ return FreeLibrary((HMODULE)handle) ? 0 : -1;+}++char *dlerror(void)+{+ if (!dl_failed)+ return NULL;+ dl_failed = 0;+ return dl_error;+}++/* the events WSAPoll accepts as asked for (it refuses the others) */+#define ASKABLE (POLLRDNORM | POLLRDBAND | POLLWRNORM)++static int is_socket(int fd)+{+ int type;+ int len = sizeof type;+ return getsockopt((SOCKET)(intptr_t)fd, SOL_SOCKET, SO_TYPE, (char *)&type,+ &len) == 0;+}++/* Whether the console has a key typed: what is not a key (the mouse, focus,+ a resize, a key let go) is taken out of the way, so that a read that+ follows does not wait. */+static int console_has_key(HANDLE h)+{+ for (;;) {+ INPUT_RECORD r;+ DWORD n = 0;+ if (!PeekConsoleInputW(h, &r, 1, &n) || n == 0)+ return 0;+ if (r.EventType == KEY_EVENT && r.Event.KeyEvent.bKeyDown)+ return 1;+ ReadConsoleInputW(h, &r, 1, &n);+ }+}++static short fd_ready(int fd, short events)+{+ if (fd < 0)+ return 0;+ if (is_socket(fd)) {+ WSAPOLLFD p = {.fd = (SOCKET)(intptr_t)fd,+ .events = (short)(events & ASKABLE)};+ if (WSAPoll(&p, 1, 0) < 0)+ return POLLERR;+ return p.revents;+ }+ HANDLE h = (HANDLE)_get_osfhandle(fd);+ if (h == INVALID_HANDLE_VALUE)+ return POLLNVAL;+ short r = 0;+ switch (GetFileType(h)) {+ case FILE_TYPE_PIPE: {+ DWORD avail = 0;+ if (!PeekNamedPipe(h, NULL, 0, NULL, &avail, NULL))+ return POLLHUP; /* the other end has gone */+ if ((events & POLLIN) && avail > 0)+ r |= POLLIN;+ if (events & POLLOUT)+ r |= POLLOUT;+ return r;+ }+ case FILE_TYPE_CHAR:+ if ((events & POLLIN) && console_has_key(h))+ r |= POLLIN;+ if (events & POLLOUT)+ r |= POLLOUT;+ return r;+ default: /* a file is always ready */+ return (short)(events & (POLLIN | POLLOUT));+ }+}++int janas_poll(struct pollfd *fds, nfds_t n, int timeout_ms)+{+ /* sockets alone: Winsock's own, which waits without turning */+ int all_sockets = n > 0;+ for (nfds_t i = 0; i < n && all_sockets; i++)+ all_sockets = fds[i].fd < 0 || is_socket(fds[i].fd);+ if (all_sockets) {+ WSAPOLLFD p[64];+ if (n <= 64) {+ for (nfds_t i = 0; i < n; i++)+ p[i] = (WSAPOLLFD){.fd = fds[i].fd < 0+ ? INVALID_SOCKET+ : (SOCKET)(intptr_t)fds[i].fd,+ .events = (short)(fds[i].events & ASKABLE)};+ int r = WSAPoll(p, (ULONG)n, timeout_ms);+ for (nfds_t i = 0; i < n; i++)+ fds[i].revents = p[i].revents;+ return r;+ }+ }+ /* pipes and the console have nothing to wait on with sockets: look,+ and look again a millisecond later */+ ULONGLONG start = GetTickCount64();+ for (;;) {+ int ready = 0;+ for (nfds_t i = 0; i < n; i++) {+ fds[i].revents = fd_ready(fds[i].fd, fds[i].events);+ if (fds[i].revents)+ ready++;+ }+ if (ready || timeout_ms == 0)+ return ready;+ if (timeout_ms > 0 && GetTickCount64() - start >= (ULONGLONG)timeout_ms)+ return 0;+ Sleep(1);+ }+}++#endif /* _WIN32 */diff --git a/src/common/win_start.c b/src/common/win_start.cnew file mode 100644index 0000000..d577c35--- /dev/null+++ b/src/common/win_start.c@@ -0,0 +1,24 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * win_start.c - what every program of Janas does first on Windows, before+ * main: the console made to show UTF-8, and to take the escape sequences of+ * colours and of the cursor as a Linux terminal does. Linked into the+ * programs only (build.sh), never into the libraries: a program of+ * someone else's that loads them keeps its console as it set it.+ */+#ifdef _WIN32+#include <windows.h>++__attribute__((constructor)) static void janas_win_start(void)+{+ SetConsoleOutputCP(CP_UTF8);+ DWORD std[2] = {STD_OUTPUT_HANDLE, STD_ERROR_HANDLE};+ for (int i = 0; i < 2; i++) {+ HANDLE h = GetStdHandle(std[i]);+ DWORD m;+ if (h != INVALID_HANDLE_VALUE && GetConsoleMode(h, &m))+ SetConsoleMode(h, m | ENABLE_VIRTUAL_TERMINAL_PROCESSING);+ }+}+#endifdiff --git a/src/get/steps.c b/src/get/steps.cindex eab8af9..21e22b6 100644--- a/src/get/steps.c+++ b/src/get/steps.c@@ -8,18 +8,17 @@#define _GNU_SOURCE#include "steps.h"-#include <spawn.h>#include <stdint.h>+#include <stdlib.h>#include <stdio.h>#include <string.h>-#include <sys/wait.h>#include <time.h>#include <unistd.h>#include "common/hf_fetch.h"#include "common/sha256.h"--extern char **environ;+#include "common/proc.h"+#include "common/sysinfo.h"void get_local(char *out, size_t len, const char *dir, const char *path){@@ -110,21 +109,33 @@ int get_fetch(const char *repo, const char *path, const char *dir,int get_run(const char *tool, char *const argv[]){char self[4096], path[4200];- ssize_t n = readlink("/proc/self/exe", self, sizeof(self) - 1);- if (n <= 0)+ if (janas_exe_path(self, sizeof self) < 0)return -1;- self[n] = 0;char *slash = strrchr(self, '/');if (slash)*slash = 0;snprintf(path, sizeof(path), "%s/%s", self, tool);- pid_t pid;- if (posix_spawn(&pid, path, NULL, NULL, argv, environ) != 0) {+ /* the program by its path, the rest of the line as the caller has it */+ size_t n = 0;+ while (argv[n])+ n++;+ const char **args = calloc(n + 1, sizeof *args);+ if (!args)+ return -1;+ args[0] = path;+ for (size_t i = 1; i < n; i++)+ args[i] = argv[i];+ struct janas_proc pr;+ char err[256];+ int rc =+ janas_proc_start(&pr, args, NULL, NULL, -1, -1, -1, 0, err, sizeof err);+ free(args);+ if (rc != 0) {fprintf(stderr, "janas-get: cannot run %s\n", path);return -1;}- int st;- if (waitpid(pid, &st, 0) != pid)+ int code = -1;+ if (janas_proc_wait(&pr, -1, &code) != 1)return -1;- return WIFEXITED(st) ? WEXITSTATUS(st) : -1;+ return code;}diff --git a/src/llm/api_keep_disk.c b/src/llm/api_keep_disk.cindex dbb7115..70db8fa 100644--- a/src/llm/api_keep_disk.c+++ b/src/llm/api_keep_disk.c@@ -25,6 +25,9 @@#include <string.h>#include <sys/stat.h>#include <sys/statvfs.h>+#ifdef _WIN32+#include <sys/utime.h>+#endif#include <unistd.h>#include "llm/jns.h"@@ -48,7 +51,21 @@ static int path_of(const janas_llm_chat *c, const char *name, char *buf,static int64_t mtime_ns(const struct stat *st){+#ifdef _WIN32+ return (int64_t)st->st_mtime * 1000000000; /* seconds only there */+#elsereturn (int64_t)st->st_mtim.tv_sec * 1000000000 + st->st_mtim.tv_nsec;+#endif+}++/* The file's time of change set to now: its turn to go comes last. */+static int touch(const char *p)+{+#ifdef _WIN32+ return _utime(p, NULL);+#else+ return utimensat(AT_FDCWD, p, NULL, 0);+#endif}static void forget(janas_llm_chat *c, int32_t i, int unlink_it)@@ -228,7 +245,7 @@ struct janas_llm_saved *janas_api_disk_take(janas_llm_chat *c, int32_t i,*prefix = c->disk[i].prefix;/* used now: the last to go */struct stat st;- if (utimensat(AT_FDCWD, p, NULL, 0) == 0 && stat(p, &st) == 0)+ if (touch(p) == 0 && stat(p, &st) == 0)c->disk[i].used = mtime_ns(&st);return sv;}diff --git a/src/llm/chat.h b/src/llm/chat.hindex 857c2f2..8999a9d 100644--- a/src/llm/chat.h+++ b/src/llm/chat.h@@ -213,7 +213,7 @@ struct janas_llm_chat {/* The last error, on this thread; returns code. */int32_t janas_api_fail(int32_t code, const char *fmt, ...)- __attribute__((format(printf, 2, 3)));+ __attribute__((format(gnu_printf, 2, 3)));double janas_api_now(void);/* The power mode in effect: auto follows the power source. */void janas_api_apply_mode(janas_llm *llm);diff --git a/src/llm/expert_cache.c b/src/llm/expert_cache.cindex 39941de..357da78 100644--- a/src/llm/expert_cache.c+++ b/src/llm/expert_cache.c@@ -7,6 +7,7 @@#define _GNU_SOURCE#include "expert_cache.h"+#include "common/reopen.h"#include "common/uring.h"#include <errno.h>@@ -475,9 +476,7 @@ struct janas_expert_cache *janas_expert_cache_create(const struct janas_jns *j,c->n_slots = n_slots;c->head = c->tail = NONE;- char path[64];- snprintf(path, sizeof(path), "/proc/self/fd/%d", j->fd);- c->fd = open(path, O_RDONLY | O_DIRECT | O_CLOEXEC);+ c->fd = janas_reopen_read(j->fd, 1);size_t arena_bytes = n_slots * slot_bytes + JANAS_ARENA_GUARD;c->arena = aligned_alloc(JANAS_JNS_ALIGN, arena_bytes);c->where = malloc(n_keys * sizeof(int32_t));@@ -779,9 +778,7 @@ int janas_expert_cache_rebase(struct janas_expert_cache *c, uint8_t *arena)pthread_mutex_unlock(&c->lock);/* the new memory takes no O_DIRECT reads (a GPU driver's mapping):the file opened again without it, for the loads that may still come */- char path[64];- snprintf(path, sizeof(path), "/proc/self/fd/%d", c->j->fd);- int fd = busy ? -1 : open(path, O_RDONLY | O_CLOEXEC);+ int fd = busy ? -1 : janas_reopen_read(c->j->fd, 0);if (fd < 0) {pthread_mutex_unlock(&c->api_lock);return -1;diff --git a/src/llm/gpu.c b/src/llm/gpu.cindex 98e20b7..0ac5c71 100644--- a/src/llm/gpu.c+++ b/src/llm/gpu.c@@ -401,9 +401,14 @@ struct janas_gpu *janas_gpu_create(char *err, size_t err_len)snprintf(err, err_len, "out of memory");return NULL;}- g->lib = dlopen("libvulkan.so.1", RTLD_NOW | RTLD_LOCAL);+#ifdef _WIN32+#define VULKAN_LOADER "vulkan-1.dll"+#else+#define VULKAN_LOADER "libvulkan.so.1"+#endif+ g->lib = dlopen(VULKAN_LOADER, RTLD_NOW | RTLD_LOCAL);if (!g->lib) {- snprintf(err, err_len, "no Vulkan loader (libvulkan.so.1)");+ snprintf(err, err_len, "no Vulkan loader (" VULKAN_LOADER ")");free(g);return NULL;}diff --git a/src/llm/json.h b/src/llm/json.hindex 1210000..862d6a5 100644--- a/src/llm/json.h+++ b/src/llm/json.h@@ -65,7 +65,7 @@ struct janas_buf {void janas_buf_put(struct janas_buf *b, const char *s, size_t n);void janas_buf_puts(struct janas_buf *b, const char *s);void janas_buf_printf(struct janas_buf *b, const char *fmt, ...)- __attribute__((format(printf, 2, 3)));+ __attribute__((format(gnu_printf, 2, 3)));void janas_buf_free(struct janas_buf *b);/* v as JSON text, the way the chat templates' tojson writes it. */diff --git a/src/llm/metrics.c b/src/llm/metrics.cindex 47fc8f2..ca7845e 100644--- a/src/llm/metrics.c+++ b/src/llm/metrics.c@@ -53,7 +53,7 @@ static int on(void)/* One JSON line: the event, its time, and the members (text without thebraces), written in one piece so lines from several threads never mix. */static void emit(const char *event, const char *fmt, ...)- __attribute__((format(printf, 2, 3)));+ __attribute__((format(gnu_printf, 2, 3)));static void emit(const char *event, const char *fmt, ...){if (json_fd < 0)@@ -61,7 +61,8 @@ static void emit(const char *event, const char *fmt, ...)struct timeval tv;gettimeofday(&tv, NULL);struct tm tm;- gmtime_r(&tv.tv_sec, &tm);+ time_t sec = tv.tv_sec; /* a long on Windows, not a time_t */+ gmtime_r(&sec, &tm);char when[40];strftime(when, sizeof(when), "%Y-%m-%dT%H:%M:%S", &tm);struct janas_buf b = {0};@@ -84,7 +85,8 @@ static void emit(const char *event, const char *fmt, ...)janas_buf_free(&b);}-static void human(const char *fmt, ...) __attribute__((format(printf, 1, 2)));+static void human(const char *fmt, ...)+ __attribute__((format(gnu_printf, 1, 2)));static void human(const char *fmt, ...){if (human_every <= 0)diff --git a/src/llm/model_load.c b/src/llm/model_load.cindex b56f47b..5f0425b 100644--- a/src/llm/model_load.c+++ b/src/llm/model_load.c@@ -1101,10 +1101,9 @@ struct janas_llm_model *janas_llm_model_load(const char *path,/* the caller pinned for the time the model lives, and given its CPUsback when it goes: a model opened after another in the same process(the chat measuring, a reload) would otherwise see one CPU */- _Static_assert(sizeof(cpu_set_t) <= sizeof(m->caller_cpus), "cpu set");+ _Static_assert(JANAS_CPU_SAVE_BYTES <= sizeof(m->caller_cpus), "cpu set");if (pin >= 0) {- m->caller_pinned = sched_getaffinity(0, sizeof(cpu_set_t),- (cpu_set_t *)m->caller_cpus) == 0;+ m->caller_pinned = janas_cpus_save(m->caller_cpus) == 0;janas_pin_current_thread(pin);}m->cache = janas_expert_cache_create(&m->j, o->cache_bytes, m->exp_level,@@ -1226,7 +1225,7 @@ void janas_llm_model_free(struct janas_llm_model *m)if (!m)return;if (m->caller_pinned)- sched_setaffinity(0, sizeof(cpu_set_t), (cpu_set_t *)m->caller_cpus);+ janas_cpus_restore(m->caller_cpus);if (m->tune_key[0])janas_tuner_save(&m->tuner, m->tune_key);if (m->use_count) {diff --git a/src/server/main.c b/src/server/main.cindex 353ddba..fbdabad 100644--- a/src/server/main.c+++ b/src/server/main.c@@ -8,6 +8,8 @@#include "server.h"#include "common/env_names.h"+#include "common/sock.h"+#include "common/stop.h"#include "common/words.h"#include <netdb.h>@@ -326,6 +328,7 @@ int main(int argc, char **argv).ai_socktype = SOCK_STREAM,.ai_flags = AI_PASSIVE | AI_NUMERICSERV},*ai = NULL;+ janas_sock_init();int gai = getaddrinfo(c->host, port, &hints, &ai);if (gai != 0) {fprintf(stderr, "janas-server: %s: %s\n", c->host, gai_strerror(gai));@@ -340,13 +343,8 @@ int main(int argc, char **argv)"Set one with --api-key.\n",c->host);- /* the signals that stop it, blocked in every thread and awaited here */- sigset_t stop;- sigemptyset(&stop);- sigaddset(&stop, SIGINT);- sigaddset(&stop, SIGTERM);- pthread_sigmask(SIG_BLOCK, &stop, NULL);- signal(SIGPIPE, SIG_IGN);+ /* the requests to stop, held back from every thread and awaited here */+ janas_stop_prepare();/* the store too: a directory another server holds should not waitfor the model either */@@ -400,8 +398,7 @@ int main(int argc, char **argv)strchr(c->host, ':') ? "[" : "",strcmp(c->host, "0.0.0.0") ? c->host : "127.0.0.1",strchr(c->host, ':') ? "]" : "", (unsigned)c->port);- int sig;- sigwait(&stop, &sig);+ janas_stop_wait();fprintf(stderr, "janas-server: stopping\n");srv_http_stop(&s);srv_engine_stop(s.engine);diff --git a/src/server/request.h b/src/server/request.hindex cae090a..70cde26 100644--- a/src/server/request.h+++ b/src/server/request.h@@ -14,7 +14,7 @@/* The error of a request that cannot be served, for the 400 answer: alwaysreturns 0, so that BAD() can sit inside an expression. */int srv_perr(struct srv_perr *e, const char *code, const char *fmt, ...)- __attribute__((format(printf, 3, 4)));+ __attribute__((format(gnu_printf, 3, 4)));#define BAD(...) srv_perr(e, __VA_ARGS__)/* Marks the request failed; returns -1. */diff --git a/src/server/server.h b/src/server/server.hindex b9c84b2..80f9bf7 100644--- a/src/server/server.h+++ b/src/server/server.h@@ -238,7 +238,7 @@ typedef int (*srv_handler)(struct srv_req *r);int srv_reply_json(struct srv_req *r, unsigned status, char *json, size_t n);int srv_reply_error(struct srv_req *r, unsigned status, const char *type,const char *code, const char *fmt, ...)- __attribute__((format(printf, 5, 6)));+ __attribute__((format(gnu_printf, 5, 6)));/* A job refused for an input above --max-input: a 400 with the numbers(input_tokens, max_input_tokens, excess_tokens and the parts) as fieldsof the error, for a client to shorten the input by. */diff --git a/src/services/common/locate.c b/src/services/common/locate.cindex 17acab9..2249b9d 100644--- a/src/services/common/locate.c+++ b/src/services/common/locate.c@@ -16,6 +16,7 @@#include "services/common/geo.h"#include "services/common/https_get.h"#include "services/common/locate.h"+#include "services/common/tz.h"#define DEG(x) ((x) * 1e-5)#define KEEP_S 3600 /* a connection seldom moves within the hour */@@ -150,21 +151,13 @@ static int from_net(const char *url, const char *who,return r;}-/* the city of the machine's zone: TZ, or where /etc/localtime points */+/* the city of the machine's zone: TZ, or where /etc/localtime points+ (Windows: the zone the system is set to, as ICU names it) */static int from_zone(struct janas_where *w){- char path[256] = "";- const char *tz = getenv("TZ");- if (tz && *tz) {- copy(path, sizeof path, tz[0] == ':' ? tz + 1 : tz);- } else {- ssize_t n = readlink("/etc/localtime", path, sizeof path - 1);- if (n <= 0)- return -1;- path[n] = 0;- }- const char *z = strstr(path, "zoneinfo/");- z = z ? z + 9 : path; /* "Europe/Rome" */+ char z[sizeof w->tz];+ if (janas_tz_machine(z, sizeof z) != 0)+ return -1;const char *slash = strrchr(z, '/');if (!slash) /* "UTC", "CET": no city */return -1;diff --git a/src/services/common/run.c b/src/services/common/run.cindex 865a39d..7a5d0cc 100644--- a/src/services/common/run.c+++ b/src/services/common/run.c@@ -4,18 +4,16 @@* run.c - a program run by a service (see run.h): no shell, no terminal,* a time limit for it and what it started.*/-#define _GNU_SOURCE#include <errno.h>#include <fcntl.h>#include <poll.h>-#include <signal.h>#include <stdio.h>#include <stdlib.h>#include <string.h>-#include <sys/wait.h>#include <time.h>#include <unistd.h>+#include "common/proc.h"#include "run.h"static double now_ms(void)@@ -32,38 +30,38 @@ int janas_run(const char *dir, const char *const *argv, const char *const *env,const char *name = strrchr(argv[0], '/');name = name ? name + 1 : argv[0];int po[2], pe[2];- if (pipe2(po, O_CLOEXEC) != 0) {+ if (janas_pipe(po) != 0) {snprintf(why, why_len, "no pipe: %s", strerror(errno));return -1;}- if (pipe2(pe, O_CLOEXEC) != 0) {+ if (janas_pipe(pe) != 0) {close(po[0]);close(po[1]);snprintf(why, why_len, "no pipe: %s", strerror(errno));return -1;}- pid_t pid = fork();- if (pid < 0) {- snprintf(why, why_len, "cannot start %s: %s", name, strerror(errno));- close(po[0]), close(po[1]), close(pe[0]), close(pe[1]);- return -1;- }- if (pid == 0) {- setsid(); /* no terminal: nothing can be asked of the user */- int nul = open("/dev/null", O_RDONLY);- if (nul >= 0)- dup2(nul, 0);- dup2(po[1], 1);- dup2(pe[1], 2);- if (dir && chdir(dir) != 0)- _exit(126);- for (size_t i = 0; env && env[i]; i++)- putenv((char *)env[i]);- execvp(argv[0], (char *const *)argv);- _exit(127);- }+ /* no terminal: nothing can be asked of the user */+ struct janas_proc pr;+ char e[256];+ int nul = janas_null_fd(0);+ int started = janas_proc_start(&pr, argv, env, dir, nul, po[1], pe[1],+ JANAS_PROC_DETACHED, e, sizeof e);+ int start_errno = errno;+ if (nul >= 0)+ close(nul);close(po[1]);close(pe[1]);+ if (started != 0) {+ close(po[0]);+ close(pe[0]);+ if (start_errno == ENOENT)+ snprintf(why, why_len, "%s is not installed", name);+ else if (start_errno == ENOTDIR)+ snprintf(why, why_len, "cannot enter %s", dir);+ else+ snprintf(why, why_len, "%s", e);+ return -1;+ }struct pollfd fd[2] = {{.fd = po[0], .events = POLLIN},{.fd = pe[0], .events = POLLIN}};struct janas_buf *to[2] = {out, err};@@ -98,10 +96,9 @@ int janas_run(const char *dir, const char *const *argv, const char *const *env,if (fd[i].fd >= 0)close(fd[i].fd);if (late)- kill(-pid, SIGKILL); /* it and what it started */- int st = 0;- while (waitpid(pid, &st, 0) < 0 && errno == EINTR)- ;+ janas_proc_kill(&pr, 1); /* it and what it started */+ int code = -1;+ janas_proc_wait(&pr, -1, &code);janas_buf_put(out, "", 1);out->n--;janas_buf_put(err, "", 1);@@ -111,17 +108,9 @@ int janas_run(const char *dir, const char *const *argv, const char *const *env,timeout_ms / 1000);return -1;}- if (!WIFEXITED(st)) {+ if (code < 0) {snprintf(why, why_len, "%s stopped by a signal", name);return -1;}- if (WEXITSTATUS(st) == 127) {- snprintf(why, why_len, "%s is not installed", name);- return -1;- }- if (WEXITSTATUS(st) == 126) {- snprintf(why, why_len, "cannot enter %s", dir);- return -1;- }- return WEXITSTATUS(st);+ return code;}diff --git a/src/services/common/tz.c b/src/services/common/tz.cnew file mode 100644index 0000000..3b7055e--- /dev/null+++ b/src/services/common/tz.c@@ -0,0 +1,258 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * tz.c - see tz.h.+ */+#define _GNU_SOURCE+#include "tz.h"++#include <stdio.h>+#include <stdlib.h>+#include <string.h>++#ifdef _WIN32+#include <windows.h>+#include <stdint.h>++/* ICU's C calendar, as Windows's icu.dll exports it (no version in the+ names there) */+typedef uint16_t UChar;+typedef double UDate;+typedef int UErrorCode;+typedef void UCalendar;+enum {+ F_YEAR = 1,+ F_MONTH = 2,+ F_DATE = 5,+ F_DAY_OF_YEAR = 6,+ F_DAY_OF_WEEK = 7,+ F_HOUR_OF_DAY = 11,+ F_MINUTE = 12,+ F_SECOND = 13,+ F_MILLISECOND = 14,+ F_DST_OFFSET = 16+};+enum { SHORT_STANDARD = 1, SHORT_DST = 3 };++static struct {+ UCalendar *(*open)(const UChar *, int32_t, const char *, int, UErrorCode *);+ void (*close)(UCalendar *);+ void (*set_millis)(UCalendar *, UDate, UErrorCode *);+ UDate (*get_millis)(const UCalendar *, UErrorCode *);+ int32_t (*get)(const UCalendar *, int, UErrorCode *);+ void (*set)(UCalendar *, int, int32_t);+ void (*set_date_time)(UCalendar *, int32_t, int32_t, int32_t, int32_t,+ int32_t, int32_t, UErrorCode *);+ int32_t (*zone_name)(const UCalendar *, int, const char *, UChar *, int32_t,+ UErrorCode *);+ int32_t (*default_zone)(UChar *, int32_t, UErrorCode *);+} icu;+static INIT_ONCE icu_once = INIT_ONCE_STATIC_INIT;+static int icu_ok;++/* A function of the DLL into its field: a FARPROC's bytes, as a pointer+ to a function of another type has them. */+static int icu_fn(void *field, HMODULE m, const char *name)+{+ FARPROC f = GetProcAddress(m, name);+ if (!f)+ return 0;+ memcpy(field, &f, sizeof f);+ return 1;+}+#define ICU_FN(field, name) icu_fn(&icu.field, m, name)++static BOOL CALLBACK icu_load(PINIT_ONCE once, PVOID arg, PVOID *ctx)+{+ (void)once, (void)arg, (void)ctx;+ HMODULE m = LoadLibraryExA("icu.dll", NULL, LOAD_LIBRARY_SEARCH_SYSTEM32);+ icu_ok = m && ICU_FN(open, "ucal_open") && ICU_FN(close, "ucal_close") &&+ ICU_FN(set_millis, "ucal_setMillis") &&+ ICU_FN(get_millis, "ucal_getMillis") && ICU_FN(get, "ucal_get") &&+ ICU_FN(set, "ucal_set") &&+ ICU_FN(set_date_time, "ucal_setDateTime") &&+ ICU_FN(zone_name, "ucal_getTimeZoneDisplayName") &&+ ICU_FN(default_zone, "ucal_getDefaultTimeZone");+ return TRUE;+}++/* A Gregorian calendar in the zone tz (NULL or "": the machine's). */+static UCalendar *calendar(const char *tz)+{+ InitOnceExecuteOnce(&icu_once, icu_load, NULL, NULL);+ if (!icu_ok)+ return NULL;+ UChar id[96];+ int n = 0;+ for (; tz && tz[n] && n < 95; n++)+ id[n] = (unsigned char)tz[n];+ UErrorCode e = 0;+ UCalendar *c = icu.open(n ? id : NULL, n ? n : -1, "en_US", 1, &e);+ if (e > 0) {+ if (c)+ icu.close(c);+ return NULL;+ }+ return c;+}++static void utc_tm(time_t t, struct tm *out, char *abbr, size_t abbr_len)+{+ gmtime_r(&t, out);+ if (abbr)+ snprintf(abbr, abbr_len, "UTC");+}++int janas_tz_local(const char *tz, time_t t, struct tm *out, char *abbr,+ size_t abbr_len)+{+ UCalendar *c = calendar(tz);+ if (!c) {+ utc_tm(t, out, abbr, abbr_len);+ return -1;+ }+ UErrorCode e = 0;+ icu.set_millis(c, (UDate)t * 1000.0, &e);+ memset(out, 0, sizeof *out);+ out->tm_year = icu.get(c, F_YEAR, &e) - 1900;+ out->tm_mon = icu.get(c, F_MONTH, &e);+ out->tm_mday = icu.get(c, F_DATE, &e);+ out->tm_yday = icu.get(c, F_DAY_OF_YEAR, &e) - 1;+ out->tm_wday = icu.get(c, F_DAY_OF_WEEK, &e) - 1;+ out->tm_hour = icu.get(c, F_HOUR_OF_DAY, &e);+ out->tm_min = icu.get(c, F_MINUTE, &e);+ out->tm_sec = icu.get(c, F_SECOND, &e);+ out->tm_isdst = icu.get(c, F_DST_OFFSET, &e) != 0;+ if (abbr && abbr_len) {+ /* ICU gives a zone's short name ("CEST") only in the languages+ where it is in common use, and "GMT+2" elsewhere: the English of+ the places that use it, the first that has one */+ static const char *const langs[] = {"en_US", "en_GB", "en_IE", "en_AU",+ "en_NZ", "en_IN", "en_ZA", "en_CA"};+ abbr[0] = 0;+ for (size_t l = 0; l < sizeof langs / sizeof *langs; l++) {+ UChar w[32];+ UErrorCode le = 0;+ int32_t n =+ icu.zone_name(c, out->tm_isdst ? SHORT_DST : SHORT_STANDARD,+ langs[l], w, 32, &le);+ if (le > 0 || n <= 0)+ continue;+ size_t k = 0;+ for (int32_t i = 0; i < n && i < 32 && k + 1 < abbr_len; i++)+ if (w[i] < 0x80)+ abbr[k++] = (char)w[i];+ abbr[k] = 0;+ if (strncmp(abbr, "GMT", 3) != 0 && strncmp(abbr, "UTC", 3) != 0)+ break; /* a name of its own; "GMT+2" is kept if none has */+ }+ }+ icu.close(c);+ if (e > 0) {+ utc_tm(t, out, abbr, abbr_len);+ return -1;+ }+ return 0;+}++time_t janas_tz_mktime(const char *tz, struct tm *lt)+{+ UCalendar *c = calendar(tz);+ if (!c)+ return (time_t)-1;+ UErrorCode e = 0;+ /* lenient: a 32nd day is the 1st of the next month, as mktime has it */+ icu.set_date_time(c, lt->tm_year + 1900, lt->tm_mon, lt->tm_mday,+ lt->tm_hour, lt->tm_min, lt->tm_sec, &e);+ icu.set(c, F_MILLISECOND, 0);+ UDate ms = icu.get_millis(c, &e);+ icu.close(c);+ if (e > 0)+ return (time_t)-1;+ time_t t = (time_t)(ms / 1000.0);+ janas_tz_local(tz, t, lt, NULL, 0);+ return t;+}++int janas_tz_machine(char *buf, size_t len)+{+ InitOnceExecuteOnce(&icu_once, icu_load, NULL, NULL);+ if (!icu_ok || len == 0)+ return -1;+ UChar w[96];+ UErrorCode e = 0;+ int32_t n = icu.default_zone(w, 96, &e);+ if (e > 0 || n <= 0 || n >= 96)+ return -1;+ size_t k = 0;+ for (int32_t i = 0; i < n && k + 1 < len; i++)+ buf[k++] = w[i] < 0x80 ? (char)w[i] : '?';+ buf[k] = 0;+ return 0;+}++#else+#include <unistd.h>++/* The zone set for a while and the one before it put back: what the+ services did each on its own until the C library's other systems came+ in. */+static char *zone_set(const char *tz)+{+ char *old = getenv("TZ") ? strdup(getenv("TZ")) : NULL;+ if (tz && *tz)+ setenv("TZ", tz, 1);+ tzset();+ return old;+}++static void zone_back(const char *tz, char *old)+{+ if (tz && *tz) {+ if (old)+ setenv("TZ", old, 1);+ else+ unsetenv("TZ");+ tzset();+ }+ free(old);+}++int janas_tz_local(const char *tz, time_t t, struct tm *out, char *abbr,+ size_t abbr_len)+{+ char *old = zone_set(tz);+ int rc = localtime_r(&t, out) ? 0 : -1;+ if (abbr && abbr_len)+ snprintf(abbr, abbr_len, "%s",+ rc == 0 && out->tm_zone ? out->tm_zone : "");+ zone_back(tz, old);+ return rc;+}++time_t janas_tz_mktime(const char *tz, struct tm *lt)+{+ char *old = zone_set(tz);+ time_t t = mktime(lt);+ zone_back(tz, old);+ return t;+}++int janas_tz_machine(char *buf, size_t len)+{+ char path[256] = "";+ const char *tz = getenv("TZ");+ if (tz && *tz) {+ snprintf(path, sizeof path, "%s", tz[0] == ':' ? tz + 1 : tz);+ } else {+ ssize_t n = readlink("/etc/localtime", path, sizeof path - 1);+ if (n <= 0)+ return -1;+ path[n] = 0;+ }+ const char *z = strstr(path, "zoneinfo/");+ snprintf(buf, len, "%s", z ? z + 9 : path); /* "Europe/Rome" */+ return 0;+}++#endifdiff --git a/src/services/common/tz.h b/src/services/common/tz.hnew file mode 100644index 0000000..7cfe3e5--- /dev/null+++ b/src/services/common/tz.h@@ -0,0 +1,30 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * tz.h - times in a zone named as IANA names them ("Europe/Rome"), for+ * Janas's services. POSIX: the C library's own, through TZ. Windows,+ * whose C library knows no IANA names: the ICU that comes with Windows 10+ * and 11 (icu.dll).+ */+#ifndef JANAS_SERVICES_TZ_H+#define JANAS_SERVICES_TZ_H++#include <stddef.h>+#include <time.h>++/* The time t in the zone tz (NULL or "": the machine's), into *out, and+ the zone's abbreviation there and then ("CEST") into abbr when it is not+ NULL. 0, or -1 (*out then in UTC). */+int janas_tz_local(const char *tz, time_t t, struct tm *out, char *abbr,+ size_t abbr_len);++/* The instant of the local time *lt in the zone tz (NULL or "": the+ machine's), as mktime would give it there; *lt normalized as mktime+ leaves it. -1 when it cannot be told. */+time_t janas_tz_mktime(const char *tz, struct tm *lt);++/* The machine's zone as an IANA name ("Europe/Rome"). 0, or -1 when it is+ not known. */+int janas_tz_machine(char *buf, size_t len);++#endifdiff --git a/src/services/flights/schedule.c b/src/services/flights/schedule.cindex 05a4dbf..ad97ee8 100644--- a/src/services/flights/schedule.c+++ b/src/services/flights/schedule.c@@ -14,6 +14,7 @@#include <time.h>#include "flights.h"+#include "services/common/tz.h"#include "services/common/conf.h"#define BASE "https://api.aviationstack.com/v1/flights?access_key="@@ -74,17 +75,7 @@ static time_t local_time(const char *iso, const char *tz)return 0;tm.tm_year -= 1900;tm.tm_mon -= 1;- char *old = getenv("TZ") ? strdup(getenv("TZ")) : NULL;- setenv("TZ", tz && *tz ? tz : "UTC", 1);- tzset();- time_t t = mktime(&tm);- if (old) {- setenv("TZ", old, 1);- free(old);- } else {- unsetenv("TZ");- }- tzset();+ time_t t = janas_tz_mktime(tz && *tz ? tz : "UTC", &tm);return t == (time_t)-1 ? 0 : t;}diff --git a/src/services/flights/tools.c b/src/services/flights/tools.cindex f5d41f2..2eb3e10 100644--- a/src/services/flights/tools.c+++ b/src/services/flights/tools.c@@ -21,6 +21,7 @@#include <time.h>#include <unistd.h>+#include "services/common/tz.h"#include "services/common/locate.h"#include "common/mcp_server.h"#include "flights.h"@@ -117,19 +118,9 @@ static void thousands(struct janas_buf *b, double v)/* The time t as HH:MM in the zone tz (an IANA name). */static void hhmm(time_t t, const char *tz, char *out, size_t n){- char *old = getenv("TZ") ? strdup(getenv("TZ")) : NULL;- setenv("TZ", tz, 1);- tzset();struct tm tm;- localtime_r(&t, &tm);+ janas_tz_local(tz, t, &tm, NULL, 0);strftime(out, n, "%H:%M", &tm);- if (old) {- setenv("TZ", old, 1);- free(old);- } else {- unsetenv("TZ");- }- tzset();}/* The time t as "HH:MM local time (HH:MM UTC)", with the day when it is@@ -140,22 +131,12 @@ static void when_text(struct janas_buf *b, time_t t, const char *tz)hhmm(t, tz, loc, sizeof loc);hhmm(t, "UTC", utc, sizeof utc);janas_buf_printf(b, "%s local time (%s UTC)", loc, utc);- char *old = getenv("TZ") ? strdup(getenv("TZ")) : NULL;- setenv("TZ", tz, 1);- tzset();struct tm tm;time_t now = time(NULL);- localtime_r(&now, &tm);+ janas_tz_local(tz, now, &tm, NULL, 0);strftime(today, sizeof today, "%d %b", &tm);- localtime_r(&t, &tm);+ janas_tz_local(tz, t, &tm, NULL, 0);strftime(day, sizeof day, "%d %b", &tm);- if (old) {- setenv("TZ", old, 1);- free(old);- } else {- unsetenv("TZ");- }- tzset();if (strcmp(day, today) != 0)janas_buf_printf(b, " on %s", day);}diff --git a/src/services/git/git.h b/src/services/git/git.hindex 49ba89b..c117b3a 100644--- a/src/services/git/git.h+++ b/src/services/git/git.h@@ -142,7 +142,7 @@ const char *gt_arg_str(const struct janas_json *args, const char *name);int gt_arg_bool(const struct janas_json *args, const char *name);/* The text as the tool's result, an error when is_error */int gt_fail(struct janas_buf *b, const char *fmt, ...)- __attribute__((format(printf, 2, 3)));+ __attribute__((format(gnu_printf, 2, 3)));int gt_answer(struct janas_buf *b, const char *name, struct janas_buf *d,const char *layout, const char *brief);/* A text git takes as an argument and never as an option: not empty, notdiff --git a/src/services/github/fetch.c b/src/services/github/fetch.cindex face1ff..1154626 100644--- a/src/services/github/fetch.c+++ b/src/services/github/fetch.c@@ -59,7 +59,11 @@ int gh_token_kind(void)kind = 0;if (take(getenv("GH_TOKEN"), 1) || take(getenv("GITHUB_TOKEN"), 1))return kind;+#ifdef _WIN32+ FILE *p = popen("gh auth token 2>NUL", "r"); /* through cmd.exe */+#elseFILE *p = popen("gh auth token 2>/dev/null", "r");+#endifif (p) {char line[512] = "";if (!fgets(line, sizeof line, p))diff --git a/src/services/maps/data.c b/src/services/maps/data.cindex f127d39..a0135a6 100644--- a/src/services/maps/data.c+++ b/src/services/maps/data.c@@ -12,6 +12,7 @@#include <string.h>#include <time.h>+#include "services/common/tz.h"#include "services/common/geo.h"#include "maps.h"@@ -70,14 +71,10 @@ static void jdist(struct janas_buf *b, double km)void mp_jclock(struct janas_buf *b, const char *key, time_t t, const char *tz){- char *old = getenv("TZ") ? strdup(getenv("TZ")) : NULL;- if (tz && *tz)- setenv("TZ", tz, 1);- tzset();struct tm lt, nt;time_t now = time(NULL);- localtime_r(&t, <);- localtime_r(&now, &nt);+ janas_tz_local(tz, t, <, NULL, 0);+ janas_tz_local(tz, now, &nt, NULL, 0);janas_buf_printf(b, ", \"%s\": {\"at\": \"%02d:%02d\"", key, lt.tm_hour,lt.tm_min);if (lt.tm_yday != nt.tm_yday || lt.tm_year != nt.tm_year)@@ -86,14 +83,6 @@ void mp_jclock(struct janas_buf *b, const char *key, time_t t, const char *tz)"\"mon\": %d",lt.tm_wday, lt.tm_mday, lt.tm_mon + 1);janas_buf_puts(b, "}");- if (tz && *tz) {- if (old)- setenv("TZ", old, 1);- else- unsetenv("TZ");- tzset();- }- free(old);}/* An object whose members are written as ", key: value": open it, anddiff --git a/src/services/maps/transit.c b/src/services/maps/transit.cindex 13574f2..ee95079 100644--- a/src/services/maps/transit.c+++ b/src/services/maps/transit.c@@ -13,6 +13,7 @@#include <string.h>#include <time.h>+#include "services/common/tz.h"#include "services/common/geo.h"#include "maps.h"@@ -41,12 +42,8 @@ static time_t local_time(const char *s, const char *tz)return -1;if (h < 0 || h > 23 || mi < 0 || mi > 59)return -1;- char *old = getenv("TZ") ? strdup(getenv("TZ")) : NULL;- if (tz && *tz)- setenv("TZ", tz, 1);- tzset();time_t now = time(NULL);- localtime_r(&now, &tm);+ janas_tz_local(tz, now, &tm, NULL, 0);if (whole) {tm.tm_year = y - 1900;tm.tm_mon = mo - 1;@@ -56,20 +53,12 @@ static time_t local_time(const char *s, const char *tz)tm.tm_min = mi;tm.tm_sec = 0;tm.tm_isdst = -1;- time_t t = mktime(&tm);+ time_t t = janas_tz_mktime(tz, &tm);if (!whole && t != -1 && t < now - 600) {tm.tm_mday++;tm.tm_isdst = -1;- t = mktime(&tm);+ t = janas_tz_mktime(tz, &tm);}- if (tz && *tz) {- if (old)- setenv("TZ", old, 1);- else- unsetenv("TZ");- tzset();- }- free(old);return t;}diff --git a/src/services/prices/prices.h b/src/services/prices/prices.hindex 934288a..6dfcfc1 100644--- a/src/services/prices/prices.h+++ b/src/services/prices/prices.h@@ -224,7 +224,7 @@ int pr_tools_call(void *ctx, const struct janas_json *params,const char *pr_arg_str(const struct janas_json *args, const char *name);double pr_arg_num(const struct janas_json *args, const char *name, double def);int pr_fail(struct janas_buf *b, const char *fmt, ...)- __attribute__((format(printf, 2, 3)));+ __attribute__((format(gnu_printf, 2, 3)));int pr_answer(struct janas_buf *b, const char *name, struct janas_buf *d,const char *layout, const char *brief);int pr_tool_currency(const struct janas_json *args, struct janas_buf *b);diff --git a/src/services/prices/read.c b/src/services/prices/read.cindex 04b96d5..f0b59b2 100644--- a/src/services/prices/read.c+++ b/src/services/prices/read.c@@ -18,6 +18,7 @@#include <time.h>#include "prices.h"+#include "services/common/tz.h"static void copy(char *to, size_t cap, const char *s){@@ -540,28 +541,16 @@ int pr_read_power(const char *t, size_t n, const char *tz, struct pr_series *s,int open = strstr(licence, "CC BY") != NULL;const struct janas_json *ts = janas_json_get(o, "unix_seconds");const struct janas_json *pr = janas_json_get(o, "price");- char *old = getenv("TZ") ? strdup(getenv("TZ")) : NULL;- if (tz && *tz)- setenv("TZ", tz, 1);- tzset();const struct janas_json *x = ts ? ts->child : NULL;const struct janas_json *y = pr ? pr->child : NULL;for (; open && x && y; x = x->next, y = y->next) {time_t at = (time_t)janas_json_num(x, 0);struct tm lt;- localtime_r(&at, <);+ janas_tz_local(tz, at, <, NULL, 0);char when[24];strftime(when, sizeof when, "%Y-%m-%d %H:%M", <);add(s, when, janas_json_num(y, NAN));}- if (tz && *tz) {- if (old)- setenv("TZ", old, 1);- else- unsetenv("TZ");- tzset();- }- free(old);janas_json_free(d);if (!licence[0] || (open && !s->n)) {snprintf(err, err_len, "energy-charts: no prices");diff --git a/src/services/quakes/tools.c b/src/services/quakes/tools.cindex e7ba21f..2bd1189 100644--- a/src/services/quakes/tools.c+++ b/src/services/quakes/tools.c@@ -69,7 +69,7 @@ static double arg_num(const struct janas_json *args, const char *name,}static int fail(struct janas_buf *b, const char *fmt, ...)- __attribute__((format(printf, 2, 3)));+ __attribute__((format(gnu_printf, 2, 3)));static int fail(struct janas_buf *b, const char *fmt, ...){diff --git a/src/services/system/read.c b/src/services/system/read.cindex b716660..03b1904 100644--- a/src/services/system/read.c+++ b/src/services/system/read.c@@ -265,11 +265,18 @@ void sy_err_add(struct sy_errors *e, long long at, const char *who,sy_put(x->text, sizeof x->text, t);}+/* The latest first; in the same second the one seen more often, then by+ name and words: an order qsort cannot leave to chance (it is not+ stable, and two C libraries leave equal ones in different orders). */static int later_first(const void *a, const void *b){- long long x = ((const struct sy_err *)a)->at,- y = ((const struct sy_err *)b)->at;- return x < y ? 1 : x > y ? -1 : 0;+ const struct sy_err *p = a, *q = b;+ if (p->at != q->at)+ return p->at < q->at ? 1 : -1;+ if (p->count != q->count)+ return p->count < q->count ? 1 : -1;+ int c = strcmp(p->who, q->who);+ return c ? c : strcmp(p->text, q->text);}void sy_err_order(struct sy_errors *e)diff --git a/src/services/system/tools.c b/src/services/system/tools.cindex 57bca48..77051bd 100644--- a/src/services/system/tools.c+++ b/src/services/system/tools.c@@ -66,7 +66,7 @@ static const char *arg_str(const struct janas_json *args, const char *name)}static int fail(struct janas_buf *b, const char *fmt, ...)- __attribute__((format(printf, 2, 3)));+ __attribute__((format(gnu_printf, 2, 3)));static int fail(struct janas_buf *b, const char *fmt, ...){diff --git a/src/services/weather/alerts.c b/src/services/weather/alerts.cindex 330148c..967398e 100644--- a/src/services/weather/alerts.c+++ b/src/services/weather/alerts.c@@ -21,6 +21,7 @@#include <time.h>#include "weather.h"+#include "services/common/tz.h"#define KEEP_ALARM 900 /* MeteoAlarm's feed */#define KEEP_LATEST 1800 /* which bulletin is the latest */@@ -472,30 +473,24 @@ int wx_dpc(const struct wx_place *p, struct wx_dpc *d, char *err,char bday[11];snprintf(bday, sizeof bday, "%.4s-%.2s-%.2s", d->issued, d->issued + 4,d->issued + 6);- char *old = getenv("TZ") ? strdup(getenv("TZ")) : NULL;- setenv("TZ", "Europe/Rome", 1);- tzset();+ static const char *const IT = "Europe/Rome";time_t now = time(NULL), tom_t = now + 24 * 3600;char today[11], tomorrow[11];struct tm lt;- strftime(today, sizeof today, "%Y-%m-%d", localtime_r(&now, <));- strftime(tomorrow, sizeof tomorrow, "%Y-%m-%d", localtime_r(&tom_t, <));+ janas_tz_local(IT, now, <, NULL, 0);+ strftime(today, sizeof today, "%Y-%m-%d", <);+ janas_tz_local(IT, tom_t, <, NULL, 0);+ strftime(tomorrow, sizeof tomorrow, "%Y-%m-%d", <);struct tm bt = {0};sscanf(bday, "%d-%d-%d", &bt.tm_year, &bt.tm_mon, &bt.tm_mday);bt.tm_year -= 1900;bt.tm_mon -= 1;bt.tm_hour = 12;bt.tm_isdst = -1;- time_t bnext_t = mktime(&bt) + 24 * 3600;+ time_t bnext_t = janas_tz_mktime(IT, &bt) + 24 * 3600;char bnext[11];- strftime(bnext, sizeof bnext, "%Y-%m-%d", localtime_r(&bnext_t, <));- if (old) {- setenv("TZ", old, 1);- free(old);- } else {- unsetenv("TZ");- }- tzset();+ janas_tz_local(IT, bnext_t, <, NULL, 0);+ strftime(bnext, sizeof bnext, "%Y-%m-%d", <);/* the bulletin's today and tomorrow, as far as they are still ahead:yesterday's bulletin's tomorrow is today */static const char *const which[2] = {"today", "tomorrow"};diff --git a/src/services/weather/metno.c b/src/services/weather/metno.cindex 1bc155d..bdece4b 100644--- a/src/services/weather/metno.c+++ b/src/services/weather/metno.c@@ -16,6 +16,7 @@#include <time.h>#include "weather.h"+#include "services/common/tz.h"#define MET_KEEP_S 900@@ -87,16 +88,14 @@ int wx_met_parse(const char *text, size_t n, const char *tz,snprintf(f->tz, sizeof f->tz, "%s", tz && *tz ? tz : "UTC");/* the series is put into the place's zone */- char *old = getenv("TZ") ? strdup(getenv("TZ")) : NULL;- setenv("TZ", f->tz, 1);- tzset();time_t prev_day_t = 0;for (const struct janas_json *e = ts->child; e; e = e->next) {time_t t = utc_of(janas_json_str(janas_json_get(e, "time")));if (t == (time_t)-1)continue;struct tm lt;- localtime_r(&t, <);+ char abbr[16];+ janas_tz_local(f->tz, t, <, abbr, sizeof abbr);const struct janas_json *data = janas_json_get(e, "data");const struct janas_json *in =janas_json_get(janas_json_get(data, "instant"), "details");@@ -125,7 +124,7 @@ int wx_met_parse(const char *text, size_t n, const char *tz,w->code = -1;symbol_of(n1 ? n1 : n6, w->symbol, sizeof w->symbol);f->has_now = 1;- snprintf(f->tz_abbr, sizeof f->tz_abbr, "%s", lt.tm_zone);+ snprintf(f->tz_abbr, sizeof f->tz_abbr, "%s", abbr);}if (n1 && f->n_hour < WX_HOURS) {struct wx_hour *h = &f->hour[f->n_hour++];@@ -174,13 +173,6 @@ int wx_met_parse(const char *text, size_t n, const char *tz,if (!y->symbol[0] && n12 && lt.tm_hour >= 6)symbol_of(n12, y->symbol, sizeof y->symbol);}- if (old) {- setenv("TZ", old, 1);- free(old);- } else {- unsetenv("TZ");- }- tzset();janas_json_free(d);return 0;}diff --git a/src/services/weather/tools.c b/src/services/weather/tools.cindex 5b6b45b..df9a931 100644--- a/src/services/weather/tools.c+++ b/src/services/weather/tools.c@@ -14,6 +14,7 @@#include <time.h>#include "services/common/locate.h"+#include "services/common/tz.h"#include "common/mcp_server.h"#include "weather.h"@@ -186,29 +187,29 @@ int wx_arg_place(const struct janas_json *args, struct wx_place *p,return -1;}+/* "Monday 5 October" after lead: the day without a leading zero, which+ only glibc's strftime writes (%-d) */+static void day_text(char *out, size_t cap, const char *lead,+ const struct tm *t)+{+ char wd[16], mon[16];+ strftime(wd, sizeof wd, "%A", t);+ strftime(mon, sizeof mon, "%B", t);+ snprintf(out, cap, "%s%s %d %s", lead, wd, t->tm_mday, mon);+}+void wx_local_time(time_t t, const char *tz, char *out, size_t cap){- char *old = getenv("TZ") ? strdup(getenv("TZ")) : NULL;- if (tz && *tz)- setenv("TZ", tz, 1);- tzset();struct tm lt, nt;+ char abbr[16];time_t now = time(NULL);- localtime_r(&t, <);- localtime_r(&now, &nt);- char hm[16], day[32] = "";+ janas_tz_local(tz, t, <, abbr, sizeof abbr);+ janas_tz_local(tz, now, &nt, NULL, 0);+ char hm[16], day[48] = "";strftime(hm, sizeof hm, "%H:%M", <);if (lt.tm_yday != nt.tm_yday || lt.tm_year != nt.tm_year)- strftime(day, sizeof day, " on %A %-d %B", <);- snprintf(out, cap, "%s%s %s", hm, day, lt.tm_zone ? lt.tm_zone : "");- if (tz && *tz) {- if (old)- setenv("TZ", old, 1);- else- unsetenv("TZ");- tzset();- }- free(old);+ day_text(day, sizeof day, " on ", <);+ snprintf(out, cap, "%s%s %s", hm, day, abbr);}void wx_day_name(const char *date, char *out, size_t cap)@@ -224,7 +225,7 @@ void wx_day_name(const char *date, char *out, size_t cap)time_t t = timegm(&tm);struct tm g;gmtime_r(&t, &g);- strftime(out, cap, "%A %-d %B", &g);+ day_text(out, cap, "", &g);}void wx_place_name(const struct wx_place *p, char *out, size_t cap)diff --git a/src/third_party/libmicrohttpd/origin.md b/src/third_party/libmicrohttpd/origin.mdindex 5279228..a3840c8 100644--- a/src/third_party/libmicrohttpd/origin.md+++ b/src/third_party/libmicrohttpd/origin.md@@ -27,6 +27,11 @@ Linux x86_64 (glibc) with--disable-curl --with-threads=posix --disable-shared```+`w32/MHD_config.h`, for Windows builds, is the one the same `configure`+wrote on 11 October 2026 for `--host=x86_64-w64-mingw32` (MinGW-w64, GCC+14), with the same options but `--with-threads`, which it chose itself:+Windows's own threads. It compiles the same 14 sources.+`build.sh` compiles the sources with `-D_GNU_SOURCE -DHAVE_CONFIG_H` andwithout Janas's warning flags: warnings in code that is not Janas's are notJanas's to fix here.diff --git a/src/third_party/libmicrohttpd/w32/MHD_config.h b/src/third_party/libmicrohttpd/w32/MHD_config.hnew file mode 100644index 0000000..3114245--- /dev/null+++ b/src/third_party/libmicrohttpd/w32/MHD_config.h@@ -0,0 +1,842 @@+/* MHD_config.h. Generated from MHD_config.h.in by configure. */+/* MHD_config.h.in. Generated from configure.ac by autoheader. */++/* Define if building universal (internal helper macro) */+/* #undef AC_APPLE_UNIVERSAL_BUILD */++/* Define to 1 if libmicrohttpd is compiled with Basic Auth support. */+/* #undef BAUTH_SUPPORT */++/* Define to 1 if libmicrohttpd is compiled with HTTP cookie parsing support.+ */+/* #undef COOKIE_SUPPORT */++/* This is a Cygwin system */+/* #undef CYGWIN */++/* Define to 1 if libmicrohttpd is compiled with Digest Auth support. */+/* #undef DAUTH_SUPPORT */++/* Define to 1 to enable epoll support */+/* #undef EPOLL_SUPPORT */++/* This is a FreeBSD system */+/* #undef FREEBSD */++/* Define to '1' if '__attribute__((no_sanitize("address")))' works for+ pointers compare */+/* #undef FUNC_ATTR_NOSANITIZE_WORKS */++/* Define to '1' if '__attribute__((no_sanitize("pointer-compare")))' works */+/* #undef FUNC_ATTR_PTRCOMPARE_WORKS */++/* Define to '1' if '__attribute__((no_sanitize("pointer-subtract")))' works+ */+/* #undef FUNC_ATTR_PTRSUBTRACT_WORKS */++/* Define to '1' if cast to 'uintptr_t' works for safely processing+ user-poisoned pointer */+/* #undef FUNC_PTRCOMPARE_CAST_WORKAROUND_WORKS */++/* Define to `1' if host machine runs on GNU Hurd. */+/* #undef GNU_HURD */++/* Define to 1 if your system allow overriding the value of FD_SETSIZE macro+ */+#define HAS_FD_SETSIZE_OVERRIDABLE 1++/* Define to 1 if your socket type is signed */+/* #undef HAS_SIGNED_SOCKET */++/* Define to 1 if you have the 'accept4' function. */+/* #undef HAVE_ACCEPT4 */++/* Define to 1 if you have the <arpa/inet.h> header file. */+/* #undef HAVE_ARPA_INET_H */++/* Define if you have usable assert() and assert.h */+/* #undef HAVE_ASSERT */++/* Define to 1 if you have the boolean type that takes only 'true' and+ 'false'. */+#define HAVE_BUILTIN_TYPE_BOOL 1++/* Define to 1 if you have the `gmtime_s' function in C11 form. */+/* #undef HAVE_C11_GMTIME_S */++/* Define to 1 if you have the usable `calloc' function. */+#define HAVE_CALLOC 1++/* Define to '1' if you have clock_gettime() function */+/* #undef HAVE_CLOCK_GETTIME */++/* Define to 1 if you have the 'clock_get_time' function. */+/* #undef HAVE_CLOCK_GET_TIME */++/* Define to 1 if you have the 'cpuset_getaffinity' function. */+/* #undef HAVE_CPUSET_GETAFFINITY */++/* Define to 1 if you have the 'CPU_COUNT' function. */+/* #undef HAVE_CPU_COUNT */++/* Define to 1 if you have the 'CPU_COUNT_S' function. */+/* #undef HAVE_CPU_COUNT_S */++/* Define to 1 if your compiler supports 'alignof()' */+#define HAVE_C_ALIGNOF 1++/* Define to 1 if C supports variable-length arrays. */+#define HAVE_C_VARARRAYS 1++/* Define to 1 if you have Darwin-style sendfile(2). */+/* #undef HAVE_DARWIN_SENDFILE */++/* Define to 1 if you have the declaration of 'CPU_SETSIZE', and to 0 if you+ don't. */+/* #undef HAVE_DECL_CPU_SETSIZE */++/* Define to 1 if you have the declaration of 'CTL_HW', and to 0 if you don't.+ */+/* #undef HAVE_DECL_CTL_HW */++/* Define to 1 if you have the declaration of 'CTL_NET', and to 0 if you+ don't. */+/* #undef HAVE_DECL_CTL_NET */++/* Define to 1 if you have the declaration of 'HW_AVAILCPU', and to 0 if you+ don't. */+/* #undef HAVE_DECL_HW_AVAILCPU */++/* Define to 1 if you have the declaration of 'HW_NCPU', and to 0 if you+ don't. */+/* #undef HAVE_DECL_HW_NCPU */++/* Define to 1 if you have the declaration of 'HW_NCPUONLINE', and to 0 if you+ don't. */+/* #undef HAVE_DECL_HW_NCPUONLINE */++/* Define to 1 if you have the declaration of 'ICMPCTL_ICMPLIM', and to 0 if+ you don't. */+/* #undef HAVE_DECL_ICMPCTL_ICMPLIM */++/* Define to 1 if you have the declaration of 'IPPROTO_ICMP', and to 0 if you+ don't. */+/* #undef HAVE_DECL_IPPROTO_ICMP */++/* Define to 1 if you have the declaration of 'PF_INET', and to 0 if you+ don't. */+/* #undef HAVE_DECL_PF_INET */++/* Define to 1 if you have the declaration of '_SC_CRAY_NCPU', and to 0 if you+ don't. */+/* #undef HAVE_DECL__SC_CRAY_NCPU */++/* Define to 1 if you have the declaration of '_SC_NPROCESSORS_CONF', and to 0+ if you don't. */+/* #undef HAVE_DECL__SC_NPROCESSORS_CONF */++/* Define to 1 if you have the declaration of '_SC_NPROCESSORS_ONLN', and to 0+ if you don't. */+/* #undef HAVE_DECL__SC_NPROCESSORS_ONLN */++/* Define to 1 if you have the declaration of '_SC_NPROC_ONLN', and to 0 if+ you don't. */+/* #undef HAVE_DECL__SC_NPROC_ONLN */++/* Define to 1 if you have the <dlfcn.h> header file. */+/* #undef HAVE_DLFCN_H */++/* Define to 1 if you have the <endian.h> header file. */+/* #undef HAVE_ENDIAN_H */++/* Define to 1 if you have the 'epoll_create1' function. */+/* #undef HAVE_EPOLL_CREATE1 */++/* Define to 1 if you have the <errno.h> header file. */+#define HAVE_ERRNO_H 1++/* Define to 1 if you have the <fcntl.h> header file. */+#define HAVE_FCNTL_H 1++/* Define to 1 if you have the <features.h> header file. */+/* #undef HAVE_FEATURES_H */++/* Define to 1 if you have the usable `fork' function. */+/* #undef HAVE_FORK */++/* Define to 1 if you have FreeBSD-style sendfile(2). */+/* #undef HAVE_FREEBSD_SENDFILE */++/* Define to 1 if fseeko (and ftello) are declared in stdio.h. */+#define HAVE_FSEEKO 1++/* Define to 1 if you have the <gcrypt.h> header file. */+/* #undef HAVE_GCRYPT_H */++/* Define to 1 if you have the 'gethrtime' function. */+/* #undef HAVE_GETHRTIME */++/* Define to 1 if you have the 'getpid' function. */+/* #undef HAVE_GETPID */++/* Define to 1 if you have the 'gettimeofday' function. */+#define HAVE_GETTIMEOFDAY 1++/* Define to 1 if you have the 'gmtime_r' function. */+/* #undef HAVE_GMTIME_R */++/* Define to 1 if you have the 'gnutls_check_version' function. */+/* #undef HAVE_GNUTLS_CHECK_VERSION */++/* Define to 1 if you have the <gnutls/gnutls.h> header file. */+/* #undef HAVE_GNUTLS_GNUTLS_H */++/* Define to '1' if you have IPv6 headers */+#define HAVE_INET6 1++/* Define to 1 if you have the <inetLib.h> header file. */+/* #undef HAVE_INETLIB_H */++/* Define to 1 if your C compiler supports inline functions. */+#define HAVE_INLINE_FUNCS 1++/* Define to 1 if you have the <inttypes.h> header file. */+#define HAVE_INTTYPES_H 1++/* Define to 1 if you have the <jansson.h> header file. */+/* #undef HAVE_JANSSON_H */++/* Define to 1 if you have a functional curl library. */+/* #undef HAVE_LIBCURL */++/* Define to 1 if you have the <limits.h> header file. */+#define HAVE_LIMITS_H 1++/* Define to 1 if you have linux-style sendfile(2). */+/* #undef HAVE_LINUX_SENDFILE */++/* can use shutdown on listen sockets */+/* #undef HAVE_LISTEN_SHUTDOWN */++/* Define to 1 if you have the 'lseek64' function. */+#define HAVE_LSEEK64 1++/* Define to 1 if you have the <machine/endian.h> header file. */+/* #undef HAVE_MACHINE_ENDIAN_H */++/* Define to 1 if you have the <machine/param.h> header file. */+/* #undef HAVE_MACHINE_PARAM_H */++/* Define to 1 if you have the 'magic_open' function. */+/* #undef HAVE_MAGIC_OPEN */++/* Define to 1 if you have the 'memmem' function. */+/* #undef HAVE_MEMMEM */++/* Define to 1 to enable support for text messages. */+#define HAVE_MESSAGES 1++/* Define to 1 if you have the 'nanosleep' function. */+/* #undef HAVE_NANOSLEEP */++/* Define to 1 if you have the <netdb.h> header file. */+/* #undef HAVE_NETDB_H */++/* Define to 1 if you have the <netinet/icmp_var.h> header file. */+/* #undef HAVE_NETINET_ICMP_VAR_H */++/* Define to 1 if you have the <netinet/in.h> header file. */+/* #undef HAVE_NETINET_IN_H */++/* Define to 1 if you have the <netinet/in_systm.h> header file. */+/* #undef HAVE_NETINET_IN_SYSTM_H */++/* Define to 1 if you have the <netinet/ip.h> header file. */+/* #undef HAVE_NETINET_IP_H */++/* Define to 1 if you have the <netinet/ip_icmp.h> header file. */+/* #undef HAVE_NETINET_IP_ICMP_H */++/* Define to 1 if you have the <netinet/tcp.h> header file. */+/* #undef HAVE_NETINET_TCP_H */++/* Define to 1 if you have the <net/if.h> header file. */+/* #undef HAVE_NET_IF_H */++/* Define if you have usable pipe2(2) function */+/* #undef HAVE_PIPE2_FUNC */++/* Define to 1 if you have the 'poll' function. */+#define HAVE_POLL 1++/* Define to 1 if you have the <poll.h> header file. */+/* #undef HAVE_POLL_H */++/* Define to 1 if libmicrohttpd is compiled with postprocessor support. */+/* #undef HAVE_POSTPROCESSOR */++/* Define to 1 if you have the 'pread' function. */+/* #undef HAVE_PREAD */++/* Define to 1 if you have the 'pread64' function. */+/* #undef HAVE_PREAD64 */++/* Define to 1 if you have the 'pstat_getdynamic' function. */+/* #undef HAVE_PSTAT_GETDYNAMIC */++/* Define if you have IBM i form (or Solaris form) of+ pthread_attr_setname_np(3) function. */+/* #undef HAVE_PTHREAD_ATTR_SETNAME_NP_IBMI */++/* Define if you have NetBSD form (or OSF1 form) of pthread_attr_setname_np(3)+ function. */+/* #undef HAVE_PTHREAD_ATTR_SETNAME_NP_NETBSD */++/* Define to 1 if you have the <pthread.h> header file. */+#define HAVE_PTHREAD_H 1++/* Define to 1 if you have the <pthread_np.h> header file. */+/* #undef HAVE_PTHREAD_NP_H */++/* Have PTHREAD_PRIO_INHERIT. */+#define HAVE_PTHREAD_PRIO_INHERIT 1++/* Define if you have Darwin form of pthread_setname_np(3) function. */+/* #undef HAVE_PTHREAD_SETNAME_NP_DARWIN */++/* Define if you have GNU/Linux form of pthread_setname_np(3) function. */+/* #undef HAVE_PTHREAD_SETNAME_NP_GNU */++/* Define if you have NetBSD form (or OSF1 form) of pthread_setname_np(3)+ function. */+/* #undef HAVE_PTHREAD_SETNAME_NP_NETBSD */++/* Define if you have FreeBSD form of pthread_set_name_np(3) function. */+/* #undef HAVE_PTHREAD_SET_NAME_NP_FREEBSD */++/* Define to 1 if you have the pthread_sigmask(3) function. */+/* #undef HAVE_PTHREAD_SIGMASK */++/* Define to 1 if you have the 'rand' function. */+#define HAVE_RAND 1++/* Define to 1 if you have the 'random' function. */+/* #undef HAVE_RANDOM */++/* Define to 1 if you have the <sanitizer/asan_interface.h> header file. */+/* #undef HAVE_SANITIZER_ASAN_INTERFACE_H */++/* Define to 1 if you have the 'sched_getaffinity' function. */+/* #undef HAVE_SCHED_GETAFFINITY */++/* Define to 1 if you have the 'sched_getaffinity_np' function. */+/* #undef HAVE_SCHED_GETAFFINITY_NP */++/* Define to 1 if you have the <sched.h> header file. */+/* #undef HAVE_SCHED_H */++/* Define to 1 if you have the <sdkddkver.h> header file. */+#define HAVE_SDKDDKVER_H 1++/* Define to 1 if you have the 'sendfile64' function. */+/* #undef HAVE_SENDFILE64 */++/* Define to '1' if your have sendmsg() function */+/* #undef HAVE_SENDMSG */++/* Define to 1 if you have the <signal.h> header file. */+#define HAVE_SIGNAL_H 1++/* Define to 1 if you have the 'snprintf' function. */+#define HAVE_SNPRINTF 1++/* Define to 1 if you have the <sockLib.h> header file. */+/* #undef HAVE_SOCKLIB_H */++/* SOCK_NONBLOCK is defined in a socket header */+/* #undef HAVE_SOCK_NONBLOCK */++/* Define to 1 if you have Solaris-style sendfile(3). */+/* #undef HAVE_SOLARIS_SENDFILE */++/* Define to 1 if you have the <stdalign.h> header file. */+#define HAVE_STDALIGN_H 1++/* Define to 1 if you have the <stdbool.h> header file and <stdbool.h> is+ required to use 'bool' type. */+#define HAVE_STDBOOL_H 1++/* Define to 1 if you have the <stddef.h> header file. */+#define HAVE_STDDEF_H 1++/* Define to 1 if you have the <stdint.h> header file. */+#define HAVE_STDINT_H 1++/* Define to 1 if you have the <stdio.h> header file. */+#define HAVE_STDIO_H 1++/* Define to 1 if you have the <stdlib.h> header file. */+#define HAVE_STDLIB_H 1++/* Define to 1 if you have the <strings.h> header file. */+#define HAVE_STRINGS_H 1++/* Define to 1 if you have the <string.h> header file. */+#define HAVE_STRING_H 1++/* Define to 1 if 'sin6_len' is a member of 'struct sockaddr_in6'. */+/* #undef HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN */++/* Define to 1 if 'sin_len' is a member of 'struct sockaddr_in'. */+/* #undef HAVE_STRUCT_SOCKADDR_IN_SIN_LEN */++/* Define to 1 if 'sa_len' is a member of 'struct sockaddr'. */+/* #undef HAVE_STRUCT_SOCKADDR_SA_LEN */++/* Define to 1 if 'ss_len' is a member of 'struct sockaddr_storage'. */+/* #undef HAVE_STRUCT_SOCKADDR_STORAGE_SS_LEN */++/* Define to 1 if you have the 'sysconf' function. */+/* #undef HAVE_SYSCONF */++/* Define to 1 if you have the 'sysctl' function. */+/* #undef HAVE_SYSCTL */++/* Define to 1 if you have the 'sysctlbyname' function. */+/* #undef HAVE_SYSCTLBYNAME */++/* Define to 1 if you have the <sys/byteorder.h> header file. */+/* #undef HAVE_SYS_BYTEORDER_H */++/* Define to 1 if you have the <sys/cpuset.h> header file. */+/* #undef HAVE_SYS_CPUSET_H */++/* Define to 1 if you have the <sys/endian.h> header file. */+/* #undef HAVE_SYS_ENDIAN_H */++/* Define to 1 if you have the <sys/ioctl.h> header file. */+/* #undef HAVE_SYS_IOCTL_H */++/* Define to 1 if you have the <sys/isa_defs.h> header file. */+/* #undef HAVE_SYS_ISA_DEFS_H */++/* Define to 1 if you have the <sys/machine.h> header file. */+/* #undef HAVE_SYS_MACHINE_H */++/* Define to 1 if you have the <sys/mman.h> header file. */+/* #undef HAVE_SYS_MMAN_H */++/* Define to 1 if you have the <sys/msg.h> header file. */+/* #undef HAVE_SYS_MSG_H */++/* Define to 1 if you have the <sys/param.h> header file. */+#define HAVE_SYS_PARAM_H 1++/* Define to 1 if you have the <sys/pstat.h> header file. */+/* #undef HAVE_SYS_PSTAT_H */++/* Define to 1 if you have the <sys/select.h> header file. */+/* #undef HAVE_SYS_SELECT_H */++/* Define to 1 if you have the <sys/socket.h> header file. */+/* #undef HAVE_SYS_SOCKET_H */++/* Define to 1 if you have the <sys/stat.h> header file. */+#define HAVE_SYS_STAT_H 1++/* Define to 1 if you have the <sys/sysctl.h> header file. */+/* #undef HAVE_SYS_SYSCTL_H */++/* Define to 1 if you have the <sys/time.h> header file. */+#define HAVE_SYS_TIME_H 1++/* Define to 1 if you have the <sys/types.h> header file. */+#define HAVE_SYS_TYPES_H 1++/* Define to 1 if you have the <sys/uio.h> header file. */+/* #undef HAVE_SYS_UIO_H */++/* Define to 1 if you have the <sys/_cpuset.h> header file. */+/* #undef HAVE_SYS__CPUSET_H */++/* Define to 1 if you have the 'timespec_get' function. */+/* #undef HAVE_TIMESPEC_GET */++/* Define to 1 if you have the <time.h> header file. */+#define HAVE_TIME_H 1++/* Define to 1 if you have the <unistd.h> header file. */+#define HAVE_UNISTD_H 1++/* Define to 1 if you have the 'usleep' function. */+#define HAVE_USLEEP 1++/* Define to 1 if you have the 'vxCpuEnabledGet' function. */+/* #undef HAVE_VXCPUENABLEDGET */++/* Define to 1 if you have the <vxCpuLib.h> header file. */+/* #undef HAVE_VXCPULIB_H */++/* Define to 1 if you have the `gmtime_s' function in W32 form. */+#define HAVE_W32_GMTIME_S 1++/* Define to 1 if you have the usable `waitpid' function. */+/* #undef HAVE_WAITPID */++/* Define to 1 if you have the <windows.h> header file. */+#define HAVE_WINDOWS_H 1++/* Define to 1 if you have the <winsock2.h> header file. */+#define HAVE_WINSOCK2_H 1++/* Define to 1 if you have the 'writev' function. */+/* #undef HAVE_WRITEV */++/* Define to 1 if you have the <ws2tcpip.h> header file. */+#define HAVE_WS2TCPIP_H 1++/* Define to 1 if you have the 'WSAPoll' function. */+#define HAVE_WSAPOLL 1++/* Define to 1 if you have the <zlib.h> header file. */+/* #undef HAVE_ZLIB_H */++/* Define to 1 if you have the '__asan_address_is_poisoned' function. */+/* #undef HAVE___ASAN_ADDRESS_IS_POISONED */++/* Define to 1 if you have the '__asan_region_is_poisoned' function. */+/* #undef HAVE___ASAN_REGION_IS_POISONED */++/* Define to 1 if your compiler supports __FUNCTION__ magic-macro. */+/* #undef HAVE___FUNCTION__ */++/* Define to 1 if your compiler supports __func__ magic-macro. */+#define HAVE___FUNC__ 1++/* Define to 1 if your compiler supports __PRETTY_FUNCTION__ magic-macro. */+/* #undef HAVE___PRETTY_FUNCTION__ */++/* Define to 1 if libmicrohttpd is compiled with HTTPS support. */+/* #undef HTTPS_SUPPORT */++/* Defined if libcurl supports AsynchDNS */+/* #undef LIBCURL_FEATURE_ASYNCHDNS */++/* Defined if libcurl supports IDN */+/* #undef LIBCURL_FEATURE_IDN */++/* Defined if libcurl supports IPv6 */+/* #undef LIBCURL_FEATURE_IPV6 */++/* Defined if libcurl supports KRB4 */+/* #undef LIBCURL_FEATURE_KRB4 */++/* Defined if libcurl supports libz */+/* #undef LIBCURL_FEATURE_LIBZ */++/* Defined if libcurl supports NTLM */+/* #undef LIBCURL_FEATURE_NTLM */++/* Defined if libcurl supports SSL */+/* #undef LIBCURL_FEATURE_SSL */++/* Defined if libcurl supports SSPI */+/* #undef LIBCURL_FEATURE_SSPI */++/* Defined if libcurl supports DICT */+/* #undef LIBCURL_PROTOCOL_DICT */++/* Defined if libcurl supports FILE */+/* #undef LIBCURL_PROTOCOL_FILE */++/* Defined if libcurl supports FTP */+/* #undef LIBCURL_PROTOCOL_FTP */++/* Defined if libcurl supports FTPS */+/* #undef LIBCURL_PROTOCOL_FTPS */++/* Defined if libcurl supports HTTP */+/* #undef LIBCURL_PROTOCOL_HTTP */++/* Defined if libcurl supports HTTPS */+/* #undef LIBCURL_PROTOCOL_HTTPS */++/* Defined if libcurl supports IMAP */+/* #undef LIBCURL_PROTOCOL_IMAP */++/* Defined if libcurl supports LDAP */+/* #undef LIBCURL_PROTOCOL_LDAP */++/* Defined if libcurl supports POP3 */+/* #undef LIBCURL_PROTOCOL_POP3 */++/* Defined if libcurl supports RTSP */+/* #undef LIBCURL_PROTOCOL_RTSP */++/* Defined if libcurl supports SMTP */+/* #undef LIBCURL_PROTOCOL_SMTP */++/* Defined if libcurl supports TELNET */+/* #undef LIBCURL_PROTOCOL_TELNET */++/* Defined if libcurl supports TFTP */+/* #undef LIBCURL_PROTOCOL_TFTP */++/* This is a Linux kernel */+/* #undef LINUX */++/* Define to the sub-directory where libtool stores uninstalled libraries. */+#define LT_OBJDIR ".libs/"++/* Define to '1' if you have address sanitizer enabled */+/* #undef MHD_ASAN_ACTIVE */++/* Define to '1' if user memory poison is used */+/* #undef MHD_ASAN_POISON_ACTIVE */++/* The default HTTP Digest Auth default maximum nc (nonce count) value */+/* #undef MHD_DAUTH_DEF_MAX_NC_ */++/* The default HTTP Digest Auth default nonce timeout value (in seconds) */+/* #undef MHD_DAUTH_DEF_TIMEOUT_ */++/* Define to '1' to use fast (and larger) code version */+#define MHD_FAVOR_FAST_CODE 1++/* Define to '1' to use compact code version */+/* #undef MHD_FAVOR_SMALL_CODE */++/* Define to '1' if CPU_COUNT_S() function expects max CPU number as 'size'+ parameter */+/* #undef MHD_FUNC_CPU_COUNT_S_GETS_CPUS */++/* Define to 1 if you have suitable libmagic. */+/* #undef MHD_HAVE_LIBMAGIC */++/* Define to 1 if you have __builtin_bswap32() builtin function */+#define MHD_HAVE___BUILTIN_BSWAP32 1++/* Define to 1 if you have __builtin_bswap64() builtin function */+#define MHD_HAVE___BUILTIN_BSWAP64 1++/* Define to `1' if HTTPS require initialisation of libgcrypt */+/* #undef MHD_HTTPS_REQUIRE_GCRYPT */++/* Define to 1 if libmicrohttpd is compiled with MD5 hashing support. */+/* #undef MHD_MD5_SUPPORT */++/* Define to 1 if libmicrohttpd is compiled with MD5 hashing by TLS library.+ */+/* #undef MHD_MD5_TLSLIB */++/* Define to 1 to disable setting name on generated threads */+#define MHD_NO_THREAD_NAMES 1++/* tls plugins */+#define MHD_PLUGIN_INSTALL_PREFIX "/usr/local/lib/libmicrohttpd"++/* Define to 1 if libmicrohttpd is compiled with SHA-256 hashing support. */+/* #undef MHD_SHA256_SUPPORT */++/* Define to 1 if libmicrohttpd is compiled with SHA-256 hashing by TLS+ library. */+/* #undef MHD_SHA256_TLSLIB */++/* Define to 1 if libmicrohttpd is compiled with SHA-512/256 hashing support.+ */+/* #undef MHD_SHA512_256_SUPPORT */++/* Define to system default value of FD_SETSIZE macro */+#define MHD_SYS_FD_SETSIZE_ 64++/* Define if you have usable `getsockname' function. */+#define MHD_USE_GETSOCKNAME 1++/* Define if you have usable PAGESIZE macro */+/* #undef MHD_USE_PAGESIZE_MACRO */++/* Define if you have PAGESIZE macro usable for static init */+/* #undef MHD_USE_PAGESIZE_MACRO_STATIC */++/* Define if you have usable PAGE_SIZE macro */+/* #undef MHD_USE_PAGE_SIZE_MACRO */++/* Define if you have PAGE_SIZE macro usable for static init */+/* #undef MHD_USE_PAGE_SIZE_MACRO_STATIC */++/* define to use pthreads */+/* #undef MHD_USE_POSIX_THREADS */++/* Define to 1 if you have properly working tsearch(), tfind() and tdelete()+ functions. */+#define MHD_USE_SYS_TSEARCH 1++/* define to use W32 threads */+#define MHD_USE_W32_THREADS 1++/* This is a MinGW system */+#define MINGW 1++/* This is a NetBSD system */+/* #undef NETBSD */++/* This is an OpenBSD system */+/* #undef OPENBSD */++/* This is a OS/390 system */+/* #undef OS390 */++/* This is an OS X system */+/* #undef OSX */++/* Some strange OS */+/* #undef OTHEROS */++/* Name of package */+#define PACKAGE "libmicrohttpd"++/* Define to the address where bug reports for this package should be sent. */+#define PACKAGE_BUGREPORT "[email protected]"++/* Define to the full name of this package. */+#define PACKAGE_NAME "GNU libmicrohttpd"++/* Define to the full name and version of this package. */+#define PACKAGE_STRING "GNU libmicrohttpd 1.0.10"++/* Define to the one symbol short name of this package. */+#define PACKAGE_TARNAME "libmicrohttpd"++/* Define to the home page for this package. */+#define PACKAGE_URL "https://www.gnu.org/software/libmicrohttpd/"++/* Define to the version of this package. */+#define PACKAGE_VERSION "1.0.10"++/* Define to necessary symbol if this constant uses a non-standard name on+ your system. */+/* #undef PTHREAD_CREATE_JOINABLE */++/* The size of 'int', as computed by sizeof. */+#define SIZEOF_INT 4++/* The size of 'int64_t', as computed by sizeof. */+#define SIZEOF_INT64_T 8++/* The size of 'size_t', as computed by sizeof. */+#define SIZEOF_SIZE_T 8++/* The size of `tv_sec' member of `struct timeval', as computed by sizeof */+#define SIZEOF_STRUCT_TIMEVAL_TV_SEC 4++/* The size of 'uint64_t', as computed by sizeof. */+#define SIZEOF_UINT64_T 8++/* The size of 'unsigned int', as computed by sizeof. */+#define SIZEOF_UNSIGNED_INT 4++/* The size of 'unsigned long long', as computed by sizeof. */+#define SIZEOF_UNSIGNED_LONG_LONG 8++/* This is a Solaris system */+/* #undef SOLARIS */++/* This is a BSD system */+/* #undef SOMEBSD */++/* Define to 1 if all of the C89 standard headers exist (not just the ones+ required in a freestanding environment). This macro is provided for+ backward compatibility; new code need not use it. */+#define STDC_HEADERS 1++/* Define to 1 if libmicrohttpd is compiled with HTTP Upgrade support. */+/* #undef UPGRADE_SUPPORT */++/* Define to 1 if your kernel supports IPv6 and IPv6 is enabled and useful for+ testing. */+/* #undef USE_IPV6_TESTING */++/* Version number of package */+#define VERSION "1.0.10"++/* This is a Windows system */+#define WINDOWS 1++/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most+ significant byte first (like Motorola and SPARC, unlike Intel). */+#if defined AC_APPLE_UNIVERSAL_BUILD+# if defined __BIG_ENDIAN__+# define WORDS_BIGENDIAN 1+# endif+#else+# ifndef WORDS_BIGENDIAN+/* # undef WORDS_BIGENDIAN */+# endif+#endif++/* Number of bits in a file offset, on hosts where this is settable. */+#define _FILE_OFFSET_BITS 64++/* Define to 1 if necessary to make fseeko visible. */+/* #undef _LARGEFILE_SOURCE */++/* Define to 1 on platforms where this makes off_t a 64-bit type. */+/* #undef _LARGE_FILES */++/* defines how to decorate public symbols while building the library */+#define _MHD_EXTERN __attribute__((visibility("default"))) extern++/* Define to 1 to enable "heavy" test paths. */+/* #undef _MHD_HEAVY_TESTS */++/* Define to use eventFD for inter-thread communication */+/* #undef _MHD_ITC_EVENTFD */++/* Define to use pipe for inter-thread communication */+/* #undef _MHD_ITC_PIPE */++/* Define to use socketpair for inter-thread communication */+#define _MHD_ITC_SOCKETPAIR 1++/* Define to supported 'noreturn' function declaration */+#define _MHD_NORETURN [[noreturn]]++/* Define to 1 to enable "very heavy" test paths. */+/* #undef _MHD_VHEAVY_TESTS */++/* Define to prefix which will be used with MHD static inline functions. */+#define _MHD_static_inline static inline __attribute__((always_inline))++/* Need with solaris or errno does not work */+/* #undef _REENTRANT */++/* Number of bits in time_t, on hosts where this is settable. */+/* #undef _TIME_BITS */++/* Define to 1 on platforms where this makes time_t a 64-bit type. */+/* #undef __MINGW_USE_VC2005_COMPAT */++/* Define to 1 if C does not support variable-length arrays, and if the+ compiler does not already define this. */+/* #undef __STDC_NO_VLA__ */++/* Define to the name of the type which is used as a replacemnt for boolean+ type. */+/* #undef bool */++/* Define curl_free() as free() if our version of curl lacks curl_free. */+/* #undef curl_free */++/* Define to value interpreted by compiler as boolean "false", if "false" is+ not a keyword and not defined by headers. */+/* #undef false */++/* Define to '__inline__' or '__inline' if that's what the C compiler+ calls it, or to nothing if 'inline' is not supported under any name. */+#ifndef __cplusplus+/* #undef inline */+#endif++/* Define to value interpreted by compiler as boolean "true", if "true" is not+ a keyword and not defined by headers. */+/* #undef true */diff --git a/tests/bench_long.c b/tests/bench_long.cindex ca5add1..43e85fd 100644--- a/tests/bench_long.c+++ b/tests/bench_long.c@@ -29,7 +29,9 @@#include <string.h>#include <sys/resource.h>#include <sys/stat.h>+#ifndef _WIN32#include <sys/sysmacros.h>+#endif#include <time.h>#include <unistd.h>@@ -45,9 +47,13 @@ static double now(void)}/* Milliseconds the block device (partition) of path has been busy, from- /proc/diskstats (io_ticks), or -1. */+ /proc/diskstats (io_ticks), or -1 (always on Windows). */static long long disk_busy_ms(const char *path){+#ifdef _WIN32+ (void)path;+ return -1;+#elsestruct stat st;if (stat(path, &st) != 0)return -1;@@ -72,6 +78,7 @@ static long long disk_busy_ms(const char *path)}fclose(f);return busy;+#endif}static int32_t argmax(const float *v, uint32_t n)diff --git a/tests/mcp_fake_server.c b/tests/mcp_fake_server.cindex afc2555..83fdbf8 100644--- a/tests/mcp_fake_server.c+++ b/tests/mcp_fake_server.c@@ -36,6 +36,7 @@#include <unistd.h>#include "common/mcp_rpc.h"+#include "common/sock.h"enum { MODERN = 1, LEGACY = 2 };static int eras = MODERN;@@ -254,6 +255,20 @@ static void header(const char *head, const char *name, char *v, size_t cap)}}+/* Every byte to the connection, or -1 (a socket is not a file on+ Windows: send, not write). */+static long put_all(int fd, const char *p, size_t n)+{+ while (n > 0) {+ long w = janas_sock_send(fd, p, n);+ if (w <= 0)+ return -1;+ p += w;+ n -= (size_t)w;+ }+ return 0;+}+static void reply(int fd, int status, const char *type, const char *extra,const char *body, size_t n){@@ -262,7 +277,7 @@ static void reply(int fd, int status, const char *type, const char *extra,"HTTP/1.1 %d X\r\nContent-Type: %s\r\n%sContent-Length: ""%zu\r\nConnection: close\r\n\r\n",status, type, extra, n);- if (write(fd, head, (size_t)k) < 0 || write(fd, body, n) < 0)+ if (put_all(fd, head, (size_t)k) < 0 || put_all(fd, body, n) < 0)fprintf(stderr, "write failed\n");}@@ -288,14 +303,15 @@ static void reply_sse(int fd, const char *body, size_t n)l += ln + 1;}janas_buf_puts(&b, "0\r\n\r\n");- if (write(fd, b.p, b.n) < 0)+ if (put_all(fd, b.p, b.n) < 0)fprintf(stderr, "write failed\n");janas_buf_free(&b);}static void serve_http(void){- int s = socket(AF_INET, SOCK_STREAM, 0);+ janas_sock_init();+ int s = (int)socket(AF_INET, SOCK_STREAM, 0);struct sockaddr_in a = {.sin_family = AF_INET,.sin_addr.s_addr = htonl(INADDR_LOOPBACK)};socklen_t al = sizeof(a);@@ -320,14 +336,14 @@ static void serve_http(void)}if (!(pf[0].revents & POLLIN))continue;- int fd = accept(s, NULL, NULL);+ int fd = (int)accept(s, NULL, NULL);if (fd < 0)continue;struct janas_buf in = {0};char chunk[4096];long got;size_t head_end = 0, want = 0;- while ((got = read(fd, chunk, sizeof(chunk))) > 0) {+ while ((got = janas_sock_recv(fd, chunk, sizeof(chunk))) > 0) {janas_buf_put(&in, chunk, (size_t)got);janas_buf_put(&in, "", 1);in.n--;@@ -342,7 +358,7 @@ static void serve_http(void)break;}if (!head_end) {- close(fd);+ janas_sock_close(fd);janas_buf_free(&in);continue;}@@ -403,7 +419,7 @@ static void serve_http(void)strcspn(out, "\n"));free(out);}- close(fd);+ janas_sock_close(fd);janas_buf_free(&in);}}diff --git a/tests/test_mcp.c b/tests/test_mcp.cindex abb39b1..09ec09d 100644--- a/tests/test_mcp.c+++ b/tests/test_mcp.c@@ -545,10 +545,14 @@ int main(int argc, char **argv)test_rpc();test_config();/* the fake server is next to this program, with the same suffix */- char self[1024];+ char self[1024], name[1024];snprintf(self, sizeof(self), "%s", argv[0]);- const char *base = strrchr(argv[0], '/');- base = base ? base + 1 : argv[0];+ for (char *c = self; *c; c++)+ if (*c == '\\')+ *c = '/'; /* Windows writes its paths with either */+ const char *base = strrchr(self, '/');+ snprintf(name, sizeof name, "%s", base ? base + 1 : self);+ base = name;const char *suffix = strchr(base, '-');snprintf(fake, sizeof(fake), "%s/mcp_fake_server%s", dirname(self),suffix ? suffix : "");