# SimpleRemoter Build Script # Usage: .\build.ps1 [-Config Release|Debug] [-Platform x64|x86|all] [-ServerOnly] [-ClientOnly] [-Clean] [-Publish] # # Requirements: # - Visual Studio 2019 or 2022 # - v142 toolset (MSVC v142 - VS 2019 C++ build tools) # - ATL (C++ ATL for v142 build tools) # - MFC libraries (C++ MFC for v142 build tools) param( [ValidateSet("Release", "Debug")] [string]$Config = "Release", [ValidateSet("x64", "x86", "all")] [string]$Platform = "x64", [switch]$ServerOnly, # Only build main server (Yama), skip client projects [switch]$ClientOnly, # Only build the client executable (ghost), skip server [switch]$Clean, # Clean before build [switch]$Publish, # Publish mode: rebuild all deps + x64 Release + UPX compress [switch]$GoServer, # Build Go fallback server (server/go) -> Bin/YamaGo_x64.exe [switch]$GoServerLinux # Cross-compile the Go server for Linux -> Bin/server_linux_amd64 ) $ErrorActionPreference = "Stop" $rootDir = $PSScriptRoot $binDir = Join-Path $rootDir "Bin" $upxPath = Join-Path $rootDir "server\2015Remote\res\3rd\upx.exe" # Build Go fallback server. No-op (with warning) if Go compiler is not installed. # When -Compress is set, run UPX --best on the output (mirrors C++ publish flow). function Build-GoServer { param( [string]$Configuration, [switch]$Compress, # "linux" cross-compiles an ELF binary from Windows (CGO off). Output # name matches the ReadMe/Makefile convention so the artifact can be # scp'd as-is. [ValidateSet("windows", "linux")] [string]$TargetOS = "windows" ) Write-Host "" Write-Host "Building Go server (server/go) for $TargetOS..." -ForegroundColor Magenta $goCmd = Get-Command go -ErrorAction SilentlyContinue if (-not $goCmd) { Write-Host "WARNING: Go compiler not found in PATH. Skipping Go server build." -ForegroundColor Yellow Write-Host " Install from https://go.dev/dl/ and ensure 'go' is in PATH." -ForegroundColor DarkGray return $false } Write-Host "Using Go: $($goCmd.Source)" -ForegroundColor Cyan $goDir = Join-Path $rootDir "server\go" if (-not (Test-Path $goDir)) { Write-Host "ERROR: Go source directory not found at $goDir" -ForegroundColor Red return $false } # Sync web assets (mirrors Makefile `sync` target — single source is server/web/index.html) $webSrc = Join-Path $rootDir "server\web\index.html" $webDstDir = Join-Path $goDir "web\assets" if (Test-Path $webSrc) { if (-not (Test-Path $webDstDir)) { New-Item -ItemType Directory -Path $webDstDir -Force | Out-Null } Copy-Item -Path $webSrc -Destination (Join-Path $webDstDir "index.html") -Force } if (-not (Test-Path $binDir)) { New-Item -ItemType Directory -Path $binDir -Force | Out-Null } $outFile = if ($TargetOS -eq "linux") { Join-Path $binDir "server_linux_amd64" } else { Join-Path $binDir "YamaGo_x64.exe" } # Version/commit metadata injected into serverInfo and get_server_status. # Empty when git is unavailable (source tarball, IDE build) — the server # then reports no version rather than a fabricated one. $gitVersion = "" $gitCommit = "" if (Get-Command git -ErrorAction SilentlyContinue) { $gitVersion = (& git -C $rootDir describe --tags --always --dirty 2>$null | Select-Object -First 1) if ($LASTEXITCODE -ne 0 -or -not $gitVersion) { $gitVersion = "" } else { $gitVersion = "$gitVersion".Trim() } $gitCommit = (& git -C $rootDir rev-parse --short HEAD 2>$null | Select-Object -First 1) if ($LASTEXITCODE -ne 0 -or -not $gitCommit) { $gitCommit = "" } else { $gitCommit = "$gitCommit".Trim() } } $buildinfoPkg = "github.com/yuanyuanxiang/SimpleRemoter/server/go/buildinfo" $ldflagParts = @() # Release strips debug info for smaller binary; Debug keeps symbols. if ($Configuration -ne "Debug") { $ldflagParts += @("-s", "-w") } if ($gitVersion) { $ldflagParts += @("-X", "$buildinfoPkg.Version=$gitVersion") } if ($gitCommit) { $ldflagParts += @("-X", "$buildinfoPkg.Commit=$gitCommit") } $ldflags = $ldflagParts -join " " if ($gitVersion) { Write-Host "Version: $gitVersion ($gitCommit)" -ForegroundColor DarkGray } # Save the caller's Go env so a direct .\build.ps1 invocation does not # leave GOOS=linux behind for later builds in the same shell. $oldGoos = $env:GOOS $oldGoarch = $env:GOARCH $oldCgoEnabled = $env:CGO_ENABLED Push-Location $goDir try { $env:GOOS = $TargetOS $env:GOARCH = "amd64" # Cross-compiling for Linux requires a pure-Go build; the server has # no cgo dependencies, so this is the normal configuration. if ($TargetOS -eq "linux") { $env:CGO_ENABLED = "0" } # Refresh the Windows resources before linking: go-winres rewrites the # manifest identity, FileVersion and ProductVersion from the git tag so # Explorer's file properties match the tag while the runtime version # string stays the full `git describe` output. Missing go-winres or a # non-git tree keeps the checked-in .syso files unchanged. if ($TargetOS -eq "windows" -and $gitVersion) { if (Get-Command go-winres -ErrorAction SilentlyContinue) { & go-winres make --in cmd/winres/winres.json --out cmd/rsrc --product-version git-tag --file-version git-tag if ($LASTEXITCODE -ne 0) { Write-Host "WARNING: go-winres failed; keeping existing cmd/rsrc_*.syso" -ForegroundColor Yellow } } else { Write-Host "WARNING: go-winres not found; version resources not refreshed (go install github.com/tc-hib/go-winres@latest)" -ForegroundColor Yellow } } if ($ldflags) { & go build -ldflags $ldflags -o $outFile ./cmd } else { & go build -o $outFile ./cmd } $code = $LASTEXITCODE } finally { Pop-Location $env:GOOS = $oldGoos $env:GOARCH = $oldGoarch $env:CGO_ENABLED = $oldCgoEnabled } if ($code -ne 0) { Write-Host "ERROR: Go build failed (exit $code)" -ForegroundColor Red return $false } $size = (Get-Item $outFile).Length / 1MB Write-Host "OK: $outFile ($($size.ToString('F2')) MB)" -ForegroundColor Green # In-place UPX compression. Failure is a warning, not an error — the # uncompressed binary is still usable, and UPX occasionally refuses on # certain PE sections. if ($Compress -and $TargetOS -ne "windows") { Write-Host "WARNING: UPX compression is skipped for $TargetOS output (script ships upx.exe only for the Windows build)." -ForegroundColor Yellow } elseif ($Compress) { Write-Host "" Write-Host "UPX compressing Go server..." -ForegroundColor Magenta if (-not (Test-Path $upxPath)) { Write-Host "WARNING: UPX not found at $upxPath — skipping compression" -ForegroundColor Yellow } else { $sizeBefore = (Get-Item $outFile).Length / 1MB Write-Host " Before: $($sizeBefore.ToString('F2')) MB" -ForegroundColor DarkGray & $upxPath --best $outFile if ($LASTEXITCODE -ne 0) { Write-Host "WARNING: UPX compression failed, uncompressed binary kept" -ForegroundColor Yellow } else { $sizeAfter = (Get-Item $outFile).Length / 1MB $ratio = (1 - $sizeAfter / $sizeBefore) * 100 Write-Host " After: $($sizeAfter.ToString('F2')) MB (-$($ratio.ToString('F1'))%)" -ForegroundColor Green } } } return $true } # Go-only fast path: skip MSBuild entirely. -Publish here means "compress the # Go binary too" (not the full C++ publish flow). -GoServerLinux cross-compiles # the same server for Linux into Bin\server_linux_amd64. if ($GoServer -or $GoServerLinux) { $targetOS = if ($GoServerLinux) { "linux" } else { "windows" } $ok = Build-GoServer -Configuration $Config -Compress:$Publish -TargetOS $targetOS if (-not $ok) { exit 1 } exit 0 } # 判断某个 VS 安装是否带 ATL/MFC 组件。ATL 头文件用 #pragma comment(lib, "atls.lib") # 自动链接,只装了编译工具(BuildTools)的实例常常没有这一块:编译能过、链接报 # LNK1104 无法打开 atls.lib。同机既装 BuildTools 又装 IDE 时,按路径取第一个会挑错。 function Test-VcAtlPresent { param([string]$VsRoot) if (-not $VsRoot) { return $false } $atlLib = Join-Path $VsRoot "VC\Tools\MSVC\*\atlmfc\lib\x86\atls.lib" return [bool](Get-ChildItem $atlLib -ErrorAction SilentlyContinue | Select-Object -First 1) } # 从 ...\MSBuild\Current\Bin\MSBuild.exe 反推 VS 安装根目录。 function Get-VsRootFromMsBuild { param([string]$MsBuildPath) $idx = $MsBuildPath.IndexOf("\MSBuild\", [System.StringComparison]::OrdinalIgnoreCase) if ($idx -lt 0) { return $null } return $MsBuildPath.Substring(0, $idx) } # Find MSBuild (VS2019 or VS2022, including Insiders/Preview) # Order: Prefer installations with v142 toolset (VS2019) over VS2022 BuildTools, # and within that prefer instances that actually carry ATL/MFC. $msBuildPaths = @( # VS2019 Insiders/Preview (non-standard path) - has v142 + MFC "${env:ProgramFiles}\Microsoft Visual Studio\18\*\MSBuild\Current\Bin\MSBuild.exe", "${env:ProgramFiles(x86)}\Microsoft Visual Studio\18\*\MSBuild\Current\Bin\MSBuild.exe", # VS2019 standard "${env:ProgramFiles}\Microsoft Visual Studio\2019\*\MSBuild\Current\Bin\MSBuild.exe", "${env:ProgramFiles(x86)}\Microsoft Visual Studio\2019\*\MSBuild\Current\Bin\MSBuild.exe", # VS2022 (may need v142 toolset installed separately) "${env:ProgramFiles}\Microsoft Visual Studio\2022\*\MSBuild\Current\Bin\MSBuild.exe", "${env:ProgramFiles(x86)}\Microsoft Visual Studio\2022\*\MSBuild\Current\Bin\MSBuild.exe" ) $msBuild = $null $fallbackMsBuild = $null # 第一个找到的候选(可能不带 ATL),仅在没有带 ATL 的实例时兜底 foreach ($pattern in $msBuildPaths) { foreach ($found in @(Get-ChildItem $pattern -ErrorAction SilentlyContinue)) { if (-not $fallbackMsBuild) { $fallbackMsBuild = $found.FullName } if (Test-VcAtlPresent (Get-VsRootFromMsBuild $found.FullName)) { $msBuild = $found.FullName break } Write-Host "Skipping MSBuild without ATL/MFC: $($found.FullName)" -ForegroundColor DarkYellow } if ($msBuild) { break } } # 兜底:默认路径找不到(例如 VS 装在 D 盘)时,用 vswhere 反查。 # vswhere.exe 由 VS Installer 维护,固定在 %ProgramFiles(x86)% 下,与 VS 本体盘符无关。 if (-not $msBuild) { $vswhere = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe" if (Test-Path $vswhere) { # 不能用 -requires Microsoft.VisualStudio.Component.VC.ATL 过滤组件 id: # 各 VS 版本的 id 不一样(v142/v143/预览版),且预览实例可能根本查不到。 # 因此列出全部实例,再逐个用 atls.lib 落地校验(上面那条 glob 只看得到 C 盘, # VS 装在 D 盘时只能靠这里找到)。 $hits = @(& $vswhere -products * -requires Microsoft.Component.MSBuild ` -find "MSBuild\**\Bin\MSBuild.exe" 2>$null) foreach ($hit in $hits) { if (-not $hit) { continue } if (-not $fallbackMsBuild) { $fallbackMsBuild = $hit } if (Test-VcAtlPresent (Get-VsRootFromMsBuild $hit)) { $msBuild = $hit; break } } } } # 一个带 ATL 的实例都没有:仍用兜底候选,让 MSBuild 报出更具体的错误。 if (-not $msBuild -and $fallbackMsBuild) { Write-Host "WARNING: no VS instance with ATL/MFC found, using $fallbackMsBuild" -ForegroundColor Yellow Write-Host " Install 'C++ ATL for v142 build tools' if linking fails on atls.lib." -ForegroundColor DarkGray $msBuild = $fallbackMsBuild } if (-not $msBuild) { Write-Host "ERROR: MSBuild not found." -ForegroundColor Red Write-Host "" Write-Host "Please install Visual Studio 2019 or 2022 with:" -ForegroundColor Yellow Write-Host " - Desktop development with C++" -ForegroundColor White Write-Host " - MSVC v142 - VS 2019 C++ x64/x86 build tools" -ForegroundColor White Write-Host " - C++ ATL for v142 build tools" -ForegroundColor White Write-Host " - C++ MFC for v142 build tools" -ForegroundColor White exit 1 } # Detect VS version $vsYear = "2019" if ($msBuild -match "\\2022\\") { $vsYear = "2022" } elseif ($msBuild -match "\\18\\") { $vsYear = "2019 Insiders" } Write-Host "Using MSBuild: $msBuild" -ForegroundColor Cyan $slnFile = Join-Path $rootDir "YAMA.sln" # Publish mode overrides if ($Publish) { $Config = "Release" $Platform = "x64" $ServerOnly = $false $Clean = $true } # Build function function Build-Project { param( [string]$Project, [string]$Configuration, [string]$Platform, [bool]$ForceClean = $false ) # Solution uses x86/x64, projects use Win32/x64 - MSBuild needs solution platform names $platArg = $Platform Write-Host "" Write-Host "Building: $Project | $Configuration | $Platform" -ForegroundColor Yellow $buildArgs = @( $slnFile, "/t:$Project", "/p:Configuration=$Configuration", "/p:Platform=$platArg", "/m", # Parallel build "/v:minimal" # Minimal verbosity ) if ($Clean -or $ForceClean) { # Use :Rebuild target for single project rebuild $buildArgs[1] = "/t:${Project}:Rebuild" } & $msBuild $buildArgs if ($LASTEXITCODE -ne 0) { Write-Host "ERROR: Build failed for $Project" -ForegroundColor Red Write-Host "" Write-Host "If you see 'v142 build tools cannot be found':" -ForegroundColor Yellow Write-Host " Install 'MSVC v142 - VS 2019 C++ build tools' via VS Installer" -ForegroundColor White Write-Host "" Write-Host "If you see 'LNK1104: cannot open file atls.lib':" -ForegroundColor Yellow Write-Host " Install 'C++ ATL for v142 build tools' via VS Installer" -ForegroundColor White Write-Host "" Write-Host "If you see 'MFC libraries are required':" -ForegroundColor Yellow Write-Host " Install 'C++ MFC for v142 build tools' via VS Installer" -ForegroundColor White exit 1 } Write-Host "OK: $Project" -ForegroundColor Green } # Debug client fast path: build the client executable and stop. # Only ghost is built — the other client projects (ServerDll, TestRun, TinyRun, # SCLoader) exist to be embedded in the server and are irrelevant when the goal # is debugging the client itself. if ($ClientOnly) { $clientProject = "ghost" $clientPlatforms = if ($Platform -eq "all") { @("x86", "x64") } else { @($Platform) } $startTime = Get-Date Write-Host "" Write-Host "========================================" -ForegroundColor Cyan Write-Host " SimpleRemoter Client Build" -ForegroundColor Cyan Write-Host " Config: $Config" -ForegroundColor Cyan Write-Host " Platform: $Platform" -ForegroundColor Cyan Write-Host " VS: $vsYear" -ForegroundColor Cyan Write-Host " Clean: $Clean" -ForegroundColor Cyan Write-Host "========================================" -ForegroundColor Cyan foreach ($plat in $clientPlatforms) { Build-Project -Project $clientProject -Configuration $Config -Platform $plat -ForceClean $Clean } $elapsed = (Get-Date) - $startTime Write-Host "" Write-Host "========================================" -ForegroundColor Green Write-Host " Build Completed!" -ForegroundColor Green Write-Host " Time: $($elapsed.TotalSeconds.ToString('F1')) seconds" -ForegroundColor Green Write-Host "========================================" -ForegroundColor Green Write-Host "" Write-Host "Output files:" -ForegroundColor Cyan # VS default OutDir for this project: $(SolutionDir)$(Platform)\$(Configuration)\ # x86 output lands in \Debug, x64 in \x64\Debug. foreach ($plat in $clientPlatforms) { $outDir = if ($plat -eq "x64") { Join-Path (Join-Path $rootDir "x64") $Config } else { Join-Path $rootDir $Config } $clientOut = Join-Path $outDir "ghost.exe" if (Test-Path $clientOut) { $size = (Get-Item $clientOut).Length / 1MB Write-Host " $clientOut ($($size.ToString('F2')) MB)" -ForegroundColor White } else { Write-Host " WARNING: expected output not found at $clientOut" -ForegroundColor Yellow } } exit 0 } # Determine platforms to build $platforms = if ($Platform -eq "all") { @("x86", "x64") } else { @($Platform) } # Client projects (dependencies) - must build both x86 and x64 for embedding $clientProjects = @( "ServerDll", # ClientDll_vs2015.vcxproj -> ServerDll.dll "ghost", # ghost_vs2015.vcxproj -> ghost.exe "TestRun", # TestRun_vs2015.vcxproj -> TestRun.exe "TinyRun", # TinyRun.vcxproj -> TinyRun.dll "SCLoader" # SCLoader.vcxproj -> SCLoader.exe ) # Server project $serverProject = "Yama" # 2015Remote_vs2015.vcxproj -> Yama.exe $startTime = Get-Date Write-Host "" Write-Host "========================================" -ForegroundColor Cyan if ($Publish) { Write-Host " SimpleRemoter PUBLISH Build" -ForegroundColor Cyan } else { Write-Host " SimpleRemoter Build" -ForegroundColor Cyan } Write-Host " Config: $Config" -ForegroundColor Cyan Write-Host " Platform: $Platform" -ForegroundColor Cyan Write-Host " VS: $vsYear" -ForegroundColor Cyan Write-Host " Clean: $Clean" -ForegroundColor Cyan if ($Publish) { Write-Host " UPX: Yes" -ForegroundColor Cyan } Write-Host "========================================" -ForegroundColor Cyan if (-not $ServerOnly) { Write-Host "" Write-Host "Step 1: Building client projects (Release x86 + x64)..." -ForegroundColor Magenta Write-Host " (Always Release - embedded in server resources)" -ForegroundColor DarkGray # Client projects are always built as Release (embedded in server resources) # In Publish mode, force clean rebuild foreach ($proj in $clientProjects) { Build-Project -Project $proj -Configuration "Release" -Platform "x86" -ForceClean $Publish Build-Project -Project $proj -Configuration "Release" -Platform "x64" -ForceClean $Publish } } Write-Host "" Write-Host "Step 2: Building server (Yama)..." -ForegroundColor Magenta foreach ($plat in $platforms) { Build-Project -Project $serverProject -Configuration $Config -Platform $plat -ForceClean $Publish } # UPX compression in Publish mode $finalOutput = $null if ($Publish) { Write-Host "" Write-Host "Step 3: UPX compression..." -ForegroundColor Magenta $binPath = Join-Path (Join-Path $rootDir "Bin") "Yama_x64.exe" if (-not (Test-Path $upxPath)) { Write-Host "ERROR: UPX not found at $upxPath" -ForegroundColor Red exit 1 } if (-not (Test-Path $binPath)) { Write-Host "ERROR: Output file not found at $binPath" -ForegroundColor Red exit 1 } $sizeBefore = (Get-Item $binPath).Length / 1MB Write-Host " Before: $($sizeBefore.ToString('F2')) MB" -ForegroundColor DarkGray & $upxPath --best $binPath if ($LASTEXITCODE -ne 0) { Write-Host "WARNING: UPX compression failed, but build succeeded" -ForegroundColor Yellow } else { $sizeAfter = (Get-Item $binPath).Length / 1MB $ratio = (1 - $sizeAfter / $sizeBefore) * 100 Write-Host " After: $($sizeAfter.ToString('F2')) MB (-$($ratio.ToString('F1'))%)" -ForegroundColor Green } $finalOutput = $binPath } $elapsed = (Get-Date) - $startTime Write-Host "" Write-Host "========================================" -ForegroundColor Green if ($Publish) { Write-Host " Publish Completed!" -ForegroundColor Green } else { Write-Host " Build Completed!" -ForegroundColor Green } Write-Host " Time: $($elapsed.TotalSeconds.ToString('F1')) seconds" -ForegroundColor Green Write-Host "========================================" -ForegroundColor Green # Show output files Write-Host "" Write-Host "Output files:" -ForegroundColor Cyan if ($finalOutput) { $size = (Get-Item $finalOutput).Length / 1MB Write-Host " $finalOutput ($($size.ToString('F2')) MB)" -ForegroundColor White } else { foreach ($plat in $platforms) { # Check both possible output locations (project has custom OutputFile) $suffix = if ($plat -eq "x86") { "_x86" } else { "_x64" } if ($Config -eq "Debug") { $suffix += "d" } $binPath = Join-Path (Join-Path $rootDir "Bin") "Yama$suffix.exe" $outDir = if ($plat -eq "x86") { "Release" } else { "x64\Release" } if ($Config -eq "Debug") { $outDir = if ($plat -eq "x86") { "Debug" } else { "x64\Debug" } } $stdPath = Join-Path (Join-Path $rootDir $outDir) "Yama.exe" # Prefer Bin output, fallback to standard path $outPath = if (Test-Path $binPath) { $binPath } elseif (Test-Path $stdPath) { $stdPath } else { $null } if ($outPath) { $size = (Get-Item $outPath).Length / 1MB Write-Host " $outPath ($($size.ToString('F2')) MB)" -ForegroundColor White } } }