From ea02948113703d97d87116f01fee2b5f19267479 Mon Sep 17 00:00:00 2001 From: Pritpal Bedi Date: Sun, 15 Nov 2026 10:48:30 -0600 Subject: [PATCH 1/7] Add FS-facing OS byte locks with shared/exclusive and client-side WAIT; native same-handle IO and process proofs --- contrib/oads_hb/FILE_LOCKS_MTFIX85.txt | 53 +++++++++++ contrib/oads_hb/oads_hb.c | 37 ++++++++ include/openads/ace.h | 6 ++ src/abi/ace_exports.cpp | 50 +++++++++++ src/abi/adsfunc.c | 9 ++ src/engine/server_fs.cpp | 111 +++++++++++++++++------- src/engine/server_fs.h | 40 ++++++++- src/network/client.cpp | 17 ++++ src/network/client.h | 2 + src/network/session.cpp | 18 ++++ src/network/wire.cpp | 1 + src/network/wire.h | 4 + src/openads_ace.def | 6 ++ src/openads_ace_x86_stdcall.def | 3 + tests/CMakeLists.txt | 8 ++ tests/fs_lock85_probe.cpp | 43 +++++++++ tests/unit/abi_oads_file_funcs_test.cpp | 77 ++++++++++++++++ 17 files changed, 453 insertions(+), 32 deletions(-) create mode 100644 contrib/oads_hb/FILE_LOCKS_MTFIX85.txt create mode 100644 tests/fs_lock85_probe.cpp diff --git a/contrib/oads_hb/FILE_LOCKS_MTFIX85.txt b/contrib/oads_hb/FILE_LOCKS_MTFIX85.txt new file mode 100644 index 00000000..8f1cd645 --- /dev/null +++ b/contrib/oads_hb/FILE_LOCKS_MTFIX85.txt @@ -0,0 +1,53 @@ +OpenADS FS byte locks - mtfix85 +Pritpal Bedi +2026-11-15 10:48 + +OAds_FLock( hFile, nStart, nLen, nType ) -> lOk +OAds_FUnlock( hFile, nStart, nLen ) -> lOk +OAds_FLockTest( hFile, nStart, nLen, nType ) -> nResult + +hFile comes from OAds_FOpen or OAds_FCreate. These are file-system +byte-range locks, not RDD record locks. They use the server host's OS +locks and work across processes. I/O and locks use the same native file +handle, including on Windows. Close/disconnect releases held locks. +EnableFileFunc must be enabled on the server. Jail rules remain in force. + +nType flags, added with hb_bitOr(): + 0x0000 = exclusive, no wait (default) + 0x0100 = shared + 0x0200 = wait until success + 0x0300 = shared, wait until success + +NO_WAIT makes one attempt and returns .F. on contention. +WAIT repeats until success or a real error, closed handle, or connection +failure. Each server request makes one non-blocking OS attempt: there +is no server-side sleep or lock wait. The client retries every 10 ms, +releasing the file/connection/registry mutexes between attempts. The +Harbour wrapper releases the VM during the call. Another thread or +connection can unlock while the caller waits. A caller asking for WAIT +can wait indefinitely if the owner never releases. There is no hidden +30-second overall timeout and no change to the RDD's lock settings. + +FLockTest is a momentary check, not a reservation: + 0 = no conflicting lock for the requested shared/exclusive mode + 1 = conflict (also returned for an overlapping lock owned by this handle) + -1 = error + +First-scope differences from Harbour: +- Unlock requires the exact start and length that were acquired. + Partial unlock and an unlock spanning multiple acquired ranges fail. +- nLen must be positive. Zero-length/to-EOF locks are not implemented. +- Ranges must fit below the signed 64-bit file-offset limit. +- Overlapping locks on one handle must be unlocked before changing mode. + Taking the identical same-mode range again succeeds without a new lock. +- LockTest reports 1, not the POSIX process ID of the lock owner. +- Exclusive locking on a read-only file handle fails. Harbour's Unix + implementation can turn a read-only handle's request into shared mode. +- At most 1024 acquired ranges per file handle. +- These do not implement Harbour virtual-file drivers or socket handles. + +Windows enforces byte locks on I/O. POSIX byte locks are advisory, so +other programs must cooperate. This is OS behavior, not RDD policy. + +Test with the MinGW x86 kit's librddads.a and matching DLL. Use the +matching 64-bit server. Keep the earlier kit for rollback. diff --git a/contrib/oads_hb/oads_hb.c b/contrib/oads_hb/oads_hb.c index 47068a60..55975615 100644 --- a/contrib/oads_hb/oads_hb.c +++ b/contrib/oads_hb/oads_hb.c @@ -708,6 +708,43 @@ HB_FUNC( OADS_SETFILETIME ) /* ------------------------------------------------------------------ */ /* OADS_FTrunc( hFile, nSize ) -> lOk */ /* ------------------------------------------------------------------ */ +/* FS byte locks only, independent of RDD record locks. + * nType: 0 exclusive/no-wait, 0x100 shared, 0x200 wait until success. + * Unlock requires the exact range. LockTest: 0 free, 1 conflict, -1 error. + * WAIT releases the Harbour VM so another Harbour thread can unlock. + */ +HB_FUNC( OADS_FLOCK ) +{ + ADSHANDLE h = ( ADSHANDLE ) hb_parnint( 1 ); + HB_MAXINT start = hb_parnint( 2 ), len = hb_parnint( 3 ); + UNSIGNED16 type = ( UNSIGNED16 ) hb_parni( 4 ); + UNSIGNED32 rc = 5000; + if( h && start >= 0 && len > 0 ) + { + hb_vmUnlock(); + rc = oads_FLock( h, ( UNSIGNED64 ) start, ( UNSIGNED64 ) len, type ); + hb_vmLock(); + } + hb_retl( rc == 0 ); +} +HB_FUNC( OADS_FUNLOCK ) +{ + ADSHANDLE h = ( ADSHANDLE ) hb_parnint( 1 ); + HB_MAXINT start = hb_parnint( 2 ), len = hb_parnint( 3 ); + hb_retl( h && start >= 0 && len > 0 && + oads_FUnlock( h, ( UNSIGNED64 ) start, ( UNSIGNED64 ) len ) == 0 ); +} +HB_FUNC( OADS_FLOCKTEST ) +{ + ADSHANDLE h = ( ADSHANDLE ) hb_parnint( 1 ); + HB_MAXINT start = hb_parnint( 2 ), len = hb_parnint( 3 ); + SIGNED32 result = -1; + if( h && start >= 0 && len > 0 ) + oads_FLockTest( h, ( UNSIGNED64 ) start, ( UNSIGNED64 ) len, + ( UNSIGNED16 ) hb_parni( 4 ), &result ); + hb_retni( result ); +} + HB_FUNC( OADS_FTRUNC ) { ADSHANDLE hFile = ( ADSHANDLE ) hb_parnint( 1 ); diff --git a/include/openads/ace.h b/include/openads/ace.h index f9062e6e..9717957f 100644 --- a/include/openads/ace.h +++ b/include/openads/ace.h @@ -127,6 +127,9 @@ UNSIGNED32 ENTRYPOINT AdsSetFileTime (ADSHANDLE hConnect, UNSIGNED8* pucName, UNSIGNED16 usYear, UNSIGNED8 ucMon, UNSIGNED8 ucDay, UNSIGNED8 ucHour, UNSIGNED8 ucMin, UNSIGNED8 ucSec); +UNSIGNED32 ENTRYPOINT AdsFLock(ADSHANDLE hFile, UNSIGNED64 ullStart, UNSIGNED64 ullLen, UNSIGNED16 usType); +UNSIGNED32 ENTRYPOINT AdsFUnlock(ADSHANDLE hFile, UNSIGNED64 ullStart, UNSIGNED64 ullLen); +UNSIGNED32 ENTRYPOINT AdsFLockTest(ADSHANDLE hFile, UNSIGNED64 ullStart, UNSIGNED64 ullLen, UNSIGNED16 usType, SIGNED32* plResult); UNSIGNED32 ENTRYPOINT AdsFTrunc (ADSHANDLE hFile, UNSIGNED64 ullSize); // Creates an empty uniquely named file under pucDir; the name lands in @@ -237,6 +240,9 @@ UNSIGNED32 OADSAPI oads_SetFileTime (ADSHANDLE hConnect, UNSIGNED8* pucName, UNSIGNED16 usYear, UNSIGNED8 ucMon, UNSIGNED8 ucDay, UNSIGNED8 ucHour, UNSIGNED8 ucMin, UNSIGNED8 ucSec); +UNSIGNED32 OADSAPI oads_FLock(ADSHANDLE hFile, UNSIGNED64 ullStart, UNSIGNED64 ullLen, UNSIGNED16 usType); +UNSIGNED32 OADSAPI oads_FUnlock(ADSHANDLE hFile, UNSIGNED64 ullStart, UNSIGNED64 ullLen); +UNSIGNED32 OADSAPI oads_FLockTest(ADSHANDLE hFile, UNSIGNED64 ullStart, UNSIGNED64 ullLen, UNSIGNED16 usType, SIGNED32* plResult); UNSIGNED32 OADSAPI oads_FTrunc (ADSHANDLE hFile, UNSIGNED64 ullSize); UNSIGNED32 OADSAPI oads_TempFile (ADSHANDLE hConnect, UNSIGNED8* pucDir, diff --git a/src/abi/ace_exports.cpp b/src/abi/ace_exports.cpp index 7ad9dae7..2c267e5a 100644 --- a/src/abi/ace_exports.cpp +++ b/src/abi/ace_exports.cpp @@ -11560,6 +11560,56 @@ UNSIGNED32 ENTRYPOINT AdsSetFileTime(ADSHANDLE hConn, UNSIGNED8* pucName, return ok(); } +// Each invocation makes one non-blocking attempt. Never sleep while holding +// the ABI registry mutex or the per-file/connection mutex. +extern "C++" { +static openads::util::Result oads_fs_lock_once(ADSHANDLE hFile, + UNSIGNED64 start, UNSIGNED64 len, UNSIGNED16 type, std::uint8_t op) { + auto& s = state(); + std::unique_lock lk(s.mu); + if (auto it = remote_files_map().find(hFile); it != remote_files_map().end()) { + auto rf = it->second; + lk.unlock(); + std::lock_guard file_lk(rf->mu); + if (rf->closed) return openads::util::Error{5000, 0, "closed file", ""}; + return rf->conn->file_lock_step(rf->file_id, start, len, type, op); + } + if (auto* lf = s.registry.lookup( + hFile, openads::session::HandleKind::LocalFile)) + return openads::engine::fs_lock_step(*lf, start, len, type, op); + return openads::util::Error{5000, 0, "bad file handle", ""}; +} +} + +UNSIGNED32 ENTRYPOINT AdsFLock(ADSHANDLE hFile, UNSIGNED64 ullStart, + UNSIGNED64 ullLen, UNSIGNED16 usType) { + arc2_trace("AdsFLock"); + for (;;) { + auto v = oads_fs_lock_once(hFile, ullStart, ullLen, usType, 0); + if (!v) return fail(v.error()); + if (v.value()) return ok(); + if ((usType & 0x0200u) == 0) return fail(5012, "file lock busy"); + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } +} +UNSIGNED32 ENTRYPOINT AdsFUnlock(ADSHANDLE hFile, UNSIGNED64 ullStart, + UNSIGNED64 ullLen) { + arc2_trace("AdsFUnlock"); + auto v = oads_fs_lock_once(hFile, ullStart, ullLen, 0, 1); + if (!v) return fail(v.error()); + return ok(); +} +UNSIGNED32 ENTRYPOINT AdsFLockTest(ADSHANDLE hFile, UNSIGNED64 ullStart, + UNSIGNED64 ullLen, UNSIGNED16 usType, SIGNED32* plResult) { + arc2_trace("AdsFLockTest"); + if (!plResult) return fail(5000, "null lock-test result"); + *plResult = -1; + auto v = oads_fs_lock_once(hFile, ullStart, ullLen, usType, 2); + if (!v) return fail(v.error()); + *plResult = v.value() ? 1 : 0; + return ok(); +} + UNSIGNED32 ENTRYPOINT AdsFTrunc(ADSHANDLE hFile, UNSIGNED64 ullSize) { arc2_trace("AdsFTrunc"); auto& s = state(); diff --git a/src/abi/adsfunc.c b/src/abi/adsfunc.c index ca2f28b8..0c309646 100644 --- a/src/abi/adsfunc.c +++ b/src/abi/adsfunc.c @@ -240,3 +240,12 @@ UNSIGNED32 OADSAPI oads_Directory( ADSHANDLE hConnect, { return AdsDirectory( hConnect, pucMask, usAttr, pucBuffer, pulBufLen ); } + +UNSIGNED32 OADSAPI oads_FLock(ADSHANDLE hFile, UNSIGNED64 ullStart, UNSIGNED64 ullLen, UNSIGNED16 usType) +{ return AdsFLock(hFile, ullStart, ullLen, usType); } + +UNSIGNED32 OADSAPI oads_FUnlock(ADSHANDLE hFile, UNSIGNED64 ullStart, UNSIGNED64 ullLen) +{ return AdsFUnlock(hFile, ullStart, ullLen); } + +UNSIGNED32 OADSAPI oads_FLockTest(ADSHANDLE hFile, UNSIGNED64 ullStart, UNSIGNED64 ullLen, UNSIGNED16 usType, SIGNED32* plResult) +{ return AdsFLockTest(hFile, ullStart, ullLen, usType, plResult); } diff --git a/src/engine/server_fs.cpp b/src/engine/server_fs.cpp index 89287c0e..a9e6f6ea 100644 --- a/src/engine/server_fs.cpp +++ b/src/engine/server_fs.cpp @@ -301,7 +301,7 @@ util::Result fs_truncate(FsFile& file, std::uint64_t size) { if (!file.stream) return io_err(static_cast(openads::AE_INTERNAL_ERROR), "flush failed", file.path); - auto r = fs_truncate(file.path, size); + auto r = file.stream.file.truncate(size); if (!r) return r; file.stream.clear(); if (pos >= 0) { @@ -462,40 +462,91 @@ util::Result fs_dir_remove(const std::string& abs_path) { return {}; } +void FsStream::read(char* data, std::streamsize n) { + count_ = 0; + if (!good_ || n < 0) { good_ = false; return; } + auto v = file.read_at(static_cast(pos_), data, static_cast(n)); + if (!v) { good_ = false; return; } + count_ = static_cast(v.value()); + pos_ += static_cast(v.value()); +} +void FsStream::write(const char* data, std::streamsize n) { + if (!good_ || n < 0) { good_ = false; return; } + auto v = file.write_at(static_cast(pos_), data, static_cast(n)); + if (!v) { good_ = false; return; } + pos_ += static_cast(v.value()); + good_ = v.value() == static_cast(n); +} +void FsStream::flush() { + if (good_ && writable) good_ = file.sync().has_value(); +} +void FsStream::seekg(std::streamoff off, std::ios::seekdir way) { + std::streamoff base = 0; + if (way == std::ios::cur) base = pos_; + else if (way == std::ios::end) { + auto n = file.size(); + if (!n || n.value() > 0x7FFFFFFFFFFFFFFFULL) { good_ = false; return; } + base = static_cast(n.value()); + } + if ((off > 0 && base > 0x7FFFFFFFFFFFFFFFLL - off) || + (off < 0 && off < -base)) { good_ = false; return; } + pos_ = base + off; +} + +util::Result fs_lock_step(FsFile& f, std::uint64_t start, + std::uint64_t len, std::uint16_t type, + std::uint8_t op) { + if (op > 2 || (type & ~0x0300u) != 0 || len == 0 || + start > 0x7FFFFFFFFFFFFFFFULL || len > 0x7FFFFFFFFFFFFFFFULL - start) + return io_err(5000, "invalid lock range or flags", f.path); + bool shared = (type & 0x0100u) != 0; + if (op == 1) { + for (auto it = f.locks.begin(); it != f.locks.end(); ++it) { + if (it->start == start && it->len == len) { + auto v = it->lock.release(); + if (!v) return v.error(); + f.locks.erase(it); + return true; + } + } + return io_err(5000, "unlock range not held", f.path); + } + for (const auto& h : f.locks) { + if (start < h.start + h.len && h.start < start + len) { + if (op == 2) return true; // Harbour LockTest reports own registrations too + if (start == h.start && len == h.len && shared == h.shared) return true; + return io_err(5000, "overlapping own lock; unlock it first", f.path); + } + } + if (!shared && !f.writable) + return io_err(7079, "exclusive lock needs writable handle", f.path); + if (f.locks.size() >= 1024) return io_err(5000, "file lock limit", f.path); + auto v = platform::ByteLock::try_acquire(f.stream.file, start, len, + shared ? platform::LockKind::Shared : platform::LockKind::Exclusive); + if (!v) { + if (v.error().code == 5012) return op == 2; + return v.error(); + } + if (op == 2) return false; // temporary lock releases on destruction + f.locks.push_back({start, len, shared, std::move(v.value())}); + return true; +} + util::Result> fs_open(const std::string& abs_path, - std::uint16_t mode, - bool create) { + std::uint16_t mode, bool create) { auto f = std::make_unique(); f->path = abs_path; f->writable = create || (mode != ADS_FO_READ && mode != 3); - std::ios::openmode om = std::ios::binary; - if (create) { - om |= std::ios::in | std::ios::out | std::ios::trunc; - } else if (mode == ADS_FO_READ || mode == 3 /*ADS_READONLY*/) { - // Two conventions reach here: Harbour-style FO_READ (0) and the - // SAP ace.h ADS_READONLY (3) that oads_FOpen callers pass. Both - // must open read-only so FWrite on the handle fails. - om |= std::ios::in; - } else if (mode == ADS_FO_WRITE) { - om |= std::ios::in | std::ios::out; - } else { - om |= std::ios::in | std::ios::out; - } - f->stream.open(abs_path, om); - if (!f->stream) { - // Try create parent path for FCreate. - if (create) { - std::error_code ec; - fs::create_directories(fs::path(abs_path).parent_path(), ec); - f->stream.clear(); - f->stream.open(abs_path, om); - } + auto native = platform::File::open(abs_path, create ? platform::OpenMode::CreateRW : + f->writable ? platform::OpenMode::ReadWrite : platform::OpenMode::ReadOnly); + if (!native && create) { + std::error_code ec; + fs::create_directories(fs::path(abs_path).parent_path(), ec); + native = platform::File::open(abs_path, platform::OpenMode::CreateRW); } - if (!f->stream) - return io_err(static_cast( - create ? openads::AE_INTERNAL_ERROR - : openads::AE_NO_FILE_FOUND), - create ? "create failed" : "open failed", abs_path); + if (!native) return native.error(); + f->stream.file = std::move(native.value()); + f->stream.writable = f->writable; return f; } diff --git a/src/engine/server_fs.h b/src/engine/server_fs.h index 66b24526..3796a808 100644 --- a/src/engine/server_fs.h +++ b/src/engine/server_fs.h @@ -1,6 +1,8 @@ #pragma once #include "util/result.h" +#include "platform/file.h" +#include "platform/lock.h" #include #include @@ -70,11 +72,45 @@ util::Result fs_dir_exist(const std::string& abs_path); util::Result fs_dir_make(const std::string& abs_path); util::Result fs_dir_remove(const std::string& abs_path); +// Low-level file-function stream facade. I/O and locks use the SAME native +// handle, which Windows requires for the owner to read/write locked bytes. +// This is independent of the RDD/CDX engine's file and lock state. +class FsStream { +public: + platform::File file; + bool writable = false; + void clear() { good_ = true; } + explicit operator bool() const { return good_ && file.is_open(); } + void read(char* data, std::streamsize n); + void write(const char* data, std::streamsize n); + void flush(); + std::streamsize gcount() const { return count_; } + std::streampos tellg() const { return good_ ? std::streampos(pos_) : std::streampos(-1); } + void seekg(std::streamoff off, std::ios::seekdir way = std::ios::beg); + void seekg(std::streampos pos) { seekg(static_cast(pos)); } + void seekp(std::streampos pos) { seekg(pos); } +private: + std::streamoff pos_ = 0; + std::streamsize count_ = 0; + bool good_ = true; +}; +struct FsHeldLock { + std::uint64_t start, len; + bool shared; + platform::ByteLock lock; +}; struct FsFile { - std::fstream stream; - std::string path; + FsStream stream; + std::string path; bool writable = false; + // Destroy locks before the native handle (reverse member order). + std::vector locks; }; +// One non-blocking OS attempt. op: 0 lock, 1 exact-range unlock, 2 test. +// Lock returns false for contention. Test returns true for a conflict. +util::Result fs_lock_step(FsFile& file, std::uint64_t start, + std::uint64_t len, std::uint16_t type, + std::uint8_t op); util::Result fs_truncate(FsFile& file, std::uint64_t size); // create=true → create/truncate (FCreate). mode uses ADS_FO_*. diff --git a/src/network/client.cpp b/src/network/client.cpp index 8e6e47db..a21be7b4 100644 --- a/src/network/client.cpp +++ b/src/network/client.cpp @@ -3117,6 +3117,23 @@ RemoteConnection::file_set_time(const std::string& path, std::uint16_t year, return {}; } +util::Result +RemoteConnection::file_lock_step(std::uint32_t id, std::uint64_t start, + std::uint64_t len, std::uint16_t type, std::uint8_t op) { + Frame req; + req.opcode = Opcode::FileLockOp; + write_u32_le(id, req.payload); + write_u64_le(start, req.payload); + write_u64_le(len, req.payload); + write_u16_le(type, req.payload); + req.payload.push_back(op); + auto rep = request(req); + if (!rep) return rep.error(); + if (rep.value().opcode != Opcode::FileLockOp || rep.value().payload.size() != 1) + return fs_wire_err(rep.value(), "FileLockOp"); + return rep.value().payload[0] != 0; +} + util::Result RemoteConnection::ftruncate(std::uint32_t file_id, std::uint64_t size) { Frame req; diff --git a/src/network/client.h b/src/network/client.h index 2601693f..07c7fede 100644 --- a/src/network/client.h +++ b/src/network/client.h @@ -450,6 +450,8 @@ class RemoteConnection { std::uint8_t hh, std::uint8_t mm, std::uint8_t ss); + util::Result file_lock_step(std::uint32_t file_id, std::uint64_t start, + std::uint64_t len, std::uint16_t type, std::uint8_t op); util::Result ftruncate(std::uint32_t file_id, std::uint64_t size); util::Result file_temp(const std::string& dir, diff --git a/src/network/session.cpp b/src/network/session.cpp index 34d9c671..a4b47f4f 100644 --- a/src/network/session.cpp +++ b/src/network/session.cpp @@ -1712,6 +1712,7 @@ DispatchResult Session::dispatch(const Frame& f) { case Opcode::FRead: case Opcode::FWrite: case Opcode::FSeek: case Opcode::FileReadAt: case Opcode::FileWriteAt: case Opcode::FileFlush: case Opcode::FileEof: + case Opcode::FileLockOp: case Opcode::FileTrunc: case Opcode::ZipArchive: case Opcode::UnzipArchive: case Opcode::ZipList: if (!admin) return denied(); @@ -4259,6 +4260,7 @@ DispatchResult Session::dispatch(const Frame& f) { case Opcode::FileWriteAt: case Opcode::FileFlush: case Opcode::FileEof: + case Opcode::FileLockOp: case Opcode::FileTrunc: { if (!srv_->enable_file_func()) { reply = err("file functions disabled", @@ -4789,6 +4791,22 @@ DispatchResult Session::dispatch(const Frame& f) { reply.opcode = Opcode::FileEofAck; reply.payload.push_back( (cur < 0 || (end >= 0 && cur >= end)) ? 1 : 0); + } else if (f.opcode == Opcode::FileLockOp) { + if (f.payload.size() != 23) { reply = err("FileLockOp: bad payload"); break; } + auto id = read_u32_le(f.payload.data()); + auto it = files_.find(id); + if (it == files_.end()) { reply = err("FileLockOp: bad handle"); break; } + std::uint64_t start = 0, len = 0; + for (std::size_t i = 0; i < 8; ++i) { + start |= static_cast(f.payload[4+i]) << (8*i); + len |= static_cast(f.payload[12+i]) << (8*i); + } + auto type = static_cast(f.payload[20] | + (static_cast(f.payload[21]) << 8)); + auto v = openads::engine::fs_lock_step(*it->second, start, len, type, f.payload[22]); + if (!v) { reply = err("FileLockOp", static_cast(v.error().code)); break; } + reply.opcode = Opcode::FileLockOp; + reply.payload.push_back(v.value() ? 1 : 0); } else if (f.opcode == Opcode::FileTrunc) { if (f.payload.size() < 12) { reply = err("FileTrunc: short payload"); break; diff --git a/src/network/wire.cpp b/src/network/wire.cpp index e7b8ecc0..49c2f01d 100644 --- a/src/network/wire.cpp +++ b/src/network/wire.cpp @@ -228,6 +228,7 @@ bool valid_opcode(std::uint8_t opcode) noexcept { case static_cast(Opcode::FileSetAttrAck): case static_cast(Opcode::FileSetTime): case static_cast(Opcode::FileSetTimeAck): + case static_cast(Opcode::FileLockOp): case static_cast(Opcode::FileTrunc): case static_cast(Opcode::FileTruncAck): case static_cast(Opcode::FileTemp): diff --git a/src/network/wire.h b/src/network/wire.h index b30d115d..491e747f 100644 --- a/src/network/wire.h +++ b/src/network/wire.h @@ -72,6 +72,10 @@ enum class Opcode : std::uint8_t { FileSetTime = 0x36, FileSetTimeAck = 0x37, // FileTrunc: [u32 file_id][u64 size] -> empty ack + // FileLockOp request: [u32 id][u64 start][u64 len][u16 type][u8 op] + // op=0 lock, 1 unlock, 2 conflict test. Same-opcode reply: [u8 result]. + // Server always makes ONE non-blocking OS attempt. WAIT belongs to client. + FileLockOp = 0x0F, FileTrunc = 0x38, FileTruncAck = 0x39, // FileTemp: [u16 dirLen][dir][u16 prefixLen][prefix] diff --git a/src/openads_ace.def b/src/openads_ace.def index bf174331..72defd14 100644 --- a/src/openads_ace.def +++ b/src/openads_ace.def @@ -130,6 +130,9 @@ EXPORTS AdsSetFileAttr AdsSetFileTime AdsFTrunc + AdsFLockTest + AdsFUnlock + AdsFLock AdsTempFile AdsDirSpace AdsGetFileSize @@ -167,6 +170,9 @@ EXPORTS oads_SetFileAttr oads_SetFileTime oads_FTrunc + oads_FLockTest + oads_FUnlock + oads_FLock oads_TempFile oads_DirSpace oads_GetFileSize diff --git a/src/openads_ace_x86_stdcall.def b/src/openads_ace_x86_stdcall.def index 7a2b8627..93a20edb 100644 --- a/src/openads_ace_x86_stdcall.def +++ b/src/openads_ace_x86_stdcall.def @@ -37,6 +37,9 @@ EXPORTS oads_SetFileAttr oads_SetFileTime oads_FTrunc + oads_FLockTest + oads_FUnlock + oads_FLock oads_TempFile oads_DirSpace oads_GetFileSize diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index f4dd2698..c4587713 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -621,3 +621,11 @@ if(UNIX AND TARGET auth_mutual_probe) "${CMAKE_BINARY_DIR}/tools/serverd/mutual-test-only.hrb") set_tests_properties(auth_mutual_v2 PROPERTIES TIMEOUT 120 RUN_SERIAL TRUE) endif() + +# mtfix85: independent-process FS byte-range lock proof, no RDD dependency. +add_executable(openads_fs_lock85_probe fs_lock85_probe.cpp) +target_link_libraries(openads_fs_lock85_probe PRIVATE openads_core) +target_include_directories(openads_fs_lock85_probe PRIVATE ${PROJECT_SOURCE_DIR}/src) +add_dependencies(openads_unit_tests openads_fs_lock85_probe) +add_test(NAME fs_lock85_process COMMAND openads_fs_lock85_probe) +set_tests_properties(fs_lock85_process PROPERTIES TIMEOUT 20) diff --git a/tests/fs_lock85_probe.cpp b/tests/fs_lock85_probe.cpp new file mode 100644 index 00000000..d30f42de --- /dev/null +++ b/tests/fs_lock85_probe.cpp @@ -0,0 +1,43 @@ +// Independent processes must contend through real OS byte-range locks. +#include "engine/server_fs.h" +#include +#include +#include +#include +#include +using namespace openads::engine; +namespace fs = std::filesystem; +int main(int argc, char** argv) { + if (argc == 5 && std::string(argv[1]) == "child") { + auto f = fs_open(argv[2], 2, false); + if (!f) return 10; + const auto type = std::string(argv[3]) == "shared" ? 0x100 : 0; + auto r = fs_lock_step(*f.value(), 0, 16, static_cast(type), 0); + if (!r) return 11; + const bool want = std::string(argv[4]) == "free"; + return r.value() == want ? 0 : 12; + } + auto dir = fs::temp_directory_path() / ("openads-lock85-" + std::to_string( + std::chrono::steady_clock::now().time_since_epoch().count())); + fs::create_directories(dir); + auto path = dir / "lock.bin"; + auto f = fs_open(path.string(), 2, true); + if (!f) return 1; + auto child = [&](const char* kind, const char* expected) { + std::string cmd = "\"" + fs::absolute(argv[0]).string() + "\" child \"" + + path.string() + "\" " + kind + " " + expected; + return std::system(cmd.c_str()) == 0; + }; + auto locked = fs_lock_step(*f.value(),0,16,0,0); + if (!locked || !locked.value() || !child("exclusive","busy") || + !child("shared","busy")) return 2; + if (!fs_lock_step(*f.value(),0,16,0,1) || !child("exclusive","free")) return 3; + auto shared = fs_lock_step(*f.value(),0,16,0x100,0); + if (!shared || !shared.value() || !child("shared","free") || + !child("exclusive","busy")) return 4; + f.value().reset(); + if (!child("exclusive","free")) return 5; + fs::remove_all(dir); + std::cout << "FS-LOCK85-CROSS-PROCESS-PASS\n"; + return 0; +} diff --git a/tests/unit/abi_oads_file_funcs_test.cpp b/tests/unit/abi_oads_file_funcs_test.cpp index 668cd2f9..5b8023fd 100644 --- a/tests/unit/abi_oads_file_funcs_test.cpp +++ b/tests/unit/abi_oads_file_funcs_test.cpp @@ -33,6 +33,8 @@ #include "network/server.h" #include +#include +#include #include #include #include @@ -637,6 +639,80 @@ TEST_CASE( "oads_* local: Load Save ReadAt WriteAt Flush Eof" ) fs::remove_all( dir, ec ); } +static void lock_round_trip( ADSHANDLE h ) +{ + ADSHANDLE a = 0, b = 0, c = 0; + REQUIRE( oads_FCreate( h, (UNSIGNED8*)"locks.bin", 0, &a ) == 0 ); + REQUIRE( oads_FOpen( h, (UNSIGNED8*)"locks.bin", 2, &b ) == 0 ); + REQUIRE( oads_FOpen( h, (UNSIGNED8*)"locks.bin", 2, &c ) == 0 ); + REQUIRE( oads_FLock( a, 0, 16, 0 ) == 0 ); + CHECK( oads_FLock( b, 0, 16, 0 ) == 5012 ); + CHECK( oads_FLock( b, 0, 16, 0x100 ) == 5012 ); + SIGNED32 result = -1; + REQUIRE( oads_FLockTest( b, 0, 16, 0, &result ) == 0 ); + CHECK( result == 1 ); + // Locking must not block I/O through the owning native handle. + UNSIGNED32 wrote = 0, got = 0; + REQUIRE( oads_FWriteAt( a, 0, "owned", 5, &wrote ) == 0 ); + CHECK( wrote == 5 ); + char buf[8] = {}; + REQUIRE( oads_FReadAt( a, 0, buf, 5, &got ) == 0 ); + CHECK( std::string( buf, got ) == "owned" ); + // A disjoint range can be held concurrently. + REQUIRE( oads_FLock( b, 64, 16, 0 ) == 0 ); + REQUIRE( oads_FUnlock( b, 64, 16 ) == 0 ); + CHECK( oads_FLock( b, 0, 0, 0 ) != 0 ); + CHECK( oads_FLock( b, 0, 16, 1 ) != 0 ); + CHECK( oads_FLock( b, 0x7FFFFFFFFFFFFFFFULL, 1, 0 ) != 0 ); + // WAIT must not hold the global registry, the VM or the connection + // between retries: the other caller can unlock on this connection. + std::atomic started{false}, done{false}; + std::atomic rc{999}; + std::thread waiter([&] { + started.store(true); + rc.store(oads_FLock(b, 0, 16, 0x200)); + done.store(true); + }); + for (int i = 0; i < 100 && !started.load(); ++i) + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + std::this_thread::sleep_for(std::chrono::milliseconds(80)); + CHECK_FALSE( done.load() ); + auto unlock_rc = oads_FUnlock( a, 0, 16 ); + CHECK( unlock_rc == 0 ); + for (int i = 0; i < 300 && !done.load(); ++i) + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + if (!done.load()) oads_FClose(b); // explicit cancellation, no test hang + waiter.join(); + CHECK( done.load() ); + CHECK( rc.load() == 0 ); + REQUIRE( oads_FUnlock( b, 0, 16 ) == 0 ); + REQUIRE( oads_FLock( a, 0, 16, 0x100 ) == 0 ); + REQUIRE( oads_FLock( b, 0, 16, 0x100 ) == 0 ); + CHECK( oads_FLock( c, 0, 16, 0 ) == 5012 ); + REQUIRE( oads_FUnlock( a, 0, 16 ) == 0 ); + REQUIRE( oads_FUnlock( b, 0, 16 ) == 0 ); + REQUIRE( oads_FLock( a, 32, 16, 0 ) == 0 ); + REQUIRE( oads_FClose(a) == 0 ); // close releases its locks + REQUIRE( oads_FLock( b, 32, 16, 0 ) == 0 ); + REQUIRE( oads_FUnlock( b, 32, 16 ) == 0 ); + REQUIRE( oads_FLockTest( c, 0, 16, 0, &result ) == 0 ); + CHECK( result == 0 ); + REQUIRE( oads_FClose(b) == 0 ); + REQUIRE( oads_FClose(c) == 0 ); + CHECK( oads_FLock( b, 0, 16, 0 ) != 0 ); +} + +TEST_CASE( "oads_* local: FS byte locks shared exclusive wait and owner IO" ) +{ + auto dir = fs::temp_directory_path() / "oads_file_g4"; + fs::remove_all(dir); + fs::create_directories(dir); + auto h = local_connect(dir); + lock_round_trip(h); + REQUIRE( AdsDisconnect(h) == 0 ); + fs::remove_all(dir); +} + static void metadata_round_trip( ADSHANDLE h, const fs::path& dir ) { REQUIRE( oads_SaveFile( h, (UNSIGNED8*)"m.txt", "0123456789", 10 ) == 0 ); @@ -885,6 +961,7 @@ TEST_CASE( "oads_* remote embedded: full round-trip" ) ADSHANDLE h = remote_connect_embedded( data, srv.port() ); oads_round_trip( h, "remote-embedded" ); metadata_round_trip( h, data ); + lock_round_trip( h ); // verify file lands in server data dir, not client cwd CHECK_FALSE( fs::exists( app / "oads_test.txt" ) ); From 3fffe6010e0a16723986c182452f57efd30b9531 Mon Sep 17 00:00:00 2001 From: Pritpal Bedi Date: Sun, 15 Nov 2026 11:00:07 -0600 Subject: [PATCH 2/7] Align FS ranges and PID queries with Harbour; correct HB_DISK constants --- contrib/oads_hb/FILE_LOCKS_MTFIX85.txt | 91 ++++---- contrib/oads_hb/oads_hb.c | 10 +- include/openads/ace.h | 2 +- src/abi/ace_exports.cpp | 4 +- src/engine/server_fs.cpp | 268 ++++++++++++++++++------ src/engine/server_fs.h | 35 ++-- src/network/client.cpp | 6 +- src/network/client.h | 2 +- src/network/session.cpp | 2 +- src/network/wire.h | 4 +- tests/fs_lock85_probe.cpp | 11 + tests/unit/abi_oads_file_funcs_test.cpp | 104 ++++++--- 12 files changed, 367 insertions(+), 172 deletions(-) diff --git a/contrib/oads_hb/FILE_LOCKS_MTFIX85.txt b/contrib/oads_hb/FILE_LOCKS_MTFIX85.txt index 8f1cd645..4e2405b4 100644 --- a/contrib/oads_hb/FILE_LOCKS_MTFIX85.txt +++ b/contrib/oads_hb/FILE_LOCKS_MTFIX85.txt @@ -1,53 +1,66 @@ OpenADS FS byte locks - mtfix85 Pritpal Bedi -2026-11-15 10:48 +2026-11-15 10:59 OAds_FLock( hFile, nStart, nLen, nType ) -> lOk OAds_FUnlock( hFile, nStart, nLen ) -> lOk OAds_FLockTest( hFile, nStart, nLen, nType ) -> nResult hFile comes from OAds_FOpen or OAds_FCreate. These are file-system -byte-range locks, not RDD record locks. They use the server host's OS -locks and work across processes. I/O and locks use the same native file -handle, including on Windows. Close/disconnect releases held locks. -EnableFileFunc must be enabled on the server. Jail rules remain in force. +byte-range locks, not RDD record locks. No RDD/CDX lock code is changed. +They use the host OS byte locks, visible across processes. Windows I/O +and locks use the same native handle. EnableFileFunc and jail rules apply. -nType flags, added with hb_bitOr(): +nType flags, combined with hb_bitOr(): 0x0000 = exclusive, no wait (default) 0x0100 = shared 0x0200 = wait until success 0x0300 = shared, wait until success -NO_WAIT makes one attempt and returns .F. on contention. -WAIT repeats until success or a real error, closed handle, or connection -failure. Each server request makes one non-blocking OS attempt: there -is no server-side sleep or lock wait. The client retries every 10 ms, -releasing the file/connection/registry mutexes between attempts. The -Harbour wrapper releases the VM during the call. Another thread or -connection can unlock while the caller waits. A caller asking for WAIT -can wait indefinitely if the owner never releases. There is no hidden -30-second overall timeout and no change to the RDD's lock settings. - -FLockTest is a momentary check, not a reservation: - 0 = no conflicting lock for the requested shared/exclusive mode - 1 = conflict (also returned for an overlapping lock owned by this handle) - -1 = error - -First-scope differences from Harbour: -- Unlock requires the exact start and length that were acquired. - Partial unlock and an unlock spanning multiple acquired ranges fail. -- nLen must be positive. Zero-length/to-EOF locks are not implemented. -- Ranges must fit below the signed 64-bit file-offset limit. -- Overlapping locks on one handle must be unlocked before changing mode. - Taking the identical same-mode range again succeeds without a new lock. -- LockTest reports 1, not the POSIX process ID of the lock owner. -- Exclusive locking on a read-only file handle fails. Harbour's Unix - implementation can turn a read-only handle's request into shared mode. -- At most 1024 acquired ranges per file handle. -- These do not implement Harbour virtual-file drivers or socket handles. - -Windows enforces byte locks on I/O. POSIX byte locks are advisory, so -other programs must cooperate. This is OS behavior, not RDD policy. - -Test with the MinGW x86 kit's librddads.a and matching DLL. Use the -matching 64-bit server. Keep the earlier kit for rollback. +NO_WAIT makes one attempt. WAIT repeats after OS contention until success +or error. Each server request makes one non-blocking OS attempt, never +sleeps, and returns. The client retries every 10 ms without holding the +file/connection/registry mutexes between requests. The Harbour wrapper +releases the VM. Connection failure or a closed handle ends the call. +A caller can wait indefinitely if an external owner never releases. + +Harbour filebuf.c behavior preserved: +- Opens of the same physical file share a merged process-local range + registry and native file. Each public handle keeps its own position. +- An overlapping lock already in that registry fails immediately, + including with WAIT. An identical re-lock is not recursive/idempotent. +- Adjacent registrations merge. Unlock removes/splits a contained range + after the native OS unlock succeeds. +- LockTest reports an overlapping own registration as locked. Otherwise + Unix F_GETLK returns the external owner PID; Windows returns 1 for + conflict. Both return 0 for free, -1 for error. It never waits. +- Closing one reference does not release shared native-file locks while + another reference remains. Last close releases the OS locks. +- Unix read-only opens request shared OS locks, as Harbour does. + +OS behavior is preserved, including: +- Unix partial unlock and zero-length-to-EOF ranges work through fcntl. +- Windows UnlockFileEx requires the exact native acquired range. A + partial unlock or one spanning distinct acquisitions can fail, just as + Harbour's Windows backend does. Zero length has Windows native meaning, + not the Unix to-EOF meaning. +- Windows locks affect I/O. Unix locks are advisory. Other programs must + cooperate. POSIX process locks can be dropped if unrelated code in the + same host process closes another descriptor for the same physical file; + the OAds FS functions reuse the native file to avoid doing that. + +Nonnegative file offsets and ranges must fit the signed 64-bit offset +space used by the cross-platform API. No virtual-file/socket drivers are +implemented by these OAds handles. Error reporting is through OAds return +values, not Harbour FError(). + +DirSpace correction in mtfix85 (supersedes mtfix84 custom values): + HB_DISK_AVAIL = 0, HB_DISK_FREE = 1, HB_DISK_USED = 2, + HB_DISK_TOTAL = 3, matching Harbour include/fileio.ch. +Do not carry mtfix84's 1=capacity or 2=free meanings into this kit. + +Reference source: +https://github.com/harbour/core/blob/master/src/rtl/vfile.c +https://github.com/harbour/core/blob/master/src/rtl/filebuf.c +https://github.com/harbour/core/blob/master/src/rtl/filesys.c +https://github.com/harbour/core/blob/master/include/fileio.ch diff --git a/contrib/oads_hb/oads_hb.c b/contrib/oads_hb/oads_hb.c index 55975615..8311e9a8 100644 --- a/contrib/oads_hb/oads_hb.c +++ b/contrib/oads_hb/oads_hb.c @@ -710,7 +710,7 @@ HB_FUNC( OADS_SETFILETIME ) /* ------------------------------------------------------------------ */ /* FS byte locks only, independent of RDD record locks. * nType: 0 exclusive/no-wait, 0x100 shared, 0x200 wait until success. - * Unlock requires the exact range. LockTest: 0 free, 1 conflict, -1 error. + * LockTest: 0 free, POSIX PID (Windows 1) locked, -1 error. * WAIT releases the Harbour VM so another Harbour thread can unlock. */ HB_FUNC( OADS_FLOCK ) @@ -719,7 +719,7 @@ HB_FUNC( OADS_FLOCK ) HB_MAXINT start = hb_parnint( 2 ), len = hb_parnint( 3 ); UNSIGNED16 type = ( UNSIGNED16 ) hb_parni( 4 ); UNSIGNED32 rc = 5000; - if( h && start >= 0 && len > 0 ) + if( h && start >= 0 && len >= 0 ) { hb_vmUnlock(); rc = oads_FLock( h, ( UNSIGNED64 ) start, ( UNSIGNED64 ) len, type ); @@ -731,7 +731,7 @@ HB_FUNC( OADS_FUNLOCK ) { ADSHANDLE h = ( ADSHANDLE ) hb_parnint( 1 ); HB_MAXINT start = hb_parnint( 2 ), len = hb_parnint( 3 ); - hb_retl( h && start >= 0 && len > 0 && + hb_retl( h && start >= 0 && len >= 0 && oads_FUnlock( h, ( UNSIGNED64 ) start, ( UNSIGNED64 ) len ) == 0 ); } HB_FUNC( OADS_FLOCKTEST ) @@ -739,7 +739,7 @@ HB_FUNC( OADS_FLOCKTEST ) ADSHANDLE h = ( ADSHANDLE ) hb_parnint( 1 ); HB_MAXINT start = hb_parnint( 2 ), len = hb_parnint( 3 ); SIGNED32 result = -1; - if( h && start >= 0 && len > 0 ) + if( h && start >= 0 && len >= 0 ) oads_FLockTest( h, ( UNSIGNED64 ) start, ( UNSIGNED64 ) len, ( UNSIGNED16 ) hb_parni( 4 ), &result ); hb_retni( result ); @@ -794,7 +794,7 @@ HB_FUNC( OADS_TEMPFILE ) /* ------------------------------------------------------------------ */ /* OADS_DirSpace( hConn, cDir, nType ) -> nBytes */ /* OADS_DirSpace( cDir, nType ) -> nBytes (default conn) */ -/* nType: 0 = free available, 1 = total capacity, 2 = free. */ +/* nType: 0 = available, 1 = free, 2 = used, 3 = total. */ /* ------------------------------------------------------------------ */ HB_FUNC( OADS_DIRSPACE ) { diff --git a/include/openads/ace.h b/include/openads/ace.h index 9717957f..aaf97350 100644 --- a/include/openads/ace.h +++ b/include/openads/ace.h @@ -137,7 +137,7 @@ UNSIGNED32 ENTRYPOINT AdsFTrunc (ADSHANDLE hFile, UNSIGNED32 ENTRYPOINT AdsTempFile (ADSHANDLE hConnect, UNSIGNED8* pucDir, UNSIGNED8* pucPrefix, UNSIGNED8* pucName, UNSIGNED16* pusNameLen); -// ucType: 0 = free available, 1 = total capacity, 2 = free. +// ucType: 0 = available, 1 = free, 2 = used, 3 = total. UNSIGNED32 ENTRYPOINT AdsDirSpace (ADSHANDLE hConnect, UNSIGNED8* pucDir, UNSIGNED8 ucType, UNSIGNED64* pullBytes); UNSIGNED32 ENTRYPOINT AdsGetFileSize (ADSHANDLE hConnect, UNSIGNED8* pucName, diff --git a/src/abi/ace_exports.cpp b/src/abi/ace_exports.cpp index 2c267e5a..2ed8562f 100644 --- a/src/abi/ace_exports.cpp +++ b/src/abi/ace_exports.cpp @@ -11563,7 +11563,7 @@ UNSIGNED32 ENTRYPOINT AdsSetFileTime(ADSHANDLE hConn, UNSIGNED8* pucName, // Each invocation makes one non-blocking attempt. Never sleep while holding // the ABI registry mutex or the per-file/connection mutex. extern "C++" { -static openads::util::Result oads_fs_lock_once(ADSHANDLE hFile, +static openads::util::Result oads_fs_lock_once(ADSHANDLE hFile, UNSIGNED64 start, UNSIGNED64 len, UNSIGNED16 type, std::uint8_t op) { auto& s = state(); std::unique_lock lk(s.mu); @@ -11606,7 +11606,7 @@ UNSIGNED32 ENTRYPOINT AdsFLockTest(ADSHANDLE hFile, UNSIGNED64 ullStart, *plResult = -1; auto v = oads_fs_lock_once(hFile, ullStart, ullLen, usType, 2); if (!v) return fail(v.error()); - *plResult = v.value() ? 1 : 0; + *plResult = v.value(); return ok(); } diff --git a/src/engine/server_fs.cpp b/src/engine/server_fs.cpp index a9e6f6ea..634ab4db 100644 --- a/src/engine/server_fs.cpp +++ b/src/engine/server_fs.cpp @@ -10,11 +10,18 @@ #include #include #include +#include +#include +#include +#include #if defined(_WIN32) #include +#define WIN32_LEAN_AND_MEAN +#include #include #else #include +#include #endif namespace fs = std::filesystem; @@ -162,21 +169,21 @@ util::Result fs_copy(const std::string& abs_src, if (!ec && same) return io_err(static_cast(openads::AE_INTERNAL_ERROR), "source and target are the same file", abs_src); - // Plain stream copy: MinGW's fs::copy_file is unreliable when the - // target already exists, and truncate-on-open is the wanted overwrite. - std::ifstream in(abs_src, std::ios::binary); - if (!in) - return io_err(static_cast(openads::AE_INTERNAL_ERROR), - "open source failed", abs_src); - std::ofstream out(abs_dst, std::ios::binary | std::ios::trunc); - if (!out) - return io_err(static_cast(openads::AE_INTERNAL_ERROR), - "open target failed", abs_dst); - out << in.rdbuf(); - out.flush(); - if (!out || in.bad()) - return io_err(static_cast(openads::AE_INTERNAL_ERROR), - "copy failed", abs_src); + auto src = fs_open(abs_src, ADS_FO_READ, false); + if (!src) return src.error(); + auto dst = fs_open(abs_dst, ADS_FO_READWRITE, true); + if (!dst) return dst.error(); + std::vector chunk(65536); + for (;;) { + src.value()->stream.read(chunk.data(), static_cast(chunk.size())); + if (!src.value()->stream) return io_err(5000, "copy read failed", abs_src); + auto n = src.value()->stream.gcount(); + if (n == 0) break; + dst.value()->stream.write(chunk.data(), n); + if (!dst.value()->stream) return io_err(5000, "copy write failed", abs_dst); + } + dst.value()->stream.flush(); + if (!dst.value()->stream) return io_err(5000, "copy flush failed", abs_dst); return {}; } @@ -192,15 +199,14 @@ util::Result> fs_load(const std::string& abs_path) { if (sz > kMaxFsWholeFile) return io_err(static_cast(openads::AE_INTERNAL_ERROR), "file too large for one call", abs_path); - std::ifstream in(abs_path, std::ios::binary); - if (!in) - return io_err(static_cast(openads::AE_NO_FILE_FOUND), - "open failed", abs_path); + auto handle = fs_open(abs_path, ADS_FO_READ, false); + if (!handle) return handle.error(); + auto& in = handle.value()->stream; std::vector out(static_cast(sz)); if (sz) in.read(reinterpret_cast(out.data()), static_cast(sz)); - if (in.bad() || static_cast(in.gcount()) != sz) + if (!in || static_cast(in.gcount()) != sz) return io_err(static_cast(openads::AE_INTERNAL_ERROR), "read failed", abs_path); return out; @@ -211,10 +217,9 @@ util::Result fs_save(const std::string& abs_path, if (size > kMaxFsWholeFile) return io_err(static_cast(openads::AE_INTERNAL_ERROR), "too large for one call", abs_path); - std::ofstream out(abs_path, std::ios::binary | std::ios::trunc); - if (!out) - return io_err(static_cast(openads::AE_ACCESS_DENIED), - "open failed", abs_path); + auto handle = fs_open(abs_path, ADS_FO_READWRITE, true); + if (!handle) return handle.error(); + auto& out = handle.value()->stream; if (size) out.write(reinterpret_cast(data), static_cast(size)); @@ -301,7 +306,9 @@ util::Result fs_truncate(FsFile& file, std::uint64_t size) { if (!file.stream) return io_err(static_cast(openads::AE_INTERNAL_ERROR), "flush failed", file.path); - auto r = file.stream.file.truncate(size); + auto native = file.stream.native; + std::lock_guard guard(native->mu); + auto r = native->file.truncate(size); if (!r) return r; file.stream.clear(); if (pos >= 0) { @@ -352,8 +359,10 @@ util::Result fs_dir_space(const std::string& abs_dir, if (ec) return io_err(static_cast(openads::AE_NO_FILE_FOUND), "space query failed", abs_dir); - if (type == 1) return static_cast(sp.capacity); - if (type == 2) return static_cast(sp.free); + // Harbour fileio.ch HB_DISK_* values, not a private numbering. + if (type == 1) return static_cast(sp.free); + if (type == 2) return static_cast(sp.capacity - sp.free); + if (type == 3) return static_cast(sp.capacity); return static_cast(sp.available); } @@ -465,26 +474,30 @@ util::Result fs_dir_remove(const std::string& abs_path) { void FsStream::read(char* data, std::streamsize n) { count_ = 0; if (!good_ || n < 0) { good_ = false; return; } - auto v = file.read_at(static_cast(pos_), data, static_cast(n)); + std::lock_guard guard(native->mu); + auto v = native->file.read_at(static_cast(pos_), data, static_cast(n)); if (!v) { good_ = false; return; } count_ = static_cast(v.value()); pos_ += static_cast(v.value()); } void FsStream::write(const char* data, std::streamsize n) { - if (!good_ || n < 0) { good_ = false; return; } - auto v = file.write_at(static_cast(pos_), data, static_cast(n)); + if (!good_ || !writable || n < 0) { good_ = false; return; } + std::lock_guard guard(native->mu); + auto v = native->file.write_at(static_cast(pos_), data, static_cast(n)); if (!v) { good_ = false; return; } pos_ += static_cast(v.value()); good_ = v.value() == static_cast(n); } void FsStream::flush() { - if (good_ && writable) good_ = file.sync().has_value(); + // Native positional I/O is unbuffered at this layer. Flush is not + // Commit: like hb_vfFlush, it does not promise a durable disk sync. } void FsStream::seekg(std::streamoff off, std::ios::seekdir way) { std::streamoff base = 0; if (way == std::ios::cur) base = pos_; else if (way == std::ios::end) { - auto n = file.size(); + std::lock_guard guard(native->mu); + auto n = native->file.size(); if (!n || n.value() > 0x7FFFFFFFFFFFFFFFULL) { good_ = false; return; } base = static_cast(n.value()); } @@ -493,43 +506,132 @@ void FsStream::seekg(std::streamoff off, std::ios::seekdir way) { pos_ = base + off; } -util::Result fs_lock_step(FsFile& f, std::uint64_t start, +namespace { +std::mutex fs_files_mu; +std::unordered_map> fs_files; +std::string fs_identity(const std::string& path) { +#if defined(_WIN32) + HANDLE h = ::CreateFileA(path.c_str(), FILE_READ_ATTRIBUTES, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, + OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + if (h == INVALID_HANDLE_VALUE) return {}; + BY_HANDLE_FILE_INFORMATION i{}; + bool ok = ::GetFileInformationByHandle(h, &i) != 0; + ::CloseHandle(h); + if (!ok) return {}; + return std::to_string(i.dwVolumeSerialNumber) + ":" + + std::to_string(i.nFileIndexHigh) + ":" + std::to_string(i.nFileIndexLow); +#else + struct stat st{}; + if (::stat(path.c_str(), &st) != 0) return {}; + return std::to_string(st.st_dev) + ":" + std::to_string(st.st_ino); +#endif +} +std::int32_t own_lock_pid() { +#if defined(_WIN32) + return 1; +#else + return static_cast(::getpid()); +#endif +} +util::Error native_lock_error(const char* msg, const std::string& path) { +#if defined(_WIN32) + auto code = static_cast(::GetLastError()); +#else + auto code = errno; +#endif + return util::Error{5013, code, msg, path}; +} +} + +util::Result fs_lock_step(FsFile& f, std::uint64_t start, std::uint64_t len, std::uint16_t type, std::uint8_t op) { - if (op > 2 || (type & ~0x0300u) != 0 || len == 0 || - start > 0x7FFFFFFFFFFFFFFFULL || len > 0x7FFFFFFFFFFFFFFFULL - start) + if (op > 2 || (type & ~0x0300u) != 0 || start > 0x7FFFFFFFFFFFFFFFULL || + len > 0x7FFFFFFFFFFFFFFFULL - start) return io_err(5000, "invalid lock range or flags", f.path); + auto state = f.stream.native; + std::lock_guard guard(state->mu); + const auto end = len == 0 ? 0x8000000000000000ULL : start + len; + auto overlap = [&](const FsRange& h) { + const auto he = h.len == 0 ? 0x8000000000000000ULL : h.start + h.len; + return start < he && h.start < end; + }; + auto& ranges = state->ranges; + // Like Harbour filebuf.c: test the merged process-local registrations + // first. Re-locking an owned overlap is an error, even with WAIT. + if (op != 1 && std::any_of(ranges.begin(), ranges.end(), overlap)) { + if (op == 2) return own_lock_pid(); + return io_err(5012, "range already locked by this process", f.path); + } + auto containing = ranges.end(); + if (op == 1) { + containing = std::find_if(ranges.begin(), ranges.end(), [&](const FsRange& h) { + auto he = h.len == 0 ? 0x8000000000000000ULL : h.start + h.len; + return start >= h.start && end <= he; + }); + if (containing == ranges.end()) return io_err(5012, "unlock range not held", f.path); + } bool shared = (type & 0x0100u) != 0; +#if !defined(_WIN32) + // Harbour's Unix backend forces read-only opens to shared locks. + if (!f.writable) shared = true; +#endif +#if defined(_WIN32) + OVERLAPPED ov{}; + ov.Offset = static_cast(start); + ov.OffsetHigh = static_cast(start >> 32); + auto h = reinterpret_cast(state->file.native_handle()); + auto lo = static_cast(len), hi = static_cast(len >> 32); if (op == 1) { - for (auto it = f.locks.begin(); it != f.locks.end(); ++it) { - if (it->start == start && it->len == len) { - auto v = it->lock.release(); - if (!v) return v.error(); - f.locks.erase(it); - return true; - } + if (!::UnlockFileEx(h, 0, lo, hi, &ov)) return native_lock_error("UnlockFileEx", f.path); + } else { + DWORD flags = LOCKFILE_FAIL_IMMEDIATELY | (shared ? 0 : LOCKFILE_EXCLUSIVE_LOCK); + if (!::LockFileEx(h, flags, 0, lo, hi, &ov)) { + if (::GetLastError() == ERROR_LOCK_VIOLATION) return op == 2 ? 1 : 0; + return native_lock_error("LockFileEx", f.path); } - return io_err(5000, "unlock range not held", f.path); - } - for (const auto& h : f.locks) { - if (start < h.start + h.len && h.start < start + len) { - if (op == 2) return true; // Harbour LockTest reports own registrations too - if (start == h.start && len == h.len && shared == h.shared) return true; - return io_err(5000, "overlapping own lock; unlock it first", f.path); + if (op == 2) { + if (!::UnlockFileEx(h, 0, lo, hi, &ov)) return native_lock_error("UnlockFileEx test", f.path); + return 0; } } - if (!shared && !f.writable) - return io_err(7079, "exclusive lock needs writable handle", f.path); - if (f.locks.size() >= 1024) return io_err(5000, "file lock limit", f.path); - auto v = platform::ByteLock::try_acquire(f.stream.file, start, len, - shared ? platform::LockKind::Shared : platform::LockKind::Exclusive); - if (!v) { - if (v.error().code == 5012) return op == 2; - return v.error(); +#else + int fd = static_cast(reinterpret_cast(state->file.native_handle()) - 1); + struct flock fl{}; + fl.l_whence = SEEK_SET; + fl.l_start = static_cast(start); + fl.l_len = static_cast(len); + fl.l_type = op == 1 ? F_UNLCK : shared ? F_RDLCK : F_WRLCK; + if (op == 2) { + if (::fcntl(fd, F_GETLK, &fl) != 0) return native_lock_error("F_GETLK", f.path); + return fl.l_type == F_UNLCK ? 0 : static_cast(fl.l_pid); } - if (op == 2) return false; // temporary lock releases on destruction - f.locks.push_back({start, len, shared, std::move(v.value())}); - return true; + if (::fcntl(fd, F_SETLK, &fl) != 0) { + if (op == 0 && (errno == EAGAIN || errno == EACCES)) return 0; + return native_lock_error("F_SETLK", f.path); + } +#endif + if (op == 1) { + const auto hs = containing->start; + const auto he = containing->len == 0 ? 0x8000000000000000ULL : hs + containing->len; + auto idx = static_cast(containing - ranges.begin()); + ranges.erase(containing); + if (hs < start) ranges.insert(ranges.begin() + static_cast(idx++), {hs, start-hs}); + if (end < he) ranges.insert(ranges.begin() + static_cast(idx), + {end, he == 0x8000000000000000ULL ? 0 : he-end}); + } else { + ranges.push_back({start,len}); + std::sort(ranges.begin(), ranges.end(), [](const FsRange& a, const FsRange& b) { return a.start < b.start; }); + for (std::size_t i = 1; i < ranges.size();) { + auto& prev = ranges[i-1]; + if (prev.len != 0 && prev.start + prev.len == ranges[i].start) { + prev.len = ranges[i].len == 0 ? 0 : prev.len + ranges[i].len; + ranges.erase(ranges.begin() + static_cast(i)); + } else ++i; + } + } + return 1; } util::Result> fs_open(const std::string& abs_path, @@ -537,15 +639,47 @@ util::Result> fs_open(const std::string& abs_path, auto f = std::make_unique(); f->path = abs_path; f->writable = create || (mode != ADS_FO_READ && mode != 3); - auto native = platform::File::open(abs_path, create ? platform::OpenMode::CreateRW : + std::lock_guard global(fs_files_mu); + auto key = fs_identity(abs_path); + std::shared_ptr state; + if (!key.empty()) state = fs_files[key].lock(); + if (state) { + std::lock_guard guard(state->mu); + if (f->writable && !state->writable) { + // Win32 lock ownership is per native handle. Never switch away + // from a handle that still holds byte ranges. +#if defined(_WIN32) + if (!state->ranges.empty()) return io_err(5012, "locked read-only file cannot upgrade", abs_path); +#endif + auto upgraded = platform::File::open(abs_path, platform::OpenMode::ReadWrite); + if (!upgraded) return upgraded.error(); + state->retained.push_back(std::move(state->file)); + state->file = std::move(upgraded.value()); + state->writable = true; + } + if (create) { + auto v = state->file.truncate(0); + if (!v) return v.error(); + } + } else { + auto native = platform::File::open(abs_path, create ? platform::OpenMode::CreateRW : f->writable ? platform::OpenMode::ReadWrite : platform::OpenMode::ReadOnly); - if (!native && create) { - std::error_code ec; - fs::create_directories(fs::path(abs_path).parent_path(), ec); - native = platform::File::open(abs_path, platform::OpenMode::CreateRW); + if (!native && create) { + std::error_code ec; + fs::create_directories(fs::path(abs_path).parent_path(), ec); + native = platform::File::open(abs_path, platform::OpenMode::CreateRW); + } + if (!native) return native.error(); + state = std::make_shared(); + state->file = std::move(native.value()); + state->writable = f->writable; + key = fs_identity(abs_path); + if (!key.empty()) fs_files[key] = state; + // Remove expired weak entries so file churn does not retain names. + for (auto it = fs_files.begin(); it != fs_files.end();) + if (it->second.expired()) it = fs_files.erase(it); else ++it; } - if (!native) return native.error(); - f->stream.file = std::move(native.value()); + f->stream.native = std::move(state); f->stream.writable = f->writable; return f; } diff --git a/src/engine/server_fs.h b/src/engine/server_fs.h index 3796a808..7ea3e89a 100644 --- a/src/engine/server_fs.h +++ b/src/engine/server_fs.h @@ -2,7 +2,7 @@ #include "util/result.h" #include "platform/file.h" -#include "platform/lock.h" +#include #include #include @@ -59,7 +59,7 @@ util::Result fs_truncate(const std::string& abs_path, // with prefix; returns the file name (not the full path). util::Result fs_tempfile(const std::string& abs_dir, const std::string& prefix); -// type 0 = free available, 1 = total capacity, 2 = free. +// type 0 = available, 1 = free, 2 = used, 3 = total. util::Result fs_dir_space(const std::string& abs_dir, std::uint8_t type); util::Result fs_size(const std::string& abs_path); @@ -72,15 +72,23 @@ util::Result fs_dir_exist(const std::string& abs_path); util::Result fs_dir_make(const std::string& abs_path); util::Result fs_dir_remove(const std::string& abs_path); -// Low-level file-function stream facade. I/O and locks use the SAME native -// handle, which Windows requires for the owner to read/write locked bytes. -// This is independent of the RDD/CDX engine's file and lock state. +// FS-only native state and merged byte ranges, separate from RDD locks. +struct FsRange { std::uint64_t start, len; }; +struct FsNative { + platform::File file; + // POSIX closing ANY fd drops process locks, so retain an old read-only + // descriptor across an upgrade until the last file reference closes. + std::vector retained; + std::mutex mu; + std::vector ranges; + bool writable = false; +}; class FsStream { public: - platform::File file; + std::shared_ptr native; bool writable = false; void clear() { good_ = true; } - explicit operator bool() const { return good_ && file.is_open(); } + explicit operator bool() const { return good_ && native && native->file.is_open(); } void read(char* data, std::streamsize n); void write(const char* data, std::streamsize n); void flush(); @@ -94,21 +102,14 @@ class FsStream { std::streamsize count_ = 0; bool good_ = true; }; -struct FsHeldLock { - std::uint64_t start, len; - bool shared; - platform::ByteLock lock; -}; struct FsFile { FsStream stream; std::string path; bool writable = false; - // Destroy locks before the native handle (reverse member order). - std::vector locks; }; -// One non-blocking OS attempt. op: 0 lock, 1 exact-range unlock, 2 test. -// Lock returns false for contention. Test returns true for a conflict. -util::Result fs_lock_step(FsFile& file, std::uint64_t start, +// One non-blocking native attempt. op 0 lock, 1 unlock, 2 query. +// Lock result 0 busy, 1 success. Query 0 free, positive owner, -1 error. +util::Result fs_lock_step(FsFile& file, std::uint64_t start, std::uint64_t len, std::uint16_t type, std::uint8_t op); util::Result fs_truncate(FsFile& file, std::uint64_t size); diff --git a/src/network/client.cpp b/src/network/client.cpp index a21be7b4..59024a3c 100644 --- a/src/network/client.cpp +++ b/src/network/client.cpp @@ -3117,7 +3117,7 @@ RemoteConnection::file_set_time(const std::string& path, std::uint16_t year, return {}; } -util::Result +util::Result RemoteConnection::file_lock_step(std::uint32_t id, std::uint64_t start, std::uint64_t len, std::uint16_t type, std::uint8_t op) { Frame req; @@ -3129,9 +3129,9 @@ RemoteConnection::file_lock_step(std::uint32_t id, std::uint64_t start, req.payload.push_back(op); auto rep = request(req); if (!rep) return rep.error(); - if (rep.value().opcode != Opcode::FileLockOp || rep.value().payload.size() != 1) + if (rep.value().opcode != Opcode::FileLockOp || rep.value().payload.size() != 4) return fs_wire_err(rep.value(), "FileLockOp"); - return rep.value().payload[0] != 0; + return static_cast(read_u32_le(rep.value().payload.data())); } util::Result diff --git a/src/network/client.h b/src/network/client.h index 07c7fede..982b9597 100644 --- a/src/network/client.h +++ b/src/network/client.h @@ -450,7 +450,7 @@ class RemoteConnection { std::uint8_t hh, std::uint8_t mm, std::uint8_t ss); - util::Result file_lock_step(std::uint32_t file_id, std::uint64_t start, + util::Result file_lock_step(std::uint32_t file_id, std::uint64_t start, std::uint64_t len, std::uint16_t type, std::uint8_t op); util::Result ftruncate(std::uint32_t file_id, std::uint64_t size); diff --git a/src/network/session.cpp b/src/network/session.cpp index a4b47f4f..363ed28b 100644 --- a/src/network/session.cpp +++ b/src/network/session.cpp @@ -4806,7 +4806,7 @@ DispatchResult Session::dispatch(const Frame& f) { auto v = openads::engine::fs_lock_step(*it->second, start, len, type, f.payload[22]); if (!v) { reply = err("FileLockOp", static_cast(v.error().code)); break; } reply.opcode = Opcode::FileLockOp; - reply.payload.push_back(v.value() ? 1 : 0); + write_u32_le(static_cast(v.value()), reply.payload); } else if (f.opcode == Opcode::FileTrunc) { if (f.payload.size() < 12) { reply = err("FileTrunc: short payload"); break; diff --git a/src/network/wire.h b/src/network/wire.h index 491e747f..355e4e83 100644 --- a/src/network/wire.h +++ b/src/network/wire.h @@ -73,7 +73,7 @@ enum class Opcode : std::uint8_t { FileSetTimeAck = 0x37, // FileTrunc: [u32 file_id][u64 size] -> empty ack // FileLockOp request: [u32 id][u64 start][u64 len][u16 type][u8 op] - // op=0 lock, 1 unlock, 2 conflict test. Same-opcode reply: [u8 result]. + // op=0 lock, 1 unlock, 2 conflict test. Same-opcode reply: [i32 result/PID]. // Server always makes ONE non-blocking OS attempt. WAIT belongs to client. FileLockOp = 0x0F, FileTrunc = 0x38, @@ -83,7 +83,7 @@ enum class Opcode : std::uint8_t { FileTemp = 0x3A, FileTempAck = 0x3B, // DirSpace: [u16 dirLen][dir][u8 type] -> [u64 bytes] - // type 0 = free available, 1 = total capacity, 2 = free + // type 0 = available, 1 = free, 2 = used, 3 = total DirSpace = 0x3C, DirSpaceAck = 0x1F, // 0x3D+ is taken; last free slot below 0x20 ExecuteSQL = 0x30, diff --git a/tests/fs_lock85_probe.cpp b/tests/fs_lock85_probe.cpp index d30f42de..672ff89e 100644 --- a/tests/fs_lock85_probe.cpp +++ b/tests/fs_lock85_probe.cpp @@ -2,12 +2,23 @@ #include "engine/server_fs.h" #include #include +#include +#include #include #include #include using namespace openads::engine; namespace fs = std::filesystem; int main(int argc, char** argv) { + if (argc == 4 && std::string(argv[1]) == "hold") { + auto f = fs_open(argv[2], 2, false); + if (!f) return 20; + auto v = fs_lock_step(*f.value(), 128, 16, 0, 0); + if (!v || !v.value()) return 21; + std::ofstream marker(argv[3]); marker << "ready"; marker.close(); + std::this_thread::sleep_for(std::chrono::milliseconds(2000)); + return 0; + } if (argc == 5 && std::string(argv[1]) == "child") { auto f = fs_open(argv[2], 2, false); if (!f) return 10; diff --git a/tests/unit/abi_oads_file_funcs_test.cpp b/tests/unit/abi_oads_file_funcs_test.cpp index 5b8023fd..e83ab794 100644 --- a/tests/unit/abi_oads_file_funcs_test.cpp +++ b/tests/unit/abi_oads_file_funcs_test.cpp @@ -31,6 +31,7 @@ #include "openads/ace.h" #include "openads/error.h" #include "network/server.h" +#include "platform/path.h" #include #include @@ -639,7 +640,7 @@ TEST_CASE( "oads_* local: Load Save ReadAt WriteAt Flush Eof" ) fs::remove_all( dir, ec ); } -static void lock_round_trip( ADSHANDLE h ) +static void lock_round_trip( ADSHANDLE h, const fs::path& dir ) { ADSHANDLE a = 0, b = 0, c = 0; REQUIRE( oads_FCreate( h, (UNSIGNED8*)"locks.bin", 0, &a ) == 0 ); @@ -650,7 +651,7 @@ static void lock_round_trip( ADSHANDLE h ) CHECK( oads_FLock( b, 0, 16, 0x100 ) == 5012 ); SIGNED32 result = -1; REQUIRE( oads_FLockTest( b, 0, 16, 0, &result ) == 0 ); - CHECK( result == 1 ); + CHECK( result > 0 ); // Locking must not block I/O through the owning native handle. UNSIGNED32 wrote = 0, got = 0; REQUIRE( oads_FWriteAt( a, 0, "owned", 5, &wrote ) == 0 ); @@ -661,39 +662,68 @@ static void lock_round_trip( ADSHANDLE h ) // A disjoint range can be held concurrently. REQUIRE( oads_FLock( b, 64, 16, 0 ) == 0 ); REQUIRE( oads_FUnlock( b, 64, 16 ) == 0 ); - CHECK( oads_FLock( b, 0, 0, 0 ) != 0 ); + CHECK( oads_FLock( b, 0, 16, 1 ) != 0 ); CHECK( oads_FLock( b, 0x7FFFFFFFFFFFFFFFULL, 1, 0 ) != 0 ); - // WAIT must not hold the global registry, the VM or the connection - // between retries: the other caller can unlock on this connection. - std::atomic started{false}, done{false}; - std::atomic rc{999}; - std::thread waiter([&] { - started.store(true); - rc.store(oads_FLock(b, 0, 16, 0x200)); - done.store(true); - }); - for (int i = 0; i < 100 && !started.load(); ++i) - std::this_thread::sleep_for(std::chrono::milliseconds(1)); - std::this_thread::sleep_for(std::chrono::milliseconds(80)); - CHECK_FALSE( done.load() ); - auto unlock_rc = oads_FUnlock( a, 0, 16 ); - CHECK( unlock_rc == 0 ); - for (int i = 0; i < 300 && !done.load(); ++i) - std::this_thread::sleep_for(std::chrono::milliseconds(10)); - if (!done.load()) oads_FClose(b); // explicit cancellation, no test hang - waiter.join(); - CHECK( done.load() ); - CHECK( rc.load() == 0 ); - REQUIRE( oads_FUnlock( b, 0, 16 ) == 0 ); + // Harbour refuses own/process-local overlapping relocks, even WAIT. + CHECK( oads_FLock( b, 0, 16, 0x200 ) == 5012 ); + REQUIRE( oads_FUnlock( a, 0, 16 ) == 0 ); REQUIRE( oads_FLock( a, 0, 16, 0x100 ) == 0 ); - REQUIRE( oads_FLock( b, 0, 16, 0x100 ) == 0 ); - CHECK( oads_FLock( c, 0, 16, 0 ) == 5012 ); + CHECK( oads_FLock( b, 0, 16, 0x100 ) == 5012 ); REQUIRE( oads_FUnlock( a, 0, 16 ) == 0 ); - REQUIRE( oads_FUnlock( b, 0, 16 ) == 0 ); + // Adjacent locks merge in the registry. Unix can split that merged + // range with partial unlock; Windows preserves native exact unlock. + REQUIRE( oads_FLock( a, 0, 8, 0 ) == 0 ); + REQUIRE( oads_FLock( a, 8, 8, 0 ) == 0 ); +#if defined(_WIN32) + CHECK( oads_FUnlock( a, 4, 4 ) != 0 ); + REQUIRE( oads_FUnlock( a, 0, 8 ) == 0 ); + REQUIRE( oads_FUnlock( a, 8, 8 ) == 0 ); +#else + REQUIRE( oads_FUnlock( a, 4, 4 ) == 0 ); + REQUIRE( oads_FLockTest( b, 4, 4, 0, &result ) == 0 ); + CHECK( result == 0 ); + REQUIRE( oads_FUnlock( a, 0, 4 ) == 0 ); + REQUIRE( oads_FUnlock( a, 8, 8 ) == 0 ); + REQUIRE( oads_FLock( a, 64, 0, 0 ) == 0 ); // to EOF on Unix + REQUIRE( oads_FUnlock( a, 64, 0 ) == 0 ); +#endif + // A real other process holds byte 128 until it exits. WAIT must + // complete after that release, without blocking the server thread. + auto module = openads::platform::module_directory(); + REQUIRE( module.has_value() ); + fs::path probe = fs::path(*module) / "openads_fs_lock85_probe"; +#if defined(_WIN32) + probe += ".exe"; +#endif + REQUIRE( fs::exists(probe) ); + auto marker = dir / "holder-ready"; + fs::remove(marker); + std::string command = "\"" + probe.string() + "\" hold \"" + + (dir / "locks.bin").string() + "\" \"" + marker.string() + "\""; + std::atomic child_rc{-1}; + std::thread holder([&] { child_rc.store(std::system(command.c_str())); }); + bool ready = false; + for (int i = 0; i < 300; ++i) { + if (fs::exists(marker)) { ready = true; break; } + if (child_rc.load() != -1) break; + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } + UNSIGNED32 wait_rc = 999; + if (ready) { + CHECK( oads_FLock( a, 128, 16, 0 ) == 5012 ); + CHECK( oads_FLockTest( a, 128, 16, 0, &result ) == 0 ); + CHECK( result > 0 ); // POSIX PID, Windows 1 + wait_rc = oads_FLock( a, 128, 16, 0x200 ); + if (wait_rc == 0) oads_FUnlock( a, 128, 16 ); + } + holder.join(); + CHECK( ready ); + CHECK( child_rc.load() == 0 ); + CHECK( wait_rc == 0 ); REQUIRE( oads_FLock( a, 32, 16, 0 ) == 0 ); - REQUIRE( oads_FClose(a) == 0 ); // close releases its locks - REQUIRE( oads_FLock( b, 32, 16, 0 ) == 0 ); + REQUIRE( oads_FClose(a) == 0 ); // other references retain merged locks + CHECK( oads_FLock( b, 32, 16, 0 ) == 5012 ); REQUIRE( oads_FUnlock( b, 32, 16 ) == 0 ); REQUIRE( oads_FLockTest( c, 0, 16, 0, &result ) == 0 ); CHECK( result == 0 ); @@ -708,7 +738,7 @@ TEST_CASE( "oads_* local: FS byte locks shared exclusive wait and owner IO" ) fs::remove_all(dir); fs::create_directories(dir); auto h = local_connect(dir); - lock_round_trip(h); + lock_round_trip(h, dir); REQUIRE( AdsDisconnect(h) == 0 ); fs::remove_all(dir); } @@ -782,12 +812,18 @@ static void metadata_round_trip( ADSHANDLE h, const fs::path& dir ) // DirSpace: capacity positive, available/free no more than capacity UNSIGNED64 ullCap = 0, ullAvail = 0, ullFree = 0; - REQUIRE( oads_DirSpace( h, (UNSIGNED8*)"", 1, &ullCap ) == 0 ); + REQUIRE( oads_DirSpace( h, (UNSIGNED8*)"", 3, &ullCap ) == 0 ); REQUIRE( oads_DirSpace( h, (UNSIGNED8*)"", 0, &ullAvail ) == 0 ); - REQUIRE( oads_DirSpace( h, (UNSIGNED8*)"", 2, &ullFree ) == 0 ); + REQUIRE( oads_DirSpace( h, (UNSIGNED8*)"", 1, &ullFree ) == 0 ); CHECK( ullCap > 0 ); CHECK( ullAvail <= ullCap ); CHECK( ullFree <= ullCap ); + UNSIGNED64 ullUsed = 0; + REQUIRE( oads_DirSpace( h, (UNSIGNED8*)"", 2, &ullUsed ) == 0 ); + CHECK( ullUsed <= ullCap ); + // Disk use can move between requests; allow 64 MiB of runner activity. + auto sum = ullUsed + ullFree; + CHECK( (sum > ullCap ? sum - ullCap : ullCap - sum) < 64ull*1024ull*1024ull ); CHECK( oads_SetFileAttr( h, (UNSIGNED8*)"../outside.txt", 1 ) != 0 ); CHECK( oads_SetFileTime( h, (UNSIGNED8*)"../outside.txt", 2021, 3, 4, 5, 6, 7 ) != 0 ); @@ -961,7 +997,7 @@ TEST_CASE( "oads_* remote embedded: full round-trip" ) ADSHANDLE h = remote_connect_embedded( data, srv.port() ); oads_round_trip( h, "remote-embedded" ); metadata_round_trip( h, data ); - lock_round_trip( h ); + lock_round_trip( h, data ); // verify file lands in server data dir, not client cwd CHECK_FALSE( fs::exists( app / "oads_test.txt" ) ); From a555d9fc859d893140aeba741f3a4179c5620435 Mon Sep 17 00:00:00 2001 From: Pritpal Bedi Date: Sun, 15 Nov 2026 11:03:04 -0600 Subject: [PATCH 3/7] Separate remote FS lock owners while preserving within-owner Harbour ranges; exercise two-client WAIT --- contrib/oads_hb/FILE_LOCKS_MTFIX85.txt | 21 ++++++++++----- src/engine/server_fs.cpp | 31 ++++++++++++++++----- src/engine/server_fs.h | 13 +++++++-- src/network/session.cpp | 2 ++ tests/unit/abi_oads_file_funcs_test.cpp | 36 +++++++++++++++++++++++++ tests/unit/network_server_test.cpp | 7 ++--- 6 files changed, 90 insertions(+), 20 deletions(-) diff --git a/contrib/oads_hb/FILE_LOCKS_MTFIX85.txt b/contrib/oads_hb/FILE_LOCKS_MTFIX85.txt index 4e2405b4..cd7f0f15 100644 --- a/contrib/oads_hb/FILE_LOCKS_MTFIX85.txt +++ b/contrib/oads_hb/FILE_LOCKS_MTFIX85.txt @@ -1,6 +1,12 @@ OpenADS FS byte locks - mtfix85 Pritpal Bedi -2026-11-15 10:59 +2026-11-15 11:01 + +Remote ownership choice for review: each client connection is a separate +lock owner, like a separate Harbour process. Within that connection, file +opens share the merged registry. Different clients can share read locks, +and WAIT can wait for a different client. They do not all become one +owner merely because one server process handles them. OAds_FLock( hFile, nStart, nLen, nType ) -> lOk OAds_FUnlock( hFile, nStart, nLen ) -> lOk @@ -25,18 +31,23 @@ releases the VM. Connection failure or a closed handle ends the call. A caller can wait indefinitely if an external owner never releases. Harbour filebuf.c behavior preserved: -- Opens of the same physical file share a merged process-local range +- Opens of the same physical file within one owner share a merged range registry and native file. Each public handle keeps its own position. - An overlapping lock already in that registry fails immediately, including with WAIT. An identical re-lock is not recursive/idempotent. - Adjacent registrations merge. Unlock removes/splits a contained range after the native OS unlock succeeds. - LockTest reports an overlapping own registration as locked. Otherwise - Unix F_GETLK returns the external owner PID; Windows returns 1 for + Unix queries return the external owner PID where the OS supplies one; + OFD locks have no PID, so they return 1. Windows returns 1 for conflict. Both return 0 for free, -1 for error. It never waits. - Closing one reference does not release shared native-file locks while another reference remains. Last close releases the OS locks. - Unix read-only opens request shared OS locks, as Harbour does. +- POSIX uses OFD locks so separate client connections retain independent + ownership and closing one cannot drop another's locks. This differs + from Harbour's process-owned fcntl locks. OS-reported classic-lock PIDs + are returned when available; an OFD owner has no PID and returns 1. OS behavior is preserved, including: - Unix partial unlock and zero-length-to-EOF ranges work through fcntl. @@ -45,9 +56,7 @@ OS behavior is preserved, including: Harbour's Windows backend does. Zero length has Windows native meaning, not the Unix to-EOF meaning. - Windows locks affect I/O. Unix locks are advisory. Other programs must - cooperate. POSIX process locks can be dropped if unrelated code in the - same host process closes another descriptor for the same physical file; - the OAds FS functions reuse the native file to avoid doing that. + cooperate. Nonnegative file offsets and ranges must fit the signed 64-bit offset space used by the cross-platform API. No virtual-file/socket drivers are diff --git a/src/engine/server_fs.cpp b/src/engine/server_fs.cpp index 634ab4db..07ff06ac 100644 --- a/src/engine/server_fs.cpp +++ b/src/engine/server_fs.cpp @@ -507,6 +507,7 @@ void FsStream::seekg(std::streamoff off, std::ios::seekdir way) { } namespace { +thread_local std::uint64_t fs_current_owner = 0; std::mutex fs_files_mu; std::unordered_map> fs_files; std::string fs_identity(const std::string& path) { @@ -544,6 +545,11 @@ util::Error native_lock_error(const char* msg, const std::string& path) { } } +FsOwnerScope::FsOwnerScope(std::uint64_t owner) : previous_(fs_current_owner) { + fs_current_owner = owner; +} +FsOwnerScope::~FsOwnerScope() { fs_current_owner = previous_; } + util::Result fs_lock_step(FsFile& f, std::uint64_t start, std::uint64_t len, std::uint16_t type, std::uint8_t op) { @@ -603,11 +609,21 @@ util::Result fs_lock_step(FsFile& f, std::uint64_t start, fl.l_start = static_cast(start); fl.l_len = static_cast(len); fl.l_type = op == 1 ? F_UNLCK : shared ? F_RDLCK : F_WRLCK; + fl.l_pid = 0; + // OFD locks preserve ownership for separate clients in one server + // process, and closing another client's descriptor cannot drop them. +#if defined(F_OFD_SETLK) && defined(F_OFD_GETLK) + constexpr int set_cmd = F_OFD_SETLK; + constexpr int get_cmd = F_OFD_GETLK; +#else +#error "FS client-owned locks require OFD byte-range lock support on this POSIX platform" +#endif if (op == 2) { - if (::fcntl(fd, F_GETLK, &fl) != 0) return native_lock_error("F_GETLK", f.path); - return fl.l_type == F_UNLCK ? 0 : static_cast(fl.l_pid); + if (::fcntl(fd, get_cmd, &fl) != 0) return native_lock_error("F_OFD_GETLK", f.path); + // POSIX reports -1 for an OFD owner: no process ID exists there. + return fl.l_type == F_UNLCK ? 0 : fl.l_pid > 0 ? static_cast(fl.l_pid) : 1; } - if (::fcntl(fd, F_SETLK, &fl) != 0) { + if (::fcntl(fd, set_cmd, &fl) != 0) { if (op == 0 && (errno == EAGAIN || errno == EACCES)) return 0; return native_lock_error("F_SETLK", f.path); } @@ -640,7 +656,10 @@ util::Result> fs_open(const std::string& abs_path, f->path = abs_path; f->writable = create || (mode != ADS_FO_READ && mode != 3); std::lock_guard global(fs_files_mu); - auto key = fs_identity(abs_path); + auto owner_key = [&](const std::string& identity) { + return identity.empty() ? identity : identity + ":owner:" + std::to_string(fs_current_owner); + }; + auto key = owner_key(fs_identity(abs_path)); std::shared_ptr state; if (!key.empty()) state = fs_files[key].lock(); if (state) { @@ -648,9 +667,7 @@ util::Result> fs_open(const std::string& abs_path, if (f->writable && !state->writable) { // Win32 lock ownership is per native handle. Never switch away // from a handle that still holds byte ranges. -#if defined(_WIN32) if (!state->ranges.empty()) return io_err(5012, "locked read-only file cannot upgrade", abs_path); -#endif auto upgraded = platform::File::open(abs_path, platform::OpenMode::ReadWrite); if (!upgraded) return upgraded.error(); state->retained.push_back(std::move(state->file)); @@ -673,7 +690,7 @@ util::Result> fs_open(const std::string& abs_path, state = std::make_shared(); state->file = std::move(native.value()); state->writable = f->writable; - key = fs_identity(abs_path); + key = owner_key(fs_identity(abs_path)); if (!key.empty()) fs_files[key] = state; // Remove expired weak entries so file churn does not retain names. for (auto it = fs_files.begin(); it != fs_files.end();) diff --git a/src/engine/server_fs.h b/src/engine/server_fs.h index 7ea3e89a..3096d693 100644 --- a/src/engine/server_fs.h +++ b/src/engine/server_fs.h @@ -72,12 +72,21 @@ util::Result fs_dir_exist(const std::string& abs_path); util::Result fs_dir_make(const std::string& abs_path); util::Result fs_dir_remove(const std::string& abs_path); +// Remote connections own separate native lock state, like separate Harbour +// processes; within an owner opens share Harbour-style merged byte ranges. +class FsOwnerScope { +public: + explicit FsOwnerScope(std::uint64_t owner); + ~FsOwnerScope(); +private: + std::uint64_t previous_; +}; // FS-only native state and merged byte ranges, separate from RDD locks. struct FsRange { std::uint64_t start, len; }; struct FsNative { platform::File file; - // POSIX closing ANY fd drops process locks, so retain an old read-only - // descriptor across an upgrade until the last file reference closes. + // Keep prior descriptors alive through a read-only to read/write upgrade; + // no upgrade is allowed while this owner's file holds byte ranges. std::vector retained; std::mutex mu; std::vector ranges; diff --git a/src/network/session.cpp b/src/network/session.cpp index 363ed28b..d1b5475f 100644 --- a/src/network/session.cpp +++ b/src/network/session.cpp @@ -1658,6 +1658,8 @@ void Session::append_open_warm_sections(std::vector& out, } DispatchResult Session::dispatch(const Frame& f) { + // Distinct remote connections behave as distinct Harbour processes. + openads::engine::FsOwnerScope fs_owner(reinterpret_cast(this)); Frame reply; if (srv_->auth_required() && (f.opcode == Opcode::Connect || f.opcode == Opcode::MgConnect)) return {err("Challenge authentication required", openads::AE_LOGIN_FAILED), true}; diff --git a/tests/unit/abi_oads_file_funcs_test.cpp b/tests/unit/abi_oads_file_funcs_test.cpp index e83ab794..bfea83a2 100644 --- a/tests/unit/abi_oads_file_funcs_test.cpp +++ b/tests/unit/abi_oads_file_funcs_test.cpp @@ -701,6 +701,9 @@ static void lock_round_trip( ADSHANDLE h, const fs::path& dir ) fs::remove(marker); std::string command = "\"" + probe.string() + "\" hold \"" + (dir / "locks.bin").string() + "\" \"" + marker.string() + "\""; +#if defined(_WIN32) + command = "\"" + command + "\""; +#endif std::atomic child_rc{-1}; std::thread holder([&] { child_rc.store(std::system(command.c_str())); }); bool ready = false; @@ -999,6 +1002,39 @@ TEST_CASE( "oads_* remote embedded: full round-trip" ) metadata_round_trip( h, data ); lock_round_trip( h, data ); + // Different client connections are separate lock owners, like two + // Harbour processes. Same-client opens still share merged ranges. + auto peer = remote_connect_embedded(data, srv.port()); + ADSHANDLE left = 0, right = 0; + REQUIRE( oads_FOpen(h, (UNSIGNED8*)"locks.bin", 2, &left) == 0 ); + REQUIRE( oads_FOpen(peer, (UNSIGNED8*)"locks.bin", 2, &right) == 0 ); + REQUIRE( oads_FLock(left, 0, 16, 0x100) == 0 ); + REQUIRE( oads_FLock(right, 0, 16, 0x100) == 0 ); + REQUIRE( oads_FUnlock(left, 0, 16) == 0 ); + REQUIRE( oads_FUnlock(right, 0, 16) == 0 ); + REQUIRE( oads_FLock(left, 0, 16, 0) == 0 ); + CHECK( oads_FLock(right, 0, 16, 0) == 5012 ); + std::atomic done{false}; + std::atomic wait_rc{999}; + std::thread waiter([&] { wait_rc.store(oads_FLock(right,0,16,0x200)); done.store(true); }); + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + CHECK_FALSE(done.load()); + CHECK( oads_FUnlock(left,0,16) == 0 ); + for (int i=0; i<300 && !done.load(); ++i) + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + if (!done.load()) oads_FClose(right); + waiter.join(); + CHECK(wait_rc.load() == 0); + CHECK(oads_FUnlock(right,0,16) == 0); + CHECK(oads_FLock(left,32,16,0) == 0); + CHECK(oads_FClose(left) == 0); + REQUIRE(AdsDisconnect(h) == 0); + CHECK(oads_FLock(right,32,16,0) == 0); + CHECK(oads_FUnlock(right,32,16) == 0); + CHECK(oads_FClose(right) == 0); + REQUIRE(AdsDisconnect(peer) == 0); + h = remote_connect_embedded(data,srv.port()); + // verify file lands in server data dir, not client cwd CHECK_FALSE( fs::exists( app / "oads_test.txt" ) ); CHECK( fs::exists( data / "oads_test.txt" ) ); diff --git a/tests/unit/network_server_test.cpp b/tests/unit/network_server_test.cpp index f8c18dfa..33515ee7 100644 --- a/tests/unit/network_server_test.cpp +++ b/tests/unit/network_server_test.cpp @@ -162,11 +162,8 @@ TEST_CASE("M12.3 server unknown opcode returns Error frame") { Socket cs = cli.value(); Frame req; - // Pick a value outside every defined op so the server's - // default-case path is what answers. 0xFE was claimed by the - // Mutex service (M12.32); 0x0F sits in a gap between FindRecordAck - // (0x0E) and Connect (0x10) with nothing defined. - req.opcode = static_cast(0x0F); // truly unknown + // 0x0F is now FileLockOp. 0x00 remains unassigned. + req.opcode = static_cast(0x00); REQUIRE(write_frame(cs, req).has_value()); auto reply = read_frame(cs); REQUIRE(reply.has_value()); From 984700ac75fb9995600bdd940727c29dca6d5918 Mon Sep 17 00:00:00 2001 From: Pritpal Bedi Date: Sat, 21 Nov 2026 01:03:39 -0600 Subject: [PATCH 4/7] test: resolve the fs_lock85 probe path before the embedded round trip changes the working directory, so the check is independent of how the test binary was invoked --- tests/unit/abi_oads_file_funcs_test.cpp | 27 ++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/tests/unit/abi_oads_file_funcs_test.cpp b/tests/unit/abi_oads_file_funcs_test.cpp index bfea83a2..fca24bd7 100644 --- a/tests/unit/abi_oads_file_funcs_test.cpp +++ b/tests/unit/abi_oads_file_funcs_test.cpp @@ -640,7 +640,21 @@ TEST_CASE( "oads_* local: Load Save ReadAt WriteAt Flush Eof" ) fs::remove_all( dir, ec ); } -static void lock_round_trip( ADSHANDLE h, const fs::path& dir ) +static fs::path lock85_probe_path() +{ + // Resolve before any case changes the working directory: dladdr can + // return a relative loader path when the test binary is invoked by a + // relative path, and absolute() would then anchor at the wrong cwd. + auto module = openads::platform::module_directory(); + REQUIRE( module.has_value() ); + fs::path probe = fs::absolute( fs::path( *module ) ) / "openads_fs_lock85_probe"; +#if defined(_WIN32) + probe += ".exe"; +#endif + return probe; +} + +static void lock_round_trip( ADSHANDLE h, const fs::path& dir, const fs::path& probe ) { ADSHANDLE a = 0, b = 0, c = 0; REQUIRE( oads_FCreate( h, (UNSIGNED8*)"locks.bin", 0, &a ) == 0 ); @@ -690,12 +704,6 @@ static void lock_round_trip( ADSHANDLE h, const fs::path& dir ) #endif // A real other process holds byte 128 until it exits. WAIT must // complete after that release, without blocking the server thread. - auto module = openads::platform::module_directory(); - REQUIRE( module.has_value() ); - fs::path probe = fs::path(*module) / "openads_fs_lock85_probe"; -#if defined(_WIN32) - probe += ".exe"; -#endif REQUIRE( fs::exists(probe) ); auto marker = dir / "holder-ready"; fs::remove(marker); @@ -741,7 +749,7 @@ TEST_CASE( "oads_* local: FS byte locks shared exclusive wait and owner IO" ) fs::remove_all(dir); fs::create_directories(dir); auto h = local_connect(dir); - lock_round_trip(h, dir); + lock_round_trip(h, dir, lock85_probe_path()); REQUIRE( AdsDisconnect(h) == 0 ); fs::remove_all(dir); } @@ -995,12 +1003,13 @@ TEST_CASE( "oads_* remote embedded: full round-trip" ) REQUIRE( srv.start( "127.0.0.1", 0 ).has_value() ); auto prev = fs::current_path(); + const fs::path probe85 = lock85_probe_path(); fs::current_path( app ); ADSHANDLE h = remote_connect_embedded( data, srv.port() ); oads_round_trip( h, "remote-embedded" ); metadata_round_trip( h, data ); - lock_round_trip( h, data ); + lock_round_trip( h, data, probe85 ); // Different client connections are separate lock owners, like two // Harbour processes. Same-client opens still share merged ranges. From 86b82ff08ac8a6f31e267bb2bae9de426c5e2c56 Mon Sep 17 00:00:00 2001 From: Pritpal Bedi Date: Sat, 21 Nov 2026 01:35:24 -0600 Subject: [PATCH 5/7] test: compare the fs_lock85 probe result as an integer so MSVC does not trip C4805 --- tests/fs_lock85_probe.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/fs_lock85_probe.cpp b/tests/fs_lock85_probe.cpp index 672ff89e..0ae4e983 100644 --- a/tests/fs_lock85_probe.cpp +++ b/tests/fs_lock85_probe.cpp @@ -26,7 +26,7 @@ int main(int argc, char** argv) { auto r = fs_lock_step(*f.value(), 0, 16, static_cast(type), 0); if (!r) return 11; const bool want = std::string(argv[4]) == "free"; - return r.value() == want ? 0 : 12; + return ( r.value() != 0 ) == want ? 0 : 12; } auto dir = fs::temp_directory_path() / ("openads-lock85-" + std::to_string( std::chrono::steady_clock::now().time_since_epoch().count())); From 9ea773ad1af054f1514a27c18f6aef4bf01bc389 Mon Sep 17 00:00:00 2001 From: Pritpal Bedi Date: Sat, 21 Nov 2026 02:44:06 -0600 Subject: [PATCH 6/7] test: give the fs_lock85 probe child command native path separators so cmd.exe accepts it --- tests/fs_lock85_probe.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/fs_lock85_probe.cpp b/tests/fs_lock85_probe.cpp index 0ae4e983..0b30c2b7 100644 --- a/tests/fs_lock85_probe.cpp +++ b/tests/fs_lock85_probe.cpp @@ -35,7 +35,9 @@ int main(int argc, char** argv) { auto f = fs_open(path.string(), 2, true); if (!f) return 1; auto child = [&](const char* kind, const char* expected) { - std::string cmd = "\"" + fs::absolute(argv[0]).string() + "\" child \"" + + // ctest registers the binary with forward slashes; cmd.exe rejects + // that in the child command line, so use native separators. + std::string cmd = "\"" + fs::absolute(argv[0]).make_preferred().string() + "\" child \"" + path.string() + "\" " + kind + " " + expected; return std::system(cmd.c_str()) == 0; }; From ee73535f2ab2e825a880d6c4be703baa7f6857b9 Mon Sep 17 00:00:00 2001 From: Pritpal Bedi Date: Sat, 21 Nov 2026 03:11:32 -0600 Subject: [PATCH 7/7] test: wrap the fs_lock85 probe child command in outer quotes for cmd.exe, matching the holder spawn --- tests/fs_lock85_probe.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/tests/fs_lock85_probe.cpp b/tests/fs_lock85_probe.cpp index 0b30c2b7..5b687760 100644 --- a/tests/fs_lock85_probe.cpp +++ b/tests/fs_lock85_probe.cpp @@ -39,6 +39,12 @@ int main(int argc, char** argv) { // that in the child command line, so use native separators. std::string cmd = "\"" + fs::absolute(argv[0]).make_preferred().string() + "\" child \"" + path.string() + "\" " + kind + " " + expected; +#if defined(_WIN32) + // cmd.exe strips a leading quote plus the last quote on the line, + // mangling the inner paths; an outer quote pair keeps them intact + // (same pattern as the holder spawn in abi_oads_file_funcs_test). + cmd = "\"" + cmd + "\""; +#endif return std::system(cmd.c_str()) == 0; }; auto locked = fs_lock_step(*f.value(),0,16,0,0);