diff --git a/.gitattributes b/.gitattributes index 5012f36..0d6bd9c 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,2 +1,5 @@ # Shell scripts must stay LF or bash on the CI runner chokes on \r. *.sh text eol=lf + +# Batch files need CRLF: cmd misreads labels and call targets with LF endings. +*.bat text eol=crlf diff --git a/.github/scripts/configure-simplysign.ps1 b/.github/scripts/configure-simplysign.ps1 deleted file mode 100644 index 7abc4ea..0000000 --- a/.github/scripts/configure-simplysign.ps1 +++ /dev/null @@ -1,28 +0,0 @@ -# Pre-configure SimplySign Desktop for unattended use: -# - auto-show the login dialog on launch (so the TOTP keystrokes have a target) -# - cache the smart-card PIN in the CSP, so signtool signs without a per-call -# PIN prompt, and forget it again when the session disconnects. -# Mirrors the settings used by the blinkdisk / docuscope CI signing setups. - -$ErrorActionPreference = "Stop" - -$RegistryPath = "HKCU:\Software\Certum\SimplySign" - -$settings = [ordered]@{ - ShowLoginDialogOnStart = 1 - ShowLoginDialogOnAppRequest = 1 - RememberLastUserName = 0 - Autostart = 0 - UnregisterCertificatesOnDisconnect = 0 - RememberPINinCSP = 1 - ForgetPINinCSPonDisconnect = 1 - LangID = 9 -} - -Write-Host "=== Configuring SimplySign Desktop registry ===" -New-Item -Path $RegistryPath -Force | Out-Null -foreach ($name in $settings.Keys) { - Set-ItemProperty -Path $RegistryPath -Name $name -Value $settings[$name] -Type DWord - Write-Host " $name = $($settings[$name])" -} -Write-Host "Done." diff --git a/.github/scripts/connect-simplysign.ps1 b/.github/scripts/connect-simplysign.ps1 deleted file mode 100644 index 2d312ed..0000000 --- a/.github/scripts/connect-simplysign.ps1 +++ /dev/null @@ -1,245 +0,0 @@ -# Authenticate SimplySign Desktop non-interactively. -# -# Certum's SimplySign cloud has no headless login: the certificate only reaches -# the Windows store after the GUI client authenticates. So we generate the -# current TOTP from the otpauth:// secret (CERTUM_OTP_URI) and paste the -# credentials into the login dialog. This needs an interactive desktop session, -# which GitHub-hosted Windows runners provide. -# -# Based on https://www.devas.life/how-to-automate-signing-your-windows-app-with-certum/ -# and the refinements in blinkdisk's connect-simplysign.ps1. - -param( - [string]$OtpUri = $env:CERTUM_OTP_URI, - [string]$UserId = $env:CERTUM_USERID, - [string]$ExePath = $env:CERTUM_EXE_PATH -) - -if (-not $OtpUri) { Write-Host "ERROR: CERTUM_OTP_URI not provided"; exit 1 } -if (-not $UserId) { Write-Host "ERROR: CERTUM_USERID not provided"; exit 1 } -if (-not $ExePath) { - $ExePath = "C:\Program Files\Certum\SimplySign Desktop\SimplySignDesktop.exe" -} - -Write-Host "=== SimplySign Desktop TOTP authentication ===" -if (-not (Test-Path $ExePath)) { - Write-Host "ERROR: SimplySign Desktop not found at $ExePath" - exit 1 -} - -# --- Parse the otpauth:// URI (works on PowerShell 5.1 and 7+) --------------- -$uri = [Uri]$OtpUri -try { - $q = [System.Web.HttpUtility]::ParseQueryString($uri.Query) -} catch { - $q = @{} - foreach ($part in $uri.Query.TrimStart('?') -split '&') { - $kv = $part -split '=', 2 - if ($kv.Count -eq 2) { $q[$kv[0]] = [Uri]::UnescapeDataString($kv[1]) } - } -} - -$Base32 = $q['secret'] -$Digits = if ($q['digits']) { [int]$q['digits'] } else { 6 } -$Period = if ($q['period']) { [int]$q['period'] } else { 30 } -$Algorithm = if ($q['algorithm']) { $q['algorithm'].ToUpper() } else { 'SHA256' } - -if (-not $Base32) { Write-Host "ERROR: otpauth URI has no 'secret'"; exit 1 } -if ($Algorithm -notin @('SHA1', 'SHA256', 'SHA512')) { - Write-Host "ERROR: unsupported TOTP algorithm: $Algorithm" - exit 1 -} - -# --- TOTP generator (RFC 6238), inline C# so there are no dependencies -------- -Add-Type -Language CSharp @" -using System; -using System.Security.Cryptography; - -public static class Totp -{ - private const string B32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; - - private static byte[] Base32Decode(string s) - { - s = s.TrimEnd('=').ToUpperInvariant(); - byte[] bytes = new byte[s.Length * 5 / 8]; - int bitBuffer = 0, bitsLeft = 0, idx = 0; - foreach (char c in s) - { - int val = B32.IndexOf(c); - if (val < 0) throw new ArgumentException("Invalid Base32 char: " + c); - bitBuffer = (bitBuffer << 5) | val; - bitsLeft += 5; - if (bitsLeft >= 8) { bytes[idx++] = (byte)(bitBuffer >> (bitsLeft - 8)); bitsLeft -= 8; } - } - return bytes; - } - - private static HMAC Hmac(string algorithm, byte[] key) - { - switch (algorithm.ToUpper()) - { - case "SHA1": return new HMACSHA1(key); - case "SHA256": return new HMACSHA256(key); - case "SHA512": return new HMACSHA512(key); - default: throw new ArgumentException("Unsupported algorithm: " + algorithm); - } - } - - public static string Now(string secret, int digits, int period, string algorithm) - { - byte[] key = Base32Decode(secret); - long counter = DateTimeOffset.UtcNow.ToUnixTimeSeconds() / period; - byte[] cnt = BitConverter.GetBytes(counter); - if (BitConverter.IsLittleEndian) Array.Reverse(cnt); - - byte[] hash; - using (var h = Hmac(algorithm, key)) { hash = h.ComputeHash(cnt); } - - int offset = hash[hash.Length - 1] & 0x0F; - int binary = - ((hash[offset] & 0x7F) << 24) | - ((hash[offset + 1] & 0xFF) << 16) | - ((hash[offset + 2] & 0xFF) << 8) | - (hash[offset + 3] & 0xFF); - int otp = binary % (int)Math.Pow(10, digits); - return otp.ToString(new string('0', digits)); - } -} -"@ - -function Find-UiByName($el, $walker, $name) { - $c = $walker.GetFirstChild($el) - while ($c) { - if ($c.Current.Name -eq $name) { return $c } - $r = Find-UiByName $c $walker $name - if ($r) { return $r } - $c = $walker.GetNextSibling($c) - } - return $null -} - -# An outdated SimplySign build pops a modal "New version found - download?" box -# over the login form, which swallows the credential keystrokes. Decline it by -# clicking "No" (Invoke / legacy default action / click the element's point). -function Dismiss-UpdatePrompt { - try { Add-Type -AssemblyName UIAutomationClient, UIAutomationTypes -ErrorAction Stop } catch { return $false } - if (-not ('Win32Mouse' -as [type])) { - Add-Type @" -using System; -using System.Runtime.InteropServices; -public static class Win32Mouse { - [DllImport("user32.dll")] static extern bool SetCursorPos(int x, int y); - [DllImport("user32.dll")] static extern void mouse_event(uint f, uint x, uint y, uint d, int e); - public static void Click(int x, int y){ SetCursorPos(x,y); mouse_event(0x02,0,0,0,0); mouse_event(0x04,0,0,0,0); } -} -"@ - } - $procIds = @((Get-Process -Name '*SimplySign*' -ErrorAction SilentlyContinue).Id) - $walker = [System.Windows.Automation.TreeWalker]::ControlViewWalker - $top = $walker.GetFirstChild([System.Windows.Automation.AutomationElement]::RootElement) - while ($top) { - if ($procIds -contains $top.Current.ProcessId) { - $no = Find-UiByName $top $walker "No" - if ($no) { - Write-Host "Update prompt detected; declining (clicking 'No')." - try { ($no.GetCurrentPattern([System.Windows.Automation.InvokePattern]::Pattern)).Invoke(); return $true } catch {} - try { ($no.GetCurrentPattern([System.Windows.Automation.LegacyIAccessiblePattern]::Pattern)).DoDefaultAction(); return $true } catch {} - try { $pt = $no.GetClickablePoint(); [Win32Mouse]::Click([int]$pt.X, [int]$pt.Y); return $true } catch { Write-Host "Click 'No' failed: $($_.Exception.Message)" } - } - } - $top = $walker.GetNextSibling($top) - } - return $false -} - -# Start from a clean slate so a stale window/session can't swallow the keystrokes. -if ($existing = Get-Process -Name "SimplySignDesktop" -ErrorAction Ignore) { - Write-Host "Killing existing SimplySignDesktop process..." - $existing | Stop-Process -Force - Start-Sleep -Seconds 1 -} - -Write-Host "Launching SimplySign Desktop..." -$proc = Start-Process -FilePath $ExePath -PassThru -Start-Sleep -Seconds 3 - -$wshell = New-Object -ComObject WScript.Shell - -Write-Host "Focusing the login window..." -$focused = $wshell.AppActivate($proc.Id) -if (-not $focused) { $focused = $wshell.AppActivate('SimplySign Desktop') } -for ($i = 0; (-not $focused) -and ($i -lt 10); $i++) { - Start-Sleep -Milliseconds 500 - $focused = $wshell.AppActivate($proc.Id) -or $wshell.AppActivate('SimplySign Desktop') -} -if (-not $focused) { - Write-Host "ERROR: could not bring SimplySign Desktop to the foreground" - exit 1 -} - -# Decline the "new version available" modal if it's covering the login form. -if (Dismiss-UpdatePrompt) { Start-Sleep -Milliseconds 800 } - -# Re-assert focus: dismissing the dialog can move the foreground window, and -# keystrokes sent to the wrong window are silently dropped. -$wshell.AppActivate($proc.Id) | Out-Null -$wshell.AppActivate('SimplySign Desktop') | Out-Null -Start-Sleep -Milliseconds 400 - -# Paste rather than type: SendKeys mangles characters like + ^ % ( ) and can -# drop characters; pasting delivers the exact string. Falls back to typing if -# the clipboard is unavailable. -function Set-Field([string]$text) { - try { - Set-Clipboard -Value $text -ErrorAction Stop - Start-Sleep -Milliseconds 150 - $wshell.SendKeys("^v") - } catch { - Write-Host "Clipboard unavailable ($($_.Exception.Message)); typing instead." - $wshell.SendKeys($text) - } - Start-Sleep -Milliseconds 250 -} - -Write-Host "Injecting credentials..." -Set-Field $UserId -$wshell.SendKeys("{TAB}") -Start-Sleep -Milliseconds 200 - -# Generate the code right before sending it so it can't expire while we focus. -$otp = [Totp]::Now($Base32, $Digits, $Period, $Algorithm) -Set-Field $otp -Start-Sleep -Milliseconds 200 -$wshell.SendKeys("{ENTER}") - -# Don't leave the OTP / username sitting on the clipboard afterwards. -try { Set-Clipboard -Value " " -ErrorAction Stop } catch {} - -Write-Host "Waiting for authentication to settle..." -Start-Sleep -Seconds 5 - -if (-not (Get-Process -Id $proc.Id -ErrorAction SilentlyContinue)) { - Write-Host "ERROR: SimplySign Desktop exited - authentication failed." - exit 1 -} - -# Confirm the login actually mounted the signing certificate into the store. -$thumb = if ($env:CERTUM_CERT_SHA1) { ($env:CERTUM_CERT_SHA1 -replace '\s', '').ToUpperInvariant() } else { $null } -Write-Host "Verifying the signing certificate reached the store..." -$deadline = (Get-Date).AddSeconds(60) -$found = $false -do { - $certs = Get-ChildItem Cert:\CurrentUser\My, Cert:\LocalMachine\My -ErrorAction SilentlyContinue - if ($thumb) { $found = [bool]($certs | Where-Object { $_.Thumbprint -eq $thumb }) } - else { $found = [bool]($certs | Where-Object { $_.Subject -like '*Certum*' -or $_.Issuer -like '*Certum*' }) } - if ($found) { break } - Start-Sleep -Seconds 3 -} while ((Get-Date) -lt $deadline) - -if ($found) { - Write-Host "=== Authentication complete: signing certificate is available. ===" -} else { - Write-Host "ERROR: signing certificate did not appear after authentication." - exit 1 -} diff --git a/.github/scripts/install-simplysign.sh b/.github/scripts/install-simplysign.sh deleted file mode 100644 index 6e4f30a..0000000 --- a/.github/scripts/install-simplysign.sh +++ /dev/null @@ -1,46 +0,0 @@ -#!/bin/bash -# Install Certum SimplySign Desktop on the (ephemeral) Windows runner. -# SimplySign Desktop is what mounts the cloud signing certificate as a virtual -# smart card into the Windows certificate store; signtool then selects it by -# thumbprint. The version + checksum are pinned for reproducibility. - -set -euo pipefail - -VERSION="9.3.4.72" -URL="https://files.certum.eu/software/SimplySignDesktop/Windows/${VERSION}/SimplySignDesktop-${VERSION}-64-bit-en.msi" -EXPECTED_SHA256="bd51ebbaaac20fc7d59ab7103b5ed532b7800586df4e31f6999d03a394f9c515" -INSTALLER="SimplySignDesktop.msi" -INSTALL_DIR="/c/Program Files/Certum/SimplySign Desktop" - -echo "=== Installing Certum SimplySign Desktop ${VERSION} ===" - -# Idempotent: a cached/pre-provisioned image may already have it. -if [ -d "$INSTALL_DIR" ]; then - echo "Already installed at: $INSTALL_DIR" - exit 0 -fi - -echo "Downloading installer..." -curl -L "$URL" -o "$INSTALLER" --fail --max-time 600 - -ACTUAL_SHA256=$(sha256sum "$INSTALLER" | awk '{print $1}') -if [ "$EXPECTED_SHA256" != "$ACTUAL_SHA256" ]; then - echo "ERROR: checksum mismatch" - echo " expected: $EXPECTED_SHA256" - echo " actual: $ACTUAL_SHA256" - exit 1 -fi -echo "Checksum verified." - -echo "Running msiexec (silent)..." -# Start-Process inherits this CWD, so the relative installer path resolves here. -powershell -Command "Start-Process msiexec.exe -ArgumentList '/i','${INSTALLER}','/quiet','/norestart','/l*v','install.log','ALLUSERS=1','REBOOT=ReallySuppress' -Wait -NoNewWindow" - -if [ ! -d "$INSTALL_DIR" ]; then - echo "ERROR: installation directory not found after install" - echo "Last 20 lines of install.log:" - tail -20 install.log 2>/dev/null || echo "(no install.log)" - exit 1 -fi - -echo "SimplySign Desktop installed." diff --git a/.github/scripts/sign-certum.ps1 b/.github/scripts/sign-certum.ps1 deleted file mode 100644 index 7f679f2..0000000 --- a/.github/scripts/sign-certum.ps1 +++ /dev/null @@ -1,66 +0,0 @@ -# Sign the given files with the Certum cloud certificate (selected by SHA1 -# thumbprint from the store) and verify each signature. Assumes SimplySign -# Desktop has already authenticated (connect-simplysign.ps1). - -[CmdletBinding()] -param( - [Parameter(Mandatory = $true)] - [string[]]$Files, - [string]$CertSha1 = $env:CERTUM_CERT_SHA1, - [string]$TimestampUrl = "http://time.certum.pl" -) - -$ErrorActionPreference = "Stop" - -if (-not $CertSha1) { throw "CERTUM_CERT_SHA1 not provided." } -$thumb = ($CertSha1 -replace '\s', '').ToUpperInvariant() - -# Resolve the newest signtool.exe from the installed Windows SDK(s). -$kitsBin = "C:\Program Files (x86)\Windows Kits\10\bin" -$signtool = Get-ChildItem -Path $kitsBin -Recurse -Filter signtool.exe -File -ErrorAction SilentlyContinue | - Where-Object { $_.FullName -like '*\x64\*' } | - Sort-Object { [version]$_.Directory.Parent.Name } | - Select-Object -Last 1 -ExpandProperty FullName -if (-not $signtool) { throw "signtool.exe not found under $kitsBin" } -Write-Host "Using signtool: $signtool" - -# The SimplySign virtual smart card registers in the store a moment after the -# desktop client authenticates; poll for our certificate before signing. -Write-Host "Waiting for certificate $thumb to appear in the store..." -$deadline = (Get-Date).AddSeconds(120) -$cert = $null -$elapsed = 0 -do { - $cert = Get-ChildItem Cert:\CurrentUser\My, Cert:\LocalMachine\My -ErrorAction SilentlyContinue | - Where-Object { $_.Thumbprint -eq $thumb } | Select-Object -First 1 - if ($cert) { break } - Start-Sleep -Seconds 3 - $elapsed += 3 - Write-Host " ...still waiting (${elapsed}s)" -} while ((Get-Date) -lt $deadline) - -if (-not $cert) { - Write-Host "Certificate not found. CurrentUser\My + LocalMachine\My contents:" - Get-ChildItem Cert:\CurrentUser\My, Cert:\LocalMachine\My -ErrorAction SilentlyContinue | - Select-Object Thumbprint, Subject, HasPrivateKey | Format-Table -AutoSize | Out-String | Write-Host - Write-Host "SimplySign processes:" - Get-Process -Name '*SimplySign*' -ErrorAction SilentlyContinue | - Select-Object Name, Id, Responding, MainWindowTitle | Format-Table -AutoSize | Out-String | Write-Host - throw "Certificate $thumb not found in the store - SimplySign authentication likely failed (see dump above)." -} -Write-Host "Found signing certificate: $($cert.Subject)" - -$failed = @() -foreach ($file in $Files) { - if (-not (Test-Path $file)) { throw "File to sign not found: $file" } - Write-Host "=== Signing $file ===" - & $signtool sign /sha1 $thumb /fd sha256 /td sha256 /tr $TimestampUrl /v $file - if ($LASTEXITCODE -ne 0) { $failed += $file; continue } - & $signtool verify /pa /v $file - if ($LASTEXITCODE -ne 0) { $failed += $file } -} - -if ($failed.Count -gt 0) { - throw "Signing/verification failed for: $($failed -join ', ')" -} -Write-Host "All binaries signed and verified." diff --git a/.github/scripts/verify-certum.sh b/.github/scripts/verify-certum.sh new file mode 100644 index 0000000..c1db680 --- /dev/null +++ b/.github/scripts/verify-certum.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash +set -euo pipefail +export LC_ALL=C + +thumb="${CERTUM_CERT_SHA1:?CERTUM_CERT_SHA1 is required}" +thumb="${thumb//[[:space:]]/}" +if [[ ! "$thumb" =~ ^[[:xdigit:]]{40}$ ]] || (( $# == 0 )); then + echo 'Usage: CERTUM_CERT_SHA1= bash verify-certum.sh [...]' >&2 + exit 1 +fi + +ca_file="${SSL_CERT_FILE:-/etc/ssl/certs/ca-certificates.crt}" +for file in "$@"; do + echo "Verifying $file" + if ! output=$(osslsigncode verify -CAfile "$ca_file" -TSA-CAfile "$ca_file" \ + -require-leaf-hash "sha1:$thumb" -in "$file" 2>&1); then + printf '%s\n' "$output" >&2 + exit 1 + fi + printf '%s\n' "$output" + # A valid signature without a timestamp also returns success from osslsigncode. + if ! grep -qx 'Timestamp Server Signature verification: ok' <<< "$output"; then + echo "Missing verified timestamp: $file" >&2 + exit 1 + fi +done diff --git a/.github/workflows/cd.yaml b/.github/workflows/cd.yaml index 0387c08..b9dfab4 100644 --- a/.github/workflows/cd.yaml +++ b/.github/workflows/cd.yaml @@ -1,101 +1,136 @@ -name: gMod CD Pipeline +name: gMod CD Pipeline on: push: branches: - master workflow_dispatch: - -jobs: - - build: - strategy: - matrix: - targetplatform: [x86] +permissions: + contents: write - runs-on: windows-2025-vs2026 - - permissions: - contents: write +env: + CERTUM_OTP_URI: ${{ secrets.CERTUM_OTP_URI }} + CERTUM_USERID: ${{ secrets.CERTUM_USERID }} + CERTUM_CERT_SHA1: ${{ secrets.CERTUM_CERT_SHA1 }} +jobs: + build: + runs-on: ubuntu-24.04 + outputs: + version: ${{ steps.version.outputs.version }} + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Bootstrap + run: bash bootstrap.sh + + - name: Build + run: python3 scripts/build.py --preset release + + - name: Read version + id: version + run: echo "version=$(python3 scripts/version.py)" >> "$GITHUB_OUTPUT" + + # Same as GWToolbox: keep the PDB and the split DWARF file, gzipped, next to the binaries. gzip -k keeps the + # originals in bin/ for later steps. + - name: Compress the debug info + run: | + gzip -kf bin/gMod.pdb + gzip -kf bin/gMod.debug + + # TpfConvert.exe and gMod.dll link to d3dx9_43.dll only at run time. It is a Microsoft redistributable that + # the MinGW build does not produce, so carry the copy from the latest release forward unchanged. + - name: Fetch d3dx9_43.dll from the latest release + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + mkdir -p release + gh release download --repo "$GITHUB_REPOSITORY" --pattern d3dx9_43.dll --dir release --clobber + cp bin/gMod.dll bin/TpfConvert.exe bin/gMod.pdb.gz bin/gMod.debug.gz release/ + + - name: Upload unsigned binaries + uses: actions/upload-artifact@v4 + with: + name: release + path: release/ + if-no-files-found: error + + # Signs on Linux with Certum's cloud certificate, through the pinned ssign client (no SimplySign Desktop, no + # Windows runner). Without the Certum secrets (forks, or no access) the binaries are passed through unsigned. + sign: + needs: build + runs-on: ubuntu-24.04 + timeout-minutes: 20 env: - Configuration: Release - Actions_Allow_Unsecure_Commands: true - CERTUM_OTP_URI: ${{ secrets.CERTUM_OTP_URI }} - CERTUM_USERID: ${{ secrets.CERTUM_USERID }} - CERTUM_CERT_SHA1: ${{ secrets.CERTUM_CERT_SHA1 }} - + HAS_CERTUM_CREDENTIALS: ${{ secrets.CERTUM_OTP_URI != '' && secrets.CERTUM_USERID != '' && secrets.CERTUM_CERT_SHA1 != '' }} + steps: + - name: Checkout (for the verify script) + uses: actions/checkout@v4 + + - name: Download unsigned binaries + uses: actions/download-artifact@v4 + with: + name: release + path: release + + - name: Install the signing tools + if: env.HAS_CERTUM_CREDENTIALS == 'true' + run: | + set -euo pipefail + sudo apt-get update -qq + sudo apt-get install -y --no-install-recommends osslsigncode ca-certificates + curl --fail --location --retry 3 --output "$RUNNER_TEMP/ssign.tar.gz" \ + https://github.com/Le-Syl21/ssign/releases/download/v0.1.8/ssign-linux-x86_64.tar.gz + echo "fc38f083ea1f061a097a3a9c5dc1a056c9c7310a47e40f56a8976895ec5a928d $RUNNER_TEMP/ssign.tar.gz" | sha256sum --check + mkdir -p "$RUNNER_TEMP/ssign-bin" + tar -xzf "$RUNNER_TEMP/ssign.tar.gz" -C "$RUNNER_TEMP/ssign-bin" + "$RUNNER_TEMP/ssign-bin/ssign" --version + osslsigncode --version + + - name: Sign the Windows binaries with Certum + if: env.HAS_CERTUM_CREDENTIALS == 'true' + timeout-minutes: 10 + env: + # ssign reads the account e-mail and the TOTP seed (or the full otpauth:// URI) from these variables, so + # they never reach the command line or the shell history. + CERTUM_EMAIL: ${{ secrets.CERTUM_USERID }} + CERTUM_OTP: ${{ secrets.CERTUM_OTP_URI }} + run: | + "$RUNNER_TEMP/ssign-bin/ssign" --timestamp-url http://time.certum.pl/ \ + release/gMod.dll release/TpfConvert.exe + + - name: Verify the signatures, timestamps and signer + if: env.HAS_CERTUM_CREDENTIALS == 'true' + timeout-minutes: 5 + run: bash .github/scripts/verify-certum.sh release/gMod.dll release/TpfConvert.exe + + - name: Upload signed binaries + uses: actions/upload-artifact@v4 + with: + name: release-signed + path: release/ + if-no-files-found: error + + publish: + needs: [build, sign] + runs-on: ubuntu-24.04 steps: - - name: Checkout - uses: actions/checkout@v4 - with: - fetch-depth: 0 - - - name: Setup MSBuild.exe - uses: microsoft/setup-msbuild@v1.3.1 - - - name: Install vcpkg - run: | - git clone https://github.com/microsoft/vcpkg.git - .\vcpkg\bootstrap-vcpkg.bat - - - name: Set VCPKG_ROOT - run: | - echo "VCPKG_ROOT=$(Get-Location)\vcpkg" >> $env:GITHUB_ENV - shell: powershell - - - name: Build CMake Files with vcpkg toolchain - run: cmake --preset=vcpkg - env: - VCPKG_ROOT: ${{ env.VCPKG_ROOT }} - - - name: Build binaries - run: cmake --build build --config Release - - # Signing only runs when the Certum secrets are present (i.e. on the real - # repo, not forks); without them the build still produces unsigned binaries. - - name: Set up Certum SimplySign - if: env.CERTUM_OTP_URI != '' - shell: bash - run: | - chmod +x ./.github/scripts/install-simplysign.sh - ./.github/scripts/install-simplysign.sh - powershell -ExecutionPolicy Bypass -File "./.github/scripts/configure-simplysign.ps1" - - - name: Authenticate Certum SimplySign - if: env.CERTUM_OTP_URI != '' - shell: bash - run: powershell -ExecutionPolicy Bypass -File "./.github/scripts/connect-simplysign.ps1" - - - name: Sign release binaries - if: env.CERTUM_OTP_URI != '' - shell: pwsh - run: | - ./.github/scripts/sign-certum.ps1 -Files @(".\bin\Release\gMod.dll", ".\bin\Release\TpfConvert.exe") - - - name: Retrieve version - id: set_version - run: | - $fileVersionInfo = (Get-Item -Path .\bin\Release\gMod.dll).VersionInfo.FileVersion - if ([string]::IsNullOrEmpty($fileVersionInfo)) { - Write-Host "The DLL file version information could not be retrieved." - exit 1 - } else { - Write-Host "FileVersionInfo: $fileVersionInfo" - echo "::set-output name=version::$fileVersionInfo" - } - shell: pwsh - - - name: Publish release - uses: Xotl/cool-github-releases@v1.1.8 - with: - mode: update - tag_name: v${{ steps.set_version.outputs.version }} - release_name: gMod v${{ steps.set_version.outputs.version }} - assets: .\bin\Release\gMod.dll;.\bin\Release\TpfConvert.exe;.\bin\Release\d3dx9_43.dll - github_token: ${{ env.GITHUB_TOKEN }} - replace_assets: true - body_mrkdwn: ${{ env.Changelog }} - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + - name: Download binaries to publish + uses: actions/download-artifact@v4 + with: + name: release-signed + path: release + + - name: Publish release + uses: Xotl/cool-github-releases@v1.1.8 + with: + mode: update + tag_name: v${{ needs.build.outputs.version }} + release_name: gMod v${{ needs.build.outputs.version }} + assets: release/gMod.dll;release/TpfConvert.exe;release/d3dx9_43.dll;release/gMod.pdb.gz;release/gMod.debug.gz + github_token: ${{ secrets.GITHUB_TOKEN }} + replace_assets: true diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index d734590..4af3ed5 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -10,41 +10,29 @@ on: workflow_dispatch: jobs: - build: - - strategy: - matrix: - targetplatform: [x86] - - runs-on: windows-2025-vs2026 - - env: - Configuration: Release - Actions_Allow_Unsecure_Commands: true - + build-linux: + runs-on: ubuntu-24.04 steps: - - name: Checkout - uses: actions/checkout@v4 - with: - fetch-depth: 0 - - - name: Setup MSBuild.exe - uses: microsoft/setup-msbuild@v1.3.1 - - - name: Install vcpkg - run: | - git clone https://github.com/microsoft/vcpkg.git - .\vcpkg\bootstrap-vcpkg.bat - - - name: Set VCPKG_ROOT - run: | - echo "VCPKG_ROOT=$(Get-Location)\vcpkg" >> $env:GITHUB_ENV - shell: powershell - - - name: Build CMake Files with vcpkg toolchain - run: cmake --preset=vcpkg - env: - VCPKG_ROOT: ${{ env.VCPKG_ROOT }} + - name: Checkout + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + # Installs the pinned llvm-mingw, CMake and vcpkg, then configures the release preset. + - name: Bootstrap + run: bash bootstrap.sh + + - name: Build + run: python3 scripts/build.py --preset release + + - name: Upload binaries + uses: actions/upload-artifact@v4 + with: + name: gMod-linux-release + path: | + bin/gMod.dll + bin/gMod.pdb + bin/TpfConvert.exe + bin/TpfConvert.pdb + if-no-files-found: error - - name: Build binaries - run: cmake --build build --config Release diff --git a/.github/workflows/lint.yaml b/.github/workflows/lint.yaml index 54a1933..6d9717b 100644 --- a/.github/workflows/lint.yaml +++ b/.github/workflows/lint.yaml @@ -26,7 +26,7 @@ jobs: run: pipx install clang-format==22.1.5 - name: Apply clang-format - run: clang-format -i header/*.h source/*.cpp modules/*.ixx TpfConvert/src/*.ixx + run: clang-format -i header/*.h source/*.cpp modules/*.ixx TpfConvert/src/*.cpp TpfConvert/src/*.ixx # Push / same-repo PRs: commit the fixes back. Fork PRs can't be pushed to, # so fail the check instead and let the contributor format. diff --git a/.gitignore b/.gitignore index 5857832..98f32a2 100644 --- a/.gitignore +++ b/.gitignore @@ -65,4 +65,15 @@ vcpkg_installed /build /_deps -.idea \ No newline at end of file +.idea +# Toolchain and dependency provisioning (scripts/bootstrap.py) +/.toolchain +/.vcpkg +/logs +__pycache__/ + +# IDE outputs generated by scripts/bootstrap.py (the settings themselves live in bootstrap/) +/.vs-projects +/gMod.slnx +/obj +.vscode diff --git a/CLAUDE.md b/CLAUDE.md index 710c013..c6d60a6 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -14,25 +14,25 @@ A 32-bit Windows DLL that hooks Direct3D 9 to load texture mods for Guild Wars. ## Build -Requires Visual Studio 2022, CMake 3.29+, and vcpkg — all via the VS 2022 Developer PowerShell. +Builds with llvm-mingw (clang, lld, libc++, MinGW-w64) on Linux or Windows, the same way GWToolbox does. No MSVC. ``` -cmake --preset=vcpkg -cmake --open build -# then compile inside Visual Studio, or: -cmake --build build --config Release +bash bootstrap.sh # Linux; on Windows: bootstrap.bat +python3 scripts/build.py # relwithdebinfo preset; --preset debug|release ``` -- Target: 32-bit only (`-A Win32` / `CMAKE_GENERATOR_PLATFORM=win32`) -- Standard: C++23 -- Output: `bin/` (gMod.dll, TpfConvert.exe) -- Version: set in `CMakeLists.txt` (`VERSION_MAJOR/MINOR/PATCH/TWEAK`) +- The bootstrap installs the pinned llvm-mingw (`scripts/llvm-mingw.version`) into `.toolchain/` and vcpkg into `.vcpkg/`, then configures `build///`. +- Target: 32-bit only (i686, `Win32`). +- Standard: C++23, with `import std`. The experimental flag's UUID in `CMakeLists.txt` belongs to one CMake version, so + CMake is pinned in `scripts/cmake.version` (4.4.4) and the bootstrap installs that exact version. Change the pin and + the UUID together. +- Output: `bin/` (gMod.dll, TpfConvert.exe, each with a .pdb). +- Version: set in `CMakeLists.txt` (`VERSION_MAJOR/MINOR/PATCH/TWEAK`). +- The Windows CI and release workflows (`.github/workflows/`) still use the old MSVC build; see the note in Notes. -> **Cannot be built or run in this agent environment** (Linux, no MSVC, no 32-bit -> D3D9, no Guild Wars to inject into). Don't burn turns attempting `cmake`/builds -> here — validate changes by reading and matching existing patterns, and lean on -> Windows CI (`ci.yaml`) for the real build. When an actual compile/test is needed, -> ask the user to do it in Visual Studio rather than trying locally. +> **Not built or run in agent environments by default.** The build runs on Linux now, but nothing here can +> run the DLL: there is no 32-bit D3D9 to hook and no Guild Wars to inject into. Compile checks are fine; for +> runtime checks ask the user to run the DLL in Guild Wars. ## Key dependencies (via vcpkg) @@ -94,3 +94,7 @@ CreateTexture/Volume/Cube, UpdateTexture, BeginScene, Set/GetTexture, Release). - Must be injected before d3d9.dll loads, or renamed to d3d9.dll in the GW folder - Reshade > 5.0.1 causes glitches; recommend 5.0.1 or 4.9.1 - `modlist.txt` contains full paths to .tpf/.zip mod files, one per line +- CI (`ci.yaml`) builds on Linux and Windows with `bootstrap`/`build.py`. CD (`cd.yaml`) builds on Linux, signs with + Certum's cloud certificate on Linux through the pinned `ssign` client, verifies with `osslsigncode`, then publishes; + d3dx9_43.dll is carried forward from the latest release because the + MinGW build does not produce it. Those workflows have not run on GitHub yet. diff --git a/CMakeLists.txt b/CMakeLists.txt index 78b3511..e2ee932 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,17 +1,19 @@ -cmake_minimum_required(VERSION 3.29) +cmake_minimum_required(VERSION 3.30) -set(CMAKE_GENERATOR_PLATFORM win32) +# import std (the C++23 standard library module) needs this experimental switch, set before project(). +set(CMAKE_EXPERIMENTAL_CXX_IMPORT_STD "f35a9ac6-8463-4d38-8eec-5d6008153e7d") project(gMod) +enable_language(RC) set_property(GLOBAL PROPERTY USE_FOLDERS ON) if(NOT(CMAKE_SIZEOF_VOID_P EQUAL 4)) - message(FATAL_ERROR "You are configuring a non 32-bit build, this is not supported. Run cmake with `-A Win32`") + message(FATAL_ERROR "You are configuring a non 32-bit build, this is not supported. Use the llvm-mingw presets (i686).") endif() set(VERSION_MAJOR 1) set(VERSION_MINOR 10) -set(VERSION_PATCH 0) +set(VERSION_PATCH 1) set(VERSION_TWEAK 0) set(VERSION_RC "${CMAKE_CURRENT_BINARY_DIR}/version.rc") @@ -20,47 +22,72 @@ configure_file("${CMAKE_CURRENT_SOURCE_DIR}/version.rc.in" "${VERSION_RC}" @ONLY set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${PROJECT_SOURCE_DIR}/bin") set(CMAKE_CXX_STANDARD 23) set(CMAKE_CXX_STANDARD_REQUIRED ON) -set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") - -add_compile_options(/MP /permissive-) list(APPEND CMAKE_MODULE_PATH "${PROJECT_SOURCE_DIR}/cmake") + find_package(libzippp CONFIG REQUIRED) find_package(minhook CONFIG REQUIRED) find_package(Microsoft.GSL CONFIG REQUIRED) -include(dxtk) +find_package(directxtex CONFIG REQUIRED) +# vcpkg's directxtex has no DDS/WIC texture loaders; these come from the same DirectXTex release, fetched by CMake. +include(directxtexloader) + +# Drop unreferenced sections (the vcpkg ports and DirectXTex build with -ffunction-sections -fdata-sections) and fold +# identical code outside Debug. Exports are roots, so the DLL's entry points stay. +add_link_options(-Wl,--gc-sections $<$>:-Wl,--icf=all>) add_library(gMod SHARED) file(GLOB SOURCES "header/*.h" "source/*.cpp" - "modules/*.ixx" ${VERSION_RC} ) +file(GLOB MODULE_SOURCES "modules/*.ixx") target_include_directories(gMod PRIVATE "header" - ${CMAKE_INSTALL_PREFIX}/include ) -source_group(TREE "${CMAKE_CURRENT_SOURCE_DIR}" FILES ${SOURCES}) +source_group(TREE "${CMAKE_CURRENT_SOURCE_DIR}" FILES ${SOURCES} ${MODULE_SOURCES}) target_sources(gMod PRIVATE ${SOURCES}) -target_compile_options(gMod PRIVATE /W4 /WX) +# CMake only scans C++ modules declared in a CXX_MODULES file set. +target_sources(gMod PRIVATE + FILE_SET CXX_MODULES + FILES ${MODULE_SOURCES} + ) + +# The C++ modules (modules/*.ixx) need the module scanner, and the module-aware standard library for import std. +set_target_properties(gMod PROPERTIES + CXX_SCAN_FOR_MODULES ON + CXX_MODULE_STD ON + PREFIX "" # MinGW would name the dll libgMod.dll; gMod.dll is the name the launchers expect + ) + +# clang's warnings in place of MSVC's /W4 /WX. +# -gdwarf-4 keeps DWARF in the link so the split below can take it out; the PDB is written separately. +# -fno-exceptions: the DLL reports failures through return values and error_code, so no unwind runtime is needed. +target_compile_options(gMod PRIVATE -Wall -Wextra -gdwarf-4 -fno-exceptions) + +# The DLL ships without DWARF. GWToolboxdll.debug-style split: the debug sections go to gMod.debug for GDB, and the +# DLL is stripped. The CodeView PDB (gMod.pdb) is unaffected. +find_program(GMOD_LLVM_OBJCOPY NAMES llvm-objcopy llvm-objcopy.exe HINTS "${LLVM_MINGW_ROOT}/bin" REQUIRED) +add_custom_command(TARGET gMod POST_BUILD + COMMAND "${GMOD_LLVM_OBJCOPY}" --only-keep-debug "$" "$/gMod.debug" + COMMAND "${GMOD_LLVM_OBJCOPY}" --strip-all "$" + VERBATIM) target_link_libraries(gMod PRIVATE dxguid libzippp::libzippp psapi minhook::minhook - directxtex + Microsoft::DirectXTex + directxtexloader Microsoft.GSL::GSL ) target_link_options(gMod PRIVATE - "$<$:/NODEFAULTLIB:LIBCMT>" - "/LARGEADDRESSAWARE" + "-Wl,--large-address-aware" ) -source_group(TREE "${CMAKE_CURRENT_SOURCE_DIR}" FILES ${SOURCES}) -target_sources(gMod PRIVATE ${SOURCES}) target_compile_definitions(gMod PRIVATE "NOMINMAX" "_WIN32_WINNT=_WIN32_WINNT_WIN7" @@ -69,5 +96,5 @@ target_compile_definitions(gMod PRIVATE DIRECT_INJECTION LOG_MESSAGE ) - + add_subdirectory(TpfConvert) diff --git a/CMakePresets.json b/CMakePresets.json index 34d75ec..59814c3 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -1,15 +1,61 @@ { - "version": 2, + "version": 3, "configurePresets": [ { - "name": "vcpkg", - "generator": "Visual Studio 18 2026", - "architecture": "Win32", - "binaryDir": "${sourceDir}/build", + "name": "base", + "hidden": true, + "displayName": "Base (not for selection)", + "description": "Builds the x86 Windows target with llvm-mingw (clang, lld, libc++, MinGW-w64) from .toolchain/, on Linux or Windows, each host in its own build// so a dual-boot checkout keeps both; each binary gets a .pdb. vcpkg comes from VCPKG_ROOT or .vcpkg/. The bootstrap scripts install both: bash bootstrap.sh (Linux) or bootstrap.bat (Windows).", + "generator": "Ninja", + "architecture": { + "value": "Win32", + "strategy": "external" + }, "cacheVariables": { - "VCPKG_OVERLAY_TRIPLETS": "${sourceDir}/triplets", - "VCPKG_TARGET_TRIPLET": "x86-windows-mixed", - "CMAKE_TOOLCHAIN_FILE": "$env{VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake" + "CMAKE_TOOLCHAIN_FILE": "${sourceDir}/cmake/vcpkg-toolchain.cmake", + "VCPKG_CHAINLOAD_TOOLCHAIN_FILE": "${sourceDir}/cmake/toolchain.cmake", + "VCPKG_OVERLAY_TRIPLETS": "${sourceDir}/vcpkg-overlays/triplets", + "VCPKG_TARGET_TRIPLET": "x86-mingw-mixed", + "CMAKE_SHARED_LINKER_FLAGS": "-static -Wl,--pdb=", + "CMAKE_EXPORT_COMPILE_COMMANDS": "ON", + "VCPKG_APPLOCAL_DEPS": "OFF", + "VCPKG_INSTALLED_DIR": "${sourceDir}/build/${hostSystemName}/vcpkg_installed" + }, + "vendor": { + "microsoft.com/VisualStudioSettings/CMake/1.0": { + "hostOS": [ + "Windows", + "Linux" + ], + "intelliSenseMode": "windows-clang-x86" + } + } + }, + { + "name": "relwithdebinfo", + "inherits": "base", + "displayName": "RelWithDebInfo (build//relwithdebinfo/)", + "binaryDir": "${sourceDir}/build/${hostSystemName}/relwithdebinfo", + "cacheVariables": { + "CMAKE_BUILD_TYPE": "RelWithDebInfo" + } + }, + { + "name": "debug", + "inherits": "base", + "displayName": "Debug (build//debug/)", + "binaryDir": "${sourceDir}/build/${hostSystemName}/debug", + "cacheVariables": { + "CMAKE_BUILD_TYPE": "Debug" + } + }, + { + "name": "release", + "inherits": "base", + "displayName": "Release (build//release/)", + "binaryDir": "${sourceDir}/build/${hostSystemName}/release", + "cacheVariables": { + "CMAKE_BUILD_TYPE": "Release" } } ] diff --git a/CMakeSettings.json b/CMakeSettings.json deleted file mode 100644 index fd27fd8..0000000 --- a/CMakeSettings.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "configurations": [ - { - "name": "x86-Debug", - "generator": "Visual Studio 17 2022", - "configurationType": "Debug", - "inheritEnvironments": [ "msvc_x86" ], - "buildRoot": "${projectDir}\\out\\build\\${name}", - "installRoot": "${projectDir}\\out\\install\\${name}", - "cmakeCommandArgs": "", - "buildCommandArgs": "", - "ctestCommandArgs": "" - }, - { - "name": "x86-Release", - "generator": "Visual Studio 17 2022", - "configurationType": "Release", - "inheritEnvironments": [ "msvc_x86" ], - "buildRoot": "${projectDir}\\out\\build\\${name}", - "installRoot": "${projectDir}\\out\\install\\${name}", - "cmakeCommandArgs": "", - "buildCommandArgs": "", - "ctestCommandArgs": "" - } - ] -} \ No newline at end of file diff --git a/README.md b/README.md index 3c12f2a..05b9285 100644 --- a/README.md +++ b/README.md @@ -26,15 +26,13 @@ If you would like to use Reshade in combination with gMod, we recommend running **Build from source** -Requirements: -- Visual Studio 2022 -- CMake 3.29+, integrated into the Developer Powershell for VS 2022 -- vcpkg, integrated into the Developer Powershell for VS 2022 +Requirements: git, Python 3.9+ and Ninja. The bootstrap installs the pinned CMake, llvm-mingw and vcpkg into the checkout. +- Linux: `bash bootstrap.sh` (installs the host packages with apt or dnf) +- Windows: `bootstrap.bat` (installs CMake and Ninja with winget if they are missing) Compile: -- cmake --preset=vcpkg -- cmake --open build -- compile +- `python3 scripts/build.py` (on Windows `python scripts\build.py`), or `--preset debug` / `--preset release` +- The DLL and TpfConvert.exe land in `bin/` **TpfConvert** Small utility to convert old .tpf files with invalid images into .zip files with working images. diff --git a/TpfConvert/CMakeLists.txt b/TpfConvert/CMakeLists.txt index 6548fdc..cbad64c 100644 --- a/TpfConvert/CMakeLists.txt +++ b/TpfConvert/CMakeLists.txt @@ -1,14 +1,20 @@ add_executable(TpfConvert) -# Find all .ixx files in the TpfConvert folder -file(GLOB TPF_SOURCES "src/*.ixx") +# .ixx files are C++ module interfaces; the .cpp file holds main() and is an ordinary source. +file(GLOB TPF_MODULES "src/*.ixx") +file(GLOB TPF_SOURCES "src/*.cpp") -# Add the .ixx files to the TpfConvert target target_sources(TpfConvert PRIVATE ${TPF_SOURCES}) +target_sources(TpfConvert PRIVATE + FILE_SET CXX_MODULES + FILES ${TPF_MODULES} + ) set_target_properties(TpfConvert PROPERTIES CXX_STANDARD 23 CXX_STANDARD_REQUIRED ON + CXX_SCAN_FOR_MODULES ON + CXX_MODULE_STD ON ) target_compile_definitions(TpfConvert PRIVATE @@ -30,10 +36,9 @@ else() message(STATUS "CMAKE_TOOLCHAIN_FILE is not set") endif() -find_package(dxsdk-d3dx CONFIG REQUIRED) - +# D3DX9 comes from llvm-mingw's MinGW-w64 import libraries (libd3dx9_43), not a vcpkg port. target_link_libraries(TpfConvert PRIVATE libzippp::libzippp - Microsoft::D3DX9 + d3dx9 d3d9 ) diff --git a/TpfConvert/src/ModfileLoader.ixx b/TpfConvert/src/ModfileLoader.ixx index 707c400..2f8c94e 100644 --- a/TpfConvert/src/ModfileLoader.ixx +++ b/TpfConvert/src/ModfileLoader.ixx @@ -1,7 +1,10 @@ +module; + +#include + export module ModfileLoader; import std; -import ; import ModfileLoader.TpfReader; export using HashType = uint64_t; diff --git a/TpfConvert/src/TpfConvert.ixx b/TpfConvert/src/TpfConvert.cpp similarity index 98% rename from TpfConvert/src/TpfConvert.ixx rename to TpfConvert/src/TpfConvert.cpp index 5260c6f..ab5e63d 100644 --- a/TpfConvert/src/TpfConvert.ixx +++ b/TpfConvert/src/TpfConvert.cpp @@ -1,13 +1,10 @@ -#include #include #include #include +#include import std; import ModfileLoader; -import ; - -struct TexEntry; namespace { IDirect3D9* pD3D = nullptr; diff --git a/bootstrap.bat b/bootstrap.bat new file mode 100644 index 0000000..05adc5a --- /dev/null +++ b/bootstrap.bat @@ -0,0 +1,118 @@ +@echo off +rem bootstrap.bat - checks and installs what Windows needs before scripts\bootstrap.py can run, then runs it. +rem bootstrap.py (shared with bootstrap.sh) installs llvm-mingw and vcpkg into the checkout and configures the build. +rem No MSVC compiler is used. +rem +rem 1. Checks for git, Python 3.9+ and Ninja (Ninja is installed with winget when missing). CMake is pinned in +rem scripts\cmake.version and installed by bootstrap.py. +rem Nothing is changed until the required ones are all present. +rem 2. Runs scripts\bootstrap.py, which also sets up the CLion, Rider and VS Code settings and writes gMod.slnx. +rem +rem Run it from the repo folder (or double-click it). + +setlocal EnableExtensions DisableDelayedExpansion +set "REPO_ROOT=%~dp0" +set "REPO_ROOT=%REPO_ROOT:~0,-1%" +cd /d "%REPO_ROOT%" + +for /f %%t in ('powershell -NoProfile -Command "Get-Date -Format yyyyMMdd-HHmmss"') do set "STAMP=%%t" +if not exist "%REPO_ROOT%\logs" mkdir "%REPO_ROOT%\logs" +set "BOOTSTRAP_LOG=%REPO_ROOT%\logs\bootstrap-%STAMP%.log" +set PROBLEMS=0 +set EXIT_CODE=0 + +call :say "bootstrap log: %BOOTSTRAP_LOG%" +call :say "==> checking prerequisites" +for %%i in (clion64.exe rider64.exe) do ( + tasklist /fi "imagename eq %%i" /nh 2>nul | find /i "%%i" >nul && call :problem "%%i is running. Close it and re-run, so it does not overwrite the .idea files." +) + +where git >nul 2>&1 && (call :say " git: found") || call :problem "git is not on PATH. Install it with: winget install --id Git.Git -e Then open a new terminal and re-run." + +set "PYTHON=" +for %%c in (python py) do if not defined PYTHON call :find_python %%c +if defined PYTHON (call :say " python: %PYTHON%") else call :problem "Python 3.9 or newer (scripts\require_python.py) is not on PATH. Install it with: winget install --id Python.Python.3.13 -e Then open a new terminal and re-run." + +set "HAS_WINGET=" +where winget >nul 2>&1 && set HAS_WINGET=1 + +where ninja >nul 2>&1 +if not errorlevel 1 ( + call :say " ninja: found" +) else if defined HAS_WINGET ( + call :say " ninja: not found; it will be installed with winget" +) else ( + call :problem "Ninja is missing and winget is not available. Install it from https://github.com/ninja-build/ninja/releases." +) + +rem Only the .slnx needs Visual Studio, and only for its C++ project system: the compiler is llvm-mingw. +set "VSWHERE=%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe" +set "VS=" +setlocal EnableDelayedExpansion +if exist "!VSWHERE!" for /f "delims=" %%v in ('call "!VSWHERE!" -latest -products * -requires Microsoft.VisualStudio.Component.VC.CoreIde -property installationPath') do set "VS=%%v" +endlocal & set "VS=%VS%" +if defined VS ( + call :say " Visual Studio with C++: %VS%" +) else ( + call :say "WARNING: Visual Studio with the Desktop development with C++ workload was not found; gMod.slnx is still written, but needs it to open. CLion, Rider and the terminal do not." +) + +if %PROBLEMS% gtr 0 ( + call :say "Missing prerequisites. Nothing was changed." + set EXIT_CODE=1 + goto finish +) + +where ninja >nul 2>&1 +if errorlevel 1 ( + call :say "==> installing Ninja with winget" + winget install -e --id Ninja-build.Ninja --accept-source-agreements --accept-package-agreements + call :refresh_path +) +where ninja >nul 2>&1 +if errorlevel 1 ( + call :say "Ninja was installed but this shell cannot see it yet. Open a new terminal and re-run." + set EXIT_CODE=1 + goto finish +) + +"%PYTHON%" "%REPO_ROOT%\scripts\bootstrap.py" --log "%BOOTSTRAP_LOG%" +set EXIT_CODE=%errorlevel% + +rem Keeps a double-clicked window open to read; with input from nul (bootstrap.bat ^nul +exit /b %EXIT_CODE% + + +rem Echoed through delayed expansion, so cmd does not read the > in "==>" as a redirection. +:say +setlocal EnableDelayedExpansion +set "MESSAGE=%~1" +echo(!MESSAGE! +>>"%BOOTSTRAP_LOG%" echo(!MESSAGE! +endlocal +exit /b 0 + +:problem +set /a PROBLEMS+=1 +call :say " - %~1" +exit /b 0 + +rem Each python on PATH except the Microsoft Store placeholder, which only opens the Store; the scripts' own check +rem prints the interpreter's path when it is new enough. +:find_python +for /f "delims=" %%p in ('where %1 2^>nul') do ( + echo %%p| find /i "\WindowsApps\" >nul || ( + if not defined PYTHON for /f "delims=" %%e in ('call "%%p" "%REPO_ROOT%\scripts\require_python.py" 2^>nul') do set "PYTHON=%%e" + ) +) +exit /b 0 + +rem winget updates the machine and user PATH; pick that up without starting a new shell. +:refresh_path +for /f "delims=" %%p in ('powershell -NoProfile -Command "[Environment]::GetEnvironmentVariable('Path','Machine') + ';' + [Environment]::GetEnvironmentVariable('Path','User')"') do set "PATH=%%p" +exit /b 0 diff --git a/bootstrap.sh b/bootstrap.sh new file mode 100644 index 0000000..2101a2e --- /dev/null +++ b/bootstrap.sh @@ -0,0 +1,90 @@ +#!/usr/bin/env bash +# Checks and installs what Linux needs before scripts/bootstrap.py can run, then runs it. bootstrap.py installs +# llvm-mingw and vcpkg into the checkout and configures the build. It builds nothing; the last lines say how. +# +# 1. Installs the missing host packages with apt (Debian/Ubuntu) or dnf (Fedora): git, curl, python3, ninja, +# and vcpkg's zip/unzip/pkg-config. CMake is pinned in scripts/cmake.version and installed by bootstrap.py. +# 2. Runs scripts/bootstrap.py. +# +# Run it from anywhere: bash bootstrap.sh +set -euo pipefail + +if [ "$(uname -s)" != "Linux" ]; then + echo "bootstrap.sh is for Linux. On Windows run bootstrap.bat instead." >&2 + exit 1 +fi + +REPO_ROOT=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd) +cd "$REPO_ROOT" + +# Everything this script prints also goes to a timestamped log, which bootstrap.py then appends to. +mkdir -p logs +BOOTSTRAP_LOG="${REPO_ROOT}/logs/bootstrap-$(date +%Y%m%d-%H%M%S).log" +exec 3>&1 4>&2 +exec > >(tee -a "$BOOTSTRAP_LOG") 2>&1 +echo "bootstrap log: ${BOOTSTRAP_LOG}" + +log() { echo "==> $*"; } +die() { echo "bootstrap: $*" >&2; exit 1; } + +# A running CLion or Rider rewrites its .idea files on exit, which would undo what the bootstrap writes there. A Flatpak +# IDE's sandbox is a bwrap process whose descendants are the IDE. After the IDE closes, only the JetBrains daemon can be +# left behind, so a sandbox counts as running only when it has a descendant other than that daemon. +ide_sandbox_busy() { + local child + for child in $(pgrep -P "$1" 2>/dev/null); do + if [ "$(ps -o comm= -p "$child")" != "jetbrainsd" ] || ide_sandbox_busy "$child"; then + return 0 + fi + done + return 1 +} +running_ides="" +for sandbox in $(pgrep -f 'bwrap .*-- (rider-wrapper|clion)( |$)' 2>/dev/null); do + if ide_sandbox_busy "$sandbox"; then + running_ides="$running_ides $sandbox" + fi +done +if pgrep -x clion >/dev/null 2>&1 || pgrep -x rider >/dev/null 2>&1 || [ -n "$running_ides" ]; then + die "CLion or Rider is running (${running_ides:-native}). Close it and re-run, so it does not overwrite the .idea files." +fi +# The IDEs run CMake on the host through flatpak-spawn, so closing or killing the IDE does not stop a reload that is +# under way; it keeps writing into build/ and would race the bootstrap's configure. +if pgrep -f -- "${REPO_ROOT}/build/" >/dev/null 2>&1; then + die "A CMake run started by an IDE is still using this checkout's build/. Wait for it to finish, then re-run." +fi + +APT_PACKAGES=(git curl tar xz-utils python3 ninja-build zip unzip pkg-config) +DNF_PACKAGES=(git curl tar xz python3 ninja-build zip unzip pkgconf-pkg-config) + +if command -v dpkg-query >/dev/null 2>&1; then + missing=() + for pkg in "${APT_PACKAGES[@]}"; do + dpkg-query -W -f='${Status}' "$pkg" 2>/dev/null | grep -q "install ok installed" || missing+=("$pkg") + done + if [ "${#missing[@]}" -eq 0 ]; then + log "host packages already present" + else + log "installing missing packages with apt: ${missing[*]}" + sudo apt-get update + sudo apt-get install -y --no-install-recommends "${missing[@]}" + fi +elif command -v dnf >/dev/null 2>&1; then + missing=() + for pkg in "${DNF_PACKAGES[@]}"; do + rpm -q "$pkg" >/dev/null 2>&1 || missing+=("$pkg") + done + if [ "${#missing[@]}" -eq 0 ]; then + log "host packages already present" + else + log "installing missing packages with dnf: ${missing[*]}" + sudo dnf install -y "${missing[@]}" + fi +else + die "this script installs packages with apt or dnf; on another distro install the equivalents of: ${APT_PACKAGES[*]}, then run python3 scripts/bootstrap.py" +fi + +python3 "${REPO_ROOT}/scripts/require_python.py" >/dev/null || die "install a newer python3, then re-run" + +exec 1>&3 2>&4 3>&- 4>&- +exec python3 "${REPO_ROOT}/scripts/bootstrap.py" --log "$BOOTSTRAP_LOG" diff --git a/bootstrap/README.md b/bootstrap/README.md new file mode 100644 index 0000000..9947d6b --- /dev/null +++ b/bootstrap/README.md @@ -0,0 +1,19 @@ +# IDE settings + +`scripts/bootstrap.py` copies these into the checkout (backing up what it replaces to `bootstrap-backup/`): + +- `idea/` (Linux) and `idea-windows/` (Windows): the CLion module file. It excludes the toolchain, vcpkg, build, + bin and log folders from indexing. +- `vscode/`: settings and recommended extensions for VS Code (clangd and CMake Tools), pointed at the presets and + `.toolchain/`. + +CLion and Rider use the `relwithdebinfo`, `debug` and `release` CMake profiles from `CMakePresets.json`. On Linux the +bootstrap also sets up the Flatpak CLion and Rider: their sandbox reaches the host's CMake and ninja through +`.toolchain/host-tools/bin/host-tool`, and their Default toolchain points at the pinned CMake (`scripts/cmake.version`). + +On Windows the bootstrap writes `gMod.slnx` for Visual Studio and Rider, from `scripts/vs_solution.py`. Its build, +clean and rebuild commands call `scripts/build.py --target`. Re-run `python scripts/vs_solution.py` after adding or +removing source files. + +Close CLion and Rider before running the bootstrap: both rewrite their own settings on exit. `bootstrap.sh` and +`bootstrap.bat` refuse to run while either is open. diff --git a/bootstrap/idea-windows/gMod.iml b/bootstrap/idea-windows/gMod.iml new file mode 100644 index 0000000..649e0a4 --- /dev/null +++ b/bootstrap/idea-windows/gMod.iml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/bootstrap/idea/gMod.iml b/bootstrap/idea/gMod.iml new file mode 100644 index 0000000..649e0a4 --- /dev/null +++ b/bootstrap/idea/gMod.iml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/bootstrap/vscode/extensions.json b/bootstrap/vscode/extensions.json new file mode 100644 index 0000000..891fd2b --- /dev/null +++ b/bootstrap/vscode/extensions.json @@ -0,0 +1,9 @@ +{ + "recommendations": [ + "llvm-vs-code-extensions.vscode-clangd", + "ms-vscode.cmake-tools" + ], + "unwantedRecommendations": [ + "ms-vscode.cpptools" + ] +} diff --git a/bootstrap/vscode/settings.json b/bootstrap/vscode/settings.json new file mode 100644 index 0000000..cba7511 --- /dev/null +++ b/bootstrap/vscode/settings.json @@ -0,0 +1,30 @@ +{ + "clangd.path": "${workspaceFolder}/.toolchain/llvm-mingw-linux/bin/clangd", + "clangd.checkUpdates": false, + "clangd.arguments": [ + "--compile-commands-dir=${workspaceFolder}/build/Linux/relwithdebinfo", + "--background-index=false", + "--header-insertion=never" + ], + "C_Cpp.intelliSenseEngine": "disabled", + "cmake.useCMakePresets": "always", + "cmake.configureOnOpen": false, + "files.watcherExclude": { + "**/.toolchain/**": true, + "**/.vcpkg/**": true, + "**/.vs-projects/**": true, + "**/build*/**": true, + "**/bin*/**": true, + "**/logs/**": true, + "**/obj/**": true + }, + "search.exclude": { + "**/.toolchain": true, + "**/.vcpkg": true, + "**/.vs-projects": true, + "**/build*": true, + "**/bin*": true, + "**/logs": true, + "**/obj": true + } +} diff --git a/cmake/directxtexloader.cmake b/cmake/directxtexloader.cmake new file mode 100644 index 0000000..826c189 --- /dev/null +++ b/cmake/directxtexloader.cmake @@ -0,0 +1,29 @@ +include_guard() +include(FetchContent) + +cmake_policy(PUSH) +cmake_policy(SET CMP0169 OLD) +FetchContent_Declare( + directxtexloader + URL https://github.com/microsoft/DirectXTex/archive/refs/tags/oct2024.tar.gz + URL_HASH SHA256=0caea49c52bba24eb6025ad1f46c9aa00224e91c075b55a21b738a23ed5fedfe) +FetchContent_GetProperties(directxtexloader) +if (directxtexloader_POPULATED) + return() +endif() + +FetchContent_Populate(directxtexloader) +cmake_policy(POP) + +add_library(directxtexloader) +set(SOURCES + "${directxtexloader_SOURCE_DIR}/DDSTextureLoader/DDSTextureLoader9.h" + "${directxtexloader_SOURCE_DIR}/DDSTextureLoader/DDSTextureLoader9.cpp" + "${directxtexloader_SOURCE_DIR}/WICTextureLoader/WICTextureLoader9.h" + "${directxtexloader_SOURCE_DIR}/WICTextureLoader/WICTextureLoader9.cpp" + ) +source_group(TREE ${directxtexloader_SOURCE_DIR} FILES ${SOURCES}) +target_sources(directxtexloader PRIVATE ${SOURCES}) +target_include_directories(directxtexloader PUBLIC "${directxtexloader_SOURCE_DIR}") + +set_target_properties(directxtexloader PROPERTIES FOLDER "Dependencies/") diff --git a/cmake/dxtk.cmake b/cmake/dxtk.cmake deleted file mode 100644 index bd6e79d..0000000 --- a/cmake/dxtk.cmake +++ /dev/null @@ -1,31 +0,0 @@ -include_guard() -include(FetchContent) - -FetchContent_Declare( - DirectXTex - GIT_REPOSITORY https://github.com/microsoft/DirectXTex - GIT_TAG oct2023) -FetchContent_GetProperties(directxtex) -if (directxtex_POPULATED) - return() -endif() - -FetchContent_Populate(directxtex) - -add_library(directxtex) -file(GLOB SOURCES - "${directxtex_SOURCE_DIR}/DDSTextureLoader/DDSTextureLoader9.h" - "${directxtex_SOURCE_DIR}/DDSTextureLoader/DDSTextureLoader9.cpp" - "${directxtex_SOURCE_DIR}/WICTextureLoader/WICTextureLoader9.h" - "${directxtex_SOURCE_DIR}/WICTextureLoader/WICTextureLoader9.cpp" - "${directxtex_SOURCE_DIR}/DirectXTex/*.h" - "${directxtex_SOURCE_DIR}/DirectXTex/*.cpp" - ) -list(REMOVE_ITEM SOURCES - "${directxtex_SOURCE_DIR}/DirectXTex/BCDirectCompute.cpp" - ) -source_group(TREE ${directxtex_SOURCE_DIR} FILES ${SOURCES}) -target_sources(directxtex PRIVATE ${SOURCES}) -target_include_directories(directxtex PUBLIC "${directxtex_SOURCE_DIR}") - -set_target_properties(directxtex PROPERTIES FOLDER "Dependencies/") diff --git a/cmake/toolchain.cmake b/cmake/toolchain.cmake new file mode 100644 index 0000000..a8aa98d --- /dev/null +++ b/cmake/toolchain.cmake @@ -0,0 +1,48 @@ +set(CMAKE_SYSTEM_NAME Windows) +set(CMAKE_SYSTEM_PROCESSOR x86) + +# llvm-mingw (clang, lld, libc++, MinGW-w64), installed by bootstrap.sh / bootstrap.bat. +# clang rather than GCC because only clang writes CodeView, so crash dumps are debugged against a .pdb. +# One folder per host, so a dual-boot checkout keeps both builds instead of each bootstrap replacing the other's. +if(CMAKE_HOST_WIN32) + set(LLVM_MINGW_HOST "windows") + set(LLVM_MINGW_EXE ".exe") +else() + set(LLVM_MINGW_HOST "linux") +endif() +get_filename_component(LLVM_MINGW_ROOT "${CMAKE_CURRENT_LIST_DIR}/../.toolchain/llvm-mingw-${LLVM_MINGW_HOST}" ABSOLUTE) +if(NOT EXISTS "${LLVM_MINGW_ROOT}/bin") + message(FATAL_ERROR "llvm-mingw not found at ${LLVM_MINGW_ROOT}; run the bootstrap script for this platform") +endif() +set(LLVM_MINGW_PREFIX "${LLVM_MINGW_ROOT}/bin/i686-w64-mingw32-") + +set(CMAKE_C_COMPILER "${LLVM_MINGW_PREFIX}clang${LLVM_MINGW_EXE}") +set(CMAKE_CXX_COMPILER "${LLVM_MINGW_PREFIX}clang++${LLVM_MINGW_EXE}") +set(CMAKE_RC_COMPILER "${LLVM_MINGW_PREFIX}windres${LLVM_MINGW_EXE}") +set(CMAKE_AR "${LLVM_MINGW_PREFIX}ar${LLVM_MINGW_EXE}") +set(CMAKE_RANLIB "${LLVM_MINGW_PREFIX}ranlib${LLVM_MINGW_EXE}") + +# On a case-sensitive host, includes like resolve through symlinks made by scripts/toolchain.py. +# Never on Windows: a dual-boot checkout's Linux symlinks are unreadable there and shadow the real headers. +get_filename_component(MINGW_CASE_INCLUDE_DIR "${CMAKE_CURRENT_LIST_DIR}/../.toolchain/case-include" ABSOLUTE) +if(NOT CMAKE_HOST_WIN32 AND EXISTS "${MINGW_CASE_INCLUDE_DIR}") + set(CMAKE_C_STANDARD_INCLUDE_DIRECTORIES "${MINGW_CASE_INCLUDE_DIR}") + set(CMAKE_CXX_STANDARD_INCLUDE_DIRECTORIES "${MINGW_CASE_INCLUDE_DIR}") + set(CMAKE_RC_FLAGS_INIT "-I${MINGW_CASE_INCLUDE_DIR}") +endif() + +# Function and data sections let the linker drop what the dll doesn't use, including from the vcpkg ports, which +# build with this file too (libuv alone carried 200 KB of unused filesystem code without them). +set(CMAKE_C_FLAGS_INIT "-gcodeview -ffunction-sections -fdata-sections -Wno-error=incompatible-pointer-types -Wno-error=incompatible-function-pointer-types") +set(CMAKE_CXX_FLAGS_INIT "-gcodeview -ffunction-sections -fdata-sections") + +set(CMAKE_FIND_ROOT_PATH "${LLVM_MINGW_ROOT}/i686-w64-mingw32") +set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) +set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY BOTH) +set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE BOTH) + +# The dll is injected into Gw.exe, so the C++ runtime is linked in statically. --pdb= names the .pdb after the output. +# Shared libraries keep their DWARF through the link so the build can split it out for GDB. +set(CMAKE_EXE_LINKER_FLAGS_INIT "-static -Wl,--pdb= -Wl,-s") +set(CMAKE_MODULE_LINKER_FLAGS_INIT "-static -Wl,--pdb= -Wl,-s") +set(CMAKE_SHARED_LINKER_FLAGS_INIT "-static -Wl,--pdb=") diff --git a/cmake/vcpkg-toolchain.cmake b/cmake/vcpkg-toolchain.cmake new file mode 100644 index 0000000..19a5ffc --- /dev/null +++ b/cmake/vcpkg-toolchain.cmake @@ -0,0 +1,8 @@ +# vcpkg from VCPKG_ROOT, or else the checkout the bootstrap scripts make in .vcpkg/, so IDEs need no environment. +if(DEFINED ENV{VCPKG_ROOT} AND EXISTS "$ENV{VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake") + include("$ENV{VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake") +elseif(EXISTS "${CMAKE_CURRENT_LIST_DIR}/../.vcpkg/scripts/buildsystems/vcpkg.cmake") + include("${CMAKE_CURRENT_LIST_DIR}/../.vcpkg/scripts/buildsystems/vcpkg.cmake") +else() + message(FATAL_ERROR "vcpkg not found in VCPKG_ROOT or .vcpkg/; run the bootstrap script for this platform") +endif() diff --git a/header/Main.h b/header/Main.h index df387cd..f5e094f 100644 --- a/header/Main.h +++ b/header/Main.h @@ -5,7 +5,6 @@ #include #include #include -#include #include #include #include @@ -19,7 +18,9 @@ #include "D3D9State.h" +#ifdef _MSC_VER #pragma warning(disable : 4477) +#endif extern unsigned int gl_ErrorState; extern HINSTANCE gl_hThisInstance; diff --git a/header/Utils.h b/header/Utils.h index 518420c..549599a 100644 --- a/header/Utils.h +++ b/header/Utils.h @@ -1,8 +1,42 @@ #pragma once +#include +#include #include namespace utils { + // The whole file as bytes, or empty if it cannot be opened. Uses the C runtime, not iostreams, to keep the DLL small. + inline std::string ReadWholeFile(const std::filesystem::path& path) + { + std::string data; + FILE* file = _wfopen(path.c_str(), L"rb"); + if (!file) return data; + char buffer[4096]; + size_t count = 0; + while ((count = std::fread(buffer, 1, sizeof(buffer), file)) > 0) { + data.append(buffer, count); + } + std::fclose(file); + return data; + } + + // The lines of text as repeated std::getline calls would return them, without the iostream machinery. + inline std::vector SplitLines(const std::string& text) + { + std::vector lines; + size_t start = 0; + while (start < text.size()) { + const auto end = text.find('\n', start); + if (end == std::string::npos) { + lines.push_back(text.substr(start)); + break; + } + lines.push_back(text.substr(start, end - start)); + start = end + 1; + } + return lines; + } + template void erase_first(std::vector& vec, const T& elem) { @@ -12,13 +46,14 @@ namespace utils { } } - inline std::wstring utf8_to_wstring(const std::string& utf8str) + // Empty when the text is not valid UTF-8 (the caller decides what to skip). + inline std::optional utf8_to_wstring(const std::string& utf8str) { - if (utf8str.empty()) return {}; + if (utf8str.empty()) return std::wstring{}; // Calculate the number of wide characters needed for the conversion const int count = MultiByteToWideChar(CP_UTF8, 0, utf8str.c_str(), -1, nullptr, 0); - if (count == 0) throw std::runtime_error("Failed to convert UTF-8 to UTF-16"); + if (count == 0) return std::nullopt; std::wstring wstr(count, 0); MultiByteToWideChar(CP_UTF8, 0, utf8str.c_str(), -1, wstr.data(), count); diff --git a/modules/ModfileLoader.ixx b/modules/ModfileLoader.ixx index e38c3cc..c3c8bb8 100644 --- a/modules/ModfileLoader.ixx +++ b/modules/ModfileLoader.ixx @@ -2,40 +2,46 @@ module; #include "Main.h" #include "Defines.h" +#include export module ModfileLoader; import std; -import ; import ModfileLoader.TpfReader; import TextureFunction; namespace { bool use_64_bit_crc = false; + // Finds the first "0x" or "0X" followed by 4 to 16 hex digits (the match a regex of 0[xX][0-9a-fA-F]{4,16} would + // give). Sixteen hex digits always fit a uint64_t, so the parse cannot fail or overflow. HashType GetCrcFromFilename(const std::string& filename) { - const static std::regex re(R"(0[xX][0-9a-fA-F]{4,16})", std::regex::optimize); - std::smatch match; - if (!std::regex_search(filename, match, re)) { - return 0; + auto is_hex = [](const char c) { + return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'); + }; + for (size_t i = 0; i + 1 < filename.size(); ++i) { + if (filename[i] != '0' || (filename[i + 1] != 'x' && filename[i + 1] != 'X')) { + continue; + } + size_t digits = 0; + while (digits < 16 && i + 2 + digits < filename.size() && is_hex(filename[i + 2 + digits])) { + ++digits; + } + if (digits < 4) { + continue; + } + uint64_t crc64_hash = 0; + for (size_t d = 0; d < digits; ++d) { + const char c = filename[i + 2 + d]; + const uint64_t value = (c >= 'a') ? (c - 'a' + 10) : (c >= 'A') ? (c - 'A' + 10) + : (c - '0'); + crc64_hash = crc64_hash * 16 + value; + } + use_64_bit_crc = use_64_bit_crc || crc64_hash > 0xFFFFFFFF; + return crc64_hash; } - - uint64_t crc64_hash = 0; - const auto number_str = match.str(); - try { - crc64_hash = std::stoull(number_str, nullptr, 16); - } - catch (const std::invalid_argument&) { - Warning("Failed to parse %s as a hash\n", filename.c_str()); - return 0; - } - catch (const std::out_of_range&) { - Warning("Out of range while parsing %s as a hash\n", filename.c_str()); - return 0; - } - use_64_bit_crc = use_64_bit_crc || crc64_hash > 0xFFFFFFFF; - return crc64_hash; + return 0; } } @@ -71,24 +77,24 @@ private: ModfileLoader::ModfileLoader(const std::filesystem::path& fileName) { - file_name = std::filesystem::absolute(fileName); + std::error_code ec; + const auto absolute_name = std::filesystem::absolute(fileName, ec); + file_name = ec ? fileName : absolute_name; } std::vector ModfileLoader::GetContents() const { - try { - return file_name.wstring().ends_with(L".tpf") ? GetTpfContents() : GetFileContents(); - } - catch (const std::exception&) { - Warning("Failed to open mod file: %s\n", file_name.c_str()); - } - return {}; + return file_name.wstring().ends_with(L".tpf") ? GetTpfContents() : GetFileContents(); } std::vector ModfileLoader::GetTpfContents() const { std::vector entries; auto tpf_reader = TpfReader(file_name); + if (!tpf_reader.IsOpen()) { + Warning("Failed to open mod file: %s\n", file_name.c_str()); + return {}; + } const auto buffer = tpf_reader.ReadToEnd(); const auto zip_archive = libzippp::ZipArchive::fromBuffer(buffer.data(), buffer.size(), false, TPF_PASSWORD); if (!zip_archive) { @@ -139,19 +145,40 @@ void ParseSimpleArchive(const libzippp::ZipArchive& archive, std::vector& lines, libzippp::ZipArchive& archive, std::vector& entries) { for (const auto& line : lines) { // 0xC57D73F7|GW.EXE_0xC57D73F7.tga\r\n - // match[1] | match[2] - const static auto address_file_regex = std::regex(R"(^[\\/.]*([^|]+)\|([^\r\n]+))", std::regex::optimize); - std::smatch match; - if (!std::regex_search(line, match, address_file_regex)) { + // address | file_path + std::string address_string; + std::string file_path; + if (!ParseAddressLine(line, address_string, file_path)) { Warning("Failed to parse texmod.def archive line: %s - %s", line.c_str(), line.c_str()); continue; } - const auto address_string = match[1].str(); - const auto file_path = match[2].str(); const auto crc_hash = GetCrcFromFilename(address_string); if (!crc_hash) @@ -177,15 +204,7 @@ void ModfileLoader::LoadEntries(libzippp::ZipArchive& archive, std::vector lines; - std::string line; - - while (std::getline(iss, line)) { - lines.push_back(line); - } - + auto lines = utils::SplitLines(def_file.readAsText()); ParseTexmodArchive(lines, archive, entries); } } diff --git a/modules/ModfileLoader_TpfReader.ixx b/modules/ModfileLoader_TpfReader.ixx index 36e9f9f..128b13c 100644 --- a/modules/ModfileLoader_TpfReader.ixx +++ b/modules/ModfileLoader_TpfReader.ixx @@ -1,30 +1,39 @@ +module; + +#include + export module ModfileLoader.TpfReader; import std; export class TpfReader { public: + // Reads the whole file up front through the C runtime (iostreams would pull in the locale machinery). + // Check IsOpen() before ReadToEnd(): an unreadable file leaves the reader empty. TpfReader(const std::filesystem::path& path) { - file_stream = std::ifstream(path, std::ios::binary); - if (!file_stream.seekg(0, std::ios::end).good() || !file_stream.seekg(0, std::ios::beg).good()) { - throw std::invalid_argument("Provided stream needs to have SEEK set to True"); + FILE* file = _wfopen(path.c_str(), L"rb"); + if (!file) { + return; } + char buffer[4096]; + size_t count = 0; + while ((count = std::fread(buffer, 1, sizeof(buffer), file)) > 0) { + contents.insert(contents.end(), buffer, buffer + count); + } + std::fclose(file); + line_length = static_cast(contents.size()); + opened = true; } - ~TpfReader() + [[nodiscard]] bool IsOpen() const { - file_stream.close(); + return opened; } std::vector ReadToEnd() { - file_stream.seekg(0, std::ios::end); - line_length = file_stream.tellg(); - file_stream.seekg(0, std::ios::beg); // Go to the beginning of the stream - - std::vector data(static_cast(line_length)); - file_stream.read(data.data(), line_length); + std::vector data = contents; for (auto i = 0u; i < data.size(); i++) { data[i] = XOR(data[i], i); } @@ -41,8 +50,9 @@ public: } private: - std::ifstream file_stream; - std::streamoff line_length = 0; + std::vector contents; + long line_length = 0; + bool opened = false; [[nodiscard]] char XOR(const char b, const long position) const { diff --git a/modules/TextureClient.ixx b/modules/TextureClient.ixx index 6d41f39..d3c1d56 100644 --- a/modules/TextureClient.ixx +++ b/modules/TextureClient.ixx @@ -4,7 +4,7 @@ module; #include "Error.h" #include "D3D9State.h" #include -#include +#include #include #include @@ -159,9 +159,9 @@ TextureClient::~TextureClient() std::lock_guard lk(registry_mutex); shutting_down = true; // the texture Release hook now no-ops for our textures - // Release replacements we still own (still partnered) so they aren't leaked when - // torn down with the device alive (FreeLibrary). Orphaned fakes were already - // released; a device-release teardown leaves the maps empty, so this is a no-op. + // Release replacements we still own (still partnered) so they aren't leaked. The device + // is alive here on both paths: FreeLibrary, and device release, where D3D9Hooks holds a + // reference across this teardown. Orphaned fakes were already released. for (const auto fake : fakes | std::views::values) { if (fake->partner != nullptr) { fake->partner->partner = nullptr; // detach the original's back-pointer @@ -556,7 +556,9 @@ std::vector TextureClient::GetFiles() int TextureClient::RemoveFile(const std::filesystem::path& path) { - const auto absolute_path = std::filesystem::absolute(path); + std::error_code ec; + const auto absolute_path = std::filesystem::absolute(path, ec); + if (ec) return RETURN_FILE_NOT_LOADED; std::lock_guard lk(global_mutex); const auto it = FindLoadedFile(absolute_path); if (it == loaded_files.end()) return RETURN_FILE_NOT_LOADED; @@ -571,14 +573,17 @@ int TextureClient::RemoveFile(const std::filesystem::path& path) int TextureClient::AddFile(const std::filesystem::path& path) { - const auto absolute_path = std::filesystem::absolute(path); + std::error_code ec; + const auto absolute_path = std::filesystem::absolute(path, ec); + if (ec) return RETURN_FILE_NOT_LOADED; { std::lock_guard lk(global_mutex); if (FindLoadedFile(absolute_path) != loaded_files.end()) return RETURN_EXISTS; } - if (!std::filesystem::exists(absolute_path)) return RETURN_FILE_NOT_LOADED; + if (!std::filesystem::exists(absolute_path, ec) || ec) return RETURN_FILE_NOT_LOADED; - const auto file_size = std::filesystem::file_size(absolute_path); + const auto file_size = std::filesystem::file_size(absolute_path, ec); + if (ec) return RETURN_FILE_NOT_LOADED; auto texture_file_structs = ProcessModfile(absolute_path, file_size > 400'000'000); if (texture_file_structs.empty()) return RETURN_FILE_NOT_LOADED; @@ -598,12 +603,9 @@ int TextureClient::AddFile(const std::filesystem::path& path) void TextureClient::LoadStartupModlists() { - std::locale::global(std::locale("")); std::vector modfiles; for (const auto& content : modlists_contents | std::views::values) { - std::istringstream iss(content); - std::string line; - while (std::getline(iss, line)) { + for (auto line : utils::SplitLines(content)) { if (line.starts_with("//") || line.starts_with("#") || line.empty()) { continue; } @@ -612,7 +614,14 @@ void TextureClient::LoadStartupModlists() line.erase(std::ranges::remove(line, '\n').begin(), line.end()); if (line.empty()) continue; - auto modfile = std::filesystem::absolute(std::filesystem::path(utils::utf8_to_wstring(line))); + const auto wide_line = utils::utf8_to_wstring(line); + if (!wide_line) { + Warning("Skipping modlist line that is not valid UTF-8: %s\n", line.c_str()); + continue; + } + std::error_code ec; + auto modfile = std::filesystem::absolute(std::filesystem::path(*wide_line), ec); + if (ec) continue; if (!std::ranges::contains(modfiles, modfile)) { modfiles.push_back(std::move(modfile)); } @@ -621,7 +630,10 @@ void TextureClient::LoadStartupModlists() auto total_size = 0ull; for (const auto& modfile : modfiles) { - if (std::filesystem::exists(modfile)) total_size += std::filesystem::file_size(modfile); + std::error_code ec; + if (!std::filesystem::exists(modfile, ec) || ec) continue; + const auto size = std::filesystem::file_size(modfile, ec); + if (!ec) total_size += size; } const bool compress = total_size > 400'000'000; @@ -657,8 +669,10 @@ void TextureClient::Initialize() // AddFile() before the device existed recorded files but couldn't enqueue them // (no client yet); enqueue them now. for (const auto& path : GetFiles()) { - if (!std::filesystem::exists(path)) continue; - const auto file_size = std::filesystem::file_size(path); + std::error_code ec; + if (!std::filesystem::exists(path, ec) || ec) continue; + const auto file_size = std::filesystem::file_size(path, ec); + if (ec) continue; auto texture_file_structs = ProcessModfile(path, file_size > 400'000'000); IngestModfile(texture_file_structs); } diff --git a/modules/TextureFunction.ixx b/modules/TextureFunction.ixx index a2ba01f..ae1962e 100644 --- a/modules/TextureFunction.ixx +++ b/modules/TextureFunction.ixx @@ -2,10 +2,12 @@ module; #include "Main.h" #include -#include +#include export module TextureFunction; +import std; + // clang-format off constexpr auto crctab64 = std::to_array({ 0x0000000000000000ULL, 0x7ad870c830358979ULL, 0xf5b0e190606b12f2ULL, @@ -304,27 +306,34 @@ export namespace TextureFunction { void ImageSave(const DirectX::ScratchImage& image, const TexEntry& entry) { - const auto file_name = std::format("0x{:x}.dds", entry.crc_hash); + char name_buffer[32]; + std::snprintf(name_buffer, sizeof(name_buffer), "0x%llx.dds", static_cast(entry.crc_hash)); + const std::string file_name = name_buffer; const auto file_out = gmod_dll_path.parent_path() / "textures" / file_name; - try { - if (std::filesystem::exists(file_out)) { - return; - } - if (!std::filesystem::exists(file_out.parent_path())) { - std::filesystem::create_directory(file_out.parent_path()); - } - const auto hr = DirectX::SaveToDDSFile( - image.GetImages(), - image.GetImageCount(), - image.GetMetadata(), - DirectX::DDS_FLAGS_NONE, - file_out.c_str()); - if (FAILED(hr)) { - Warning("SaveDDSImageToDisk (%#lX%s): FAILED\n", entry.crc_hash, entry.ext.c_str()); - } + std::error_code ec; + if (std::filesystem::exists(file_out, ec)) { + return; + } + if (ec) { + Warning("SaveDDSImageToDisk (%#lX%s): %s\n", entry.crc_hash, entry.ext.c_str(), ec.message().c_str()); + return; + } + const auto parent = file_out.parent_path(); + if (!std::filesystem::exists(parent, ec) && !ec) { + std::filesystem::create_directory(parent, ec); } - catch (const std::exception& e) { - Warning("SaveDDSImageToDisk (%#lX%s): %s\n", entry.crc_hash, entry.ext.c_str(), e.what()); + if (ec) { + Warning("SaveDDSImageToDisk (%#lX%s): %s\n", entry.crc_hash, entry.ext.c_str(), ec.message().c_str()); + return; + } + const auto hr = DirectX::SaveToDDSFile( + image.GetImages(), + image.GetImageCount(), + image.GetMetadata(), + DirectX::DDS_FLAGS_NONE, + file_out.c_str()); + if (FAILED(hr)) { + Warning("SaveDDSImageToDisk (%#lX%s): FAILED\n", entry.crc_hash, entry.ext.c_str()); } } diff --git a/scripts/bootstrap.py b/scripts/bootstrap.py new file mode 100644 index 0000000..705937e --- /dev/null +++ b/scripts/bootstrap.py @@ -0,0 +1,132 @@ +#!/usr/bin/env python3 +"""Sets this checkout up to build gMod with llvm-mingw from the terminal, CLion, Rider, VS Code or Visual Studio. The +native bootstrap.sh / bootstrap.bat check and install the prerequisites, then run this. It builds nothing; the last +lines say how. Re-running is cheap: each step is skipped when its output is current. + + 1. Copies the IDE settings in bootstrap/ into .idea/ (and on Linux .vscode/), backing up what they replace. + 2. Installs the pinned CMake and llvm-mingw into .toolchain/ (on Linux also the header links). + 3. Checks vcpkg out at the registry baseline into .vcpkg/, unless VCPKG_ROOT already points at a checkout. + 4. Linux: sets the CLion and Rider Flatpaks up to reach the host's CMake through a wrapper. + 5. Configures the relwithdebinfo preset into build//relwithdebinfo/ (no build). + 6. Enables the relwithdebinfo, debug and release CMake profiles for the JetBrains IDEs. + 7. Windows: writes gMod.slnx for Visual Studio and Rider. Linux: installs the VS Code extensions. +""" + +import require_python # noqa: F401 (first: stops an old Python before anything else runs) + +import argparse +import json +import os +import shutil + +import ide_setup +import toolchain +import vs_solution +from common import IS_WINDOWS, LOG_DIR, PRESET_BUILD_DIRS, REPO_ROOT, Log, capture, find_cmake, main_guard, run, timestamp + +LOCAL_VCPKG = os.path.join(REPO_ROOT, ".vcpkg") + + +# vcpkg's helper scripts are part of each package's ABI hash, so checking it out at the registry baseline gives every +# machine the same hashes, and packages built once come from vcpkg's binary cache after that. +def ensure_vcpkg(log): + existing = os.environ.get("VCPKG_ROOT") + if existing and os.path.isfile(os.path.join(existing, "scripts", "buildsystems", "vcpkg.cmake")): + log.step("using VCPKG_ROOT=" + existing) + return existing + with open(os.path.join(REPO_ROOT, "vcpkg-configuration.json"), encoding="utf-8") as file: + baseline = json.load(file)["default-registry"]["baseline"] + head = (capture(["git", "-C", LOCAL_VCPKG, "rev-parse", "HEAD"]) or "").strip() if os.path.isdir( + os.path.join(LOCAL_VCPKG, ".git")) else "" + if head != baseline: + log.step("checking vcpkg out at the registry baseline %s into .vcpkg/" % baseline[:12]) + if not os.path.isdir(os.path.join(LOCAL_VCPKG, ".git")): + run(log, ["git", "init", "-q", LOCAL_VCPKG]) + run(log, ["git", "-C", LOCAL_VCPKG, "fetch", "-q", "--depth", "1", "https://github.com/microsoft/vcpkg.git", baseline]) + run(log, ["git", "-C", LOCAL_VCPKG, "checkout", "-q", "--force", "FETCH_HEAD"]) + if not os.path.isfile(os.path.join(LOCAL_VCPKG, "vcpkg.exe" if IS_WINDOWS else "vcpkg")): + log.step("bootstrapping vcpkg") + script = "bootstrap-vcpkg.bat" if IS_WINDOWS else "bootstrap-vcpkg.sh" + run(log, [os.path.join(LOCAL_VCPKG, script), "-disableMetrics"], script) + return LOCAL_VCPKG + + +def configure(log): + log.step("configuring the relwithdebinfo preset into %s (no build)" % PRESET_BUILD_DIRS["relwithdebinfo"]) + run(log, [find_cmake(), "--preset", "relwithdebinfo"], "cmake configure") + + +def open_log(path): + if not path: + path = os.path.join(LOG_DIR, "bootstrap-%s.log" % timestamp()) + log = Log(path) + if not IS_WINDOWS: + latest = os.path.join(LOG_DIR, "bootstrap-latest.log") + if os.path.lexists(latest): + os.remove(latest) + os.symlink(path, latest) + return log + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--log", help="append to this log file (the native bootstrap passes the one it started)") + log = open_log(parser.parse_args().log) + log.line("bootstrap log: " + log.path) + + ide_setup.copy_clion_settings(log) + if not IS_WINDOWS: + ide_setup.copy_vscode_settings(log) + toolchain.provision(log) + vcpkg_root = ensure_vcpkg(log) + os.environ["VCPKG_ROOT"] = vcpkg_root + flatpak_ides, manual_cmake = ([], []) if IS_WINDOWS else ide_setup.setup_flatpak_ides(log, vcpkg_root) + configure(log) + + if IS_WINDOWS: + ide_setup.set_clion_profiles(log) + log.step("writing gMod.slnx") + names = vs_solution.write_solution() + log.note("%d projects: %s" % (len(names), ", ".join(names))) + else: + if "CLion" not in flatpak_ides: + ide_setup.set_clion_profiles(log) + ide_setup.install_vscode_extensions(log) + ide_setup.clear_ide_locks(log, flatpak_ides) + + log.step("done. Nothing was opened or built.") + if vcpkg_root != LOCAL_VCPKG: + log.note("(vcpkg is VCPKG_ROOT=%s; without it set, the presets use .vcpkg/)" % vcpkg_root) + print_next_steps(log, flatpak_ides, manual_cmake) + log.close() + + +def print_next_steps(log, flatpak_ides, manual_cmake): + log.line() + log.line("What to do next:") + step = 1 + for ide in manual_cmake: + log.line(" %d. In %s, open Settings > Build, Execution, Deployment > Toolchains and set CMake to" % (step, ide)) + log.line(" %s/cmake (the host CMake; the bundled one cannot run vcpkg)." % ide_setup.HOST_TOOLS_DIR) + step += 1 + log.line(" %d. Open the project in one of:" % step) + if IS_WINDOWS: + log.line(" Visual Studio or Rider: gMod.slnx (configurations Debug, RelWithDebInfo and Release)") + log.line(" CLion: this folder (CMake profiles relwithdebinfo, debug and release)") + log.line(" a terminal: python scripts\\build.py [--preset debug]") + else: + for ide in flatpak_ides: + log.line(" %s: flatpak run %s %s (CMake profiles relwithdebinfo, debug and release)" + % (ide, ide_setup.FLATPAK_IDES[ide]["app"], ide_setup.FLATPAK_IDES[ide]["open"])) + clion = ide_setup.host_clion_command() + if clion and "CLion" not in flatpak_ides: + log.line(" CLion: %s %s (CMake profiles relwithdebinfo, debug and release)" % (clion, REPO_ROOT)) + if shutil.which("code"): + log.line(" VS Code: code %s (then pick the relwithdebinfo preset in the CMake Tools status bar)" % REPO_ROOT) + log.line(" a terminal: python3 scripts/build.py [--preset debug]") + log.line(" %d. Build. gMod.dll and TpfConvert.exe land in bin//." % (step + 1)) + log.line("Re-running this bootstrap is safe and quick; do it after pulling changes to the toolchain or presets.") + + +if __name__ == "__main__": + main_guard(main) diff --git a/scripts/build.py b/scripts/build.py new file mode 100644 index 0000000..9ed2fd8 --- /dev/null +++ b/scripts/build.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python3 +"""Builds gMod.dll and TpfConvert with llvm-mingw into build///, configuring the preset first when it +has not been configured yet. Output lands in bin/ (the presets point CMAKE_RUNTIME_OUTPUT_DIRECTORY there). + + python3 scripts/build.py [--preset relwithdebinfo|debug|release] [--target gMod|TpfConvert] + [--clean | --rebuild] + +--target builds only that target (both by default). --clean removes the outputs of the target(s) only, or the whole +build folder when no target is given. --rebuild cleans the target(s) and then builds them. Visual Studio's build, +clean and rebuild commands call this script with these options. +""" + +import require_python # noqa: F401 (first: stops an old Python before anything else runs) + +import argparse +import os + +from common import (LOG_DIR, PRESET_BUILD_DIRS, PRESETS, REPO_ROOT, FolderLock, Log, find_cmake, main_guard, run, + timestamp) + +TARGETS = ("gMod", "TpfConvert") + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--preset", choices=sorted(PRESETS), default="relwithdebinfo") + parser.add_argument("--target", choices=TARGETS, action="append", + help="build only this target (repeat for several); default is all of them") + action = parser.add_mutually_exclusive_group() + action.add_argument("--clean", action="store_true", help="remove the outputs of the target(s), or the whole build") + action.add_argument("--rebuild", action="store_true", help="clean the target(s), then build them") + args = parser.parse_args() + log = Log(os.path.join(LOG_DIR, "build-%s-%s.log" % (args.preset, timestamp()))) + cmake = find_cmake() + build_dir = os.path.join(REPO_ROOT, PRESET_BUILD_DIRS[args.preset]) + targets = args.target or [] + lock = FolderLock(build_dir, log) + try: + if not os.path.isfile(os.path.join(build_dir, "build.ninja")): + log.step("configuring the %s preset" % args.preset) + run(log, [cmake, "--preset", args.preset], "cmake configure") + if args.clean or args.rebuild: + if targets: + for target in targets: + log.step("cleaning %s (%s preset)" % (target, args.preset)) + run(log, [cmake, "--build", build_dir, "--target", target, "--", "-t", "clean"], "clean") + else: + log.step("cleaning the %s build folder" % args.preset) + run(log, [cmake, "--build", build_dir, "--target", "clean"], "clean") + if args.clean: + log.line("cleaned") + return + log.step("building %s (%s preset)" % (", ".join(targets) or "all targets", args.preset)) + command = [cmake, "--build", build_dir] + for target in targets: + command += ["--target", target] + run(log, command, "cmake build") + log.line("built into bin/") + finally: + lock.release() + log.close() + + +if __name__ == "__main__": + main_guard(main) diff --git a/scripts/cmake.version b/scripts/cmake.version new file mode 100644 index 0000000..bc7354c --- /dev/null +++ b/scripts/cmake.version @@ -0,0 +1,5 @@ +version=4.4.4 +linux_asset=cmake-4.4.4-linux-x86_64.tar.gz +linux_sha256=e5bb807f7728cb60cd8b27ebc97a2edb469b68655f21e844a600c3575b76f5bb +windows_asset=cmake-4.4.4-windows-x86_64.zip +windows_sha256=bace36e94b31c68ab6fa295f26dfa11219e0701cf7c94b0284a7d1cb13dac536 diff --git a/scripts/common.py b/scripts/common.py new file mode 100644 index 0000000..21c9d15 --- /dev/null +++ b/scripts/common.py @@ -0,0 +1,140 @@ +"""Shared by the build's Python scripts: repo paths, presets, logging, processes and the build-folder lock.""" + +import datetime +import os +import re +import shutil +import subprocess +import sys +import time + +IS_WINDOWS = os.name == "nt" +HOST = "windows" if IS_WINDOWS else "linux" +# CMake's name for the host, which the presets put in each build folder: build/Windows/, build/Linux/. +CMAKE_HOST = "Windows" if IS_WINDOWS else "Linux" +REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +TOOLCHAIN_DIR = os.path.join(REPO_ROOT, ".toolchain") +LLVM_MINGW_DIR = os.path.join(TOOLCHAIN_DIR, "llvm-mingw-" + HOST) +CMAKE_DIR = os.path.join(TOOLCHAIN_DIR, "cmake-" + HOST) +LOG_DIR = os.path.join(REPO_ROOT, "logs") +EXE = ".exe" if IS_WINDOWS else "" + +PRESETS = {"relwithdebinfo": "RelWithDebInfo", "debug": "Debug", "release": "Release"} +PRESET_BUILD_DIRS = {preset: os.path.join("build", CMAKE_HOST, preset) for preset in PRESETS} +BIN_DIR = os.path.join(REPO_ROOT, "bin") + + +class Failure(Exception): + pass + + +class Log: + def __init__(self, path): + self.path = path + os.makedirs(os.path.dirname(path), exist_ok=True) + self.file = open(path, "a", encoding="utf-8", newline="\n") + + def line(self, text=""): + console = sys.stdout.encoding or "utf-8" + print(text.encode(console, errors="replace").decode(console), flush=True) + self.file.write(text + "\n") + self.file.flush() + + def step(self, text): + self.line("==> " + text) + + def note(self, text): + self.line(" " + text) + + def close(self): + self.file.close() + + +def timestamp(): + return datetime.datetime.now().strftime("%Y%m%d-%H%M%S") + + +def run(log, command, what=None, env=None, cwd=REPO_ROOT, check=True): + process = subprocess.Popen(command, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) + for raw in process.stdout: + log.line(raw.decode("utf-8", errors="replace").rstrip("\r\n")) + code = process.wait() + if check and code != 0: + raise Failure("%s failed with exit code %d" % (what or os.path.basename(command[0]), code)) + return code + + +def capture(command, cwd=REPO_ROOT): + try: + result = subprocess.run(command, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) + except OSError: + return None + return result.stdout.decode("utf-8", errors="replace") if result.returncode == 0 else None + + +def read_pin(name="llvm-mingw.version"): + pin = {} + with open(os.path.join(REPO_ROOT, "scripts", name), encoding="utf-8") as file: + for line in file: + match = re.match(r"^(\w+)=(.+)$", line.strip()) + if match: + pin[match.group(1)] = match.group(2).strip() + return pin + + +def find_cmake(): + # The pinned CMake only: the import std UUID in CMakeLists.txt is tied to this exact version. Its bin folder also + # goes first on PATH, so vcpkg, which runs cmake itself, uses the same binary. + cmake = os.path.join(CMAKE_DIR, "bin", "cmake" + EXE) + expected = read_pin("cmake.version")["version"] + if not os.path.isfile(cmake): + raise Failure("CMake %s is not installed in .toolchain/; run the bootstrap script for this platform" % expected) + output = capture([cmake, "--version"]) or "" + match = re.search(r"cmake version (\S+)", output) + if not match or match.group(1) != expected: + raise Failure("expected CMake %s in .toolchain/, found %s; re-run the bootstrap script" + % (expected, match.group(1) if match else "nothing")) + os.environ["PATH"] = os.path.join(CMAKE_DIR, "bin") + os.pathsep + os.environ.get("PATH", "") + return cmake + + +class FolderLock: + # Two ninja runs in one build folder at once corrupt its logs, so runs on a folder take turns. + + def __init__(self, folder, log): + os.makedirs(folder, exist_ok=True) + self.file = open(os.path.join(folder, ".build.lock"), "a+b") + if not self._try(): + log.step("waiting for another build in %s to finish" % os.path.relpath(folder, REPO_ROOT)) + while not self._try(): + time.sleep(0.5) + + def _try(self): + try: + if IS_WINDOWS: + import msvcrt + self.file.seek(0) + msvcrt.locking(self.file.fileno(), msvcrt.LK_NBLCK, 1) + else: + import fcntl + fcntl.flock(self.file.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) + return True + except OSError: + return False + + def release(self): + if IS_WINDOWS: + import msvcrt + self.file.seek(0) + msvcrt.locking(self.file.fileno(), msvcrt.LK_UNLCK, 1) + self.file.close() + + +def main_guard(function): + try: + sys.exit(function() or 0) + except Failure as error: + print("error: %s" % error, file=sys.stderr, flush=True) + sys.exit(1) + except KeyboardInterrupt: + sys.exit(130) diff --git a/scripts/ide_setup.py b/scripts/ide_setup.py new file mode 100644 index 0000000..5df324b --- /dev/null +++ b/scripts/ide_setup.py @@ -0,0 +1,409 @@ +"""IDE setup for the bootstrap: CLion, Rider and VS Code settings, the CMake profiles they build, and on Linux the +Flatpak sandbox plumbing that lets the JetBrains IDEs reach the host's CMake, ninja and gdb.""" + +import glob +import os +import re +import shutil +import subprocess + +from common import CMAKE_DIR, IS_WINDOWS, LOG_DIR, PRESETS, REPO_ROOT, TOOLCHAIN_DIR, capture + +RUN_CONFIGURATIONS = ["gMod", "TpfConvert"] +PROFILES = list(PRESETS) +SELECTED_PROFILE = os.environ.get("SELECTED_PROFILE", "relwithdebinfo") +# Profiles earlier bootstraps enabled whose presets are gone: the MSVC and mingw names. +RETIRED_PROFILES = ["vcpkg", "windows", "clang", "mingw", "mingw-debug", "mingw-release", "minsizerel"] +HOST_TOOLS_DIR = os.path.join(TOOLCHAIN_DIR, "host-tools", "bin") +SANDBOX_TOOLS = ["cmake", "ctest", "cpack", "ninja", "gdb"] +VSCODE_EXTENSIONS = ["llvm-vs-code-extensions.vscode-clangd", "ms-vscode.cmake-tools"] +# Both Flatpak JetBrains IDEs use the same CMake integration, but CLion opens the folder and keeps the project in +# .idea/workspace.xml, while Rider opens CMakeLists.txt and keeps its own project under .idea/.idea..cmake/. +FLATPAK_IDES = { + "CLion": {"app": "com.jetbrains.CLion", "open": REPO_ROOT, + "workspace": os.path.join(REPO_ROOT, ".idea", "workspace.xml")}, + "Rider": {"app": "com.jetbrains.Rider", "open": os.path.join(REPO_ROOT, "CMakeLists.txt"), + "workspace": os.path.join(REPO_ROOT, ".idea", ".idea.%s.cmake" % os.path.basename(REPO_ROOT), ".idea", + "workspace.xml")}, +} + + +def copy_settings(log, source, destination): + backup = os.path.join(destination, "bootstrap-backup") + for name in sorted(os.listdir(source)): + if name.startswith("README"): + continue + os.makedirs(destination, exist_ok=True) + target = os.path.join(destination, name) + if os.path.lexists(target): + os.makedirs(backup, exist_ok=True) + remove(os.path.join(backup, name)) + copy(target, os.path.join(backup, name)) + remove(target) + copy(os.path.join(source, name), target) + log.note("copied " + name) + + +def copy(source, destination): + if os.path.isdir(source): + shutil.copytree(source, destination, symlinks=True) + else: + shutil.copy2(source, destination) + + +def remove(path): + if os.path.isdir(path) and not os.path.islink(path): + shutil.rmtree(path) + elif os.path.lexists(path): + os.remove(path) + + +def read(path): + with open(path, encoding="utf-8") as file: + return file.read() + + +def write(path, text): + with open(path, "w", encoding="utf-8", newline="\n") as file: + file.write(text) + + +def prune_run_configurations(log, workspace): + if not os.path.isfile(workspace): + return + text = read(workspace) + removed = [] + + def keep_or_drop(match): + target = re.search(r'TARGET_NAME="([^"]*)"', match.group(0)) + if target is None or target.group(1) in RUN_CONFIGURATIONS: + return match.group(0) + removed.append(match.group(1)) + return "" + + text = re.sub(r'\n?[ \t]*.*?', + keep_or_drop, text, flags=re.S) + for name in removed: + text = re.sub(r'\n[ \t]*' % re.escape(name), "", text) + selected = re.search(r']*/>\r?\n?', "", text) + if kept != text: + write(vcs, kept) + log.note("dropped the VCS mappings into build folders from .idea/vcs.xml") + + +def copy_vscode_settings(log): + log.step("copying VS Code settings from bootstrap/vscode/ into .vscode/") + copy_settings(log, os.path.join(REPO_ROOT, "bootstrap", "vscode"), os.path.join(REPO_ROOT, ".vscode")) + + +def install_vscode_extensions(log): + code = shutil.which("code") + if not code: + log.step("VS Code ('code') is not on PATH; its settings are in .vscode/, but no extensions were installed") + return + log.step("installing VS Code extensions that are missing") + installed = (capture([code, "--list-extensions"]) or "").lower().split() + for extension in VSCODE_EXTENSIONS: + if extension.lower() in installed: + log.note(extension + " already installed") + elif subprocess.call([code, "--install-extension", extension]) != 0: + log.note("could not install %s (marketplace error); re-run the bootstrap to retry" % extension) + + +def set_profiles(log, workspace, label): + """Enables the CMake profiles in a JetBrains workspace.xml and selects SELECTED_PROFILE. The IDE keeps the profiles + (enabled or not) there; ones it has not listed yet are added, retired ones disabled, others left alone.""" + if os.path.isfile(workspace): + text = read(workspace) + shutil.copy2(workspace, workspace + ".bootstrap-backup") + else: + os.makedirs(os.path.dirname(workspace), exist_ok=True) + text = '\n\n\n' + + # No GENERATION_DIR: the preset's binaryDir differs per host, and both hosts of a dual-boot checkout share this file. + def configuration(name): + return ' ' % name + + full_block = ('\n \n%s\n \n ' + % "\n".join(configuration(name) for name in PROFILES)) + text = re.sub(r'', lambda _: full_block, text, count=1) + match = re.search(r'.*?', text, re.S) + if not match: + text = text.replace("", " %s\n" % full_block, 1) + else: + block = match.group(0) + for name in PROFILES: + element = re.search(r']*?(/>|>.*?)' % re.escape(name), block, re.S) + if element: + tag = re.sub(r'\s+GENERATION_DIR="[^"]*"', "", element.group(0), count=1) + tag = re.sub(r'(ENABLED=")[a-z]+(")', r"\1true\2", tag, count=1) + block = block[:element.start()] + tag + block[element.end():] + else: + block = re.sub(r"(\n\s*)", lambda m: "\n" + configuration(name) + m.group(1), block, count=1) + for name in RETIRED_PROFILES: + block = re.sub(r'(PROFILE_NAME="%s"[^>]*?ENABLED=")[a-z]+(")' % re.escape(name), r"\1false\2", block, count=1) + text = text[:match.start()] + block + text[match.end():] + target = '' % SELECTED_PROFILE + text, count = re.subn(r']*/>', lambda _: target, text, count=1) + if count == 0: + text = text.replace("", " %s\n" % target, 1) + write(workspace, text) + log.step("enabled the CMake profiles (%s) for %s, disabled the retired ones and selected %s" + % (", ".join(PROFILES), label, SELECTED_PROFILE)) + prune_run_configurations(log, workspace) + + +def set_clion_profiles(log): + set_profiles(log, os.path.join(REPO_ROOT, ".idea", "workspace.xml"), "CLion") + + +def flatpak_ides(): + if not shutil.which("flatpak"): + return [] + return [ide for ide, info in FLATPAK_IDES.items() if subprocess.call( + ["flatpak", "info", info["app"]], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) == 0] + + +def host_clion_command(): + path = shutil.which("clion") + if path: + return path + launches = glob.glob(os.path.expanduser("~/.local/share/JetBrains/Toolbox/apps/clion*/bin/clion.sh")) + return max(launches, key=lambda script: [int(n) for n in re.findall(r"\d+", script)]) if launches else None + + +def resolve_host_tool(tool): + for directory in os.environ.get("PATH", "").split(os.pathsep): + candidate = os.path.join(directory, tool) + if not os.access(candidate, os.X_OK) or os.path.isdir(candidate): + continue + real = os.path.realpath(candidate) + if real.startswith(HOST_TOOLS_DIR + os.sep) or os.path.basename(real) == "host-tool": + continue + return real + return None + + +def shell_quote(text): + return "'" + text.replace("'", "'\\''") + "'" + + +# The IDE Flatpaks cannot run the host's CMake or ninja directly, so they are reached through this wrapper, which calls +# flatpak-spawn --host; everything they start then runs on the host. The compiler itself is llvm-mingw in .toolchain/, +# which also runs inside the sandbox, where the IDE probes it. +HOST_TOOL_BODY = r''' *) + echo "host-tool: unknown tool '$name'" >&2 + exit 1 ;; +esac +if [ -n "$FLATPAK_ID" ]; then + # The sandbox's /tmp is private, so files passed in from it are copied to a directory the host can read. + # Each call gets its own folder there, so concurrent calls never overwrite each other's copies. + share="$HOME/.cache/gmod/tmp" + mkdir -p "$share" + call_dir=$(mktemp -d "$share/call.XXXXXX") + trap 'rm -rf "$call_dir"' EXIT + n=$# + i=0 + while [ "$i" -lt "$n" ]; do + arg=$1 + shift + case "$arg" in + /tmp/*) + if [ -f "$arg" ]; then + cp -f "$arg" "$call_dir/${arg##*/}" + arg="$call_dir/${arg##*/}" + fi ;; + esac + set -- "$@" "$arg" + i=$((i + 1)) + done + # flatpak-spawn does not forward the sandbox environment, so pass the variables the build reads. + run_tool() { + flatpak-spawn --host --directory="$PWD" \ + --env=VCPKG_ROOT="$VCPKG_ROOT" \ + "$tool" "$@" + } +else + run_tool() { "$tool" "$@"; } +fi +# Builds are logged to logs/ninja-*.log in the repo, whichever IDE started them. Tool queries (ninja -t) are not builds. +case " $* " in + *" -t "*) run_tool "$@"; exit $? ;; +esac +if [ "$name" = ninja ]; then + mkdir -p "$LOG_DIR" + log="$LOG_DIR/ninja-$(date +%Y%m%d-%H%M%S)-$$.log" + echo "ninja output also written to $log" >&2 + run_tool "$@" 2>&1 | tee -a "$log" + exit "${PIPESTATUS[0]}" +fi +# CMake configure and --build runs (what an IDE's reload and build issue) are logged to logs/cmake-*.log. +# Script mode (-E, -P) and version queries (the IDEs send -version) run many times per configure, so they are not logged. +if [ "$name" = cmake ]; then + case " $* " in + *" -E "*|*" -P "*|*" --version "*|*" -version "*) run_tool "$@"; exit $? ;; + esac + mkdir -p "$LOG_DIR" + log="$LOG_DIR/cmake-$(date +%Y%m%d-%H%M%S)-$$.log" + echo "cmake output also written to $log" >&2 + run_tool "$@" 2>&1 | tee -a "$log" + exit "${PIPESTATUS[0]}" +fi +run_tool "$@" +''' + + +def write_host_tool_wrapper(log): + os.makedirs(HOST_TOOLS_DIR, exist_ok=True) + lines = ["#!/bin/bash", "# Generated by scripts/ide_setup.py. Runs a host build tool whichever name it is called by.", + 'name=$(basename "$0")', "LOG_DIR=" + shell_quote(LOG_DIR), 'case "$name" in'] + found = [] + for tool in SANDBOX_TOOLS: + # The pinned CMake (scripts/cmake.version) comes first: the import std UUID in CMakeLists.txt only works with it. + pinned = os.path.join(CMAKE_DIR, "bin", tool) + path = pinned if tool in ("cmake", "ctest", "cpack") and os.path.isfile(pinned) else resolve_host_tool(tool) + if not path: + log.note("%s not found on the host; skipping it" % tool) + continue + found.append(tool) + lines.append(" %s) tool=%s ;;" % (tool, shell_quote(path))) + wrapper = os.path.join(HOST_TOOLS_DIR, "host-tool") + write(wrapper, "\n".join(lines) + "\n" + HOST_TOOL_BODY) + os.chmod(wrapper, 0o755) + for tool in found: + link = os.path.join(HOST_TOOLS_DIR, tool) + remove(link) + os.symlink("host-tool", link) + + +def ide_options_dir(ide): + # The newest settings folder, e.g. .../JetBrains/Rider2026.2/options. Only . counts, so copies + # such as CLion2025.3-backup are skipped. + base = os.path.expanduser("~/.var/app/%s/config/JetBrains" % FLATPAK_IDES[ide]["app"]) + versions = [path for path in glob.glob(os.path.join(base, ide + "[0-9]*")) if re.search(r"%s\d+\.\d+$" % ide, path)] + if not versions: + return None + newest = max(versions, key=lambda path: [int(n) for n in re.findall(r"\d+", os.path.basename(path))]) + return os.path.join(newest, "options") + + +def set_ide_environment(log, ide, vcpkg_root): + app = FLATPAK_IDES[ide]["app"] + path = "%s:/app/bin:/usr/bin" % HOST_TOOLS_DIR + # The app ID matters: without it flatpak writes a global override that every Flatpak app inherits, while the + # app's own (possibly older) override file still wins for the keys it sets. + subprocess.call(["flatpak", "override", "--user", "--env=PATH=" + path, "--env=VCPKG_ROOT=" + vcpkg_root, app]) + # flatpak override can exit 0 without writing anything (e.g. from a sandboxed shell), so read it back. + shown = (capture(["flatpak", "override", "--user", "--show", app]) or "").splitlines() + if "PATH=" + path in shown and "VCPKG_ROOT=" + vcpkg_root in shown: + log.step("set the %s Flatpak environment (PATH to the host tools, VCPKG_ROOT)" % ide) + else: + log.line("WARNING: the %s Flatpak override did not take effect. Run this from a normal terminal:" % ide) + log.note("flatpak override --user --env=PATH=%s --env=VCPKG_ROOT=%s %s" % (path, vcpkg_root, app)) + + +def ide_tool_path(tool): + path = os.path.join(HOST_TOOLS_DIR, tool) + home = os.path.expanduser("~") + return "$USER_HOME$" + path[len(home):] if path.startswith(home + os.sep) else path + + +def set_ide_cmake_path(log, ide): + """Points the IDE's Default toolchain at the wrapper's cmake and gdb. Their bundled copies live under /app, which only + exists inside the sandbox; the IDE keeps the paths as customCMakePath and customGDBPath in options/linux/toolchains.xml.""" + options = ide_options_dir(ide) + file = os.path.join(options, "linux", "toolchains.xml") if options else None + text = read(file) if file and os.path.isfile(file) else "" + if not re.search(r']*name="Default"', text): + log.note("%s has no toolchains.xml with a Default toolchain yet (start %s once, then re-run the bootstrap)" % (ide, ide)) + return False + cmake = ide_tool_path("cmake") + gdb = ide_tool_path("gdb") + + def fix(match): + tag = match.group(0) + for attribute in ("customCMakePath", "debuggerKind", "customGDBPath"): + tag = re.sub(r'\s+%s="[^"]*"' % attribute, "", tag) + return tag.replace("]*name="Default"[^>]*/>', fix, text, count=1)) + log.step("set %s's CMake path to %s and its GDB to %s (backup: %s.bootstrap-backup)" % (ide, cmake, gdb, file)) + return True + + +def link_ide_log(log, ide): + # Errors the IDE raises after CMake has finished ("[Failed to reload]") never pass through the wrapper, so its + # own idea.log is linked into logs/ next to the CMake and ninja logs. + options = ide_options_dir(ide) + if not options: + return + version = os.path.basename(os.path.dirname(options)) + target = os.path.expanduser("~/.var/app/%s/cache/JetBrains/%s/log/idea.log" % (FLATPAK_IDES[ide]["app"], version)) + link = os.path.join(LOG_DIR, ide.lower() + "-idea.log") + os.makedirs(LOG_DIR, exist_ok=True) + remove(link) + os.symlink(target, link) + log.step("linked %s's idea.log to logs/%s (CMake reload and File API errors the IDE reports itself)" + % (ide, os.path.basename(link))) + + +def clear_ide_locks(log, ides): + # A lock, port or pid file left by a crashed IDE stops the next start with "Start Failed" even when nothing is + # running. The bootstrap only runs with neither IDE open, so those files are stale. + for ide in ides: + # The lock files are shared by every project of that IDE, so they are only stale when the IDE is not running. + if subprocess.call(["pgrep", "-f", FLATPAK_IDES[ide]["app"]], stdout=subprocess.DEVNULL) == 0: + log.step("%s is running, so its lock files were left alone" % ide) + continue + data = os.path.expanduser("~/.var/app/" + FLATPAK_IDES[ide]["app"]) + removed = [] + for directory, _, names in os.walk(data): + for name in names: + if name in (".lock", ".port", ".pid"): + path = os.path.join(directory, name) + os.remove(path) + removed.append(path) + if removed: + log.step("removed stale %s lock files:" % ide) + for path in removed: + log.note(path) + + +def setup_flatpak_ides(log, vcpkg_root): + """Returns the IDEs set up, and those whose CMake path is still manual.""" + ides = flatpak_ides() + if not ides: + log.step("neither CLion nor Rider is installed as a Flatpak; skipping the IDE sandbox setup") + return [], [] + log.step("setting up host tools for the %s Flatpak sandbox in %s" % (" and ".join(ides), HOST_TOOLS_DIR)) + write_host_tool_wrapper(log) + manual = [] + for ide in ides: + set_ide_environment(log, ide, vcpkg_root) + if not set_ide_cmake_path(log, ide): + manual.append(ide) + set_profiles(log, FLATPAK_IDES[ide]["workspace"], ide) + link_ide_log(log, ide) + return ides, manual diff --git a/scripts/llvm-mingw.version b/scripts/llvm-mingw.version new file mode 100644 index 0000000..a8fd700 --- /dev/null +++ b/scripts/llvm-mingw.version @@ -0,0 +1,5 @@ +version=20260616 +linux_asset=llvm-mingw-20260616-msvcrt-ubuntu-22.04-x86_64.tar.xz +linux_sha256=a1f7968b48ba8d949194d6dee6c76f3cd0f61cba91658599af2c2c834a55ab87 +windows_asset=llvm-mingw-20260616-msvcrt-x86_64.zip +windows_sha256=744809646fdefe24a357399788d68fb07ecc65fa0be71baa2406793ce25c9813 diff --git a/scripts/require_python.py b/scripts/require_python.py new file mode 100644 index 0000000..aa9ae3e --- /dev/null +++ b/scripts/require_python.py @@ -0,0 +1,14 @@ +"""Imported first by every build script, so it must run on any Python, 2 included. Run directly, it prints the +interpreter's path when it is new enough, which is how the bootstrap scripts pick one.""" + +import sys + +MINIMUM = (3, 9) + +if sys.version_info < MINIMUM: + sys.exit("error: these scripts need Python %d.%d or newer, but %s is Python %d.%d. Run them with a newer one, e.g. " + "py -3 on Windows or python3 on Linux." % (MINIMUM + (sys.executable or "this interpreter",) + + tuple(sys.version_info[:2]))) + +if __name__ == "__main__": + print(sys.executable) diff --git a/scripts/toolchain.py b/scripts/toolchain.py new file mode 100644 index 0000000..fc727fe --- /dev/null +++ b/scripts/toolchain.py @@ -0,0 +1,147 @@ +"""Provisions the build's toolchain into .toolchain/ (git-ignored), each step skipped when current: + llvm-mingw- the pinned release in llvm-mingw.version, checked against its SHA-256 + case-include Linux: links for the mixed-case Windows header names the sources use + + python3 scripts/toolchain.py +""" + +import require_python # noqa: F401 (first: stops an old Python before anything else runs) + +import hashlib +import os +import re +import shutil +import sys +import urllib.request + +from common import (IS_WINDOWS, capture, CMAKE_DIR, HOST, LLVM_MINGW_DIR, LOG_DIR, REPO_ROOT, TOOLCHAIN_DIR, Failure, Log, + main_guard, read_pin, run, timestamp) + +CASE_INCLUDE_DIR = os.path.join(TOOLCHAIN_DIR, "case-include") +SCANNED_FOLDERS = ("header", "source", "modules", "TpfConvert") +SCANNED_EXTENSIONS = (".cpp", ".h", ".hpp", ".inl", ".c", ".ixx") +STAMP_NAME = ".gmod-version" + + +def download(url, path): + with urllib.request.urlopen(url) as response, open(path, "wb") as file: + shutil.copyfileobj(response, file, 1 << 20) + + +def sha256(path): + digest = hashlib.sha256() + with open(path, "rb") as file: + for block in iter(lambda: file.read(1 << 20), b""): + digest.update(block) + return digest.hexdigest() + + +def read_stamp(folder): + try: + with open(os.path.join(folder, STAMP_NAME), encoding="utf-8") as file: + return file.read().strip() + except OSError: + return None + + +def install_llvm_mingw(log): + pin = read_pin() + asset, expected = pin[HOST + "_asset"], pin[HOST + "_sha256"] + stamp = "%s %s" % (pin["version"], expected) + if read_stamp(LLVM_MINGW_DIR) == stamp: + log.step("llvm-mingw %s already installed" % pin["version"]) + return + log.step("installing llvm-mingw %s into .toolchain/%s/" % (pin["version"], os.path.basename(LLVM_MINGW_DIR))) + os.makedirs(TOOLCHAIN_DIR, exist_ok=True) + archive = os.path.join(TOOLCHAIN_DIR, asset) + download("https://github.com/mstorsjo/llvm-mingw/releases/download/%s/%s" % (pin["version"], asset), archive) + actual = sha256(archive) + if actual != expected: + os.remove(archive) + raise Failure("llvm-mingw download has SHA-256 %s, expected %s" % (actual, expected)) + extracted = os.path.join(TOOLCHAIN_DIR, re.sub(r"\.(zip|tar\.xz)$", "", asset)) + for old in (LLVM_MINGW_DIR, extracted): + shutil.rmtree(old, ignore_errors=True) + # tar keeps the Linux release's symlinks; Windows' own tar.exe (not Git's) unpacks the zip far faster than zipfile. + tar = os.path.join(os.environ.get("SystemRoot", r"C:\Windows"), "System32", "tar.exe") if IS_WINDOWS else "tar" + run(log, [tar, "-xf", archive, "-C", TOOLCHAIN_DIR], "unpacking llvm-mingw") + os.remove(archive) + os.rename(extracted, LLVM_MINGW_DIR) + with open(os.path.join(LLVM_MINGW_DIR, STAMP_NAME), "w", encoding="utf-8") as file: + file.write(stamp + "\n") + + +def install_cmake(log): + # Pinned (not whatever CMake is on PATH): the import std experimental UUID in CMakeLists.txt is for this version. + pin = read_pin("cmake.version") + asset, expected = pin[HOST + "_asset"], pin[HOST + "_sha256"] + stamp = "%s %s" % (pin["version"], expected) + if read_stamp(CMAKE_DIR) == stamp: + log.step("CMake %s already installed" % pin["version"]) + return + log.step("installing CMake %s into .toolchain/%s/" % (pin["version"], os.path.basename(CMAKE_DIR))) + os.makedirs(TOOLCHAIN_DIR, exist_ok=True) + archive = os.path.join(TOOLCHAIN_DIR, asset) + download("https://github.com/Kitware/CMake/releases/download/v%s/%s" % (pin["version"], asset), archive) + actual = sha256(archive) + if actual != expected: + os.remove(archive) + raise Failure("CMake download has SHA-256 %s, expected %s" % (actual, expected)) + extracted = os.path.join(TOOLCHAIN_DIR, re.sub(r"\.(zip|tar\.gz)$", "", asset)) + for old in (CMAKE_DIR, extracted): + shutil.rmtree(old, ignore_errors=True) + tar = os.path.join(os.environ.get("SystemRoot", r"C:\Windows"), "System32", "tar.exe") if IS_WINDOWS else "tar" + run(log, [tar, "-xf", archive, "-C", TOOLCHAIN_DIR], "unpacking CMake") + os.remove(archive) + os.rename(extracted, CMAKE_DIR) + with open(os.path.join(CMAKE_DIR, STAMP_NAME), "w", encoding="utf-8") as file: + file.write(stamp + "\n") + + +def replace_link(target, link): + os.makedirs(os.path.dirname(link), exist_ok=True) + if os.path.islink(link): + if os.readlink(link) == target: + return + os.remove(link) + os.symlink(target, link) + + +def link_headers(): + mingw_include = os.environ.get("MINGW_INCLUDE_DIR", os.path.join(LLVM_MINGW_DIR, "generic-w64-mingw32", "include")) + pattern = re.compile(rb"#include <([A-Za-z0-9_./-]+\.h)>") + included = set() + for folder in SCANNED_FOLDERS: + for directory, _, names in os.walk(os.path.join(REPO_ROOT, folder)): + for name in names: + if name.endswith(SCANNED_EXTENSIONS): + with open(os.path.join(directory, name), "rb") as file: + included.update(match.decode() for match in pattern.findall(file.read())) + for header in sorted(included): + lowercase = header.lower() + if os.path.exists(os.path.join(mingw_include, header)) or not os.path.exists(os.path.join(mingw_include, lowercase)): + continue + replace_link(os.path.join(mingw_include, lowercase), os.path.join(CASE_INCLUDE_DIR, header)) + # DirectXTex includes ; clang on Linux takes the backslash literally, so link that exact name. The + # dependency file records it with a slash, and a missing dependency rebuilds the file every time, so link that too. + for windows_path in ("wrl\\client.h",): + slash_path = windows_path.replace("\\", "/") + replace_link(os.path.join(mingw_include, slash_path), os.path.join(CASE_INCLUDE_DIR, windows_path)) + replace_link(os.path.join(mingw_include, slash_path), os.path.join(CASE_INCLUDE_DIR, slash_path)) + + +def provision(log): + install_cmake(log) + install_llvm_mingw(log) + if not IS_WINDOWS: + link_headers() + + +def main(): + if len(sys.argv) != 1: + raise Failure(__doc__) + provision(Log(os.path.join(LOG_DIR, "toolchain-%s.log" % timestamp()))) + + +if __name__ == "__main__": + main_guard(main) diff --git a/scripts/version.py b/scripts/version.py new file mode 100644 index 0000000..8ce25c0 --- /dev/null +++ b/scripts/version.py @@ -0,0 +1,26 @@ +#!/usr/bin/env python3 +"""Prints gMod's file version (MAJOR.MINOR.PATCH.TWEAK) from the VERSION_* variables in CMakeLists.txt. + + python3 scripts/version.py +""" + +import os +import re + +REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + + +def version(): + with open(os.path.join(REPO_ROOT, "CMakeLists.txt"), encoding="utf-8") as file: + text = file.read() + parts = [] + for name in ("MAJOR", "MINOR", "PATCH", "TWEAK"): + match = re.search(r"^set\(VERSION_%s (\d+)\)" % name, text, re.MULTILINE) + if not match: + raise SystemExit("VERSION_%s not found in CMakeLists.txt" % name) + parts.append(match.group(1)) + return ".".join(parts) + + +if __name__ == "__main__": + print(version()) diff --git a/scripts/vs_solution.py b/scripts/vs_solution.py new file mode 100644 index 0000000..3dfbfe2 --- /dev/null +++ b/scripts/vs_solution.py @@ -0,0 +1,270 @@ +"""Writes gMod.slnx at the repo root for Visual Studio (and Rider): one Makefile project per CMake target in +build/Windows/relwithdebinfo/compile_commands.json, in .vs-projects/. Building runs scripts/build.py, so Visual Studio +builds with llvm-mingw exactly as CLion and the terminal do. Debug, RelWithDebInfo and Release are the debug, +relwithdebinfo and release presets. + +The Windows bootstrap runs it; run it again after adding or removing source files: + + python scripts/vs_solution.py + +IntelliSense gets each target's include paths and defines, but keeps Visual Studio's own standard library and Windows +SDK headers: it has no GNU clang mode for these projects and misreads libc++. Code under __MINGW32__ therefore shows as +inactive. +""" + +import require_python # noqa: F401 (first: stops an old Python before anything else runs) + +import hashlib +import json +import ntpath +import os +import re +import shutil +import sys +import uuid + +from common import PRESET_BUILD_DIRS, PRESETS, REPO_ROOT, TOOLCHAIN_DIR, Failure, main_guard + +SOLUTION_PROJECTS = ("gMod", "TpfConvert") +NOT_COMPILED_EXTENSIONS = (".h", ".hpp", ".inl", ".html", ".css", ".js", ".ts", ".tsx") +CONFIGURATIONS = {PRESETS[preset]: preset for preset in ("debug", "relwithdebinfo", "release")} +GENERATED = "" + + +def split_command_line(line): + # Quoted runs keep their spaces, and \" is a literal quote: CMake writes defines such as -DVERSION=\"1.10\". + parts, current, quoted, started = [], [], False, False + i = 0 + while i < len(line): + c = line[i] + if c == "\\" and i + 1 < len(line) and line[i + 1] == '"': + current.append('"') + started = True + i += 2 + continue + if c == '"': + quoted, started = not quoted, True + elif c.isspace() and not quoted: + if started: + parts.append("".join(current)) + current, started = [], False + else: + current.append(c) + started = True + i += 1 + if started: + parts.append("".join(current)) + return parts + + +def full_path(path, directory): + return os.path.normpath(path if os.path.isabs(path) else os.path.join(directory, path)) + + +def starts_with(path, folder): + return os.path.normcase(path).startswith(os.path.normcase(folder.rstrip("\\/") + os.sep)) + + +def relative_path(start, path): + return os.path.relpath(path, start).replace("/", "\\") + + +def stable_guid(name): + # The same GUID for the same name on every run, so regenerating keeps Visual Studio's per-project settings. + return "{%s}" % str(uuid.UUID(bytes_le=hashlib.md5(name.encode("utf-8")).digest())).upper() + + +def escape(text): + return (text.replace("&", "&").replace("<", "<").replace(">", ">").replace('"', """) + .replace("'", "'")) + + +def relocate(entry, source_root): + moved = dict(entry) + moved["file"] = entry["file"].replace(source_root, REPO_ROOT) + moved["directory"] = entry["directory"].replace(source_root, REPO_ROOT) + if "arguments" in entry: + moved["arguments"] = [argument.replace(source_root, REPO_ROOT) for argument in entry["arguments"]] + if "command" in entry: + moved["command"] = entry["command"].replace(source_root, REPO_ROOT) + return moved + + +def read_targets(database, build_dir): + with open(database, encoding="utf-8") as file: + entries = json.load(file) + if not entries: + return {} + source_root = entries[0]["directory"].split("/build/")[0] + dependencies = os.path.join(REPO_ROOT, "Dependencies") + targets = {} + for entry in entries: + entry = relocate(entry, source_root) + source = full_path(entry["file"], entry["directory"]) + # Sources fetched or generated into the build folder belong to third-party targets, which get no project. + if starts_with(source, build_dir) or starts_with(source, dependencies): + continue + arguments = entry.get("arguments") or split_command_line(entry["command"]) + if "-o" not in arguments: + continue + match = re.search(r"CMakeFiles[\\/]([^\\/]+)\.dir[\\/]", arguments[arguments.index("-o") + 1]) + if not match: + continue + target = targets.setdefault(match.group(1), {"sources": [], "arguments": arguments, "directory": entry["directory"]}) + target["sources"].append(source) + return targets + + +def compiler_settings(target): + includes, defines, forced = [], [], [] + a = target["arguments"] + i = 1 + while i < len(a): + arg, path = a[i], None + if arg in ("-I", "-isystem"): + i += 1 + path = a[i] + elif arg.startswith("-I"): + path = arg[2:] + elif arg.startswith("-D"): + defines.append(arg[2:]) + elif arg == "-include": + i += 1 + forced.append(full_path(a[i], target["directory"])) + elif arg == "-Xclang" and i + 3 < len(a) and a[i + 1] == "-include": + forced.append(full_path(a[i + 3], target["directory"])) + i += 3 + if path: + path = full_path(path, target["directory"]) + if starts_with(path, REPO_ROOT) and not starts_with(path, TOOLCHAIN_DIR) and path not in includes: + includes.append(path) + i += 1 + return includes, defines, forced + + +def walk_tree(root): + for directory, folders, names in os.walk(root): + folders[:] = [folder for folder in folders if folder not in ("node_modules", "build", "bin", "obj")] + yield directory, names + + +def project_files(target): + sources = target["sources"] + root = os.path.dirname(sources[0]) + for source in sources: + while not starts_with(source, root): + root = os.path.dirname(root) + if os.path.normcase(root) == os.path.normcase(REPO_ROOT): + # A target spanning top-level folders would otherwise take in the whole checkout, build and toolchain folders too. + candidates = [os.path.join(directory, name) for directory in sorted(set(map(os.path.dirname, sources)), key=str.lower) + for name in sorted(os.listdir(directory), key=str.lower) if os.path.isfile(os.path.join(directory, name))] + else: + candidates = [os.path.join(directory, name) for directory, names in sorted(walk_tree(root), key=lambda w: w[0].lower()) + for name in sorted(names, key=str.lower)] + headers = [path for path in candidates if path.lower().endswith(NOT_COMPILED_EXTENSIONS)] + return root, [("ClCompile", path) for path in sources] + [("ClInclude", path) for path in headers] + + +def write_project(name, target, project_dir, python): + includes, defines, forced = compiler_settings(target) + root, files = project_files(target) + build_script = "$(MSBuildProjectDirectory)\\..\\scripts\\build.py" + output = {"TpfConvert": "TpfConvert.exe"}.get(name, name + ".dll") + lines = [ + '', + GENERATED, + '', + ' ', + ] + for config in CONFIGURATIONS: + lines.append(' %sWin32' + '' % (config, config)) + lines += [ + ' ', + ' %sMakeFileProj%s' + '' % (stable_guid(name), name), + ' ', + ' Makefile' + '$(DefaultPlatformToolset)', + ' ', + ] + for config, preset in CONFIGURATIONS.items(): + build = '"%s" "%s" --preset %s' % (python, build_script, preset) + lines += [ + " " % config, + " %s" % escape("%s --target %s" % (build, name)), + " %s" % escape("%s --rebuild --target %s" % (build, name)), + " %s" % escape("%s --clean --target %s" % (build, name)), + " $(MSBuildProjectDirectory)\\..\\bin\\%s\\%s" % (config, output), + " %s" % escape(";".join(defines + ["$(NMakePreprocessorDefinitions)"])), + " %s" % escape(";".join(includes + ["$(IncludePath)"])), + " %s" % escape(";".join(forced)), + " /std:c++latest", + " $(MSBuildProjectDirectory)\\obj\\%s\\%s\\$(MSBuildProjectDirectory)\\obj\\%s\\%s\\" + % (name, config, name, config), + " ", + ] + lines.append(" ") + lines += [' <%s Include="%s" />' % (kind, escape(relative_path(project_dir, path))) for kind, path in files] + lines += [" ", ' ', ""] + write_text(os.path.join(project_dir, name + ".vcxproj"), lines) + + # Solution Explorer shows the files in their folders, relative to the shared root. + folders = set() + filters = ['', + '', " "] + for kind, path in files: + folder = os.path.dirname(relative_path(root, path)) + item = ' <%s Include="%s"' % (kind, escape(relative_path(project_dir, path))) + if folder: + filters.append("%s>%s" % (item, escape(folder), kind)) + while folder: + folders.add(folder) + folder = ntpath.dirname(folder) + else: + filters.append(item + " />") + for folder in sorted(folders, key=str.lower): + filters.append(' %s' + % (escape(folder), stable_guid("%s/%s" % (name, folder)))) + filters += [" ", ""] + write_text(os.path.join(project_dir, name + ".vcxproj.filters"), filters) + + +def write_text(path, lines): + with open(path, "w", encoding="utf-8", newline="\r\n") as file: + file.write("\n".join(lines) + "\n") + + +def write_solution(): + build_dir = os.path.join(REPO_ROOT, PRESET_BUILD_DIRS["relwithdebinfo"]) + database = os.path.join(build_dir, "compile_commands.json") + if not os.path.isfile(database): + raise Failure("%s not found; configure the relwithdebinfo preset first (the bootstrap does)" % database) + targets = read_targets(database, build_dir) + targets = {name: target for name, target in targets.items() if name in SOLUTION_PROJECTS} + if not targets: + raise Failure("no gMod targets found in " + database) + project_dir = os.path.join(REPO_ROOT, ".vs-projects") + os.makedirs(project_dir, exist_ok=True) + # The interpreter running this, so the projects build with a Python that has been seen to work. + python = sys.executable + for name, target in targets.items(): + write_project(name, target, project_dir, python) + + names = sorted(targets, key=SOLUTION_PROJECTS.index) + solution = [GENERATED, "", " "] + solution += [' ' % config for config in CONFIGURATIONS] + solution += [' ', " "] + solution += [' ' % name for name in names] + solution.append("") + write_text(os.path.join(REPO_ROOT, "gMod.slnx"), solution) + return names + + +def main(): + names = write_solution() + print("wrote gMod.slnx with %d projects: %s" % (len(names), ", ".join(names))) + + +if __name__ == "__main__": + main_guard(main) diff --git a/source/D3D9Hooks.cpp b/source/D3D9Hooks.cpp index 7b9cfda..5aab767 100644 --- a/source/D3D9Hooks.cpp +++ b/source/D3D9Hooks.cpp @@ -209,9 +209,14 @@ namespace { ULONG STDMETHODCALLTYPE h_DeviceRelease(IDirect3DDevice9* self) { + // Hold our own reference while the game's Release runs, so the device is still alive + // when we tear down our per-device state. ~TextureClient releases the fake textures + // we own, and those releases must reach a live device. Doing them after the device's + // refcount has already hit zero touches a destroyed device. + self->AddRef(); const ULONG count = o_DeviceRelease(self); - if (g_unhooked) return count; - if (count == 0) { + // `count` is what the game's Release returned. Only our reference is left when it is 1. + if (!g_unhooked && count == 1) { TextureClient* client = nullptr; { std::lock_guard lk(g_devices_mutex); @@ -221,9 +226,9 @@ namespace { g_devices.erase(it); } } - delete client; // ~TextureClient drops all side-state + delete client; // ~TextureClient drops all side-state while the device is alive } - return count; + return o_DeviceRelease(self); // drop our reference; this is the count the game sees } HRESULT STDMETHODCALLTYPE h_CreateTexture(IDirect3DDevice9* self, UINT Width, UINT Height, UINT Levels, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, diff --git a/source/dll_main.cpp b/source/dll_main.cpp index d359b72..3027314 100644 --- a/source/dll_main.cpp +++ b/source/dll_main.cpp @@ -11,8 +11,9 @@ void InitInstance(HINSTANCE hModule); namespace { +// MinHook takes void* targets. MSVC converts function pointers to void* implicitly; clang needs the cast spelled out. #define DISABLE_HOOK(var) \ - if (var) { MH_DisableHook(var); } + if (var) { MH_DisableHook(reinterpret_cast(var)); } using Direct3DCreate9_type = IDirect3D9*(APIENTRY*)(UINT); using Direct3DCreate9Ex_type = HRESULT(APIENTRY*)(UINT SDKVersion, IDirect3D9Ex** ppD3D); @@ -220,12 +221,10 @@ void LoadModlists() const auto dll_path = std::filesystem::path(dllpath).parent_path(); for (const auto& path : {exe_path, dll_path}) { const auto modlist = path / "modlist.txt"; - if (std::filesystem::exists(modlist)) { + std::error_code ec; + if (std::filesystem::exists(modlist, ec) && !ec) { Message("Initialize: found %s\n", modlist.string().c_str()); - std::ifstream t(modlist, std::ios::binary); - std::stringstream buffer; - buffer << t.rdbuf(); - modlists_contents.emplace_back(modlist.string(), buffer.str()); + modlists_contents.emplace_back(modlist.string(), utils::ReadWholeFile(modlist)); } } } @@ -250,8 +249,8 @@ void InitInstance(HINSTANCE hModule) GetProcAddress_fn = reinterpret_cast(GetProcAddress); ASSERT(GetProcAddress_fn); if (GetProcAddress_fn) { - MH_CreateHook(GetProcAddress_fn, OnGetProcAddress, (void**)&GetProcAddress_ret); - MH_EnableHook(GetProcAddress_fn); + MH_CreateHook(reinterpret_cast(GetProcAddress_fn), reinterpret_cast(OnGetProcAddress), (void**)&GetProcAddress_ret); + MH_EnableHook(reinterpret_cast(GetProcAddress_fn)); // Re-JIT the patched prologue + trampoline under the x86-on-ARM64 emulator (no-op native). const HANDLE proc = GetCurrentProcess(); FlushInstructionCache(proc, (void*)GetProcAddress_fn, 64); @@ -264,62 +263,42 @@ void InitInstance(HINSTANCE hModule) extern "C" __declspec(dllexport) int __cdecl SetDevice(IDirect3DDevice9* device) { if (!device) return RETURN_BAD_ARGUMENT; - try { - return RegisterExistingDevice(device) ? RETURN_OK : RETURN_EXISTS; - } - catch (...) { - return RETURN_FATAL_ERROR; - } + return RegisterExistingDevice(device) ? RETURN_OK : RETURN_EXISTS; } extern "C" __declspec(dllexport) int __cdecl AddFile(const wchar_t* path) { if (!path) return RETURN_BAD_ARGUMENT; - try { - return TextureClient::AddFile(std::filesystem::path(path)); - } - catch (...) { - return RETURN_FATAL_ERROR; - } + return TextureClient::AddFile(std::filesystem::path(path)); } extern "C" __declspec(dllexport) int __cdecl RemoveFile(const wchar_t* path) { if (!path) return RETURN_BAD_ARGUMENT; - try { - return TextureClient::RemoveFile(std::filesystem::path(path)); - } - catch (...) { - return RETURN_FATAL_ERROR; - } + return TextureClient::RemoveFile(std::filesystem::path(path)); } // nullptr first arg = return required size; paths come back in load (priority) order // returns paths separated by null terminator, e.g. "C:\foo.tpf\0C:\bar.zip\0\0" extern "C" __declspec(dllexport) int __cdecl GetFiles(wchar_t* buffer, const size_t buffer_size_chars) { - try { - const auto files = TextureClient::GetFiles(); - size_t required = 1; - for (const auto& path : files) { - required += path.native().size() + 1; - } + const auto files = TextureClient::GetFiles(); + size_t required = 1; + for (const auto& path : files) { + required += path.native().size() + 1; + } - if (buffer && buffer_size_chars > 0 && buffer_size_chars >= required) { - wchar_t* out = buffer; - for (const auto& path : files) { - const auto& native = path.native(); - std::ranges::copy(native, out); - out += native.size(); - *out++ = L'\0'; - } - *out = L'\0'; + if (buffer && buffer_size_chars > 0 && buffer_size_chars >= required) { + wchar_t* out = buffer; + for (const auto& path : files) { + const auto& native = path.native(); + std::ranges::copy(native, out); + out += native.size(); + *out++ = L'\0'; } - return static_cast(required); - } - catch (...) { - return RETURN_FATAL_ERROR; + *out = L'\0'; } + return static_cast(required); } // Optional clean-shutdown entry: call this from the host (on a normal thread) BEFORE diff --git a/triplets/x86-windows-mixed.cmake b/triplets/x86-windows-mixed.cmake deleted file mode 100644 index a44daab..0000000 --- a/triplets/x86-windows-mixed.cmake +++ /dev/null @@ -1,9 +0,0 @@ -set(VCPKG_TARGET_ARCHITECTURE x86) - -if(PORT MATCHES "dxsdk-d3dx") - set(VCPKG_CRT_LINKAGE dynamic) - set(VCPKG_LIBRARY_LINKAGE dynamic) -else() - set(VCPKG_CRT_LINKAGE static) - set(VCPKG_LIBRARY_LINKAGE static) -endif() diff --git a/vcpkg-overlays/triplets/x86-mingw-mixed.cmake b/vcpkg-overlays/triplets/x86-mingw-mixed.cmake new file mode 100644 index 0000000..d6ade54 --- /dev/null +++ b/vcpkg-overlays/triplets/x86-mingw-mixed.cmake @@ -0,0 +1,16 @@ +set(VCPKG_TARGET_ARCHITECTURE x86) +# The builds use Ninja, so ports must not pick a Visual Studio generator just because Visual Studio is installed. +set(VCPKG_CMAKE_GENERATOR Ninja) +set(VCPKG_CRT_LINKAGE dynamic) +set(VCPKG_LIBRARY_LINKAGE static) + +# CMake 4 refuses cmake_minimum_required below 3.5, which some ports still declare. This lets those ports configure. +set(VCPKG_CMAKE_CONFIGURE_OPTIONS "-DCMAKE_POLICY_VERSION_MINIMUM=3.5") + +# Only DirectXTex gets the MinGW system name: it needs it to pull in directx-headers, but it breaks other ports' "windows" match. +if(PORT STREQUAL "directxtex") + set(VCPKG_CMAKE_SYSTEM_NAME MinGW) + list(APPEND VCPKG_CMAKE_CONFIGURE_OPTIONS "-DBC_USE_OPENMP=OFF;-DBUILD_DX11=OFF") +endif() + +set(VCPKG_CHAINLOAD_TOOLCHAIN_FILE "${CMAKE_CURRENT_LIST_DIR}/../../cmake/toolchain.cmake") diff --git a/vcpkg.json b/vcpkg.json index a1c7ea7..059c2f0 100644 --- a/vcpkg.json +++ b/vcpkg.json @@ -1,6 +1,6 @@ { "dependencies": [ - "dxsdk-d3dx", + "directxtex", { "name": "libzippp", "features": [