From 829f0ee314de2854e57773315dd475e9d00122d9 Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Sat, 28 Nov 2026 00:22:02 -0500 Subject: [PATCH 1/3] Name each cached library by what it is linked from A file group cached with asLibrary, as hxcpp_runtime, hxcpp-cppia and hxcpp_sqlite are, is linked into //lib, named only by the toolchain's object folder and the project. Builds with other defines, as a cppia host built with HXCPP_DEBUGGER and one without, compile other objects for those groups, and linked them into the same file. One after the other, each build found the other's objects in the .hash record and linked the library again. At the same time, one could link the other's library between linking its own and linking the program. On Windows with MSVC the debugger host failed on unresolved __hxcpp_dbg_* symbols and hx::sExecutionTrace, the plain host on the same symbols defined twice, and either could fail to open a library (LNK1104) while the other's lib.exe wrote it. With a warm cache, three rounds of the two hosts built at once failed both builds every time. Stock hxcpp names the library the same way, in 4.3.2 and on master. The linker now names a library in the cache by a hash of its objects' names, which already hash each object's source, flags and compiler, and of the tool, flags and libraries it is linked with. A build with other objects gets a library of its own, and builds with the same objects share one, linked again as before when an object is newer than it, as one trimmed from the cache and compiled again is. The library is linked under a name of the build's own beside it and renamed into place, so no build links one half written, and a failed link leaves nothing behind. Windows renames onto no file that is there, and deletes none another link has open. So when the rename fails and the library there is up to date, another build linked the same objects and put it there first, and this build drops its own. One older than the objects is deleted and the rename tried again, and while another link has it open, this build links its own copy, deletes it on exit, and leaves the replacing to a later build. Libraries under the old names are no longer used and are left for trimming. Tests: test/compile_cache/shared_lib.sh, run in test.yml, builds a cached library that returns VALUE in folders of its own with one cache. On Windows x64 with MSVC 14.50 and Haxe 4.3.7, before this change a build with another VALUE changed the first build's library, the first build again linked it again, and in two runs 10 and 11 of 12 builds run four at a time failed with LNK1104 or LNK1181, while one printed another build's VALUE each time. After it, all of it passes, including a library linked again in its place after its object was removed. By hand, a build that found its library older than its object while another process held it open linked its own copy and printed the right value, and the next build replaced it. Two scriptable cppia hosts, with HXCPP_DEBUGGER and without, built at the same time against one cache with its libraries removed before each of three rounds, linked their libraries and ran a cppia script each time, and an unchanged rebuild linked nothing. --- .github/workflows/test.yml | 5 ++ Changes.md | 1 + docs/CompileCache.md | 2 + test/compile_cache/shared_lib.sh | 108 ++++++++++++++++++++++++ test/compile_cache/shared_lib/Build.xml | 20 +++++ test/compile_cache/shared_lib/lib.cpp | 1 + test/compile_cache/shared_lib/main.cpp | 9 ++ tools/hxcpp/BuildTool.hx | 4 + tools/hxcpp/Linker.hx | 86 +++++++++++++++++-- tools/hxcpp/Target.hx | 5 ++ 10 files changed, 233 insertions(+), 8 deletions(-) create mode 100644 test/compile_cache/shared_lib.sh create mode 100644 test/compile_cache/shared_lib/Build.xml create mode 100644 test/compile_cache/shared_lib/lib.cpp create mode 100644 test/compile_cache/shared_lib/main.cpp diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index d3b15f405..28ba39c7f 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -229,6 +229,11 @@ jobs: rm -f prog.map haxelib run hxcpp Build.xml -DWANT_MAP test -f prog.map + - name: build tool cached libraries of builds with other defines, at the same time too + continue-on-error: ${{ inputs.warn_only }} + if: ${{ !cancelled() && steps.setup.outcome == 'success' }} + shell: bash + run: bash test/compile_cache/shared_lib.sh -D$HXCPP_ARCH_FLAG - name: build tool fails again after a step after the link failed continue-on-error: ${{ inputs.warn_only }} if: ${{ !cancelled() && steps.setup.outcome == 'success' && runner.os == 'Windows' }} diff --git a/Changes.md b/Changes.md index e1888b737..baaab61fa 100644 --- a/Changes.md +++ b/Changes.md @@ -3,6 +3,7 @@ libhxcpp 6.0.3 (unreleased) ------------------------------------------------------------ * Fixed the C++ build tool, built with haxe compile-cpp.hxml in tools/hxcpp, not compiling since 6.0.0: ThreadPool.hx declared the class that ends a compile thread's job before one of its imports, which Haxe refuses with "import and using may not appear after a declaration". The neko build tool, hxcpp.n, was unaffected, and run.n uses a C++ build tool only once one is built, so only rebuilding it failed. CI now type-checks it (libhxcpp #471) +* Fixed builds that share one HXCPP_COMPILE_CACHE with other defines, as a cppia host with HXCPP_DEBUGGER and one without, linking each other's libraries when they ran at the same time: a cached group linked as a library, as the runtime, hxcpp-cppia and hxcpp_sqlite are, went to one file for each toolchain and project, so a build could link the other's, and fail on its debugger symbols or crash, link one half written, or fail to open it (LNK1104). One after the other, each build linked it again. The library's name now comes from its objects and how it is linked, and it is linked under a name of the build's own and then moved into place, so each build links its own and builds with the same objects share one. Libraries under the old names are no longer used, and trimming the cache removes them in time. Stock hxcpp names the library the same way * Fixed the collector marking and moving the variables a cppia closure captures in place in the closure: a closure packs its captures at 4-byte offsets, so on 64-bit a String or object captured after an Int, as text in var count = 1; var text = "x"; function() return count + text, sits at an odd multiple of 4, which is undefined behaviour, reported by UBSan, and a fault on a CPU that requires alignment. Each capture is copied out to be marked or visited now, and written back if the moving collector moved it. Interpreted and jitted closures were both affected * Fixed the cppia interpreter reading an argument's slot in place in the script frame when it fills in the argument's default value, and writing a Float or Dynamic default the same way: a frame keeps 4-byte alignment, so on 64-bit an argument after an Int, as b in f(a:Int, ?b:String = "x"), sits at an odd multiple of 4, which is undefined behaviour, reported by UBSan, and a fault on a CPU that requires alignment. The slots are copied in and out now, as the interpreter's other frame accesses have been since 6.0.0. The JIT, which compiles defaults into the function, was not affected * Fixed Semaphore.tryAcquire(-1) waiting for ever where any other negative timeout returns at once, so a timeout worked out in whole seconds as deadline - now could wait with no limit once the deadline had passed. It was kept for Haxe 5.0.0-preview.1's Lock.wait() (libhxcpp #461), but preview.1's Lock waits through the runtime's own lock, which still takes a negative timeout as no limit, as Haxe 4's does. Only Haxe 5 nightlies from March to November 2026, which libhxcpp does not support, passed -1 to the semaphore; later ones call acquire() for no timeout. Every negative timeout returns at once now, as with stock hxcpp on Linux and macOS (HaxeFoundation/haxe#13114) diff --git a/docs/CompileCache.md b/docs/CompileCache.md index 7b7a0ced8..e3454048f 100755 --- a/docs/CompileCache.md +++ b/docs/CompileCache.md @@ -33,6 +33,8 @@ When linking a file group 'asLibrary', the object files are compiled and then th then the constructor may not get called, leading to bugs. - Can help on some systems where the linker command-line length is an issue. +The library goes in the cache, named by the objects in it and how it is linked. Builds with other defines, which compile other objects, each link a library of their own, so they can share a cache at the same time, and builds with the same objects use one library. + ### Management When compiling normally, hxcpp will check the cache size and evict the least used files to maintain the specified cache size. diff --git a/test/compile_cache/shared_lib.sh b/test/compile_cache/shared_lib.sh new file mode 100644 index 000000000..1a8a5b832 --- /dev/null +++ b/test/compile_cache/shared_lib.sh @@ -0,0 +1,108 @@ +#!/usr/bin/env bash +# Builds that share one HXCPP_COMPILE_CACHE with other defines, as a host +# with HXCPP_DEBUGGER and one without do, compile other objects for a cached +# group linked as a library, as the runtime is. The library was named by the +# toolchain and the project alone, so they linked their objects into the same +# file: one after the other, each linked it again, and at the same time one +# could link the other's library, as unresolved debugger symbols showed, or +# one half written, or fail to open it (LNK1104). +# This builds shared_lib/Build.xml, whose library returns VALUE, in folders +# of its own with one cache: +# - One after the other, a build with another VALUE must leave the first +# one's library as it was, and the first build again must link nothing. +# With its object trimmed from the cache, and so compiled again under the +# same name, it must link its library again in its place. +# - With the libraries gone from the cache but their objects kept, four builds +# at once, two with VALUEs of their own and two with the same one, must each +# link and print their own VALUE, and leave no half made library behind. +# Usage: test/compile_cache/shared_lib.sh [extra build tool args, eg -DHXCPP_M64] +cd "$(dirname "$0")" +extra=("$@") +rm -rf bin/shared_lib +mkdir -p bin/shared_lib +cd bin/shared_lib +export HXCPP_COMPILE_CACHE="$PWD/cache" +libs=cache/shared_lib_test/lib +failed=0 + +# build : builds in a folder of its own and checks that the +# program prints the value. The sources keep their dates, as a newer source +# compiles its cached object again +build() { + if [ ! -d "$1" ]; then + mkdir "$1" + cp -p ../../shared_lib/* "$1/" + fi + if ! (cd "$1" && haxelib run hxcpp Build.xml -DVALUE="$2" "${extra[@]}" > build.log 2>&1); then + echo "::error::the build in $1 with VALUE=$2 failed" + tail -20 "$1/build.log" + return 1 + fi + local printed + printed=$("$1/prog" | tr -d '\r') + if [ "$printed" != "$2" ]; then + echo "::error::the program built in $1 with VALUE=$2 printed $printed" + return 1 + fi + echo "the build in $1 printed $2" +} + +# The libraries in the cache, each with a checksum +list_libs() { + find "$libs" -type f ! -name '*.hash' -exec cksum {} + | sort -k3 +} + +build one 1 || exit 1 +first=$(list_libs) +first_objects=$(find cache/shared_lib_test -path "$libs" -prune -o -type f -print) +build two 2 || exit 1 +after=$(list_libs) +if [ -n "$first" ] && grep -qxF "$first" <<< "$after"; then + echo "the build with another VALUE left the first one's library as it was" +else + echo "::error::the build with another VALUE changed the library the first one linked" + echo "before: $first" + echo "after: $after" + failed=1 +fi +build one 1 || failed=1 +if grep -q "Link:.*shared_lib_test" one/build.log; then + echo "::error::the first build linked its library again:" + grep "Link:" one/build.log + failed=1 +else + echo "the first build again linked no library" +fi +# An object trimmed from the cache is compiled again under the same name +rm -f $first_objects +build one 1 || failed=1 +if grep -q "Link:.*shared_lib_test" one/build.log && [ "$(list_libs | wc -l)" -eq 2 ]; then + echo "an object compiled again linked its library again in its place" +else + echo "::error::an object compiled again did not link its library again in its place:" + grep "Link:" one/build.log + list_libs + failed=1 +fi + +for round in 1 2 3; do + same=$((round * 10 + 3)) + for value in $((round * 10 + 1)) $((round * 10 + 2)) $same; do + build "objects$value" $value > /dev/null || exit 1 + done + rm -f "$libs"/* + build "a$round" $((round * 10 + 1)) > "a$round.out" 2>&1 & a=$! + build "b$round" $((round * 10 + 2)) > "b$round.out" 2>&1 & b=$! + build "c$round" $same > "c$round.out" 2>&1 & c=$! + build "d$round" $same > "d$round.out" 2>&1 & d=$! + for pid in $a $b $c $d; do + wait $pid || failed=1 + done + cat "a$round.out" "b$round.out" "c$round.out" "d$round.out" +done +left=$(find "$libs" -name '*.tmp-*') +if [ -n "$left" ]; then + echo "::error::the builds left libraries half made: $left" + failed=1 +fi +exit $failed diff --git a/test/compile_cache/shared_lib/Build.xml b/test/compile_cache/shared_lib/Build.xml new file mode 100644 index 000000000..490b09ec1 --- /dev/null +++ b/test/compile_cache/shared_lib/Build.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + diff --git a/test/compile_cache/shared_lib/lib.cpp b/test/compile_cache/shared_lib/lib.cpp new file mode 100644 index 000000000..c577f67ee --- /dev/null +++ b/test/compile_cache/shared_lib/lib.cpp @@ -0,0 +1 @@ +int libValue() { return VALUE; } diff --git a/test/compile_cache/shared_lib/main.cpp b/test/compile_cache/shared_lib/main.cpp new file mode 100644 index 000000000..b024be56d --- /dev/null +++ b/test/compile_cache/shared_lib/main.cpp @@ -0,0 +1,9 @@ +#include + +int libValue(); + +int main() +{ + printf("%d\n", libValue()); + return 0; +} diff --git a/tools/hxcpp/BuildTool.hx b/tools/hxcpp/BuildTool.hx index 2198179c2..ff051db1b 100644 --- a/tools/hxcpp/BuildTool.hx +++ b/tools/hxcpp/BuildTool.hx @@ -730,6 +730,10 @@ class BuildTool var libName = targetDir + "/" + mCompiler.getTargetPrefix() + "_" + group.getCacheProject(); var libTarget = new Target(libName, "linker", "static_link" ); + // Another build with other defines can link the same group into + // the cache at the same time: the linker names this one by what + // goes in it, so each build links its own + libTarget.mInCache = useCache; linker.link(libTarget,groupObjs, mCompiler, [] ); target.mAutoLibs.push(linker.mLastOutName); // Linux the libraries must be added again if the references were not resolved the firs time diff --git a/tools/hxcpp/Linker.hx b/tools/hxcpp/Linker.hx index cb87c25e4..dddd719f5 100644 --- a/tools/hxcpp/Linker.hx +++ b/tools/hxcpp/Linker.hx @@ -79,10 +79,73 @@ class Linker return inObjDir + "/" + getSimpleFilename(inTarget); } + // A library in the compile cache is shared by every build that uses the + // cache, at the same time too, and a build with other defines compiles + // other objects for it. Named by its objects, whose names hash their + // sources, flags and compiler, and by how it is linked, each build links + // a library of its own, and builds with the same objects share one + function getCacheKey(inTarget:Target, inObjs:Array) + { + return Md5.encode(mExe + "|" + mFlags.concat(inTarget.mFlags).join(" ") + "|" + + inTarget.mAutoLibs.concat(inTarget.mLibs).concat(mLibs).join(";") + "|" + + inObjs.join(";")).substr(0,16); + } + + // A name of this build's own beside inName, ending as it does + static function getTempName(inName:String, inExt:String) + { + var unique = Md5.encode(Sys.getCwd() + " " + Sys.time() + " " + Math.random()).substr(0,8); + var base = inName.endsWith(inExt) ? inName.substr(0, inName.length - inExt.length) : inName; + return base + ".tmp-" + unique + inExt; + } + + static function tryRename(inFrom:String, inTo:String) + { + try + { + FileSystem.rename(inFrom, inTo); + return true; + } + catch(e:Dynamic) { } + return false; + } + + // Moves inMade, a library this build linked, to inName in one step, so no + // build links one half written, and returns the library to link. Windows + // renames onto no file that is there, and deletes none another link has + // open. A library there that is up to date was linked from the same + // objects by another build, which put it there first; one older than the + // objects, which were compiled again since, is replaced. While another + // link has the old one open, this build links its own, and a later build + // replaces it + function putInPlace(inMade:String, inName:String, inObjs:Array) + { + for(attempt in 0...2) + { + if (tryRename(inMade, inName)) + return inName; + if (FileSystem.exists(inName) && !isOutOfDate(inName, inObjs)) + { + try { FileSystem.deleteFile(inMade); } catch(e:Dynamic) { } + return inName; + } + if (attempt==0) + try { FileSystem.deleteFile(inName); } catch(e:Dynamic) { } + } + if (!FileSystem.exists(inName)) + Log.error("Could not move \"" + inMade + "\" to \"" + inName + "\""); + Log.info("", " - \x1b[1mLinking this build's own copy, as another link has the old library open:\x1b[0m " + inMade); + Tools.addOnExitHook(function(_) try { FileSystem.deleteFile(inMade); } catch(e:Dynamic) { } ); + return inMade; + } + public function link(inTarget:Target,inObjs:Array,inCompiler:Compiler,extraDeps:Array ) { var ext = inTarget.getExt(mExt); - var file_name = mNamePrefix + inTarget.mOutput + ext; + var output = inTarget.mOutput; + if (inTarget.mInCache) + output += "_" + getCacheKey(inTarget, inObjs); + var file_name = mNamePrefix + output + ext; var tmpDir = inCompiler.mObjDir; @@ -189,6 +252,9 @@ class Linker args.push(out.substr(0,out.length-1)); out = ""; } + // A library in the cache is made under a name of this build's own, + // then moved to its name whole + var made = inTarget.mInCache ? getTempName(out_name, ext) : out_name; // Build in temp dir, and then move out so all the crap windows // creates stays out of the way if (mLibDir!="") @@ -198,12 +264,12 @@ class Linker } else { - if (mRecreate && FileSystem.exists(out_name)) + if (mRecreate && FileSystem.exists(made)) { - Log.info("\x1b[1mClean: \x1b[0m" + out_name); - FileSystem.deleteFile(out_name); + Log.info("\x1b[1mClean: \x1b[0m" + made); + FileSystem.deleteFile(made); } - args.push(out + out_name); + args.push(out + made); } args = args.concat(mFlags).concat(inTarget.mFlags); @@ -282,11 +348,13 @@ class Linker args = args.concat(libs); - var lib_name = mLibDir!="" ? mLibDir+"/"+file_name : out_name; + var lib_name = mLibDir!="" ? mLibDir+"/"+file_name : made; var result = ProcessManager.runCommand("", mExe, args, true, true, false, - "\x1b[1mLink: \x1b[0m" + lib_name); + "\x1b[1mLink: \x1b[0m" + (mLibDir!="" ? lib_name : out_name)); if (result!=0) { + if (made!=out_name) + try { FileSystem.deleteFile(made); } catch(e:Dynamic) { } Tools.exit(result); //throw "Error : " + result + " - build cancelled"; } @@ -305,9 +373,11 @@ class Linker if (mLibDir!="") { Log.info("\x1b[1mMove file: \x1b[0m" + mLibDir+"/"+file_name + " to " + out_name); - sys.io.File.copy( mLibDir+"/"+file_name, out_name ); + sys.io.File.copy( mLibDir+"/"+file_name, made ); FileSystem.deleteFile( mLibDir+"/"+file_name ); } + if (made!=out_name) + mLastOutName = putInPlace(made, out_name, inObjs); sys.io.File.saveContent(hashFile,md5); mLastHashFile = hashFile; diff --git a/tools/hxcpp/Target.hx b/tools/hxcpp/Target.hx index 946683fd7..4aa2e1635 100644 --- a/tools/hxcpp/Target.hx +++ b/tools/hxcpp/Target.hx @@ -8,6 +8,10 @@ class Target private var mExt:String; public var mFullOutputName:String; public var mFullUnstrippedName:String; + // A library in the compile cache, which other builds link at the same + // time: Linker.link names it by what it is linked from and puts it in + // place whole + public var mInCache:Bool; // These attributes are merged by the "merge" command public var mFiles:Array; @@ -36,6 +40,7 @@ class Target mFlags = []; mExt = null; mFullOutputName = null; + mInCache = false; mSubTargets = []; mFileGroups = []; mFlags = []; From 2861ad1c475176641f69ef2eb27b0d621f66590b Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Sat, 28 Nov 2026 02:47:41 -0500 Subject: [PATCH 2/3] Make cached objects and precompiled headers whole before builds see them Builds that share a compile cache with the same defines, as two projects built at once do, compile the same cached objects and make the same cached precompiled header: their names hash the source, flags and compiler, not the build. Each compiler wrote them in place, so from an empty cache both builds compiled every shared file into the same path. On Windows with MSVC, two identical scriptable cppia hosts built at once both failed on hxcpp.h's precompiled header: one could not write hxcpp.obj while the other's cl.exe did ("Could not create PCH", C1083), deleted its half made one, and the other then found no hxcpp.pch. A debugger host and a plain one, which share the pcre2, zlib and other objects that HXCPP_DEBUGGER does not change, failed with LNK1104 on an object the other build was still writing. Stock hxcpp writes them in place too, in 4.3.2 and on master. An object in the cache is now compiled under a name of the build's own beside it and renamed to its name. A precompiled header in the cache is made in a directory of the build's own, with its MSVC object, and the directory is renamed to its name, so the two always arrive together, and the cache no longer makes that directory empty in advance. When the rename fails because another build put the same one there first, as Windows renames onto nothing that is there and POSIX onto no directory with files in it, the one there is kept if it will do: an object not older than its precompiled header, or a header with its object. One that will not do is moved aside and replaced, trying for 30 seconds while another build has it open. A failed compile deletes only its own file, where it deleted the cached one, which another build may just have made. Cached libraries take the same helpers from CompileCache. PathManager.mkdir also failed when another build made the directory between its check and its make, which builds starting on an empty cache hit as "Could not create compiler cache directory". Tests: test/compile_cache/same_objects.sh, run in test.yml, builds a cached group with a precompiled header, its sources in one shared folder, in four folders at once from an empty cache, three times. On Windows x64 with MSVC 14.50 and Haxe 4.3.7, before this change all 12 builds failed (C1083 on the header and on objects, and the cache directory). After it, all 12 printed 36, each having made the header and compiled all nine files, and nothing was left half made. With -D emscripten (emsdk 3.1.74), which makes a clang precompiled header, all 12 built and printed 36 under node. shared_lib.sh and compile_errors/check.sh, with the cache and without, still pass. Two identical scriptable cppia hosts built at once from an empty cache, and a HXCPP_DEBUGGER host with a plain one, built and ran a cppia script. --- .github/workflows/test.yml | 5 + Changes.md | 1 + docs/CompileCache.md | 2 + test/compile_cache/same_objects.sh | 71 ++++++++++++++ test/compile_cache/same_objects/Build.xml | 24 +++++ test/compile_cache/same_objects/main.cpp | 16 +++ test/compile_cache/same_objects/pre.h | 7 ++ tools/hxcpp/CompileCache.hx | 91 +++++++++++++++-- tools/hxcpp/Compiler.hx | 114 ++++++++++++++-------- tools/hxcpp/Linker.hx | 48 ++------- tools/hxcpp/PathManager.hx | 12 ++- 11 files changed, 305 insertions(+), 86 deletions(-) create mode 100644 test/compile_cache/same_objects.sh create mode 100644 test/compile_cache/same_objects/Build.xml create mode 100644 test/compile_cache/same_objects/main.cpp create mode 100644 test/compile_cache/same_objects/pre.h diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 28ba39c7f..8b9aa025a 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -234,6 +234,11 @@ jobs: if: ${{ !cancelled() && steps.setup.outcome == 'success' }} shell: bash run: bash test/compile_cache/shared_lib.sh -D$HXCPP_ARCH_FLAG + - name: build tool cached objects and precompiled header that builds make at the same time + continue-on-error: ${{ inputs.warn_only }} + if: ${{ !cancelled() && steps.setup.outcome == 'success' }} + shell: bash + run: bash test/compile_cache/same_objects.sh -D$HXCPP_ARCH_FLAG - name: build tool fails again after a step after the link failed continue-on-error: ${{ inputs.warn_only }} if: ${{ !cancelled() && steps.setup.outcome == 'success' && runner.os == 'Windows' }} diff --git a/Changes.md b/Changes.md index baaab61fa..a76b3d80c 100644 --- a/Changes.md +++ b/Changes.md @@ -4,6 +4,7 @@ libhxcpp 6.0.3 (unreleased) * Fixed the C++ build tool, built with haxe compile-cpp.hxml in tools/hxcpp, not compiling since 6.0.0: ThreadPool.hx declared the class that ends a compile thread's job before one of its imports, which Haxe refuses with "import and using may not appear after a declaration". The neko build tool, hxcpp.n, was unaffected, and run.n uses a C++ build tool only once one is built, so only rebuilding it failed. CI now type-checks it (libhxcpp #471) * Fixed builds that share one HXCPP_COMPILE_CACHE with other defines, as a cppia host with HXCPP_DEBUGGER and one without, linking each other's libraries when they ran at the same time: a cached group linked as a library, as the runtime, hxcpp-cppia and hxcpp_sqlite are, went to one file for each toolchain and project, so a build could link the other's, and fail on its debugger symbols or crash, link one half written, or fail to open it (LNK1104). One after the other, each build linked it again. The library's name now comes from its objects and how it is linked, and it is linked under a name of the build's own and then moved into place, so each build links its own and builds with the same objects share one. Libraries under the old names are no longer used, and trimming the cache removes them in time. Stock hxcpp names the library the same way +* Fixed builds that share one HXCPP_COMPILE_CACHE with the same defines, as two projects built at once, failing when they ran at the same time from a cache without their objects: each compiler wrote a cached object or precompiled header in place, so one build failed to write it while another did, as hxcpp.h's did with "Could not create PCH" (C1083), or compiled or linked with one half written, or one another build deleted after its own write failed. Two builds making the cache's own directories at once also failed with "Could not create compiler cache directory". Each object and precompiled header is now made under a name of the build's own and moved into place whole, the header with its object in one directory, and when two builds make the same one, the first in place is kept. Stock hxcpp writes them in place too * Fixed the collector marking and moving the variables a cppia closure captures in place in the closure: a closure packs its captures at 4-byte offsets, so on 64-bit a String or object captured after an Int, as text in var count = 1; var text = "x"; function() return count + text, sits at an odd multiple of 4, which is undefined behaviour, reported by UBSan, and a fault on a CPU that requires alignment. Each capture is copied out to be marked or visited now, and written back if the moving collector moved it. Interpreted and jitted closures were both affected * Fixed the cppia interpreter reading an argument's slot in place in the script frame when it fills in the argument's default value, and writing a Float or Dynamic default the same way: a frame keeps 4-byte alignment, so on 64-bit an argument after an Int, as b in f(a:Int, ?b:String = "x"), sits at an odd multiple of 4, which is undefined behaviour, reported by UBSan, and a fault on a CPU that requires alignment. The slots are copied in and out now, as the interpreter's other frame accesses have been since 6.0.0. The JIT, which compiles defaults into the function, was not affected * Fixed Semaphore.tryAcquire(-1) waiting for ever where any other negative timeout returns at once, so a timeout worked out in whole seconds as deadline - now could wait with no limit once the deadline had passed. It was kept for Haxe 5.0.0-preview.1's Lock.wait() (libhxcpp #461), but preview.1's Lock waits through the runtime's own lock, which still takes a negative timeout as no limit, as Haxe 4's does. Only Haxe 5 nightlies from March to November 2026, which libhxcpp does not support, passed -1 to the semaphore; later ones call acquire() for no timeout. Every negative timeout returns at once now, as with stock hxcpp on Linux and macOS (HaxeFoundation/haxe#13114) diff --git a/docs/CompileCache.md b/docs/CompileCache.md index e3454048f..efb6bd34f 100755 --- a/docs/CompileCache.md +++ b/docs/CompileCache.md @@ -6,6 +6,8 @@ The cache uses a hashing mechanism to tell if the contents of a file or its depe Additional benefits include keeping some files outside the source tree, and being able to remove these temp files easily. +Builds can use one cache at the same time, as two projects built at once do. Each object, precompiled header and library is made under a name of the build's own and then moved into place whole, so no build reads one that another build is still writing, and when two builds make the same one, the first in place is kept. + ### Setup A directory needs to be set aside to enable the cache. If possible, this should be on fast storage, such as a SSD. This is most easily done with an entry in the .hxcpp_config.xml file: ```xml diff --git a/test/compile_cache/same_objects.sh b/test/compile_cache/same_objects.sh new file mode 100644 index 000000000..8544a461a --- /dev/null +++ b/test/compile_cache/same_objects.sh @@ -0,0 +1,71 @@ +#!/usr/bin/env bash +# Builds that share one HXCPP_COMPILE_CACHE with the same defines, as two +# projects built at once do, compile the same cached objects and make the +# same cached precompiled header, as the runtime's and hxcpp.h's are. Each +# compiler wrote them in place, so from an empty cache one build failed to +# write them while another did (C1083), or compiled or linked with one half +# written, or deleted, after its own write failed (C1083, LNK1104). +# This builds same_objects/Build.xml, whose cached group with a precompiled +# header has its sources in one folder, in four folders of its own at once, +# from an empty cache, three times. Each build must print 36, and leave +# nothing half made in the cache. +# Usage: test/compile_cache/same_objects.sh [extra build tool args, eg -DHXCPP_M64] +cd "$(dirname "$0")" +extra=("$@") +rm -rf bin/same_objects +mkdir -p bin/same_objects/shared +cp same_objects/pre.h same_objects/main.cpp bin/same_objects/shared/ +cd bin/same_objects +for part in 0 1 2 3 4 5 6 7; do + cat > "shared/part$part.cpp" < + +int part$part() +{ + std::map seen; + for (int i = 0; i <= $part; i++) + seen[std::to_string(i)] = i; + return (int)seen.size(); +} +EOF +done +# A path the compiler reads as it is, on Windows too +shared=$(cd shared && { pwd -W 2>/dev/null || pwd; }) +failed=0 + +# build : builds in a folder of its own and checks what it prints +build() { + mkdir "$1" + cp ../../same_objects/Build.xml "$1/" + if ! (cd "$1" && haxelib run hxcpp Build.xml -DSHARED="$shared" "${extra[@]}" > build.log 2>&1); then + echo "::error::the build in $1 failed" + tail -20 "$1/build.log" + return 1 + fi + local printed + printed=$("$1/prog" | tr -d '\r') + if [ "$printed" != 36 ]; then + echo "::error::the program built in $1 printed $printed" + return 1 + fi + echo "the build in $1 printed 36" +} + +for round in 1 2 3; do + export HXCPP_COMPILE_CACHE="$PWD/cache$round" + pids=() + for folder in a b c d; do + build "$folder$round" > "$folder$round.out" 2>&1 & + pids+=($!) + done + for pid in "${pids[@]}"; do + wait $pid || failed=1 + done + cat a$round.out b$round.out c$round.out d$round.out + left=$(find "$HXCPP_COMPILE_CACHE" -name '*.tmp-*' -o -name '*.old-*') + if [ -n "$left" ]; then + echo "::error::the builds left entries half made in the cache: $left" + failed=1 + fi +done +exit $failed diff --git a/test/compile_cache/same_objects/Build.xml b/test/compile_cache/same_objects/Build.xml new file mode 100644 index 000000000..f4e0245c3 --- /dev/null +++ b/test/compile_cache/same_objects/Build.xml @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/test/compile_cache/same_objects/main.cpp b/test/compile_cache/same_objects/main.cpp new file mode 100644 index 000000000..1a128afc6 --- /dev/null +++ b/test/compile_cache/same_objects/main.cpp @@ -0,0 +1,16 @@ +#include + +int part0(); +int part1(); +int part2(); +int part3(); +int part4(); +int part5(); +int part6(); +int part7(); + +int main() +{ + printf("%d\n", part0() + part1() + part2() + part3() + part4() + part5() + part6() + part7()); + return 0; +} diff --git a/test/compile_cache/same_objects/pre.h b/test/compile_cache/same_objects/pre.h new file mode 100644 index 000000000..84dbe94bc --- /dev/null +++ b/test/compile_cache/same_objects/pre.h @@ -0,0 +1,7 @@ +#include +#include +#include +#include +#include +#include +#include diff --git a/tools/hxcpp/CompileCache.hx b/tools/hxcpp/CompileCache.hx index 9392f3e1b..f51b7c4f2 100644 --- a/tools/hxcpp/CompileCache.hx +++ b/tools/hxcpp/CompileCache.hx @@ -1,10 +1,91 @@ import sys.FileSystem; +import haxe.io.Path; class CompileCache { public static var hasCache = false; public static var compileCache:String; + // Builds that share the cache can make the same entry at the same time, + // or read one while another build writes it. So an entry is made under a + // name of the build's own and moved to its name in one step + static var tempTag:String = null; + static var tempCount = 0; + + // A name of this build's own beside inName, keeping inName's extension + public static function getTempName(inName:String, inKind:String = "tmp") + { + if (tempTag==null) + tempTag = haxe.crypto.Md5.encode(Sys.getCwd() + " " + Sys.time() + " " + Math.random() + " " + Sys.args().join(" ")).substr(0,8); + var ext = Path.extension(inName); + var dotExt = ext=="" ? "" : "." + ext; + return inName.substr(0, inName.length - dotExt.length) + "." + inKind + "-" + tempTag + "-" + (tempCount++) + dotExt; + } + + public static function tryRename(inFrom:String, inTo:String) + { + try + { + FileSystem.rename(inFrom, inTo); + return true; + } + catch(e:Dynamic) { } + return false; + } + + // Removes a file, or a directory and what is in it, as far as it can + public static function removeEntry(inPath:String) + { + try + { + if (FileSystem.isDirectory(inPath)) + { + for(item in FileSystem.readDirectory(inPath)) + removeEntry(inPath + "/" + item); + FileSystem.deleteDirectory(inPath); + } + else + FileSystem.deleteFile(inPath); + } + catch(e:Dynamic) { } + } + + // Moves inMade, a file or directory this build made beside inName, to + // inName in one step. Windows renames onto nothing that is there, and + // POSIX onto no directory with files in it. So when inName is there and + // inUsable says it will do, another build made the same entry first, and + // this one is dropped. An older one is moved aside and removed, trying + // for inSeconds while another build has it open, as Windows renames no + // file that is open. Returns false when the older one stays + public static function putInPlace(inMade:String, inName:String, inUsable:Void->Bool, inSeconds:Float):Bool + { + var giveUp = Sys.time() + inSeconds; + while(true) + { + if (tryRename(inMade, inName)) + return true; + if (FileSystem.exists(inName) && inUsable()) + { + removeEntry(inMade); + return true; + } + var old = getTempName(inName, "old"); + if (tryRename(inName, old)) + { + if (tryRename(inMade, inName)) + { + removeEntry(old); + return true; + } + removeEntry(old); + continue; + } + if (Sys.time() >= giveUp) + return false; + Sys.sleep(0.1); + } + } + public static function init(inDefines:Map) : Bool { @@ -71,15 +152,11 @@ class CompileCache } */ + // The directory is made by Compiler.precompile, under a name of its own + // and then moved here whole public static function getPchDir(inProject:String,hash:String) { - var dir = compileCache + "/" + inProject + "/pch" + hash.substr(0,8); - try - { - if (!FileSystem.exists(dir)) - PathManager.mkdir(dir); - } catch(e:Dynamic) { } - return dir; + return compileCache + "/" + inProject + "/pch" + hash.substr(0,8); } public static function getCacheName(inProject:String,hash:String,inExt:String) diff --git a/tools/hxcpp/Compiler.hx b/tools/hxcpp/Compiler.hx index 691ea224b..9b2c26c91 100644 --- a/tools/hxcpp/Compiler.hx +++ b/tools/hxcpp/Compiler.hx @@ -365,6 +365,35 @@ class Compiler catch(e:Dynamic) { } } + // Whether the object in the cache at inName will do for inFile: not + // older than the precompiled header compiled with it, nor than the source + // in a group that respects timestamps + function cachedObjUsable(inName:String, inFile:File, pchTimeStamp:Null) + { + if (pchTimeStamp==null && !inFile.mGroup.mRespectTimestamp) + return true; + var time = FileSystem.stat(inName).mtime.getTime(); + if (pchTimeStamp!=null && time) + { + if (inMade==inName) + return; + if (!CompileCache.putInPlace(inMade, inName, function() return cachedObjUsable(inName, inFile, pchTimeStamp), 30)) + { + CompileCache.removeEntry(inMade); + Log.error("Could not replace \"" + inName + "\", which another build has open"); + } + } + public function compile(inFile:File,inTid:Int,headerFunc:Void->Void,pchTimeStamp:Null,inProgress:Progress) { var obj_name = getObjName(inFile); @@ -388,25 +417,12 @@ class Compiler obj_name = cacheName; } - if (FileSystem.exists(cacheName)) + if (FileSystem.exists(cacheName) && cachedObjUsable(cacheName, inFile, pchTimeStamp)) { - var newer = true; - if (pchTimeStamp!=null || inFile.mGroup.mRespectTimestamp) - { - var time = FileSystem.stat(cacheName).mtime.getTime(); - - if (pchTimeStamp!=null) - newer = time>=pchTimeStamp; - if (inFile.mGroup.mRespectTimestamp) - newer = newer && time>= FileSystem.stat(inFile.mDir + "/" + inFile.mName).mtime.getTime(); - } - if (newer) - { - //Log.info(""," copy cache for " + obj_name ); - if (!useCacheInPlace) - sys.io.File.copy(cacheName, obj_name); - found = true; - } + //Log.info(""," copy cache for " + obj_name ); + if (!useCacheInPlace) + sys.io.File.copy(cacheName, obj_name); + found = true; } } @@ -441,7 +457,11 @@ class Compiler out = ""; } - args.push(out + obj_name); + // An object in the cache is compiled under a name of this build's + // own and then moved to its name, as another build can compile the + // same one at the same time, or link it while this one writes it + var made = cacheName!=null && useCacheInPlace ? CompileCache.getTempName(obj_name) : obj_name; + args.push(out + made); if (delayedFilename!=null) args.push(delayedFilename); @@ -479,13 +499,16 @@ class Compiler BuildTool.setThreadError(err); try { - if (FileSystem.exists(obj_name)) - FileSystem.deleteFile(obj_name); + if (FileSystem.exists(made)) + FileSystem.deleteFile(made); } catch(e:Dynamic) { } } else + { + putObjInPlace(made, obj_name, inFile, pchTimeStamp); inProgress.fileDone(); + } } } else @@ -498,11 +521,12 @@ class Compiler cleanTmp(tmpFile); if (result!=0) { - if (FileSystem.exists(obj_name)) - FileSystem.deleteFile(obj_name); + if (FileSystem.exists(made)) + FileSystem.deleteFile(made); Tools.exit (result); //throw "Error : " + result + " - build cancelled"; } + putObjInPlace(made, obj_name, inFile, pchTimeStamp); inProgress.fileDone(); } @@ -645,45 +669,47 @@ class Compiler // Like objs/hxcpp.pch or objs/wx.gch var pch_name = dir + "/" + file + mPCHExt; + // No obj needed for gcc + var obj = mPCH=="msvc" ? PathManager.combine(dir, file + mExt) : null; + var complete = function() return FileSystem.exists(pch_name) && (obj==null || FileSystem.exists(obj)); mPCHRebuilt = false; - if (inGroup.isCached() || inReuseIfPossible) - { - // No obj needed for gcc - var obj = mPCH=="msvc" ? PathManager.combine(dir, file + mExt) : null; - if (FileSystem.exists(pch_name) && (obj==null || FileSystem.exists(obj)) ) - return obj; - } + if ((inGroup.isCached() || inReuseIfPossible) && complete()) + return obj; mPCHRebuilt = true; args = args.concat( mPCHFlags ); - //Log.info("", "Make pch dir " + dir ); - PathManager.mkdir(dir); + // One in the cache is made in a directory of this build's own and moved + // to its own whole: another build can make the same one at the same + // time, and one compiled with it must find its object beside it + var made = inGroup.isCached() ? CompileCache.getTempName(dir) : dir; + var made_pch = made + "/" + file + mPCHExt; + //Log.info("", "Make pch dir " + made ); + PathManager.mkdir(made); if (mPCH == "msvc") { args.push( mPCHCreate + header + ".h" ); if (!BuildTool.isMsvcLlvm()) { - var symbol = "link" + Md5.encode( PathManager.combine(dir, file + mExt) ); + var symbol = "link" + Md5.encode( obj ); args.push( "-Yl" + symbol ); } // Create a temp file for including ... - var tmp_cpp = dir + "/" + file + ".cpp"; + var tmp_cpp = made + "/" + file + ".cpp"; var outFile = sys.io.File.write(tmp_cpp,false); outFile.writeString("#include <" + header + ".h>\n"); outFile.close(); args.push( tmp_cpp ); - args.push(mPCHFilename + pch_name); - args.push(mOutFlag + PathManager.combine(dir, file + mExt)); + args.push(mPCHFilename + made_pch); + args.push(mOutFlag + PathManager.combine(made, file + mExt)); } else { Log.info("", 'Creating PCH directory "$dir"'); - PathManager.mkdir(dir); args.push( "-o" ); - args.push(pch_name); + args.push(made_pch); args.push( inGroup.mPrecompiledHeaderDir + "/" + inGroup.mPrecompiledHeader + ".h" ); } @@ -691,11 +717,13 @@ class Compiler var result = ProcessManager.runCommand("", mExe, args); if (result!=0) { + if (made!=dir) + CompileCache.removeEntry(made); var goes = 10; for(attempt in 0...goes) { try { - if (FileSystem.exists(pch_name)) + if (made==dir && FileSystem.exists(pch_name)) FileSystem.deleteFile(pch_name); break; } @@ -710,6 +738,14 @@ class Compiler //throw "Error creating pch: " + result + " - build cancelled"; } + // A complete one there was made from the same header and flags by + // another build, and is kept + if (made!=dir && !CompileCache.putInPlace(made, dir, complete, 30)) + { + CompileCache.removeEntry(made); + Log.error('Could not replace the precompiled header in "$dir", which another build has open'); + } + if (mPCH == "msvc") return PathManager.combine(dir, file + mExt); return null; diff --git a/tools/hxcpp/Linker.hx b/tools/hxcpp/Linker.hx index dddd719f5..ccce847fd 100644 --- a/tools/hxcpp/Linker.hx +++ b/tools/hxcpp/Linker.hx @@ -91,47 +91,17 @@ class Linker inObjs.join(";")).substr(0,16); } - // A name of this build's own beside inName, ending as it does - static function getTempName(inName:String, inExt:String) - { - var unique = Md5.encode(Sys.getCwd() + " " + Sys.time() + " " + Math.random()).substr(0,8); - var base = inName.endsWith(inExt) ? inName.substr(0, inName.length - inExt.length) : inName; - return base + ".tmp-" + unique + inExt; - } - - static function tryRename(inFrom:String, inTo:String) - { - try - { - FileSystem.rename(inFrom, inTo); - return true; - } - catch(e:Dynamic) { } - return false; - } - // Moves inMade, a library this build linked, to inName in one step, so no - // build links one half written, and returns the library to link. Windows - // renames onto no file that is there, and deletes none another link has - // open. A library there that is up to date was linked from the same - // objects by another build, which put it there first; one older than the - // objects, which were compiled again since, is replaced. While another - // link has the old one open, this build links its own, and a later build - // replaces it + // build links one half written, and returns the library to link. A + // library there that is up to date was linked from the same objects by + // another build, which put it there first; one older than the objects, + // which were compiled again since, is replaced. While another link has + // the old one open, this build links its own, and a later build replaces + // it function putInPlace(inMade:String, inName:String, inObjs:Array) { - for(attempt in 0...2) - { - if (tryRename(inMade, inName)) - return inName; - if (FileSystem.exists(inName) && !isOutOfDate(inName, inObjs)) - { - try { FileSystem.deleteFile(inMade); } catch(e:Dynamic) { } - return inName; - } - if (attempt==0) - try { FileSystem.deleteFile(inName); } catch(e:Dynamic) { } - } + if (CompileCache.putInPlace(inMade, inName, function() return !isOutOfDate(inName, inObjs), 0)) + return inName; if (!FileSystem.exists(inName)) Log.error("Could not move \"" + inMade + "\" to \"" + inName + "\""); Log.info("", " - \x1b[1mLinking this build's own copy, as another link has the old library open:\x1b[0m " + inMade); @@ -254,7 +224,7 @@ class Linker } // A library in the cache is made under a name of this build's own, // then moved to its name whole - var made = inTarget.mInCache ? getTempName(out_name, ext) : out_name; + var made = inTarget.mInCache ? CompileCache.getTempName(out_name) : out_name; // Build in temp dir, and then move out so all the crap windows // creates stays out of the way if (mLibDir!="") diff --git a/tools/hxcpp/PathManager.hx b/tools/hxcpp/PathManager.hx index 3872bd30b..80bf6727c 100644 --- a/tools/hxcpp/PathManager.hx +++ b/tools/hxcpp/PathManager.hx @@ -252,7 +252,17 @@ class PathManager if (!FileSystem.exists(total)) { Log.info("", " - \x1b[1mCreating directory:\x1b[0m " + total); - FileSystem.createDirectory(total); + // Another build can make it at the same time, as builds + // sharing a compile cache make its directories + try + { + FileSystem.createDirectory(total); + } + catch(e:Dynamic) + { + if (!FileSystem.exists(total)) + throw e; + } } } } From f2ec81eba9d39e385c0c7a11010e3943da3173b5 Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Sat, 28 Nov 2026 06:36:59 -0500 Subject: [PATCH 3/3] Wait a second before shared_lib.sh compiles an object again The build tool reads file dates to the second, and links a library again only for an object newer than it. On the Linux CI runner a build takes under 100 ms, so after the test removed the first build's object, the build compiled it again in the same second as the library was linked, and did not link the library again, which failed the check that it does. The object is compiled from the same source and flags, so the library was still right. The test now waits a second first, as a trimmed object compiled again later would be. Tests: test/compile_cache/shared_lib.sh passes on Windows x64 with MSVC 14.50. It failed only on Linux 64 in CI, where the build is fast enough. --- test/compile_cache/shared_lib.sh | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/test/compile_cache/shared_lib.sh b/test/compile_cache/shared_lib.sh index 1a8a5b832..83d2cc91d 100644 --- a/test/compile_cache/shared_lib.sh +++ b/test/compile_cache/shared_lib.sh @@ -73,7 +73,11 @@ if grep -q "Link:.*shared_lib_test" one/build.log; then else echo "the first build again linked no library" fi -# An object trimmed from the cache is compiled again under the same name +# An object trimmed from the cache is compiled again under the same name. +# The build tool reads dates to the second, and links again only for an +# object newer than the library, which a fast build can compile in the +# same second as the library was linked +sleep 1 rm -f $first_objects build one 1 || failed=1 if grep -q "Link:.*shared_lib_test" one/build.log && [ "$(list_libs | wc -l)" -eq 2 ]; then