diff --git a/.github/workflows/build_with_macos.yml b/.github/workflows/build_with_macos.yml index 4161c863..44828582 100644 --- a/.github/workflows/build_with_macos.yml +++ b/.github/workflows/build_with_macos.yml @@ -59,15 +59,32 @@ jobs: echo "Waiting for MySQL... ($i)" sleep 2 done - # Set root password (Homebrew MySQL starts with empty password) - # Try without password first, then with 'root' if already set - MYSQL_PWD="" mysql -h 127.0.0.1 -uroot -e "SELECT 1" 2>/dev/null && echo "MYSQL_AUTH=empty" >> $GITHUB_ENV || { - MYSQL_PWD="root" mysql -h 127.0.0.1 -uroot -e "SELECT 1" 2>/dev/null && echo "MYSQL_AUTH=root" >> $GITHUB_ENV || { - echo "MYSQL_AUTH=failed" >> $GITHUB_ENV - } - } - # Create test database (required for integration tests) - MYSQL_PWD="" mysql -h 127.0.0.1 -uroot -e "CREATE DATABASE IF NOT EXISTS test" 2>/dev/null || true + # Homebrew MySQL starts with an empty root password. The workflow + # comment previously claimed to set it, but it only detected auth and + # created the database with MYSQL_PWD="". Tests require root/root on + # 127.0.0.1:3306 and database test (same contract as Linux/Windows). + SQL=" + CREATE DATABASE IF NOT EXISTS test; + CREATE USER IF NOT EXISTS 'root'@'127.0.0.1' IDENTIFIED BY 'root'; + ALTER USER 'root'@'127.0.0.1' IDENTIFIED BY 'root'; + ALTER USER 'root'@'localhost' IDENTIFIED BY 'root'; + GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' WITH GRANT OPTION; + GRANT ALL PRIVILEGES ON *.* TO 'root'@'127.0.0.1' WITH GRANT OPTION; + FLUSH PRIVILEGES; + " + configured=0 + for pwd in "" "root"; do + if MYSQL_PWD="$pwd" mysql -h 127.0.0.1 -uroot --protocol=tcp -e "$SQL"; then + configured=1 + break + fi + done + if [ "$configured" -ne 1 ]; then + echo "Failed to configure MySQL test user (root/root) and database" + exit 1 + fi + MYSQL_PWD="root" mysql -h 127.0.0.1 -uroot --protocol=tcp -e "SELECT 1" + echo "MySQL configured (root/root, database test)" - name: Setup Redis run: | diff --git a/.github/workflows/build_with_windows.yml b/.github/workflows/build_with_windows.yml index 3f9e3619..91f99a61 100644 --- a/.github/workflows/build_with_windows.yml +++ b/.github/workflows/build_with_windows.yml @@ -37,7 +37,24 @@ jobs: - name: Install MySQL run: | - choco install mysql -y + # Unpinned `choco install mysql` follows latest. 26.10.0 (current + # latest) aborted mid-download from cdn.mysql.com on this PR with + # 404 / connection reset, even though the zip is published. Pin the + # last Approved 9.x package that still serves a live zip, and retry + # transient CDN failures. Start/Configure MySQL steps stay the same. + $version = "9.6.0" + $installed = $false + for ($i = 1; $i -le 3; $i++) { + Write-Host "Installing MySQL $version (attempt $i/3)" + choco install mysql --version=$version -y --no-progress + if ($LASTEXITCODE -eq 0) { + $installed = $true + break + } + Write-Host "MySQL install failed with exit $LASTEXITCODE" + if ($i -lt 3) { Start-Sleep -Seconds (15 * $i) } + } + if (-not $installed) { throw "Failed to install MySQL $version after 3 attempts" } echo "MySQL installed" - name: Start MySQL diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index f2f899e7..e2cac2a1 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -343,6 +343,11 @@ if (WIN32 AND NOT OPENSSL_ROOT_DIR) endif() endif() find_package(OpenSSL REQUIRED) +# Imported OpenSSL targets live in this directory scope. Mark them global so +# test/ can link them without a second find_package (which would miss the +# MinGW OPENSSL_ROOT_DIR / static-vs-shared policy set above). +set_property(TARGET OpenSSL::SSL PROPERTY IMPORTED_GLOBAL TRUE) +set_property(TARGET OpenSSL::Crypto PROPERTY IMPORTED_GLOBAL TRUE) find_package(Threads REQUIRED) if (OPENSSL_USE_STATIC_LIBS) diff --git a/src/jit/gcc_cache.cpp b/src/jit/gcc_cache.cpp index b677d60b..c4aba033 100644 --- a/src/jit/gcc_cache.cpp +++ b/src/jit/gcc_cache.cpp @@ -38,16 +38,29 @@ class WinHandle { public: HANDLE h = INVALID_HANDLE_VALUE; WinHandle() = default; - explicit WinHandle(HANDLE handle) : h(handle) {} - ~WinHandle() { reset(); } + + explicit WinHandle(HANDLE handle) : h(handle) { + } + + ~WinHandle() { + reset(); + } + WinHandle(const WinHandle &) = delete; WinHandle &operator=(const WinHandle &) = delete; - WinHandle(WinHandle &&other) noexcept : h(other.h) { other.h = INVALID_HANDLE_VALUE; } + + WinHandle(WinHandle &&other) noexcept : h(other.h) { + other.h = INVALID_HANDLE_VALUE; + } + void reset() { if (h != INVALID_HANDLE_VALUE) CloseHandle(h); h = INVALID_HANDLE_VALUE; } - explicit operator bool() const { return h != INVALID_HANDLE_VALUE; } + + explicit operator bool() const { + return h != INVALID_HANDLE_VALUE; + } }; // One-pass POSIX unlink: never retries, and does not block on a share-delete open handle. @@ -57,9 +70,11 @@ bool UnlinkPath(const fs::path &p) { const auto err = GetLastError(); return err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND; } + struct DispositionEx { DWORD Flags; } posix{0x00000001 | 0x00000002};// FILE_DISPOSITION_FLAG_DELETE | POSIX_SEMANTICS + if (SetFileInformationByHandle(handle.h, static_cast(21), &posix, sizeof(posix))) return true; FILE_DISPOSITION_INFO info{}; info.DeleteFile = TRUE; @@ -144,7 +159,9 @@ void WriteBytes(const fs::path &p, const std::string &data) { if (!out) throw std::runtime_error("cache write"); } -void RemoveTree(const fs::path &p, std::error_code &ec) { fs::remove_all(p, ec); } +void RemoveTree(const fs::path &p, std::error_code &ec) { + fs::remove_all(p, ec); +} #endif std::string Digest(const std::string &data) { @@ -412,7 +429,8 @@ class CacheFileLock { WinHandle named(CreateFileW(path_.wstring().c_str(), 0, kShareAll, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr)); if (!named) return false; BY_HANDLE_FILE_INFORMATION info{}; - return GetFileInformationByHandle(named.h, &info) && held.dwVolumeSerialNumber == info.dwVolumeSerialNumber && held.nFileIndexHigh == info.nFileIndexHigh && held.nFileIndexLow == info.nFileIndexLow; + return GetFileInformationByHandle(named.h, &info) && held.dwVolumeSerialNumber == info.dwVolumeSerialNumber && held.nFileIndexHigh == info.nFileIndexHigh && + held.nFileIndexLow == info.nFileIndexLow; #else struct stat held{}, named{}; @@ -548,9 +566,8 @@ void GccCache::Release() { } GccCache::GccCache(const StateGCCConfig &cfg, const std::string &compiler, const std::string &code, bool debug) { - // Arbitrary user headers/libraries (and coverage files) cannot be reliably - // fingerprinted as a closed toolchain. Retain the uncached behavior there. -#if !defined(USE_COV) + // Arbitrary user headers/libraries cannot be reliably fingerprinted as a + // closed toolchain. Retain the uncached behavior there. if (!cfg.enable_cache || !cfg.include_paths.empty() || !cfg.library_paths.empty() || !cfg.libraries.empty()) return; // Search-path overrides can add a newly shadowing header/library without // changing any previously recorded dependency. Such open-ended toolchains @@ -599,7 +616,6 @@ GccCache::GccCache(const StateGCCConfig &cfg, const std::string &compiler, const impl_ = std::move(p); } catch (...) { /* Caching is an optimization, never a compile requirement. */ } -#endif } bool GccCache::Restore(const std::string &destination) { diff --git a/src/jit/gcc_jit.cpp b/src/jit/gcc_jit.cpp index 5c8566b8..57b18510 100644 --- a/src/jit/gcc_jit.cpp +++ b/src/jit/gcc_jit.cpp @@ -165,7 +165,13 @@ void GccJitter::Compile(const ParseResult &pr, const GenResult &gr, const Compil } #endif - GccCache cache(s_->GetStateConfig().gcc_config, compiler, gr.c_code, cfg.debug_mode); + auto cache_config = s_->GetStateConfig().gcc_config; +#if defined(USE_COV) + // Instrumented images own per-compilation gcno/gcda paths. Never reuse them; + // keep the filesystem cache itself instrumented and directly testable. + cache_config.enable_cache = false; +#endif + GccCache cache(cache_config, compiler, gr.c_code, cfg.debug_mode); bool cache_hit = cache.Restore(so_file); const std::string dep_file = c_file + ".d"; diff --git a/src/native/http/native_http.cpp b/src/native/http/native_http.cpp index 721be213..5c146cd8 100644 --- a/src/native/http/native_http.cpp +++ b/src/native/http/native_http.cpp @@ -637,10 +637,12 @@ class HttpServerConn : public std::enable_shared_from_this { void Reply(int status, std::string reason, HeaderList headers, std::string body) { if (closed_ || writing_ || !bev_) return; - writing_ = true; HeaderSet(headers, "Server", "fakelua"); HeaderSet(headers, "Connection", "close"); std::string wire = FormatResponse(status, std::move(reason), std::move(headers), body, req_.version); + // Validation can throw. A rejected reply must not prevent a corrected + // reply from being sent on this still-open connection. + writing_ = true; bufferevent_write(bev_, wire.data(), wire.size()); ArmTimeout(); } diff --git a/src/native/mysql/mysql_connection.cpp b/src/native/mysql/mysql_connection.cpp index c67dc620..d7488917 100644 --- a/src/native/mysql/mysql_connection.cpp +++ b/src/native/mysql/mysql_connection.cpp @@ -213,6 +213,17 @@ void MysqlConnection::FinishConnect(MYSQL *ret) { pending_connect_ = true; } +void MysqlConnection::Query(const std::string &sql, const ResultCallback &callback) { + // A queued submission must not replace the callback of the query already + // in flight. Store its callback together with its SQL until it starts. + if (mysql_ && !close_pending_ && (state_ != ConnState::Ready || !ready_)) { + queued_queries_.push_back(QueuedQuery{sql, callback}); + return; + } + result_cb_ = callback; + Query(sql); +} + void MysqlConnection::Query(const std::string &sql) { // 契约:conn:query 一旦被调用,回调恰好被调用一次。 // - 连接已死(mysql_ 释放 / 已请求关闭):下一轮 tick 给回调派发错误; @@ -398,6 +409,11 @@ void MysqlConnection::StmtExecute(uint32_t stmt_id, const std::vector pending_result_ = true; return; } + if (params.size() != mysql_stmt_param_count(it->second)) { + pending_result_err_ = "statement parameter count mismatch"; + pending_result_ = true; + return; + } state_ = ConnState::Querying; query_type_ = QueryType::StmtExecute; pending_results_.clear(); diff --git a/src/native/mysql/mysql_connection.h b/src/native/mysql/mysql_connection.h index 7ddfe25f..c65085d8 100644 --- a/src/native/mysql/mysql_connection.h +++ b/src/native/mysql/mysql_connection.h @@ -97,6 +97,7 @@ class MysqlConnection { std::string ssl_ca = {}); void Query(const std::string &sql); + void Query(const std::string &sql, const ResultCallback &callback); void StmtPrepare(const std::string &sql); void StmtExecute(uint32_t stmt_id, const std::vector ¶ms); void StmtClose(uint32_t stmt_id); diff --git a/src/native/mysql/native_mysql.cpp b/src/native/mysql/native_mysql.cpp index 2befee30..06731b2d 100644 --- a/src/native/mysql/native_mysql.cpp +++ b/src/native/mysql/native_mysql.cpp @@ -278,8 +278,7 @@ CVar ConnQuery(NativeObject *self, State *s, CVar *args, int n) { // 连接未就绪(握手中/重连中/上一条 query 仍在飞行)不再抛错: // 回调随 query 入队,由连接的 tick 在可用时自动启动(见 MysqlConnection::Query)。 conn->SetState(s); - conn->SetResultCallback(cb); - conn->Query(sql); + conn->Query(sql, cb); MaybeReleaseOwnedConn(self); return inter::NativeToFakeluaNil(s); diff --git a/src/native/redis/native_redis.cpp b/src/native/redis/native_redis.cpp index 3d34f428..e2a88a63 100644 --- a/src/native/redis/native_redis.cpp +++ b/src/native/redis/native_redis.cpp @@ -361,13 +361,18 @@ class RedisConnection { op->err = std::string(reply->str, reply->len); return; } - op->reply = reply; // hiredis frees reply after callback unless we take it. Copy by keeping? // Default: hiredis frees reply after callback returns. We must copy now. // We'll convert later in Tick — so duplicate via redisReply isn't easy. // Convert immediately into Lua? Can't, might be inside poll. // Duplicate the reply tree: - op->reply = CloneReply(reply); + try { + op->reply = CloneReply(reply); + } catch (const std::exception &e) { + // Never unwind through hiredis: it still owns the original reply and + // must finish its callback cleanup even when a depth limit is hit. + op->err = e.what(); + } } static redisReply *CloneReply(const redisReply *r, int depth = 0) { diff --git a/src/native/tls_util.h b/src/native/tls_util.h index b2cc0669..235d5609 100644 --- a/src/native/tls_util.h +++ b/src/native/tls_util.h @@ -13,7 +13,10 @@ inline SSL_CTX *MakeClientContext(bool verify, const std::string &ca) { if (verify) { SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, nullptr); if (!ca.empty()) { - SSL_CTX_load_verify_locations(ctx, ca.c_str(), nullptr); + if (SSL_CTX_load_verify_locations(ctx, ca.c_str(), nullptr) != 1) { + SSL_CTX_free(ctx); + return nullptr; + } } else { SSL_CTX_set_default_verify_paths(ctx); } diff --git a/src/native/utf8/native_utf8.cpp b/src/native/utf8/native_utf8.cpp index 79680528..ff466ca1 100644 --- a/src/native/utf8/native_utf8.cpp +++ b/src/native/utf8/native_utf8.cpp @@ -1,4 +1,5 @@ #include "native/utf8/native_utf8.h" +#include "jit/jit_error_boundary.h" #include "native/native_common.h" #include "native/object/native_object.h" #include "native/string/native_string.h" @@ -247,19 +248,23 @@ extern "C" CVar Utf8CodesIterator(VarClosure *cl, CVar /*s*/, CVar /*var*/) { if (!iter_state || !gs) { return inter::NativeToFakeluaNil(iter_state); } - if (gs->pos >= gs->text.size()) { - return inter::NativeToFakeluaNil(iter_state); - } - const size_t start = gs->pos; - std::string_view sv = gs->text; - int64_t cp = DecodeUtf8(sv, gs->pos); - if (cp < 0) { - ThrowFakeluaException("invalid UTF-8 code"); - } - CVar multi = inter::AllocMultiCVar(iter_state, 2); - inter::SetMultiCVarElement(multi, 0, inter::NativeToFakeluaLonglong(iter_state, static_cast(start + 1))); - inter::SetMultiCVarElement(multi, 1, inter::NativeToFakeluaLonglong(iter_state, cp)); - return multi; + // This closure is called directly by generated C, bypassing the native + // function bridge. Do not unwind a C++ exception through a TCC frame. + return GuardJitEntry(iter_state, [&]() -> CVar { + if (gs->pos >= gs->text.size()) { + return inter::NativeToFakeluaNil(iter_state); + } + const size_t start = gs->pos; + std::string_view sv = gs->text; + int64_t cp = DecodeUtf8(sv, gs->pos); + if (cp < 0) { + ThrowFakeluaException("invalid UTF-8 code"); + } + CVar multi = inter::AllocMultiCVar(iter_state, 2); + inter::SetMultiCVarElement(multi, 0, inter::NativeToFakeluaLonglong(iter_state, static_cast(start + 1))); + inter::SetMultiCVarElement(multi, 1, inter::NativeToFakeluaLonglong(iter_state, cp)); + return multi; + }); } static CVar Utf8Codes(State *state, CVar *args, int n) { diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index f8d123f0..aa7453de 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -78,6 +78,12 @@ ELSE () ENDIF () add_executable(unit_tests ${TEST_SRC_LIST}) +# Direct MySQL connection/pool unit tests use their internal dependency headers. +foreach (_fl_test_dependency event_core mariadbclient libmariadb) + if (TARGET ${_fl_test_dependency}) + target_include_directories(unit_tests PRIVATE $) + endif () +endforeach () if (USE_COV) target_compile_definitions(unit_tests PRIVATE FAKELUA_TEST_NO_GCC_CACHE=1) endif () @@ -87,7 +93,9 @@ if (NOT WIN32 AND NOT APPLE) target_link_libraries(unit_tests PRIVATE dl) endif () find_package(Threads REQUIRED) -target_link_libraries(unit_tests PRIVATE fakelua gtest_main ${LUA_LIBRARIES} Threads::Threads) +# test_crypto calls OpenSSL APIs directly; Windows fakelua.dll does not +# re-export them (--exclude-libs,ALL), so unit_tests must link OpenSSL itself. +target_link_libraries(unit_tests PRIVATE fakelua gtest_main ${LUA_LIBRARIES} Threads::Threads Boost::container lz4_static OpenSSL::SSL OpenSSL::Crypto) add_test(NAME unit COMMAND ${CMAKE_BINARY_DIR}/${CMAKE_INSTALL_BINDIR}/unit_tests WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/${CMAKE_INSTALL_BINDIR}) diff --git a/test/lua/basic/test_basic_host_exceptions.lua b/test/lua/basic/test_basic_host_exceptions.lua new file mode 100644 index 00000000..1d5a6186 --- /dev/null +++ b/test/lua/basic/test_basic_host_exceptions.lua @@ -0,0 +1,18 @@ +function test_host_exception_boundaries() + local ok, message = pcall(function() host_standard_error() end) + assert(not ok and string.find(message, "host failure", 1, true)) + ok, message = pcall(function() host_unknown_error() end) + assert(not ok and string.find(message, "unknown", 1, true)) + ok, message = xpcall(function() error("original failure") end, function(err) host_standard_error() end) + assert(not ok and string.find(message, "original failure", 1, true)) + assert(not pcall(function() xpcall(function() return 1 end, 123) end)) + local key = {} + local iterator, state, control = pairs({[key] = 9}) + local returned, value = iterator(state, control) + assert(returned == key and value == 9) + assert(iterator(state, returned) == nil) + -- Protected-call failures must not poison the next ordinary call. + local success, result = pcall(function() return 42 end) + assert(success and result == 42) + return 1 +end diff --git a/test/lua/basic/test_basic_iterator_values.lua b/test/lua/basic/test_basic_iterator_values.lua new file mode 100644 index 00000000..b72ba764 --- /dev/null +++ b/test/lua/basic/test_basic_iterator_values.lua @@ -0,0 +1,37 @@ +-- Iterator triples must also work as values, not only in compiler-specialized for loops. +function test_iterator_values() + local entries = { alpha = 11, beta = 22, [5] = 33, [true] = 44 } + local iter, state, control = pairs(entries) + assert(state == entries and control == nil) + local seen = {} + local count = 0 + while true do + local key, value = iter(state, control) + if key == nil then break end + assert(seen[key] == nil) + assert(value == entries[key]) + seen[key] = true + control = key + count = count + 1 + end + assert(count == 4) + assert(iter(state, control) == nil) + + local sequence = {10, 20, 30, nil, 50} + local next_index, array, index = ipairs(sequence) + assert(array == sequence and index == 0) + local sum = 0 + for expected = 1, 3 do + local key, value = next_index(array, index) + assert(key == expected and value == expected * 10) + index = key + sum = sum + value + end + assert(sum == 60 and next_index(array, index) == nil) + assert(next_index(array, index) == nil) + local empty_pairs, empty_state, empty_control = pairs({}) + assert(empty_pairs(empty_state, empty_control) == nil) + local empty_ipairs, empty_array, empty_index = ipairs({}) + assert(empty_ipairs(empty_array, empty_index) == nil) + return 1 +end diff --git a/test/lua/basic/test_basic_tonumber_edge.lua b/test/lua/basic/test_basic_tonumber_edge.lua index ce076e9a..bbf2de29 100644 --- a/test/lua/basic/test_basic_tonumber_edge.lua +++ b/test/lua/basic/test_basic_tonumber_edge.lua @@ -79,3 +79,13 @@ function test_basic_tonumber_edge() return 5000 end + +function test_tonumber_base_and_hex_bounds() + assert(not pcall(function() tonumber("1", "not-a-base") end)) + assert(tonumber("1", "1.5") == nil) + assert(tonumber("0xnan") == nil) + assert(tonumber("0xxyz") == nil) + assert(tonumber("-0xffffffffffffffff") < -1e19) + assert(tonumber("-0xffffffffffffffff", 16) == nil) + return 1 +end diff --git a/test/lua/closure/test_closure_fixed_arity_dispatch.lua b/test/lua/closure/test_closure_fixed_arity_dispatch.lua new file mode 100644 index 00000000..ee26a806 --- /dev/null +++ b/test/lua/closure/test_closure_fixed_arity_dispatch.lua @@ -0,0 +1,173 @@ +function dispatch_arity_4() + local fn = function(a1, a2, a3, a4) return a1 + a2 + a3 + a4 end + local opaque = opaque_closure(fn) + return opaque(1, 2, 3, 4) +end + +function dispatch_arity_5() + local fn = function(a1, a2, a3, a4, a5) return a1 + a2 + a3 + a4 + a5 end + local opaque = opaque_closure(fn) + return opaque(1, 2, 3, 4, 5) +end + +function dispatch_arity_6() + local fn = function(a1, a2, a3, a4, a5, a6) return a1 + a2 + a3 + a4 + a5 + a6 end + local opaque = opaque_closure(fn) + return opaque(1, 2, 3, 4, 5, 6) +end + +function dispatch_arity_7() + local fn = function(a1, a2, a3, a4, a5, a6, a7) return a1 + a2 + a3 + a4 + a5 + a6 + a7 end + local opaque = opaque_closure(fn) + return opaque(1, 2, 3, 4, 5, 6, 7) +end + +function dispatch_arity_8() + local fn = function(a1, a2, a3, a4, a5, a6, a7, a8) return a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 end + local opaque = opaque_closure(fn) + return opaque(1, 2, 3, 4, 5, 6, 7, 8) +end + +function dispatch_arity_9() + local fn = function(a1, a2, a3, a4, a5, a6, a7, a8, a9) return a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 end + local opaque = opaque_closure(fn) + return opaque(1, 2, 3, 4, 5, 6, 7, 8, 9) +end + +function dispatch_arity_10() + local fn = function(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) return a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10 end + local opaque = opaque_closure(fn) + return opaque(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) +end + +function dispatch_arity_11() + local fn = function(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11) return a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10 + a11 end + local opaque = opaque_closure(fn) + return opaque(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) +end + +function dispatch_arity_12() + local fn = function(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12) return a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10 + a11 + a12 end + local opaque = opaque_closure(fn) + return opaque(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12) +end + +function dispatch_arity_13() + local fn = function(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13) return a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10 + a11 + a12 + a13 end + local opaque = opaque_closure(fn) + return opaque(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13) +end + +function dispatch_arity_14() + local fn = function(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14) return a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10 + a11 + a12 + a13 + a14 end + local opaque = opaque_closure(fn) + return opaque(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14) +end + +function dispatch_arity_15() + local fn = function(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15) return a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10 + a11 + a12 + a13 + a14 + a15 end + local opaque = opaque_closure(fn) + return opaque(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15) +end + +function dispatch_arity_16() + local fn = function(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16) return a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10 + a11 + a12 + a13 + a14 + a15 + a16 end + local opaque = opaque_closure(fn) + return opaque(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16) +end + +function dispatch_arity_17() + local fn = function(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17) return a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10 + a11 + a12 + a13 + a14 + a15 + a16 + a17 end + local opaque = opaque_closure(fn) + return opaque(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17) +end + +function dispatch_arity_18() + local fn = function(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18) return a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10 + a11 + a12 + a13 + a14 + a15 + a16 + a17 + a18 end + local opaque = opaque_closure(fn) + return opaque(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18) +end + +function dispatch_arity_19() + local fn = function(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19) return a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10 + a11 + a12 + a13 + a14 + a15 + a16 + a17 + a18 + a19 end + local opaque = opaque_closure(fn) + return opaque(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19) +end + +function dispatch_arity_20() + local fn = function(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20) return a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10 + a11 + a12 + a13 + a14 + a15 + a16 + a17 + a18 + a19 + a20 end + local opaque = opaque_closure(fn) + return opaque(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20) +end + +function dispatch_arity_21() + local fn = function(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21) return a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10 + a11 + a12 + a13 + a14 + a15 + a16 + a17 + a18 + a19 + a20 + a21 end + local opaque = opaque_closure(fn) + return opaque(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21) +end + +function dispatch_arity_22() + local fn = function(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22) return a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10 + a11 + a12 + a13 + a14 + a15 + a16 + a17 + a18 + a19 + a20 + a21 + a22 end + local opaque = opaque_closure(fn) + return opaque(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22) +end + +function dispatch_arity_23() + local fn = function(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23) return a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10 + a11 + a12 + a13 + a14 + a15 + a16 + a17 + a18 + a19 + a20 + a21 + a22 + a23 end + local opaque = opaque_closure(fn) + return opaque(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23) +end + +function dispatch_arity_24() + local fn = function(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24) return a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10 + a11 + a12 + a13 + a14 + a15 + a16 + a17 + a18 + a19 + a20 + a21 + a22 + a23 + a24 end + local opaque = opaque_closure(fn) + return opaque(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24) +end + +function dispatch_arity_25() + local fn = function(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25) return a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10 + a11 + a12 + a13 + a14 + a15 + a16 + a17 + a18 + a19 + a20 + a21 + a22 + a23 + a24 + a25 end + local opaque = opaque_closure(fn) + return opaque(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25) +end + +function dispatch_arity_26() + local fn = function(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26) return a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10 + a11 + a12 + a13 + a14 + a15 + a16 + a17 + a18 + a19 + a20 + a21 + a22 + a23 + a24 + a25 + a26 end + local opaque = opaque_closure(fn) + return opaque(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26) +end + +function dispatch_arity_27() + local fn = function(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27) return a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10 + a11 + a12 + a13 + a14 + a15 + a16 + a17 + a18 + a19 + a20 + a21 + a22 + a23 + a24 + a25 + a26 + a27 end + local opaque = opaque_closure(fn) + return opaque(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27) +end + +function dispatch_arity_28() + local fn = function(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28) return a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10 + a11 + a12 + a13 + a14 + a15 + a16 + a17 + a18 + a19 + a20 + a21 + a22 + a23 + a24 + a25 + a26 + a27 + a28 end + local opaque = opaque_closure(fn) + return opaque(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28) +end + +function dispatch_arity_29() + local fn = function(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29) return a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10 + a11 + a12 + a13 + a14 + a15 + a16 + a17 + a18 + a19 + a20 + a21 + a22 + a23 + a24 + a25 + a26 + a27 + a28 + a29 end + local opaque = opaque_closure(fn) + return opaque(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29) +end + +function dispatch_arity_30() + local fn = function(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29, a30) return a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10 + a11 + a12 + a13 + a14 + a15 + a16 + a17 + a18 + a19 + a20 + a21 + a22 + a23 + a24 + a25 + a26 + a27 + a28 + a29 + a30 end + local opaque = opaque_closure(fn) + return opaque(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30) +end + +function dispatch_arity_31() + local fn = function(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, a31) return a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10 + a11 + a12 + a13 + a14 + a15 + a16 + a17 + a18 + a19 + a20 + a21 + a22 + a23 + a24 + a25 + a26 + a27 + a28 + a29 + a30 + a31 end + local opaque = opaque_closure(fn) + return opaque(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31) +end + +function dispatch_arity_32() + local fn = function(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, a31, a32) return a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10 + a11 + a12 + a13 + a14 + a15 + a16 + a17 + a18 + a19 + a20 + a21 + a22 + a23 + a24 + a25 + a26 + a27 + a28 + a29 + a30 + a31 + a32 end + local opaque = opaque_closure(fn) + return opaque(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32) +end diff --git a/test/lua/closure/test_closure_loop_capture.lua b/test/lua/closure/test_closure_loop_capture.lua new file mode 100644 index 00000000..33e30a87 --- /dev/null +++ b/test/lua/closure/test_closure_loop_capture.lua @@ -0,0 +1,25 @@ +local function file_local_pair(value) + return value, value + 1, value + 2 +end + +function test_loop_capture_contracts() + local floating = {} + for value = opaque_loop_value(0.5), opaque_loop_value(1.5), opaque_loop_value(0.5) do + if value == 1.0 then continue end + floating[#floating + 1] = function() return value end + end + assert(#floating == 2 and floating[1]() == 0.5 and floating[2]() == 1.5) + local generic = {} + for key, value in ipairs({10, 20, 30}) do + if key == 2 then continue end + generic[#generic + 1] = function() return key, value end + end + local a, b = generic[1]() + local c, d = generic[2]() + assert(a == 1 and b == 10 and c == 3 and d == 30) + local first, second, third, missing = file_local_pair(10) + local result = function() return first + second + third, missing end + local total, absent = result() + assert(total == 33 and absent == nil) + return 1 +end diff --git a/test/lua/closure/test_closure_mutable_generic_loop.lua b/test/lua/closure/test_closure_mutable_generic_loop.lua new file mode 100644 index 00000000..c420f6ed --- /dev/null +++ b/test/lua/closure/test_closure_mutable_generic_loop.lua @@ -0,0 +1,54 @@ +local function nested_forward_goto(flag) + local trace = 0 + do + if flag then goto outside end + trace = trace + 1 + end + ::outside:: + return trace +end +function test_mutable_generic_loop() + local captured = {} + for key, value in ipairs({2, 4, 6}) do + value = value + 1 + captured[key] = function() return value end + if key == 1 then continue end + if key == 2 then break end + end + assert(captured[1]() == 3 and captured[2]() == 5 and captured[3] == nil) + assert(nested_forward_goto(true) == 0 and nested_forward_goto(false) == 1) + return 1 +end + + +local function custom_iteration(state, previous) + local index = previous + 1 + if index <= #state then return index, state[index] end + return nil +end + +local function declaration_pair() return 3, 4 end + +function test_generic_iterator_capture_and_multivalue_prefix_declarations() + local captured = {} + for index, value in custom_iteration, {1, 2, 3}, 0 do + captured[index] = function() return value end + value = value + 10 + if index == 1 then continue end + if index == 2 then break end + end + assert(captured[1]() == 11 and captured[2]() == 12 and captured[3] == nil) + local prefix, a, b = 7, declaration_pair() + local get_prefix = function() return prefix end + prefix = prefix + 1 + assert(get_prefix() == 8 and a == 3 and b == 4) + local shadowed = 10 + do + local shadowed, c, d = 20, declaration_pair() + assert(shadowed == 20 and c == 3 and d == 4) + end + assert(shadowed == 10) + local text, e, f = tostring(12), declaration_pair() + assert(text == "12" and e == 3 and f == 4) + return 1 +end diff --git a/test/lua/container/test_container_scalar_keys.lua b/test/lua/container/test_container_scalar_keys.lua new file mode 100644 index 00000000..fa2da808 --- /dev/null +++ b/test/lua/container/test_container_scalar_keys.lua @@ -0,0 +1,30 @@ +function test_ordered_scalar_keys() + local map = container.map() + map:set(nil, "nil") + map:set(false, "false") + map:set(true, "true") + map:set(1.0, "one") + map:set(1.5, "fraction") + map:set(0/0, "nan") + assert(map:size() == 6) + assert(map:get(nil) == "nil") + assert(map:get(1) == "one") + assert(map:get(1.5) == "fraction") + assert(map:get(0/0) == "nan") + local keys = map:keys() + assert(keys[1] == nil and keys[2] == false and keys[3] == true) + assert(keys[4] == 1 and keys[5] == 1.5 and keys[6] ~= keys[6]) + assert(not pcall(function() map:set({}, 1) end)) + assert(not pcall(function() map:set(function() return 1 end, 1) end)) + assert(map:erase(nil) and not map:has(nil)) + local set = container.set() + assert(set:insert(nil) and not set:insert(nil)) + assert(set:insert(1.0) and not set:insert(1)) + assert(set:insert(1.5) and set:insert(0/0)) + assert(set:has(0/0) and set:has(1.5)) + assert(not pcall(function() set:insert({}) end)) + map:clear() + set:clear() + assert(map:empty() and set:empty()) + return 1 +end diff --git a/test/lua/crypto/test_crypto_input_contracts.lua b/test/lua/crypto/test_crypto_input_contracts.lua new file mode 100644 index 00000000..238769a3 --- /dev/null +++ b/test/lua/crypto/test_crypto_input_contracts.lua @@ -0,0 +1,19 @@ +function test_crypto_input_contracts() + local key = string.rep(string.char(0), 16) + local function rejects(fn, text) + local ok, message = pcall(fn) + assert(not ok and string.find(message, text, 1, true)) + end + rejects(function() crypto.aes_encrypt_ecb("x", key) end, "multiple of 16") + rejects(function() crypto.aes_decrypt_ecb("x", key) end, "multiple of 16") + rejects(function() crypto.aes_encrypt_ecb(key, "short") end, "16 bytes") + rejects(function() crypto.aes_encrypt_cbc(key, key, "short") end, "16 bytes") + rejects(function() crypto.hex_decode("abc") end, "even length") + rejects(function() crypto.digest_raw("fakelua-not-a-digest", "data") end, "unknown digest") + rejects(function() crypto.encrypt("aes-128-cbc", key, key, "x", true) end, "EVP_Final") + local encrypted = crypto.encrypt("aes-128-cbc", key, key, key) + assert(crypto.decrypt("aes-128-cbc", key, key, encrypted) == key) + local corrupted = string.sub(encrypted, 1, 15) .. string.char(string.byte(encrypted, 16) ~ 1) .. string.sub(encrypted, 17) + rejects(function() crypto.decrypt("aes-128-cbc", key, key, corrupted) end, "EVP_Final") + return 1 +end diff --git a/test/lua/csv/test_csv_parser_contracts.lua b/test/lua/csv/test_csv_parser_contracts.lua new file mode 100644 index 00000000..1a386fac --- /dev/null +++ b/test/lua/csv/test_csv_parser_contracts.lua @@ -0,0 +1,11 @@ +function test_csv_parser_contracts() + local text = string.char(239, 187, 191) .. " \t\r\n\n\r left,right\r\n\"quoted\" \t,last\r\n\t " + local rows = csv.decode(text) + assert(rows[1][1] == " left" and rows[1][2] == "right") + assert(rows[2][1] == "quoted" and rows[2][2] == "last") + assert(rows[3][1] == "\t ") + assert(not pcall(function() return csv.decode('\"quoted\"invalid,next') end)) + assert(csv.encode({{true, false}}) == "true,false") + assert(csv.encode({1, "text", false}) == "1\ntext\nfalse") + return 1 +end diff --git a/test/lua/event/test_event_additional_contracts.lua b/test/lua/event/test_event_additional_contracts.lua new file mode 100644 index 00000000..8daed49d --- /dev/null +++ b/test/lua/event/test_event_additional_contracts.lua @@ -0,0 +1,24 @@ +function event_contract_callback(counter) + counter.total = counter.total + 1 +end +function test_event_contracts() + local counter = {total = 0} + event.once("cancelled_once", "event_contract_callback") + event.off("cancelled_once", "missing_callback") + event.off("cancelled_once", "event_contract_callback") + event.emit("cancelled_once", counter) + assert(counter.total == 0) + event.once("live_once", "event_contract_callback") + event.emit("live_once", counter) + event.emit("live_once", counter) + assert(counter.total == 1) + assert(not pcall(function() event.on("", "event_contract_callback") end)) + assert(not pcall(function() event.on("a", "") end)) + assert(not pcall(function() event.on(false, false) end)) + assert(not pcall(function() event.once("", "event_contract_callback") end)) + assert(not pcall(function() event.once("a", "") end)) + assert(not pcall(function() event.once(false, false) end)) + assert(event.emit("") == nil) + event.clear_all() + return 1 +end diff --git a/test/lua/http/test_http_chunked_framing.lua b/test/lua/http/test_http_chunked_framing.lua new file mode 100644 index 00000000..e0153e5e --- /dev/null +++ b/test/lua/http/test_http_chunked_framing.lua @@ -0,0 +1,137 @@ +function chunked_http_server(typ, connid, req) + assert(typ == "request") + if req.path == "/request" then + assert(req.body == "abcde" and req.query == "mode=chunk") + return {status = 201, headers = {["Transfer-Encoding"] = "ChUnKeD"}, body = "3;name=value \t\r\nabc\r\n2\r\nde\r\n0\r\nX-Trailer: done\r\n\r\n"}, 99 + end + if req.path == "/empty" then + return {headers = {["Transfer-Encoding"] = "chunked"}, body = "0\r\n\r\n"} + end + if req.path == "/badhex" then + return {headers = {["Transfer-Encoding"] = "chunked"}, body = "nothex\r\na\r\n0\r\n\r\n"} + end + if req.path == "/empty-size" then + return {headers = {["Transfer-Encoding"] = "chunked"}, body = "\r\n"} + end + if req.path == "/bad-end" then + return {headers = {["Transfer-Encoding"] = "chunked"}, body = "1\r\naXX0\r\n\r\n"} + end + if req.path == "/too-large" then + return {headers = {["Transfer-Encoding"] = "chunked"}, body = "ffffffffffffffff\r\n"} + end + if req.path == "/partial-size" then + return {headers = {["Transfer-Encoding"] = "chunked"}, body = "a"} + end + if req.path == "/partial-body" then + return {headers = {["Transfer-Encoding"] = "chunked"}, body = "5\r\nab"} + end + if req.path == "/partial-trailer" then + return {headers = {["Transfer-Encoding"] = "chunked"}, body = "0\r\nX-Trailer: unfinished\r\n"} + end + if req.path == "/oversized-header" then + return {headers = {["X-Large"] = string.rep("h", 300000)}, body = ""} + end + local status = tonumber(string.sub(req.path, 2)) + return {status = status, headers = {["Server"] = "custom"}, body = ""} +end + +function chunked_http_done(req, err, response) + req.done = true + req.error = err + if response ~= nil then + req.result_body = response.body + req.result_status = response.status + end +end + +local function await_chunked_request(req, label) + for i = 1, 3000 do + runtime.tick() + if req.done then break end + os.sleep(1) + end + local done = req.done + req:close() + assert(done, "HTTP completion timeout: " .. tostring(label)) +end + +function test_http_chunked_framing() + -- Malformed/incomplete chunk streams finish when the peer closes. Use the + -- server's bounded idle timeout rather than waiting for its 10-second default. + local server = http.server({ip = "127.0.0.1", port = 0, timeout_ms = 250}) + server:dispatch("chunked_http_server") + local base = "http://127.0.0.1:" .. tostring(server:get_port()) + local request = http.request({method = "POST", url = base .. "/request?mode=chunk", version = 10, headers = {["Transfer-Encoding"] = "chunked"}, body = "3\r\nabc\r\n2\r\nde\r\n0\r\n\r\n"}, "chunked_http_done") + await_chunked_request(request, "chunked request") + assert(request.error == nil and request.result_status == 201 and request.result_body == "abcde") + request = http.get(base .. "/empty", "chunked_http_done") + await_chunked_request(request, "empty chunk") + assert(request.error == nil and request.result_body == "") + local invalid = {"badhex", "empty-size", "bad-end", "too-large", "partial-size", "partial-body", "partial-trailer", "oversized-header"} + for i = 1, #invalid do + request = http.get(base .. "/" .. invalid[i], "chunked_http_done") + await_chunked_request(request, invalid[i]) + assert(type(request.error) == "string" and #request.error > 0, invalid[i]) + end + request = http.request({url = base .. "/empty", headers = {["X-Large"] = string.rep("h", 300000)}}, "chunked_http_done") + await_chunked_request(request, "oversized request header") + assert(type(request.error) == "string") + local statuses = {204, 301, 302, 400, 404, 500} + for i = 1, #statuses do + request = http.get(base .. "/" .. tostring(statuses[i]), "chunked_http_done") + await_chunked_request(request, tostring(statuses[i])) + assert(request.error == nil and request.result_status == statuses[i]) + end + server:close() + return 1 +end + +function test_http_configuration_contracts() + assert(not pcall(function() return http.request(1) end)) + assert(not pcall(function() return http.server(1) end)) + assert(not pcall(function() return http.server({port = 0, tls = true}) end)) + assert(not pcall(function() return http.server({port = 0, ip = "not-an-address"}) end)) + local server = http.server({port = 0, tls = 0, backlog = 8}) + server:close() + server = http.server({port = 0, tls = "disable"}) + server:close() + local urls = {"http://[", "ftp://localhost/file", "http:/missing-host"} + for i = 1, #urls do + local request = http.request({url = urls[i], tls_verify = "false", timeout_ms = 100}, "chunked_http_done") + await_chunked_request(request, urls[i]) + assert(type(request.error) == "string" and #request.error > 0) + end + return 1 +end + +function deferred_http_handler(typ, connid, request) + assert(typ == "request" and request.path == "/deferred") + remember_http_connection(connid) + return nil +end + +function test_http_deferred_reply() + assert(not pcall(function() http.request(false) end)) + local server = http.server({ip = "127.0.0.1", port = 0}) + server:dispatch("deferred_http_handler") + local request = http.get("http://127.0.0.1:" .. tostring(server:get_port()) .. "/deferred", "chunked_http_done") + local connid = 0 + for i = 1, 5000 do + runtime.tick() + connid = last_http_connection() + if connid > 0 then break end + os.sleep(1) + end + assert(connid > 0) + assert(not server:reply(-1, "missing connection")) + local ok, message = pcall(function() server:reply(connid, {reason = "bad\r\nreason"}) end) + assert(not ok and string.find(message, "reason", 1, true)) + ok, message = pcall(function() server:reply(connid, {headers = {invalid = "bad\r\nheader"}}) end) + assert(not ok and string.find(message, "header", 1, true)) + assert(server:reply(connid, {status = 202, reason = "Deferred", headers = {["X-Test"] = "retained"}, body = "deferred body"})) + await_chunked_request(request, "deferred reply") + assert(request.error == nil and request.result_status == 202 and request.result_body == "deferred body") + server:close() + assert(not server:reply(connid, "already closed")) + return 1 +end diff --git a/test/lua/ini/test_ini_encoding_contracts.lua b/test/lua/ini/test_ini_encoding_contracts.lua new file mode 100644 index 00000000..0e887501 --- /dev/null +++ b/test/lua/ini/test_ini_encoding_contracts.lua @@ -0,0 +1,15 @@ +function test_ini_encoding_contracts() + local value = {z = {flag = false}, ["a[\n"] = {["key=\0"] = 42, float = 1.25, flag = true, list = {[2] = "b", [1] = "a", z = true, y = 1.25}}} + local encoded = ini.encode(value) + assert(string.find(encoded, "[a__]", 1, true) ~= nil) + assert(string.find(encoded, "key__ = 42", 1, true) ~= nil) + assert(string.find(encoded, "list = a, b, 1.25, true", 1, true) ~= nil) + local decoded = ini.decode(encoded) + assert(decoded["a__"].float == 1.25 and decoded["a__"].flag == true and decoded.z.flag == false) + local scalars = ini.decode("[x]\nvalue=null\nleading=001\n") + assert(scalars.x.value == nil and scalars.x.leading == "001") + assert(not pcall(function() return ini.decode("a=one\0b=two") end)) + assert(not pcall(function() return ini.decode("[unfinished\n") end)) + assert(not pcall(function() return ini.encode(1) end)) + return 1 +end diff --git a/test/lua/io/test_io_numeric_read_contracts.lua b/test/lua/io/test_io_numeric_read_contracts.lua new file mode 100644 index 00000000..c1c16620 --- /dev/null +++ b/test/lua/io/test_io_numeric_read_contracts.lua @@ -0,0 +1,33 @@ +function test_numeric_read_contracts() + local file = io.tmpfile() + assert(file ~= nil) + local original = io.input() + local ok, err = pcall(function() + file:write("abc\n123\nZ") + file:seek("set", 0) + assert(file:read(0) == "") + assert(file:read(3) == "abc") + assert(file:read() == "") + assert(not pcall(function() return file:read(-1) end)) + assert(not pcall(function() return file:read(67108865) end)) + assert(not pcall(function() return file:read("67108865") end)) + assert(not pcall(function() return file:read("999999999999999999999999999999") end)) + assert(not pcall(function() return file:read("*invalid") end)) + assert(not pcall(function() return file:read(true) end)) + io.input(file) + assert(io.read() == "123") + local first, last = io.read(1, 1) + assert(first == "Z" and last == nil) + assert(io.read(0) == nil) + file:seek("set", 0) + local iterator = io.lines() + assert(iterator() == "abc" and iterator() == "123" and iterator() == "Z") + assert(iterator() == nil) + local pipe, message = io.popen("") + assert(pipe == nil and message == "missing command") + end) + io.input(original) + file:close() + assert(ok, err) + return 1 +end diff --git a/test/lua/jit/test_vararg_expansion_boundaries.lua b/test/lua/jit/test_vararg_expansion_boundaries.lua new file mode 100644 index 00000000..964bd4ae --- /dev/null +++ b/test/lua/jit/test_vararg_expansion_boundaries.lua @@ -0,0 +1,17 @@ +function expansion_values() return 1, 2, 3, 4 end +function expansion_prefix(a, b, ...) return a, b, ... end +function expansion_forward(...) return expansion_prefix(...) end + +function test_vararg_expansion_boundaries() + local a, b, c, d = expansion_prefix(expansion_values()) + assert(a == 1 and b == 2 and c == 3 and d == 4) + local e, f, g, h, i, j, k = expansion_prefix(10, 20, 30, expansion_values()) + assert(e == 10 and f == 20 and g == 30 and h == 1 and i == 2 and j == 3 and k == 4) + a, b, c = expansion_prefix(10) + assert(a == 10 and b == nil and c == nil) + a, b, c, d = expansion_forward(expansion_values()) + assert(a == 1 and b == 2 and c == 3 and d == 4) + a, b, c = expansion_prefix(expansion_values(), 9) + assert(a == 1 and b == 9 and c == nil) + return 1 +end diff --git a/test/lua/math/test_for_int64_overflow.lua b/test/lua/math/test_for_int64_overflow.lua index c4edc2f7..f082075e 100644 --- a/test/lua/math/test_for_int64_overflow.lua +++ b/test/lua/math/test_for_int64_overflow.lua @@ -49,3 +49,21 @@ function test_for_int64_overflow() return 100 end + +local function count_clamped_for(start, limit, step) + local count = 0 + for value = start, limit, step do + count = count + 1 + if count > 4 then break end + end + return count +end + +function test_for_clamped_float_limits() + assert(count_clamped_for(0, math.huge, -1) == 0) + assert(count_clamped_for(math.maxinteger, math.huge, 1) == 1) + assert(count_clamped_for(math.maxinteger, 1e30, 1) == 1) + assert(count_clamped_for(math.mininteger, -1e30, -1) == 1) + assert(count_clamped_for(0, -math.huge, 1) == 0) + return 1 +end diff --git a/test/lua/mysql/test_mysql_pool_lifecycle.lua b/test/lua/mysql/test_mysql_pool_lifecycle.lua new file mode 100644 index 00000000..1feb0dbc --- /dev/null +++ b/test/lua/mysql/test_mysql_pool_lifecycle.lua @@ -0,0 +1,37 @@ +function test_pool_lifecycle_contracts() + assert(not pcall(function() mysql_pool.create(false) end)) + for _, ssl in ipairs({false, true, 0, 1, "require", "true", "enable", "disable"}) do + local pool = mysql_pool.create({host = "127.0.0.1", port = 1, + user = "root", password = "invalid", db = "test", pool_size = 1, + ssl = ssl, ssl_ca = "", max_retries = 0, heartbeat_ms = 0}) + assert(pool:stats()[1] == 1) + assert(pool:acquire() == nil) + assert(pool:release(false) == nil) + assert(pool:release({}) == nil) + pool:close() + pool:close() + end + local pool = mysql_pool.create({host = "127.0.0.1", port = 3306, + user = "root", password = "root", db = "test", pool_size = 1, + ssl = false, heartbeat_ms = 0}) + local conn = nil + for i = 1, 5000 do + runtime.tick() + conn = pool:acquire() + if conn then break end + os.sleep(1) + end + assert(conn ~= nil) + local err = conn:error() + assert(type(err) == "table" and err[1] == 0 and err[2] == 0) + -- Closing the owner while a wrapper is borrowed invalidates the wrapper, + -- not only the pool's internal connection storage. + pool:close() + assert(conn:error() == nil) + local ok, message = pcall(function() conn:query("SELECT 1", "unused_pool_callback") end) + assert(not ok and string.find(message, "closed", 1, true)) + conn:close() + pool:release(conn) + pool:close() + return 1 +end diff --git a/test/lua/mysql/test_mysql_streamed_results.lua b/test/lua/mysql/test_mysql_streamed_results.lua new file mode 100644 index 00000000..4723d495 --- /dev/null +++ b/test/lua/mysql/test_mysql_streamed_results.lua @@ -0,0 +1,188 @@ +package "MysqlStream" + +function on_connect(conn, err, success) + conn.connected = (success == 1) + conn.connect_error = err +end + +function on_result(conn, err, result, label) + conn.result_error = err + local count = conn.callback_count + 1 + conn.callback_count = count + conn.results[count] = result + conn.labels[count] = label +end + +local function connect_with_password(password) + local conn = mysql.connect({host = "127.0.0.1", port = 3306, user = "root", password = password, db = "test"}, "MysqlStream.on_connect") + for i = 1, 5000 do + runtime.tick() + if conn.connected or conn.connect_error then break end + os.sleep(1) + end + return conn +end + +local function wait_results(conn, count) + for i = 1, 5000 do + runtime.tick() + if conn.result_error or conn.callback_count >= count then break end + os.sleep(1) + end + assert(conn.result_error == nil, conn.result_error) + assert(conn.callback_count == count) +end + +function test_large_and_queued_results() + local conn = connect_with_password("root") + if not conn.connected then + conn:close() + conn = connect_with_password("") + end + assert(conn.connected, conn.connect_error) + local ok, err = pcall(function() + conn.callback_count = 0 + conn.results = {} + conn.labels = {} + conn:query("SELECT REPEAT('x', 262144) AS payload; SELECT SLEEP(0.02) AS waited; SELECT 7 AS value", "MysqlStream.on_result", "multi") + wait_results(conn, 3) + assert(#conn.results[1][3][1][1] == 262144) + assert(string.sub(conn.results[1][3][1][1], 1, 3) == "xxx") + assert(conn.results[2][3][1][1] == 0 and conn.results[3][3][1][1] == 7) + assert(conn.labels[1] == "multi" and conn.labels[3] == "multi") + conn.callback_count = 0 + conn.results = {} + conn.labels = {} + conn:query("SELECT SLEEP(0.02) AS waited", "MysqlStream.on_result", "first") + conn:query("SELECT 77 AS value", "MysqlStream.on_result", "second") + wait_results(conn, 2) + assert(conn.labels[1] == "first" and conn.labels[2] == "second", "queued callback labels: " .. tostring(conn.labels[1]) .. ", " .. tostring(conn.labels[2])) + assert(conn.results[1][3][1][1] == 0 and conn.results[2][3][1][1] == 77) + end) + conn:close() + assert(ok, err) + return 1 +end + +local function reset_result(conn) + conn.callback_count = 0 + conn.result_error = nil + conn.results = {} + conn.labels = {} +end + +local function wait_error(conn, text) + for i = 1, 5000 do + runtime.tick() + if conn.callback_count > 0 then break end + os.sleep(1) + end + assert(conn.callback_count == 1 and type(conn.result_error) == "string") + if text then assert(string.find(string.lower(conn.result_error), text, 1, true)) end +end + +function test_statement_and_late_multi_result_errors() + local conn = connect_with_password("root") + if not conn.connected then + conn:close() + conn = connect_with_password("") + end + assert(conn.connected, conn.connect_error) + local ok, err = pcall(function() + reset_result(conn) + conn:stmt_prepare("THIS IS NOT SQL", "MysqlStream.on_result", "bad-prepare") + wait_error(conn, nil) + assert(conn.labels[1] == "bad-prepare") + reset_result(conn) + conn:query("CREATE TEMPORARY TABLE fakelua_module_stmt(value INT UNIQUE)", "MysqlStream.on_result", "create") + wait_results(conn, 1) + reset_result(conn) + conn:stmt_prepare("INSERT INTO fakelua_module_stmt VALUES(?)", "MysqlStream.on_result", "prepare") + wait_results(conn, 1) + local statement = conn.results[1] + assert(type(statement) == "number" and statement > 0) + reset_result(conn) + conn:stmt_execute(statement, {7}, "MysqlStream.on_result", "insert") + wait_results(conn, 1) + reset_result(conn) + conn:stmt_execute(statement, {7}, "MysqlStream.on_result", "duplicate") + wait_error(conn, "duplicate") + assert(conn.labels[1] == "duplicate") + conn:stmt_close(statement) + reset_result(conn) + conn:stmt_execute(statement, {8}, "MysqlStream.on_result", "closed-statement") + wait_error(conn, "not prepared") + reset_result(conn) + conn:query("SELECT 1; SELECT missing_column FROM fakelua_module_stmt", "MysqlStream.on_result", "late-error") + wait_error(conn, nil) + assert(conn.labels[1] == "late-error") + reset_result(conn) + conn:query("SELECT 9", "MysqlStream.on_result", "recovered") + wait_results(conn, 1) + assert(conn.results[1][3][1][1] == 9) + end) + conn:close() + assert(ok, err) + return 1 +end + +function test_row_stream_continuations() + local conn = connect_with_password("root") + if not conn.connected then conn:close() conn = connect_with_password("") end + assert(conn.connected, conn.connect_error) + local ok, message = pcall(function() + reset_result(conn) + local source = "(SELECT 0 AS n UNION ALL SELECT 1)" + local sql = "SELECT REPEAT('x',1024) AS payload, SLEEP(0.002) AS waited FROM " .. source .. " AS a" + for _, alias in ipairs({"b", "c", "d", "e", "f"}) do sql = sql .. " CROSS JOIN " .. source .. " AS " .. alias end + conn:query(sql .. "; SELECT 9 AS final_value", "MysqlStream.on_result", "row-stream") + wait_results(conn, 2) + local rows = conn.results[1][3] + assert(#rows == 64) + for i = 1, #rows do assert(#rows[i][1] == 1024 and rows[i][2] == 0) end + assert(conn.results[2][3][1][1] == 9) + assert(conn.labels[1] == "row-stream" and conn.labels[2] == "row-stream") + end) + conn:close() + assert(ok, message) + return 1 +end + + +function test_configuration_and_statement_parameter_contracts() + assert(not pcall(function() mysql.connect(false, "MysqlStream.on_connect") end)) + assert(not pcall(function() mysql.connect({user = "root", timeout_ms = -1}, "MysqlStream.on_connect") end)) + assert(not pcall(function() mysql.connect({user = "root", timeout_ms = 2147483648}, "MysqlStream.on_connect") end)) + for _, mode in ipairs({0, 1, "require", "enable", "disable"}) do + local unused = mysql.connect({host = "127.0.0.1", user = "root", ssl = mode}, "MysqlStream.on_connect") + unused:close() + end + local conn = connect_with_password("root") + if not conn.connected then conn:close() conn = connect_with_password("") end + assert(conn.connected, conn.connect_error) + local ok, message = pcall(function() + reset_result(conn) + conn:stmt_prepare("SELECT CAST(? AS SIGNED) AS flag, ? AS absent", "MysqlStream.on_result", "prepare") + wait_results(conn, 1) + local statement = conn.results[1] + reset_result(conn) + conn:stmt_execute(statement, {true, n = 2}, "MysqlStream.on_result", "bool-nil") + wait_results(conn, 1) + assert(conn.results[1][3][1][1] == 1 and conn.results[1][3][1][2] == nil) + assert(not pcall(function() conn:stmt_execute(statement, {n = 65536}, "MysqlStream.on_result") end)) + reset_result(conn) + conn:stmt_execute(statement, {true}, "MysqlStream.on_result", "mismatch") + wait_error(conn, "count") + conn:stmt_close(statement) + reset_result(conn) + local source = "(SELECT 0 AS n UNION ALL SELECT 1)" + local sql = "SELECT REPEAT('s',1024), SLEEP(0.002) FROM " .. source .. " AS a" + for _, alias in ipairs({"b", "c", "d", "e", "f"}) do sql = sql .. " CROSS JOIN " .. source .. " AS " .. alias end + conn:query(sql, "MysqlStream.on_result", "single-stream") + wait_results(conn, 1) + assert(#conn.results[1][3] == 64) + end) + conn:close() + assert(ok, message) + return 1 +end diff --git a/test/lua/native/test_native_snapshot_removal.lua b/test/lua/native/test_native_snapshot_removal.lua new file mode 100644 index 00000000..8345e0c0 --- /dev/null +++ b/test/lua/native/test_native_snapshot_removal.lua @@ -0,0 +1,34 @@ +function test_snapshot_removal() + local object = snapshot_object() + local count = 0 + for key, value in pairs(object) do + assert(value >= 1 and value <= 24) + assert(key == "field_" .. tostring(value)) + count = count + 1 + end + assert(count == 24) + object.field_1 = nil + object.field_12 = nil + object.field_24 = nil + assert(object.field_1 == nil and object.field_12 == nil and object.field_24 == nil) + count = 0 + for key, value in pairs(object) do + assert(value ~= 1 and value ~= 12 and value ~= 24) + assert(key == "field_" .. tostring(value)) + count = count + 1 + end + assert(count == 21) + -- Grow an already materialized snapshot; existing keys/values must survive. + for i = 25, 48 do object["field_" .. tostring(i)] = i end + count = 0 + for key, value in pairs(object) do + assert(key == "field_" .. tostring(value)) + count = count + 1 + end + assert(count == 45) + for i = 25, 48 do object["field_" .. tostring(i)] = nil end + count = 0 + for key, value in pairs(object) do count = count + 1 end + assert(count == 21) + return 1 +end diff --git a/test/lua/net/test_net_configuration_contracts.lua b/test/lua/net/test_net_configuration_contracts.lua new file mode 100644 index 00000000..d7ec7dca --- /dev/null +++ b/test/lua/net/test_net_configuration_contracts.lua @@ -0,0 +1,35 @@ +function test_net_configuration_contracts() + local function rejects(cfg, text) + local ok, message = pcall(function() net.server(cfg) end) + assert(not ok and string.find(message, text, 1, true)) + end + rejects({port = -1}, "port") + rejects({port = 65536}, "port") + rejects({port = 19970, maxconn = 0}, "maxconn") + rejects({port = 19970, maxconn = 100001}, "maxconn") + rejects({port = 19970, send_buf_size = 2147483648}, "send_buf_size") + rejects({port = 19970, recv_buf_size = 2147483648}, "recv_buf_size") + rejects({port = 19970, max_packet_len = 2147483648}, "max_packet_len") + rejects({port = 19970, tls = true}, "cert and key") + rejects({port = 19970, tls = 1, tls_verify = 1}, "cert and key") + rejects({port = 19970, tls = "require", tls_verify = "false"}, "cert and key") + rejects({port = 19970, ip = "not-an-address"}, "failed to listen") + for _, tls in ipairs({false, 0, "false", "disable"}) do + local server = net.server({port = 19970, tls = tls, tls_verify = "false", + recv_buf_size = 1024, max_packet_len = 512, framer = "unknown"}) + assert(not pcall(function() server:dispatch(false) end)) + assert(not server:close_connection(-1)) + assert(not server:close_connection(1000000)) + server:close() + assert(not server:close_connection(0)) + end + assert(not pcall(function() net.udp_client(false) end)) + assert(not pcall(function() net.udp_server(false) end)) + assert(not pcall(function() net.udp_client({port = 0}) end)) + assert(not pcall(function() net.udp_server({port = 65536}) end)) + assert(not pcall(function() net.udp_server({ip = "not-an-address", port = 0}) end)) + local socket = net.udp_server({port = 0}) + assert(not pcall(function() socket:sendto("x", "127.0.0.1", 65536) end)) + socket:close() + return 1 +end diff --git a/test/lua/net/test_net_native_parser.lua b/test/lua/net/test_net_native_parser.lua new file mode 100644 index 00000000..c56e198a --- /dev/null +++ b/test/lua/net/test_net_native_parser.lua @@ -0,0 +1,105 @@ +function native_parser_server_event(kind, connid, data, length, reason) + if kind == "recv" then + native_parser_host_check(data) + return "echo", data + end + return nil +end + +local function wait_native_parser(count) + for i = 1, 5000 do + runtime.tick() + if native_parser_received_count() >= count then break end + os.sleep(1) + end + assert(native_parser_received_count() == count) +end + +function test_native_parser_and_dispatch_recovery() + local server = net.server({ip = "127.0.0.1", port = 19971, parser = "native_three_byte_parser"}) + server:dispatch("native_parser_server_event") + local client = net.client({ip = "127.0.0.1", port = 19971, parser = "native_three_byte_parser"}) + client:dispatch("native_parser_client_event") + for i = 1, 100 do runtime.tick() os.sleep(1) end + assert(client:send("abcdef")) + wait_native_parser(2) + assert(client:send("err")) + local failed = false + for i = 1, 5000 do + local ok, message = pcall(function() runtime.tick() end) + if not ok then + assert(string.find(message, "network dispatch failure", 1, true)) + failed = true + break + end + os.sleep(1) + end + assert(failed) + assert(client:send("ghi")) + wait_native_parser(3) + assert(server:close_connection(0)) + runtime.tick() + assert(not server:close_connection(0)) + client:close() + server:close() + return 1 +end + + +function contract_parser_default(data) return data, nil end +function contract_parser_clamped(data) return data, #data + 100 end +function contract_parser_wait(data) return nil end +function contract_parser_empty(data) return "", nil end + +function custom_contract_server_event(kind, connid, data, length, reason) + if kind == "recv" then return "echo", data end + return nil +end + +function custom_contract_client_event(kind, connid, data, length, reason) + if kind == "recv" then + custom_contract_seen(data) + return "close", nil + end + return nil +end + +function test_custom_parser_return_contracts() + local parsers = {"contract_parser_default", "contract_parser_clamped", "contract_parser_wait", "contract_parser_empty", "missing_contract_parser"} + for i = 1, #parsers do + local port = 19980 + i + local server = net.server({ip = "127.0.0.1", port = port, framer = "custom", parser = parsers[i]}) + server:dispatch(string.rep("custom", 1) .. "_contract_server_event") + local client = net.client({ip = "127.0.0.1", port = port, framer = "raw"}) + client:dispatch("custom_contract_client_event") + for j = 1, 100 do + runtime.tick() + if server:get_conn_count() > 0 then break end + os.sleep(1) + end + assert(server:get_conn_count() == 1) + assert(not pcall(function() server:send(0) end)) + assert(server:send(0, false)) + assert(client:send(false)) + assert(client:send("abc")) + if i <= 2 then + for j = 1, 1000 do + runtime.tick() + if custom_contract_received() >= i then break end + os.sleep(1) + end + assert(custom_contract_received() == i) + assert(server:get_recv_count() == 1) + else + for j = 1, 10 do runtime.tick() os.sleep(1) end + assert(server:get_recv_count() == 0) + end + client:close() + server:close() + end + local udp = net.udp_server({ip = "127.0.0.1", port = 19988}) + assert(not pcall(function() udp:send("x", "127.0.0.1", 0) end)) + udp:close() + assert(not pcall(function() net.udp_client(false) end)) + return 1 +end diff --git a/test/lua/net/test_net_native_udp_callbacks.lua b/test/lua/net/test_net_native_udp_callbacks.lua new file mode 100644 index 00000000..3e16380f --- /dev/null +++ b/test/lua/net/test_net_native_udp_callbacks.lua @@ -0,0 +1,21 @@ +function test_native_udp_callbacks() + local server = net.udp_server({ip = "127.0.0.1", port = 0}) + local client = net.udp_server({ip = "127.0.0.1", port = 0}) + server:dispatch("cpp_udp_echo") + client:dispatch("cpp_udp_receive") + local payload = "a\0b" + assert(client:send(payload, "127.0.0.1", server:get_port())) + for i = 1, 3000 do + runtime.tick() + if client:get_last_data() == payload then break end + os.sleep(1) + end + local received = client:get_last_data() + local server_event = server:get_events() + local client_event = client:get_events() + server:close() + client:close() + assert(received == payload and server_event == "recv" and client_event == "recv") + assert(server:get_events() == nil and client:get_events() == nil) + return 1 +end diff --git a/test/lua/process/test_process_options.lua b/test/lua/process/test_process_options.lua new file mode 100644 index 00000000..b0c46632 --- /dev/null +++ b/test/lua/process/test_process_options.lua @@ -0,0 +1,17 @@ +function test_process_options() + assert(not pcall(function() process.run(false) end)) + assert(not pcall(function() process.run({}) end)) + assert(not pcall(function() process.run({"env"}, false) end)) + assert(not pcall(function() process.run({"env"}, {cwd = false}) end)) + assert(not pcall(function() process.run({"env"}, {env = false}) end)) + assert(not pcall(function() process.run({"env"}, {env = {bad = {}}}) end)) + local previous = os.getenv("FAKELUA_MODULE_ENV_TEST") + local path = os.getenv("PATH") + assert(type(path) == "string") + local output, errors, code = process.run({"env"}, {cwd = ".", + env = {PATH = path, FAKELUA_MODULE_ENV_TEST = "module-env-marker"}}) + assert(code == 0 and errors == "") + assert(string.find(output, "FAKELUA_MODULE_ENV_TEST=module-env-marker", 1, true)) + assert(os.getenv("FAKELUA_MODULE_ENV_TEST") == previous) + return 1 +end diff --git a/test/lua/protobuf/test_protobuf_nested_containers.lua b/test/lua/protobuf/test_protobuf_nested_containers.lua new file mode 100644 index 00000000..69652b67 --- /dev/null +++ b/test/lua/protobuf/test_protobuf_nested_containers.lua @@ -0,0 +1,53 @@ +function test_protobuf_nested_containers() + assert(protobuf.load([[ + syntax = "proto3"; + message ContainerItem { int32 value = 1; } + message Container { + map entries = 1; + repeated ContainerItem items = 2; + ContainerItem child = 3; + repeated int32 numbers = 4 [packed = false]; + } + ]]) == "ok") + local value = { + entries = { first = {value = 7}, second = {value = 9} }, + items = {{value = 11}, {value = 13}}, + child = {value = 15}, numbers = {1, -2, 3} + } + local decoded = protobuf.decode("Container", protobuf.encode("Container", value)) + assert(decoded.entries.first.value == 7 and decoded.entries.second.value == 9) + assert(#decoded.items == 2 and decoded.items[1].value == 11 and decoded.items[2].value == 13) + assert(decoded.child.value == 15 and decoded.numbers[2] == -2) + local empty = protobuf.decode("Container", protobuf.encode("Container", {items = {}, numbers = {}})) + assert(empty.child == nil) + return 1 +end + +function test_protobuf_metadata_contracts() + assert(protobuf.load([[ + enum MetadataEnum { ZERO = 0; } + message MetadataChild { int32 value = 1; } + message MetadataKinds { + double a = 1; float b = 2; int64 c = 3; uint64 d = 4; + int32 e = 5; fixed64 f = 6; fixed32 g = 7; bool h = 8; + string i = 9; bytes j = 10; uint32 k = 11; MetadataEnum l = 12; + sfixed32 m = 13; sfixed64 n = 14; sint32 o = 15; sint64 p = 16; + MetadataChild q = 17; + } + ]]) == "ok") + local expected = {"double", "float", "int64", "uint64", "int32", "fixed64", "fixed32", "bool", "string", "bytes", "uint32", "enum", "sfixed32", "sfixed64", "sint32", "sint64", "message"} + local fields = protobuf.fields("MetadataKinds") + assert(#fields == #expected) + for i = 1, #expected do + assert(fields[i].number == i and fields[i].type == expected[i]) + end + assert(fields[12].type_name == "MetadataEnum" and fields[17].type_name == "MetadataChild") + assert(not pcall(function() return protobuf.load() end)) + assert(not pcall(function() return protobuf.encode() end)) + assert(not pcall(function() return protobuf.decode() end)) + assert(not pcall(function() return protobuf.fields() end)) + assert(not pcall(function() return protobuf.fields("NotDefined") end)) + assert(not pcall(function() return protobuf.encode("NotDefined", {}) end)) + assert(not pcall(function() return protobuf.decode("NotDefined", "") end)) + return 1 +end diff --git a/test/lua/protobuf/test_protobuf_wire_compatibility.lua b/test/lua/protobuf/test_protobuf_wire_compatibility.lua new file mode 100644 index 00000000..d63ca487 --- /dev/null +++ b/test/lua/protobuf/test_protobuf_wire_compatibility.lua @@ -0,0 +1,27 @@ +function test_protobuf_wire_compatibility() + assert(protobuf.load([[ + message WireChild { int32 value = 1; WireChild child = 2; } + message WireCompatible { + repeated WireChild items = 1; + repeated string names = 2; + repeated double numbers = 3; + map entries = 4; + } + ]]) == "ok") + local decoded = protobuf.decode("WireCompatible", protobuf.encode("WireCompatible", {items = {value = 23}, names = "one", numbers = 7})) + assert(decoded.items[1].value == 23 and decoded.names[1] == "one" and decoded.numbers[1] == 7) + local valid = protobuf.decode("WireCompatible", string.char(34, 7, 10, 1, 97, 16, 7, 24, 1, 72, 1)) + assert(valid.entries.a == 7) + local bad_key = protobuf.decode("WireCompatible", string.char(34, 4, 8, 1, 16, 7)) + assert(next(bad_key.entries) == nil) + local bad_value = protobuf.decode("WireCompatible", string.char(34, 6, 10, 1, 97, 18, 1, 98)) + assert(next(bad_value.entries) == nil) + local mixed = protobuf.decode("WireCompatible", protobuf.encode("WireCompatible", {items = {99, value = 31}, names = {}, numbers = {}})) + assert(mixed.items[1].value == 31 and mixed.names == nil and mixed.numbers == nil) + local root, cursor = {}, nil + cursor = root + for i = 1, 70 do cursor.child = {} cursor = cursor.child end + local ok, message = pcall(function() protobuf.encode("WireChild", root) end) + assert(not ok and string.find(message, "nesting too deep", 1, true)) + return 1 +end diff --git a/test/lua/random/test_random_additional_contracts.lua b/test/lua/random/test_random_additional_contracts.lua new file mode 100644 index 00000000..faa83f3e --- /dev/null +++ b/test/lua/random/test_random_additional_contracts.lua @@ -0,0 +1,12 @@ +function test_random_contracts() + local a, b = random.new(123), random.new(123) + for i = 1, 20 do + assert(a:int(-9223372036854775807 - 1, 9223372036854775807) == b:int(-9223372036854775807 - 1, 9223372036854775807)) + end + a:set_state("0xabcdef0123456789") + assert(a:get_state() == "0xABCDEF0123456789") + assert(not pcall(function() a:set_state(false) end)) + assert(not pcall(function() a:weighted(false) end)) + assert(not pcall(function() a:dice(2, 9223372036854775807) end)) + return 1 +end diff --git a/test/lua/redis/test_redis_handshake_contracts.lua b/test/lua/redis/test_redis_handshake_contracts.lua new file mode 100644 index 00000000..24faade2 --- /dev/null +++ b/test/lua/redis/test_redis_handshake_contracts.lua @@ -0,0 +1,92 @@ +package "RedisHandshake" + +function on_connect(conn, err, success) + conn.connect_done = true + conn.connected = (success == 1) + conn.connect_error = err +end + +function on_command(conn, err, result) + conn.command_done = true + conn.command_error = err + conn.command_result = result + if conn.close_after_result then conn:close() end +end + +local function await_connection(conn) + for i = 1, 3000 do + runtime.tick() + if conn.connect_done then break end + os.sleep(1) + end + assert(conn.connect_done) +end + +local function command(conn, args) + conn.command_done = false + conn.command_error = nil + conn:command(args, "RedisHandshake.on_command") + for i = 1, 3000 do + runtime.tick() + if conn.command_done then break end + os.sleep(1) + end + assert(conn.command_done) +end + +function test_handshake_contracts() + local users = {"default", "fakelua_nonexistent_user"} + for i = 1, #users do + local failed = redis.connect({host = "127.0.0.1", port = 6379, user = users[i], password = "fakelua_intentionally_invalid", timeout_ms = 1000}, "RedisHandshake.on_connect") + await_connection(failed) + local accepted = failed.connected + local message = failed.connect_error + failed:close() + assert(not accepted and type(message) == "string" and #message > 0) + end + local conn = redis.connect({host = "127.0.0.1", port = 6379, db = 1, timeout_ms = 1000}, "RedisHandshake.on_connect") + await_connection(conn) + assert(conn.connected, conn.connect_error) + local ok, err = pcall(function() + command(conn, {"PING"}) + assert(conn.command_error == nil and conn.command_result == "PONG") + command(conn, {"HELLO", "3"}) + if conn.command_error == nil then + assert(type(conn.command_result) == "table" and conn.command_result.proto == 3) + command(conn, {"EVAL", "redis.setresp(3); return true", "0"}) + assert(conn.command_error == nil and conn.command_result == true) + command(conn, {"EVAL", "redis.setresp(3); return {double = 1.25}", "0"}) + assert(conn.command_error == nil and conn.command_result == 1.25) + else + -- The Windows CI Redis 5 service predates HELLO/RESP3. + assert(string.find(conn.command_error, "unknown", 1, true) ~= nil) + end + assert(not pcall(function() return conn:command(1, "RedisHandshake.on_command") end)) + conn.close_after_result = true + command(conn, {"PING"}) + assert(conn.command_error == nil and conn.command_result == "PONG") + end) + conn:close() + assert(ok, err) + assert(not pcall(function() return redis.connect(1, "RedisHandshake.on_connect") end)) + return 1 +end + + +function test_pending_connection_and_deep_reply_contracts() + local conn = redis.connect({host = "127.0.0.1", port = 6379}, "RedisHandshake.on_connect") + assert(not pcall(function() conn:command({"PING"}, "RedisHandshake.on_command") end)) + await_connection(conn) + assert(conn.connected, conn.connect_error) + local ok, message = pcall(function() + command(conn, {"EVAL", "local t = {}; local p = t; for i = 1, 70 do local n = {}; p[1] = n; p = n end; return t", "0"}) + assert(type(conn.command_error) == "string") + assert(string.find(conn.command_error, "deep", 1, true)) + command(conn, {"PING"}) + assert(conn.command_error == nil and conn.command_result == "PONG") + for i = 1, 16 do conn:command({"PING"}, "RedisHandshake.on_command") end + end) + conn:close() + assert(ok, message) + return 1 +end diff --git a/test/lua/sqlite/test_sqlite_error_contracts.lua b/test/lua/sqlite/test_sqlite_error_contracts.lua new file mode 100644 index 00000000..93ecf4f8 --- /dev/null +++ b/test/lua/sqlite/test_sqlite_error_contracts.lua @@ -0,0 +1,33 @@ +function test_sqlite_error_contracts(missing_path) + assert(not pcall(function() return sqlite.open(missing_path) end)) + local db = sqlite.open(":memory:") + local ok, err = pcall(function() + assert(not pcall(function() return db:exec("not valid SQL") end)) + assert(not pcall(function() return db:prepare("not valid SQL") end)) + assert(not pcall(function() return db:exec("SELECT abs(-9223372036854775808)") end)) + db:exec("CREATE TABLE entries(value INTEGER UNIQUE)") + local stmt = db:prepare("INSERT INTO entries VALUES (?)") + assert(not pcall(function() return stmt:bind({}) end)) + assert(not pcall(function() return stmt:bind(1, 2) end)) + stmt:bind(true) + assert(stmt:step() == nil) + stmt:reset() + stmt:bind(false) + assert(stmt:step() == nil) + stmt:reset() + stmt:bind(true) + assert(not pcall(function() return stmt:step() end)) + assert(not pcall(function() return stmt:reset() end)) + stmt:close() + assert(not pcall(function() return db:exec("INSERT INTO entries VALUES (1)") end)) + stmt = db:prepare("INSERT INTO entries VALUES (1)") + assert(not pcall(function() return stmt:step() end)) + assert(not pcall(function() return stmt:close() end)) + stmt:close() + local rows = db:exec("SELECT value FROM entries ORDER BY value") + assert(#rows == 2 and rows[1].value == 0 and rows[2].value == 1) + end) + db:close() + assert(ok, err) + return 1 +end diff --git a/test/lua/string/test_string_argument_contracts.lua b/test/lua/string/test_string_argument_contracts.lua new file mode 100644 index 00000000..adf63a13 --- /dev/null +++ b/test/lua/string/test_string_argument_contracts.lua @@ -0,0 +1,73 @@ +local function rejects(label, fn, ...) + assert(type(fn) == "function") + local ok, err = pcall(fn, ...) + assert(not ok, "expected rejection: " .. label) + assert(type(err) == "string") + assert(#err > 0) +end + +function test_string_missing_arguments() + local unary = {function(a1) return string.len(a1) end, function(a1) return string.reverse(a1) end, function(a1) return string.lower(a1) end, function(a1) return string.upper(a1) end, + function(a1) return string.trim(a1) end, function(a1) return string.trim_left(a1) end, function(a1) return string.trim_right(a1) end, + function(a1) return string.byte(a1) end, function(a1) return string.format(a1) end, function(a1) return string.dump(a1) end, function(a1) return string.pack(a1) end, + function(a1) return string.packsize(a1) end, function(a1) return load(a1) end} + assert(#unary == 13) + for _, fn in ipairs(unary) do + rejects("line 16", fn) + rejects("line 17", fn, true) + end + local binary = {function(a1, a2) return string.sub(a1, a2) end, function(a1, a2) return string.rep(a1, a2) end, function(a1, a2) return string.split(a1, a2) end, function(a1, a2) return string.starts_with(a1, a2) end, + function(a1, a2) return string.ends_with(a1, a2) end, function(a1, a2) return string.contains(a1, a2) end, function(a1, a2) return string.iequals(a1, a2) end, + function(a1, a2) return string.icontains(a1, a2) end, function(a1, a2) return string.istarts_with(a1, a2) end, function(a1, a2) return string.iends_with(a1, a2) end, + function(a1, a2) return string.find(a1, a2) end, function(a1, a2) return string.match(a1, a2) end, function(a1, a2) return string.gmatch(a1, a2) end, function(a1, a2) return string.unpack(a1, a2) end} + assert(#binary == 14) + for _, fn in ipairs(binary) do + rejects("line 25", fn) + rejects("line 26", fn, "abc") + rejects("line 27", fn, "abc", true) + end + rejects("line 29", function() return string.join() end) + rejects("line 30", function(a1) return string.join(a1) end, {}) + rejects("line 31", function(a1, a2) return string.join(a1, a2) end, true, ",") + rejects("line 32", function() return string.replace() end) + rejects("line 33", function(a1) return string.replace(a1) end, "abc") + rejects("line 34", function(a1, a2) return string.replace(a1, a2) end, "abc", "a") + rejects("line 35", function() return string.gsub() end) + rejects("line 36", function(a1) return string.gsub(a1) end, "abc") + rejects("line 37", function(a1, a2) return string.gsub(a1, a2) end, "abc", "a") + return 1 +end + +function test_string_integer_and_format_contracts() + rejects("line 42", function(a1) return string.char(a1) end, -1) + rejects("line 43", function(a1) return string.char(a1) end, 256) + rejects("line 44", function(a1) return string.char(a1) end, 1.5) + rejects("line 45", function(a1) return string.char(a1) end, true) + rejects("line 46", function(a1, a2) return string.char(a1, a2) end, 65, 256) + rejects("line 47", function(a1, a2) return string.char(a1, a2) end, 65, 1.5) + rejects("line 48", function(a1, a2) return string.char(a1, a2) end, 65, true) + rejects("line 49", function(a1, a2) return string.byte(a1, a2) end, "abc", 1.5) + rejects("line 50", function(a1, a2, a3) return string.byte(a1, a2, a3) end, "abc", 1, false) + rejects("line 51", function(a1) return string.format(a1) end, "%") + rejects("line 52", function(a1, a2) return string.format(a1, a2) end, "%k", 1) + rejects("line 53", function(a1, a2) return string.format(a1, a2) end, "%d", true) + rejects("line 54", function(a1, a2) return string.format(a1, a2) end, "%f", {}) + rejects("line 55", function(a1, a2) return string.format(a1, a2) end, "%d", 1.5) + rejects("line 56", function(a1, a2) return string.format(a1, a2) end, "%q", {}) + rejects("line 57", function(a1, a2) return string.format(a1, a2) end, "%q", function() end) + assert(string.format("%s", true) == "true") + rejects("line 59", function(a1, a2, a3) return string.gsub(a1, a2, a3) end, "abc", "a", "%") + rejects("line 60", function(a1, a2, a3) return string.gsub(a1, a2, a3) end, "abc", "a", "%x") + rejects("line 61", function(a1, a2, a3) return string.gsub(a1, a2, a3) end, "abc", "a", "%9") + assert(string.byte(string.char(65.0)) == 65) + assert(string.format("%q", true) == "true") + assert(string.format("%q", nil) == "nil") + assert(string.format("%d", "17") == "17") + assert(string.format("%.1f", "1.5") == "1.5") + assert(string.format("%q", 0 / 0) == "(0/0)") + assert(string.format("%q", math.huge) == "1e9999") + assert(string.format("%q", -math.huge) == "-1e9999") + assert(string.format("%q", 1.5) == "0x1.8p+0") + assert(string.format("%6.3s", "abcdef") == " abc") + return 1 +end diff --git a/test/lua/string/test_string_binary_boundaries.lua b/test/lua/string/test_string_binary_boundaries.lua new file mode 100644 index 00000000..9ddbe373 --- /dev/null +++ b/test/lua/string/test_string_binary_boundaries.lua @@ -0,0 +1,90 @@ +local function rejects(label, fn, ...) + assert(type(fn) == "function") + local ok, err = pcall(fn, ...) + assert(not ok and type(err) == "string", "expected rejection: " .. label) +end + +function test_string_binary_roundtrips() + for _, endian in ipairs({"<", ">", "="}) do + for _, fmt in ipairs({"b", "B", "h", "H", "l", "L", "j", "J", "T", "i1", "i2", "i3", "i4", "i5", "i6", "i7", "i8", "I1", "I2", "I3", "I4", "I5", "I6", "I7", "I8"}) do + local bytes = string.pack(endian .. fmt, 123) + local value, nextpos = string.unpack(endian .. fmt, bytes) + assert(value == 123 and nextpos == #bytes + 1) + assert(#bytes == string.packsize(endian .. fmt)) + rejects("line 14", function(a1, a2) return string.unpack(a1, a2) end, endian .. fmt, "") + end + for _, fmt in ipairs({"f", "d"}) do + local bytes = string.pack(endian .. fmt, 1.5) + local value, nextpos = string.unpack(endian .. fmt, bytes) + assert(value == 1.5 and nextpos == #bytes + 1) + rejects("line 20", function(a1, a2) return string.unpack(a1, a2) end, endian .. fmt, "") + end + for _, fmt in ipairs({"z"}) do + local bytes = string.pack(endian .. fmt, "payload") + local value, nextpos = string.unpack(endian .. fmt, bytes) + assert(value == "payload" and nextpos == #bytes + 1) + end + end + for _, fmt in ipairs({"Xz", "Xc2"}) do + assert(string.pack(fmt) == "") + assert(string.packsize(fmt) == 0) + assert(string.unpack(fmt, "") == 1) + end + local bytes = string.pack("!8 b Xd d c5", 7, 1.5, "ab") + local a, b, c, nextpos = string.unpack("!8 b Xd d c5", bytes) + assert(a == 7 and b == 1.5 and c == "ab\0\0\0" and nextpos == #bytes + 1) + assert(string.unpack(" 8 then + align = 8 + end + local pos = 1 + if pos % align ~= 0 then + pos = pos + (align - pos % align) + end + return pos + item + end + assert(string.packsize("!8bXhh") == size_after_byte(string.packsize("h"))) + assert(string.packsize("!8bXll") == size_after_byte(string.packsize("l"))) + assert(string.packsize("!8bXjj") == size_after_byte(string.packsize("j"))) + assert(string.packsize("!8bXTT") == size_after_byte(string.packsize("T"))) + assert(string.packsize("!8bXff") == 8) + assert(not pcall(function() return string.packsize("i0") end)) + assert(not pcall(function() return string.packsize("i17") end)) + assert(not pcall(function() return string.rep("x", 9223372036854775807) end)) + assert(string.format("%p", 0.0) == "0x0") + assert(string.gsub("ab", "()", "[%1]") == "[1]a[2]b[3]") + assert(string.gsub("ab", "()", {[1] = "x", [2] = "y", [3] = "z"}) == "xaybz") + assert(string.gsub("a", "a", "%%") == "%") + assert(not pcall(function() return string.gsub("a", ".", function() return {} end) end)) + local replacement = load("return 'R'") + assert(string.gsub("abc", ".", replacement) == "RRR") + return 1 +end diff --git a/test/lua/string/test_string_dump_scalar_captures.lua b/test/lua/string/test_string_dump_scalar_captures.lua new file mode 100644 index 00000000..2b3b594d --- /dev/null +++ b/test/lua/string/test_string_dump_scalar_captures.lua @@ -0,0 +1,16 @@ +function test_dump_scalar_captures() + for _, x in ipairs({2.5, true, false, 42}) do + local original = function() return x end + local dumped = string.dump(original) + local restored = load(dumped) + assert(string.dump(restored) == dumped) + local callable = load(dumped .. "return x") + assert(callable() == x) + local ok, value = pcall(callable) + assert(ok and value == x) + end + local ok, value = xpcall(function() error("expected loaded handler") end, load("return 99")) + assert(not ok and value == 99) + assert(load("return missing_loaded_function()")() == nil) + return 1 +end diff --git a/test/lua/string/test_string_runtime_intrinsics.lua b/test/lua/string/test_string_runtime_intrinsics.lua new file mode 100644 index 00000000..8a7d1a41 --- /dev/null +++ b/test/lua/string/test_string_runtime_intrinsics.lua @@ -0,0 +1,21 @@ +function test_runtime_string_intrinsics() + local text = runtime_string_value("AbC") + assert(string.lower(text) == "abc") + assert(string.upper(text) == "ABC") + assert(string.reverse(text) == "CbA") + assert(string.rep(text, 2) == "AbCAbC") + assert(string.rep(text, -1) == "") + assert(string.byte(text, 2) == 98) + assert(string.byte(text, 4) == nil) + local begin, finish = string.find(text, runtime_string_value("b"), 1, true) + assert(begin == 2 and finish == 2) + assert(string.find(text, runtime_string_value("missing"), 1, true) == nil) + assert(string.lower(runtime_string_value(123)) == "123") + assert(string.upper(runtime_string_value(123)) == "123") + assert(string.reverse(runtime_string_value(123)) == "321") + assert(string.rep(runtime_string_value(12), 2) == "1212") + assert(string.byte(runtime_string_value(65), 1) == 54) + local first, last = string.find(runtime_string_value(12345), runtime_string_value(23), 1, true) + assert(first == 2 and last == 3) + return 1 +end diff --git a/test/lua/table/test_table_dynamic_keys.lua b/test/lua/table/test_table_dynamic_keys.lua new file mode 100644 index 00000000..a589c8bb --- /dev/null +++ b/test/lua/table/test_table_dynamic_keys.lua @@ -0,0 +1,102 @@ +-- Host callbacks deliberately keep key types opaque to the compiler. This +-- exercises ordinary embedding calls, not a specialized constant-key fast path. +function test_dynamic_quick_keys() + local keys = {"a", "b", "c", "d", "e", "f", "g", "h"} + for removed = 1, 8 do + local t = {} + for i = 1, 8 do t[opaque_table_key(keys[i])] = i end + for i = 1, 8 do + assert(t[opaque_string_key(keys[i])] == i) + t[opaque_string_key(keys[i])] = i + 10 + assert(t[opaque_table_key(keys[i])] == i + 10) + end + t[opaque_table_key(keys[removed])] = nil + assert(t[opaque_string_key(keys[removed])] == nil) + local count = 0 + for k, v in pairs(t) do + assert(v >= 11 and v <= 18) + count = count + 1 + end + assert(count == 7) + for i = 1, 8 do + if i ~= removed then assert(t[opaque_string_key(keys[i])] == i + 10) end + end + end + return 1 +end + +function test_dynamic_collision_chains() + local t = {} + -- These positive 64-bit integer keys share low^high hash bits, stay outside + -- the array part, and force hash-node lookup/removal through a long chain. + for i = 1, 40 do t[opaque_table_key(i * 4294967297)] = i end + for i = 1, 40 do assert(t[opaque_table_key(i * 4294967297)] == i) end + for _, i in ipairs({1, 20, 40}) do + t[opaque_table_key(i * 4294967297)] = nil + assert(t[opaque_table_key(i * 4294967297)] == nil) + end + t[opaque_table_key(99 * 4294967297)] = nil + for i = 2, 39 do + if i ~= 20 then + assert(t[opaque_table_key(i * 4294967297)] == i) + t[opaque_table_key(i * 4294967297)] = -i + assert(t[opaque_table_key(i * 4294967297)] == -i) + end + end + for i = 41, 80 do t[opaque_table_key(i * 4294967297)] = i end + local count = 0 + for k, v in pairs(t) do count = count + 1 end + assert(count == 77) + return 1 +end + +function test_presized_move_and_mixed_sort() + local source = {} + for i = 1, 64 do source[i] = i end + local destination = {} + assert(table.move(source, 1, 64, 5, destination) == destination) + for i = 1, 64 do assert(destination[i + 4] == i) end + assert(destination[4] == nil and destination[69] == nil) + local values = {1, 1.5, 0.25, 2} + table.sort(values) + assert(values[1] == 0.25 and values[2] == 1 and values[3] == 1.5 and values[4] == 2) + assert(not pcall(function() return table.sort({{}, {}}) end)) + return 1 +end + + +local function constructor_pair() return 11, 12 end + +local function mixed_constructor(key) + return {marker = 7, ["fixed"] = 8, [string.len("abcd")] = 9, [key] = 10, constructor_pair()} +end + +local function write_unknown(table_value, key, value) table_value[key] = value end +local function write_float(table_value, index) table_value[index] = 1.25 end + +function test_mixed_constructor_and_dynamic_store_contracts() + local t = mixed_constructor(true) + assert(t.marker == 7 and t.fixed == 8 and t[4] == 9 and t[true] == 10) + assert(t[1] == 11 and t[2] == 12) + assert(not pcall(function() write_unknown(false, "key", 1) end)) + assert(not pcall(function() write_unknown({}, nil, 1) end)) + local numbers = {} + for i = 1, 8 do table.insert(numbers, i) end + write_float(numbers, 2) + assert(numbers[2] == 1.25 and #numbers == 8) + local empty_key = {[""] = 17, other = 19} + assert(empty_key[""] == 17 and empty_key.other == 19) + return 1 +end + + +function test_loaded_sort_comparator() + local values = {4, 1, 3, 2} + local compare = load("false") + table.sort(values, compare) + assert(#values == 4 and values[1] + values[2] + values[3] + values[4] == 10) + table.sort(values) + assert(values[1] == 1 and values[2] == 2 and values[3] == 3 and values[4] == 4) + assert(not pcall(function() return table.unpack(false) end)) + return 1 +end diff --git a/test/lua/table/test_table_sparse_prefix_resize.lua b/test/lua/table/test_table_sparse_prefix_resize.lua new file mode 100644 index 00000000..ba35d1bb --- /dev/null +++ b/test/lua/table/test_table_sparse_prefix_resize.lua @@ -0,0 +1,23 @@ +function test_sparse_prefix_resize() + for _, bucketed in ipairs({false, true}) do + local values = {} + if bucketed then + for i = 1, 8 do values["field" .. tostring(i)] = i * 10 end + end + for i = 2, 9 do values[i] = i * 3 end + values[100000] = "far" + assert(values[1] == nil and values[100000] == "far") + for i = 2, 9 do assert(values[i] == i * 3) end + if bucketed then + for i = 1, 8 do assert(values["field" .. tostring(i)] == i * 10) end + end + values[1] = 3 + assert(#values == 9) + values[10] = true + values[11] = false + values[12] = 2.5 + for i = 13, 14 do values[i] = 3.5 end + assert(values[10] == true and values[11] == false and values[12] == 2.5 and values[13] == 3.5 and values[14] == 3.5) + end + return 1 +end diff --git a/test/lua/toml/test_toml_additional_contracts.lua b/test/lua/toml/test_toml_additional_contracts.lua new file mode 100644 index 00000000..5f320982 --- /dev/null +++ b/test/lua/toml/test_toml_additional_contracts.lua @@ -0,0 +1,12 @@ +function test_toml_contracts() + assert(toml.encode(nil) == "") + assert(toml.encode(function() return 1 end) == "") + local decoded = toml.decode(toml.encode({[true] = "skip", child = {[false] = "skip", value = 7}, callable = function() end})) + assert(decoded.child.value == 7 and decoded.callable == nil) + local root = {} + local cursor = root + for i = 1, 70 do cursor.child = {} cursor = cursor.child end + local ok, message = pcall(function() toml.encode(root) end) + assert(not ok and string.find(message, "nesting too deep", 1, true)) + return 1 +end diff --git a/test/lua/url/test_url_additional_contracts.lua b/test/lua/url/test_url_additional_contracts.lua new file mode 100644 index 00000000..7e2ae52c --- /dev/null +++ b/test/lua/url/test_url_additional_contracts.lua @@ -0,0 +1,12 @@ +function test_url_contracts() + local formatted = url.format({scheme = "https", user = "alice", password = "secret", host = "example.invalid", port = "8443", path = "/a", query = "x=1", fragment = "tail"}) + assert(formatted == "https://alice:secret@example.invalid:8443/a?x=1#tail") + local query = url.decode_query("flag&x=1") + assert(query.flag == "" and query.x == "1") + assert(not pcall(function() url.decode("%GG") end)) + assert(not pcall(function() url.decode_query("x=%GG") end)) + assert(not pcall(function() url.parse("http://[") end)) + assert(not pcall(function() url.format(false) end)) + assert(not pcall(function() url.encode_query(false) end)) + return 1 +end diff --git a/test/lua/utf8/test_utf8_invalid_sequences.lua b/test/lua/utf8/test_utf8_invalid_sequences.lua new file mode 100644 index 00000000..077c7cd6 --- /dev/null +++ b/test/lua/utf8/test_utf8_invalid_sequences.lua @@ -0,0 +1,16 @@ +function test_utf8_invalid_sequences() + local invalid = {string.char(0xc2), string.char(0xe2, 0x28, 0xa1), + string.char(0xe0, 0x80, 0x80), string.char(0xed, 0xa0, 0x80), + string.char(0xf0, 0x80, 0x80, 0x80), string.char(0xf4, 0x90, 0x80, 0x80), + string.char(0xf0, 0x90, 0x80)} + for _, text in ipairs(invalid) do + local length, position = utf8.len(text) + assert(length == nil and position == 1) + assert(not pcall(function() utf8.codepoint(text) end)) + local iterator, state, control = utf8.codes(text) + assert(not pcall(function() iterator(state, control) end)) + end + local text = utf8.char(0x20ac) + assert(not pcall(function() utf8.offset(text, 1, 2) end)) + return 1 +end diff --git a/test/lua/xml/test_xml_structure_contracts.lua b/test/lua/xml/test_xml_structure_contracts.lua new file mode 100644 index 00000000..f5fc0541 --- /dev/null +++ b/test/lua/xml/test_xml_structure_contracts.lua @@ -0,0 +1,21 @@ +function test_xml_structure_contracts() + local decoded = xml.decode("alphaabomega") + assert(decoded._text == "alphabetaomega") + assert(#decoded.item == 2 and decoded.item[1]._text == "a" and decoded.item[2]._text == "b") + assert(xml.decode(xml.encode(true))._text == "true") + assert(xml.decode(xml.encode(1.25))._text == "1.25") + assert(xml.decode(xml.encode("plain text"))._text == "plain text") + decoded = xml.decode(xml.encode({alpha = "a", beta = "b"})) + assert(decoded.alpha._text == "a" and decoded.beta._text == "b") + decoded = xml.decode(xml.encode({root = {list = {{_text = "a"}, {_text = "b"}}}})) + assert(#decoded.list.item == 2 and decoded.list.item[2]._text == "b") + local cycle = {other = 1} + cycle.nested = cycle + local ok, err = pcall(function() return xml.encode({root = cycle}) end) + assert(not ok and string.find(err, "cyclic", 1, true) ~= nil) + local deep = {_text = "leaf"} + for i = 1, 66 do deep = {child = deep} end + ok, err = pcall(function() return xml.encode({root = deep}) end) + assert(not ok and string.find(err, "nesting too deep", 1, true) ~= nil) + return 1 +end diff --git a/test/lua/yaml/test_yaml_encoding_boundaries.lua b/test/lua/yaml/test_yaml_encoding_boundaries.lua new file mode 100644 index 00000000..24d48c53 --- /dev/null +++ b/test/lua/yaml/test_yaml_encoding_boundaries.lua @@ -0,0 +1,31 @@ +function test_yaml_scalar_encoding() + assert(yaml.decode(yaml.encode(nil)) == nil) + assert(yaml.decode(yaml.encode(true)) == true) + assert(yaml.decode(yaml.encode(false)) == false) + assert(yaml.decode(yaml.encode(1.25)) == 1.25) + assert(yaml.decode(yaml.encode(1 / 0)) == nil) + assert(yaml.decode(yaml.encode(0 / 0)) == nil) + assert(yaml.decode("'a''b[[{' ") == "a'b[[{") + assert(yaml.decode('"a\\\"[[{"') == 'a"[[{') + assert(yaml.decode("value: 7 # [[[{{{\n").value == 7) + assert(yaml.decode("999999999999999999999999999999999999") == "999999999999999999999999999999999999") + return 1 +end + +function test_yaml_encoding_rejections() + local cycle = {} + cycle[1] = cycle + local ok, err = pcall(function() return yaml.encode(cycle) end) + assert(not ok and string.find(err, "cyclic", 1, true) ~= nil) + local nested = {1} + for i = 1, 66 do nested = {nested} end + ok, err = pcall(function() return yaml.encode(nested) end) + assert(not ok and string.find(err, "nesting too deep", 1, true) ~= nil) + ok, err = pcall(function() return yaml.encode(function() return 1 end) end) + assert(not ok and string.find(err, "unsupported type", 1, true) ~= nil) + local block = "" + for i = 0, 66 do block = block .. string.rep(" ", i) .. "key:\n" end + ok, err = pcall(function() return yaml.decode(block) end) + assert(not ok and string.find(err, "nesting too deep", 1, true) ~= nil) + return 1 +end diff --git a/test/test_basic.cpp b/test/test_basic.cpp index 41dce4d4..38930461 100644 --- a/test/test_basic.cpp +++ b/test/test_basic.cpp @@ -1600,3 +1600,35 @@ TEST(test_basic, reg_limit_jit_only_execution) { FakeluaStateGuard guard; EXPECT_THROW(CompileFile(guard.GetState(), "./basic/test_reg_limit_nested_over.lua", cfg), std::exception); } + +TEST(basic, first_class_pairs_and_ipairs_iterator_contracts) { + FakeluaStateGuard state; + CompileFile(state.GetState(), "./basic/test_basic_iterator_values.lua", {}); + int64_t result = 0; + CallAll(state.GetState(), "test_iterator_values", result); + EXPECT_EQ(result, 1); +} + +TEST(basic, host_exceptions_and_failing_xpcall_handlers_are_contained) { + FakeluaStateGuard state; + RegisterNativeFunction(state.GetState(), "host_standard_error", 0, false, [](State *, CVar *, int) -> CVar { throw std::runtime_error("host failure"); }); + RegisterNativeFunction(state.GetState(), "host_unknown_error", 0, false, [](State *, CVar *, int) -> CVar { throw 7; }); + CompileFile(state.GetState(), "./basic/test_basic_host_exceptions.lua", {}); + for (auto backend: AllJitTypes()) { + SCOPED_TRACE(JitTypeName(backend)); + int64_t result = 0; + Call(state.GetState(), backend, "test_host_exception_boundaries", result); + EXPECT_EQ(result, 1); + } +} + +TEST(basic, tonumber_rejects_fractional_bases_and_overflowing_custom_hex) { + FakeluaStateGuard state; + CompileFile(state.GetState(), "./basic/test_basic_tonumber_edge.lua", {}); + for (auto backend: AllJitTypes()) { + SCOPED_TRACE(JitTypeName(backend)); + int64_t result = 0; + Call(state.GetState(), backend, "test_tonumber_base_and_hex_bounds", result); + EXPECT_EQ(result, 1); + } +} diff --git a/test/test_closure.cpp b/test/test_closure.cpp index 9ec42a51..c846b434 100644 --- a/test/test_closure.cpp +++ b/test/test_closure.cpp @@ -1,5 +1,7 @@ #include "compile/compiler.h" #include "fakelua.h" +#include "jit/vm.h" +#include "test_jit.h" #include "gtest/gtest.h" #include @@ -175,3 +177,74 @@ TEST(closure, test_closure_tail_deep_interp) { ASSERT_EQ(ret, 100000); FakeluaDeleteState(s); } + +TEST(closure, opaque_fixed_arity_dispatch_four_through_thirty_two) { + FakeluaStateGuard state; + RegisterNativeFunction(state.GetState(), "opaque_closure", 1, false, [](State *, CVar *args, int) { return args[0]; }); + CompileFile(state.GetState(), "./closure/test_closure_fixed_arity_dispatch.lua", {}); + for (int arity = 4; arity <= 32; ++arity) { + SCOPED_TRACE(arity); + for (auto backend: AllJitTypes()) { + SCOPED_TRACE(JitTypeName(backend)); + int64_t result = 0; + Call(state.GetState(), backend, "dispatch_arity_" + std::to_string(arity), result); + EXPECT_EQ(result, arity * (arity + 1) / 2); + } + } +} + +TEST(closure, callbacks_preserve_arguments_across_backends) { + FakeluaStateGuard state; + CompileString(state.GetState(), R"lua( + function make_fixed_callback() + return function(a, b) return a + b end + end + function make_vararg_callback() + return function(a, ...) return a + select("#", ...) end + end + function invoke_fixed_callback(fn) return fn(2, 3) end + function invoke_vararg_callback(fn) return fn(2, 3, 4, 5) end + )lua", + {}); + // Keep the closure alive in the same arena across the two low-level entry + // calls; the convenience Call API intentionally resets temporary storage. + for (auto producer: AllJitTypes()) { + for (auto consumer: AllJitTypes()) { + SCOPED_TRACE(::testing::Message() << "producer=" << JitTypeName(producer) << " consumer=" << JitTypeName(consumer)); + for (bool vararg: {false, true}) { + SCOPED_TRACE(vararg); + CVar callback = CallByNameArgs(state.GetState(), producer, vararg ? "make_vararg_callback" : "make_fixed_callback", 0, nullptr); + CVar result = CallByNameArgs(state.GetState(), consumer, vararg ? "invoke_vararg_callback" : "invoke_fixed_callback", 1, &callback); + EXPECT_EQ(inter::CVarToInteger(result, -1), 5); + } + } + } +} + +TEST(closure, captured_loop_values_survive_continue_and_multireturn_assignment) { + FakeluaStateGuard state; + RegisterNativeFunction(state.GetState(), "opaque_loop_value", 1, false, [](State *, CVar *args, int) { return args[0]; }); + CompileFile(state.GetState(), "./closure/test_closure_loop_capture.lua", {}); + for (auto backend: AllJitTypes()) { + SCOPED_TRACE(JitTypeName(backend)); + int64_t result = 0; + Call(state.GetState(), backend, "test_loop_capture_contracts", result); + EXPECT_EQ(result, 1); + } +} + +TEST(test_closure, mutable_generic_loop_capture_continue_break_and_nested_forward_goto) { + FakeluaStateGuard state; + CompileFile(state.GetState(), "./closure/test_closure_mutable_generic_loop.lua", {}); + int64_t result = 0; + CallAll(state.GetState(), "test_mutable_generic_loop", result); + EXPECT_EQ(result, 1); +} + +TEST(test_closure, generic_iterator_capture_and_multivalue_prefix_declarations) { + FakeluaStateGuard state; + CompileFile(state.GetState(), "./closure/test_closure_mutable_generic_loop.lua", {}); + int64_t result = 0; + CallAll(state.GetState(), "test_generic_iterator_capture_and_multivalue_prefix_declarations", result); + EXPECT_EQ(result, 1); +} diff --git a/test/test_compress.cpp b/test/test_compress.cpp index ab66080f..e6033458 100644 --- a/test/test_compress.cpp +++ b/test/test_compress.cpp @@ -1,6 +1,8 @@ #include "fakelua.h" +#include "native/compress/compress_lz4.h" #include "test_jit.h" #include "gtest/gtest.h" +#include using namespace fakelua; @@ -442,3 +444,24 @@ TEST(test_compress, zstd_edge_cases) { EXPECT_EQ(ret, 1); FakeluaDeleteState(s); } + +TEST(test_compress, lz4_unknown_size_growth_checksum_failure_and_declared_limit) { + const std::vector plain(100000, 'x'); + LZ4F_preferences_t prefs{}; + prefs.frameInfo.contentChecksumFlag = LZ4F_contentChecksumEnabled; + std::vector frame(LZ4F_compressFrameBound(plain.size(), &prefs)); + const size_t size = LZ4F_compressFrame(frame.data(), frame.size(), plain.data(), plain.size(), &prefs); + ASSERT_FALSE(LZ4F_isError(size)); + frame.resize(size); + EXPECT_EQ(compress::Lz4Decompress(frame.data(), frame.size()), plain); + frame.back() ^= 1; + EXPECT_THROW(compress::Lz4Decompress(frame.data(), frame.size()), std::exception); + LZ4F_cctx *raw = nullptr; + ASSERT_FALSE(LZ4F_isError(LZ4F_createCompressionContext(&raw, LZ4F_VERSION))); + std::unique_ptr context(raw, LZ4F_freeCompressionContext); + prefs.frameInfo.contentSize = 64ull * 1024 * 1024 + 1; + std::vector header(LZ4F_HEADER_SIZE_MAX); + const size_t header_size = LZ4F_compressBegin(context.get(), header.data(), header.size(), &prefs); + ASSERT_FALSE(LZ4F_isError(header_size)); + EXPECT_THROW(compress::Lz4Decompress(header.data(), header_size), std::exception); +} diff --git a/test/test_container.cpp b/test/test_container.cpp index abbf4dec..d27ffdb7 100644 --- a/test/test_container.cpp +++ b/test/test_container.cpp @@ -140,3 +140,14 @@ TEST(test_container, bad_fn_value) { CallThrow(s, "ContainerTest.test_bad_fn_value", ret); FakeluaDeleteState(s); } + +TEST(test_container, ordered_scalar_keys_normalize_floats_and_reject_references) { + FakeluaStateGuard state; + CompileFile(state.GetState(), "./container/test_container_scalar_keys.lua", {}); + for (auto backend: AllJitTypes()) { + SCOPED_TRACE(JitTypeName(backend)); + int64_t result = 0; + Call(state.GetState(), backend, "test_ordered_scalar_keys", result); + EXPECT_EQ(result, 1); + } +} diff --git a/test/test_crypto.cpp b/test/test_crypto.cpp index 27e7998a..1f86f74d 100644 --- a/test/test_crypto.cpp +++ b/test/test_crypto.cpp @@ -1,6 +1,15 @@ #include "fakelua.h" +#include "jit/vm.h" +#include "native/crypto/crypto_aes.h" +#include "native/crypto/crypto_cipher.h" +#include "native/crypto/crypto_digest.h" #include "test_jit.h" #include "gtest/gtest.h" +#include +#include +#include +#include +#include using namespace fakelua; @@ -428,3 +437,116 @@ TEST(test_crypto, xxhash) { EXPECT_EQ(ret, 1); FakeluaDeleteState(s); } + +TEST(test_crypto, aes_cbc_rejects_truncation_and_corrupted_padding) { + std::array input{}; + std::array key{}; + std::array iv{}; + auto encrypted = crypto::AesEncryptCbc(input.data(), input.size(), key.data(), crypto::AesKeySize::AES_128, iv.data()); + ASSERT_EQ(encrypted.size(), 32); + EXPECT_EQ(crypto::AesDecryptCbc(encrypted.data(), encrypted.size(), key.data(), crypto::AesKeySize::AES_128, iv.data()), std::vector(input.begin(), input.end())); + EXPECT_THROW(crypto::AesDecryptCbc(encrypted.data(), 0, key.data(), crypto::AesKeySize::AES_128, iv.data()), std::exception); + EXPECT_THROW(crypto::AesDecryptCbc(encrypted.data(), encrypted.size() - 1, key.data(), crypto::AesKeySize::AES_128, iv.data()), std::exception); + // CBC XORs the preceding ciphertext block into the plaintext. Flipping its + // last byte changes only the last padding byte from 16 to 17, deterministically. + encrypted[15] ^= 1; + try { + (void) crypto::AesDecryptCbc(encrypted.data(), encrypted.size(), key.data(), crypto::AesKeySize::AES_128, iv.data()); + FAIL() << "corrupted PKCS#7 padding was accepted"; + } catch (const std::exception &e) { + EXPECT_NE(std::string(e.what()).find("bad padding"), std::string::npos); + } + ERR_clear_error(); +} + +#if OPENSSL_VERSION_NUMBER >= 0x30000000L +TEST(test_crypto, unavailable_provider_is_reported_and_context_is_restored) { + FakeluaStateGuard state; + std::array key{}; + std::array input{}; + std::array output{}; + std::array iv{}; + { + std::unique_ptr context(OSSL_LIB_CTX_new(), OSSL_LIB_CTX_free); + ASSERT_NE(context, nullptr); + ASSERT_EQ(EVP_set_default_properties(context.get(), "provider=fakelua_unavailable"), 1); + + struct RestoreThreadContext { + OSSL_LIB_CTX *previous; + + ~RestoreThreadContext() { + OSSL_LIB_CTX_set0_default(previous); + ERR_clear_error(); + } + } restore{OSSL_LIB_CTX_set0_default(context.get())}; + + // Real provider selection failure, isolated to this thread/context; no + // mocks, global provider unloads, or changes to other tests' contexts. + EXPECT_THROW(crypto::AesEncryptEcb(input.data(), output.data(), key.data(), crypto::AesKeySize::AES_128), std::exception); + EXPECT_THROW(crypto::AesDecryptEcb(input.data(), output.data(), key.data(), crypto::AesKeySize::AES_128), std::exception); + EXPECT_THROW(crypto::AesEncryptCbc(input.data(), input.size(), key.data(), crypto::AesKeySize::AES_128, iv.data()), std::exception); + EXPECT_THROW(crypto::AesDecryptCbc(input.data(), input.size(), key.data(), crypto::AesKeySize::AES_128, iv.data()), std::exception); + EXPECT_THROW(crypto::AesEncryptCtr(input.data(), input.size(), key.data(), crypto::AesKeySize::AES_128, iv.data()), std::exception); + CVar digest_args[] = {inter::NativeToFakeluaString(state.GetState(), "sha256"), inter::NativeToFakeluaString(state.GetState(), "data")}; + EXPECT_THROW(CallByNameArgs(state.GetState(), JIT_INTERP, "crypto.digest", 2, digest_args), std::exception); + EXPECT_THROW(CallByNameArgs(state.GetState(), JIT_INTERP, "crypto.digest_raw", 2, digest_args), std::exception); + CVar cipher_args[] = {inter::NativeToFakeluaString(state.GetState(), "aes-128-cbc"), inter::NativeToFakeluaString(state.GetState(), std::string(16, '\0')), + inter::NativeToFakeluaString(state.GetState(), std::string(16, '\0')), inter::NativeToFakeluaString(state.GetState(), std::string(16, '\0'))}; + EXPECT_THROW(CallByNameArgs(state.GetState(), JIT_INTERP, "crypto.encrypt", 4, cipher_args), std::exception); + EXPECT_THROW(crypto::Md5(input.data(), input.size()), std::exception); + EXPECT_THROW(crypto::Sha1(input.data(), input.size()), std::exception); + EXPECT_THROW(crypto::Sha256(input.data(), input.size()), std::exception); + EXPECT_THROW(crypto::Rc4(key.data(), 16, input.data(), input.size()), std::exception); + EXPECT_THROW(crypto::BlowfishEncrypt(key.data(), 16, input.data(), input.size()), std::exception); + EXPECT_THROW(crypto::BlowfishDecrypt(key.data(), 16, input.data(), input.size()), std::exception); + EXPECT_THROW(crypto::DesEncrypt(key.data(), 8, input.data(), input.size()), std::exception); + EXPECT_THROW(crypto::DesDecrypt(key.data(), 8, input.data(), input.size()), std::exception); + EXPECT_THROW(crypto::TripleDesEncrypt(key.data(), 24, input.data(), input.size()), std::exception); + EXPECT_THROW(crypto::TripleDesDecrypt(key.data(), 24, input.data(), input.size()), std::exception); + } + // Published AES-128 zero-key/zero-block vector proves the caller's original + // provider context is usable after all failure cleanups. + crypto::AesEncryptEcb(input.data(), output.data(), key.data(), crypto::AesKeySize::AES_128); + const std::array expected{0x66, 0xe9, 0x4b, 0xd4, 0xef, 0x8a, 0x2c, 0x3b, 0x88, 0x4c, 0xfa, 0x59, 0xca, 0x34, 0x2b, 0x2e}; + EXPECT_EQ(output, expected); +} +#endif + +TEST(test_crypto, block_lengths_iv_encoding_and_generic_padding_errors) { + FakeluaStateGuard state; + CompileFile(state.GetState(), "./crypto/test_crypto_input_contracts.lua", {}); + for (auto backend: AllJitTypes()) { + SCOPED_TRACE(JitTypeName(backend)); + int64_t result = 0; + Call(state.GetState(), backend, "test_crypto_input_contracts", result); + EXPECT_EQ(result, 1); + } +} + +TEST(test_crypto, aes_192_and_256_known_answers_and_mode_roundtrips) { + const std::array plain{}; + const std::array key{}; + const std::array iv{}; + const std::array, 2> expected{{{0xaa, 0xe0, 0x69, 0x92, 0xac, 0xbf, 0x52, 0xa3, 0xe8, 0xf4, 0xa9, 0x6e, 0xc9, 0x30, 0x0b, 0xd7}, + {0xdc, 0x95, 0xc0, 0x78, 0xa2, 0x40, 0x89, 0x89, 0xad, 0x48, 0xa2, 0x14, 0x92, 0x84, 0x20, 0x87}}}; + size_t index = 0; + for (auto bits: {crypto::AesKeySize::AES_192, crypto::AesKeySize::AES_256}) { + std::array encrypted{}, restored{}; + crypto::AesEncryptEcb(plain.data(), encrypted.data(), key.data(), bits); + EXPECT_EQ(encrypted, expected[index++]); + crypto::AesDecryptEcb(encrypted.data(), restored.data(), key.data(), bits); + EXPECT_EQ(restored, plain); + std::vector message(31); + for (size_t i = 0; i < message.size(); ++i) message[i] = static_cast(i); + auto cbc = crypto::AesEncryptCbc(message.data(), message.size(), key.data(), bits, iv.data()); + EXPECT_EQ(crypto::AesDecryptCbc(cbc.data(), cbc.size(), key.data(), bits, iv.data()), message); + auto ctr = crypto::AesEncryptCtr(message.data(), message.size(), key.data(), bits, iv.data()); + EXPECT_EQ(ctr.size(), message.size()); + EXPECT_EQ(crypto::AesDecryptCtr(ctr.data(), ctr.size(), key.data(), bits, iv.data()), message); + } + std::array out{}; + const auto invalid = static_cast(0); + EXPECT_THROW(crypto::AesEncryptEcb(plain.data(), out.data(), key.data(), invalid), std::exception); + EXPECT_THROW(crypto::AesEncryptCbc(plain.data(), plain.size(), key.data(), invalid, iv.data()), std::exception); + EXPECT_THROW(crypto::AesEncryptCtr(plain.data(), plain.size(), key.data(), invalid, iv.data()), std::exception); +} diff --git a/test/test_csv.cpp b/test/test_csv.cpp index 9a65d348..9f9ac3b3 100644 --- a/test/test_csv.cpp +++ b/test/test_csv.cpp @@ -178,3 +178,13 @@ TEST(test_csv, unterminated_quote) { CallThrow(s, "CsvTest.test_unterminated_quote", ret); FakeluaDeleteState(s); } + +TEST(test_csv, bom_blank_lines_postquote_and_scalar_rows) { + FakeluaStateGuard state; + CompileFile(state.GetState(), "./csv/test_csv_parser_contracts.lua", {}); + for (auto backend: AllJitTypes()) { + int64_t result = 0; + Call(state.GetState(), backend, "test_csv_parser_contracts", result); + EXPECT_EQ(result, 1) << JitTypeName(backend); + } +} diff --git a/test/test_event.cpp b/test/test_event.cpp index c936a437..3e4204d1 100644 --- a/test/test_event.cpp +++ b/test/test_event.cpp @@ -113,3 +113,13 @@ TEST(test_event, reentrant) { EXPECT_EQ(ret, 1); FakeluaDeleteState(s); } + +TEST(test_event, once_removal_empty_names_and_gcc_callback_fallback) { + FakeluaStateGuard state; + CompileConfig config; + config.disable_jit[JIT_TCC] = true; + CompileFile(state.GetState(), "./event/test_event_additional_contracts.lua", config); + int64_t result = 0; + Call(state.GetState(), JIT_GCC, "test_event_contracts", result); + EXPECT_EQ(result, 1); +} diff --git a/test/test_http.cpp b/test/test_http.cpp index 853871b7..65a9e788 100644 --- a/test/test_http.cpp +++ b/test/test_http.cpp @@ -1,6 +1,14 @@ #include "fakelua.h" +#include "jit/vm.h" +#include "native/http/native_http.h" +#include "native/net/net_event.h" +#include "native/object/native_object.h" +#include "native/table/native_table.h" +#include "state/state.h" #include "test_jit.h" #include "gtest/gtest.h" +#include +#include using namespace fakelua; @@ -91,3 +99,149 @@ TEST(test_http, client_bad_port) { EXPECT_EQ(ret, 1); FakeluaDeleteState(s); } + +TEST(test_http, chunked_response_and_request_framing_contracts) { + FakeluaStateGuard state; + CompileFile(state.GetState(), "./http/test_http_chunked_framing.lua", {}); + for (auto backend: AllJitTypes()) { + int64_t result = 0; + Call(state.GetState(), backend, "test_http_chunked_framing", result); + EXPECT_EQ(result, 1) << JitTypeName(backend); + } +} + +TEST(test_http, configuration_validation_and_unsupported_urls) { + FakeluaStateGuard state; + CompileFile(state.GetState(), "./http/test_http_chunked_framing.lua", {}); + for (auto backend: AllJitTypes()) { + int64_t result = 0; + Call(state.GetState(), backend, "test_http_configuration_contracts", result); + EXPECT_EQ(result, 1) << JitTypeName(backend); + } +} + +TEST(test_http, deferred_reply_validation_and_gcc_callback_fallback) { + FakeluaStateGuard state; + int64_t connection_id = 0; + RegisterNativeFunction(state.GetState(), "remember_http_connection", 1, false, [&](State *s, CVar *args, int) { + connection_id = inter::CVarToInteger(args[0]); + return inter::NativeToFakeluaNil(s); + }); + RegisterNativeFunction(state.GetState(), "last_http_connection", 0, false, [&](State *s, CVar *, int) { return inter::NativeToFakeluaLonglong(s, connection_id); }); + CompileConfig config; + config.disable_jit[JIT_TCC] = true; + CompileFile(state.GetState(), "./http/test_http_chunked_framing.lua", config); + int64_t result = 0; + Call(state.GetState(), JIT_GCC, "test_http_deferred_reply", result); + EXPECT_EQ(result, 1); + EXPECT_GT(connection_id, 0); +} + +TEST(test_http, close_delimited_response_waits_for_eof_and_preserves_body) { + FakeluaStateGuard state; + auto *s = state.GetState(); + bool done = false; + std::string body, error; + RegisterNativeFunction(s, "record_close_delimited_http", 3, false, [&](State *st, CVar *args, int) { + done = true; + error = inter::CVarToString(args[1], ""); + body = inter::CVarToString(table::TableHelper::GetTableStrId(st, args[2], "body"), ""); + return inter::NativeToFakeluaNil(st); + }); + CompileConfig config; + config.disable_jit[JIT_TCC] = true; + CompileString(s, R"( + function close_delimited_http_done(req, err, response) record_close_delimited_http(req, err, response) end + function start_close_delimited_http() return http.get("http://127.0.0.1:19975/", "close_delimited_http_done") end + )", + config); + net::NetConfig server_config; + server_config.port = 19975; + server_config.framer = net::FramerType::RawStream; + net::TcpServer server(server_config, s); + server.Start(); + ASSERT_TRUE(server.Running()); + (void) CallByNameArgs(s, JIT_GCC, "start_close_delimited_http", 0, nullptr); + bool request_seen = false; + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5); + while (!request_seen && std::chrono::steady_clock::now() < deadline) { + server.DrainEventsWith([&](const auto &event) { + if (event.kind == net::EventKind::Recv) request_seen = true; + }); + http::TickAll(s); + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + ASSERT_TRUE(request_seen); + const std::string response = "HTTP/1.0 200 OK\r\nX-Test: retained\r\n\r\nclose-delimited body"; + ASSERT_TRUE(server.Send(0, response.data(), response.size())); + // Drain the nonblocking event base to write the queued response before the + // graceful close; without EOF the HTTP client must not finish this body. + server.DrainEventsWith([](const auto &) {}); + http::TickAll(s); + EXPECT_FALSE(done); + ASSERT_TRUE(server.CloseConnection(0)); + while (!done && std::chrono::steady_clock::now() < deadline) { + http::TickAll(s); + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + ASSERT_TRUE(done); + EXPECT_TRUE(error.empty()) << error; + EXPECT_EQ(body, "close-delimited body"); +} + +TEST(test_http, bodyless_requests_scalar_reply_and_unknown_status_reason) { + FakeluaStateGuard state; + auto *s = state.GetState(); + CompileConfig config; + config.disable_jit[JIT_TCC] = true; + CompileString(s, R"( + function bodyless_http_handler(kind, connid, request) + assert(kind == "request" and request.method == "GET" and request.body == "") + if request.path == "/scalar" then return "scalar body" end + return {status = 599, body = "custom body"} + end + function start_bodyless_http_server() + local server = http.server({ip = "127.0.0.1", port = 19976}) + server:dispatch("bodyless_http_handler") + return 1 + end + )", + config); + int64_t started = 0; + Call(s, JIT_GCC, "start_bodyless_http_server", started); + ASSERT_EQ(started, 1); + for (const auto &[path, expected]: std::vector>{{"/scalar", "scalar body"}, {"/custom", "custom body"}}) { + net::NetConfig client_config; + client_config.port = 19976; + client_config.framer = net::FramerType::RawStream; + net::TcpClient client(client_config, s); + client.Connect(); + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5); + auto poll = [&](std::string &response) { + http::TickAll(s); + client.DrainEventsWith([&](const auto &event) { + if (event.kind == net::EventKind::Recv) response += event.data; + }); + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + }; + std::string response; + while (!client.Connected() && std::chrono::steady_clock::now() < deadline) poll(response); + ASSERT_TRUE(client.Connected()); + const std::string request = "GET " + path + " HTTP/1.1\r\nHost: localhost\r\n\r\n"; + ASSERT_TRUE(client.Send(request.data(), request.size())); + while (response.find(expected) == std::string::npos && std::chrono::steady_clock::now() < deadline) poll(response); + EXPECT_NE(response.find(expected), std::string::npos); + EXPECT_NE(response.find(path == "/scalar" ? "200 OK" : "599 OK"), std::string::npos); + } +} + +TEST(test_http, explicit_group_destruction_unregisters_live_wrapper) { + FakeluaStateGuard state; + CompileString(state.GetState(), R"(function live_wrapper_factory() return http.server({ip = "127.0.0.1", port = 0}) end)", {}); + CVar value = CallByNameArgs(state.GetState(), JIT_INTERP, "live_wrapper_factory", 0, nullptr); + auto *object = NativeObject::Unwrap(value); + ASSERT_NE(object, nullptr); + const auto group = object->GetGroupId(); + EXPECT_EQ(state.GetState()->GetNativeObjectManager().DestroyGroup(group), 1u); + EXPECT_EQ(state.GetState()->GetNativeObjectManager().DestroyGroup(group), 0u); +} diff --git a/test/test_ini.cpp b/test/test_ini.cpp index a06ad2e6..4c210e50 100644 --- a/test/test_ini.cpp +++ b/test/test_ini.cpp @@ -93,3 +93,13 @@ TEST(test_ini, encode_value_newline) { FakeluaDeleteState(s); } } + +TEST(test_ini, scalar_array_encoding_and_invalid_input) { + FakeluaStateGuard state; + CompileFile(state.GetState(), "./ini/test_ini_encoding_contracts.lua", {}); + for (auto backend: AllJitTypes()) { + int64_t result = 0; + Call(state.GetState(), backend, "test_ini_encoding_contracts", result); + EXPECT_EQ(result, 1) << JitTypeName(backend); + } +} diff --git a/test/test_io.cpp b/test/test_io.cpp index 3454cc4e..abc52d9e 100644 --- a/test/test_io.cpp +++ b/test/test_io.cpp @@ -1,3 +1,6 @@ +#include "jit/vm.h" +#include "native/object/native_object.h" +#include "state/state.h" #include #include "fakelua.h" @@ -1029,3 +1032,64 @@ TEST(test_io, file_read_multi_nil_count) { EXPECT_EQ(ret, 1); FakeluaDeleteState(s); } + +TEST(test_io, numeric_read_formats_default_input_and_current_lines) { + FakeluaStateGuard state; + CompileFile(state.GetState(), "./io/test_io_numeric_read_contracts.lua", {}); + for (auto backend: AllJitTypes()) { + int64_t result = 0; + Call(state.GetState(), backend, "test_numeric_read_contracts", result); + EXPECT_EQ(result, 1) << JitTypeName(backend); + } +} + +TEST(test_io, iterator_after_group_destruction_and_standard_handle_close_contracts) { + FakeluaStateGuard state; + CompileString(state.GetState(), R"( + function io_iterator_factory() + local file = io.tmpfile() + assert(file:write("line\n")) + assert(file:seek("set", -1) == nil) + file:seek("set", 0) + io.input(file) + return file, file:lines() + end + function io_standard_close_contracts() + assert(io.stdin():close() and io.stdout():close() and io.stderr():close()) + assert(not pcall(function() return io.read("invalid-format") end)) + local pending = io.popen("echo io_lifecycle", "r") + assert(pending ~= nil) + return 1 + end + )", + {}); + CVar result = CallByNameArgs(state.GetState(), JIT_INTERP, "io_iterator_factory", 0, nullptr); + CVar file = inter::GetMultiCVarElement(result, 0); + CVar iterator = inter::GetMultiCVarElement(result, 1); + auto *object = NativeObject::Unwrap(file); + ASSERT_NE(object, nullptr); + ASSERT_EQ(iterator.type_, static_cast(VarType::Closure)); + EXPECT_EQ(state.GetState()->GetNativeObjectManager().DestroyGroup(object->GetGroupId()), 1u); + EXPECT_EQ(inter::DispatchCallClosure(state.GetState(), iterator.data_.cl, nullptr, 0, JIT_GCC).type_, static_cast(VarType::Nil)); + int64_t success = 0; + Call(state.GetState(), JIT_INTERP, "io_standard_close_contracts", success); + EXPECT_EQ(success, 1); +} + + +#if !defined(_WIN32) +TEST(test_io, popen_rejects_invalid_mode_without_spawning) { + FakeluaStateGuard state; + CompileString(state.GetState(), R"( + function invalid_pipe_mode_contract() + local file, message = io.popen("unused_command", "invalid-mode") + assert(file == nil and type(message) == "string" and #message > 0) + return 1 + end + )", + {}); + int64_t result = 0; + CallAll(state.GetState(), "invalid_pipe_mode_contract", result); + EXPECT_EQ(result, 1); +} +#endif diff --git a/test/test_jitter.cpp b/test/test_jitter.cpp index c2d9f9d7..e50fa766 100644 --- a/test/test_jitter.cpp +++ b/test/test_jitter.cpp @@ -3186,11 +3186,13 @@ void RemoveTreeBestEffort(const std::filesystem::path &path) { } } HANDLE handle = CreateFileW(path.wstring().c_str(), DELETE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, - FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, nullptr); + FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, nullptr); if (handle == INVALID_HANDLE_VALUE) return; + struct DispositionEx { DWORD Flags; } posix{0x00000001 | 0x00000002};// FILE_DISPOSITION_FLAG_DELETE | POSIX_SEMANTICS + if (!SetFileInformationByHandle(handle, static_cast(21), &posix, sizeof(posix))) { FILE_DISPOSITION_INFO info{}; info.DeleteFile = TRUE; @@ -3211,7 +3213,9 @@ struct JitCacheTestDir { std::filesystem::permissions(path, std::filesystem::perms::owner_all); } - ~JitCacheTestDir() { RemoveTreeBestEffort(path); } + ~JitCacheTestDir() { + RemoveTreeBestEffort(path); + } StateConfig Config() const { StateConfig cfg; @@ -3267,7 +3271,7 @@ TEST(jitter, gcc_cache_coverage_bypass) { CheckCacheState(s.GetState()); EXPECT_TRUE(dir.Entries().empty()); } -#else +#endif namespace { struct CacheTestEnvironment { struct Value { @@ -3328,6 +3332,7 @@ struct CacheArtifactFixture { }; }// namespace +#if !defined(FAKELUA_TEST_NO_GCC_CACHE) TEST(jitter, gcc_cache_default_temp_root_and_custom_override) { JitCacheTestDir temp; CacheTestEnvironment env; @@ -3366,6 +3371,8 @@ TEST(jitter, gcc_cache_default_temp_root_and_custom_override) { EXPECT_EQ(custom.Entries().size(), 1u); } +#endif + TEST(jitter, gcc_cache_fifo_limit_and_hits_do_not_reorder) { CacheArtifactFixture f; EXPECT_EQ(StateGCCConfig{}.cache_max_entries, 256u); @@ -3420,6 +3427,7 @@ TEST(jitter, gcc_cache_corrupt_fifo_metadata_does_not_poison_writes) { EXPECT_TRUE(f.Restore("after malformed", 2)); } +#if !defined(FAKELUA_TEST_NO_GCC_CACHE) TEST(jitter, gcc_cache_eviction_preserves_loaded_modules) { JitCacheTestDir dir; auto config = dir.Config(); @@ -3438,6 +3446,8 @@ TEST(jitter, gcc_cache_eviction_preserves_loaded_modules) { CheckCacheState(live.GetState()); } +#endif + TEST(jitter, gcc_cache_fifo_concurrent_publishers_and_readers) { CacheArtifactFixture f; std::atomic ready{0}, failures{0}; @@ -3618,6 +3628,7 @@ TEST(jitter, gcc_cache_removed_entry_and_root_are_recoverable) { EXPECT_TRUE(f.Restore("recreated root", 2)); } +#if !defined(FAKELUA_TEST_NO_GCC_CACHE) TEST(jitter, gcc_cache_external_cleanup_during_compile_and_live_execution) { JitCacheTestDir dir; auto config = dir.Config(); @@ -3971,6 +3982,8 @@ TEST(jitter, gcc_cache_process_race_and_reuse) { } #endif +#endif + TEST(jitter, gcc_cache_dependency_and_compiler_invalidation) { JitCacheTestDir dir; auto config = dir.Config().gcc_config; @@ -4067,6 +4080,7 @@ TEST(jitter, gcc_cache_dependency_and_compiler_invalidation) { EXPECT_EQ(dir.Entries().size(), 0u); } +#if !defined(FAKELUA_TEST_NO_GCC_CACHE) TEST(jitter, gcc_cache_failed_compile_does_not_publish) { JitCacheTestDir dir; @@ -4094,6 +4108,123 @@ TEST(jitter, gcc_cache_failed_compile_does_not_publish) { #endif// FAKELUA_TEST_NO_GCC_CACHE + +TEST(jitter, gcc_cache_rejects_open_toolchains_and_disabled_configuration) { + CacheArtifactFixture f; + auto original = f.dir.Config().gcc_config; + for (int policy = 0; policy < 4; ++policy) { + SCOPED_TRACE(policy); + auto cfg = original; + if (policy == 0) cfg.enable_cache = false; + if (policy == 1) cfg.include_paths.push_back(f.dir.path.string()); + if (policy == 2) cfg.library_paths.push_back(f.dir.path.string()); + if (policy == 3) cfg.libraries.push_back("user_library"); + GccCache cache(cfg, f.compiler, "configuration policy", false); + cache.Publish(f.binary, f.deps, f.source); + EXPECT_FALSE(cache.Restore(f.restored)); + cache.Invalidate(); + cache.Release(); + EXPECT_FALSE(cache.Restore(f.restored)); + } + EXPECT_TRUE(f.dir.Entries().empty()); + for (auto name: {"CPATH", "C_INCLUDE_PATH", "LIBRARY_PATH", "COMPILER_PATH", "GCC_EXEC_PREFIX", "CCC_OVERRIDE_OPTIONS", "CLANG_CONFIG_FILE_SYSTEM_DIR", "CLANG_CONFIG_FILE_USER_DIR"}) { + SCOPED_TRACE(name); + CacheTestEnvironment env; + env.Set(name, f.dir.path.string()); + GccCache cache(original, f.compiler, "search path policy", false); + cache.Publish(f.binary, f.deps, f.source); + EXPECT_FALSE(cache.Restore(f.restored)); + EXPECT_TRUE(f.dir.Entries().empty()); + } +} + +TEST(jitter, gcc_cache_manifest_validation_and_republication) { + CacheArtifactFixture f; + const std::vector manifests{ + "", "short\n1\n", std::string(64, '0') + "\n0\n", std::string(64, '0') + "\n10001\n", std::string(64, '0') + "\n1\n", std::string(64, '0') + "\n1\n\"missing-header\" missing-hash\n"}; + for (const auto &manifest: manifests) { + SCOPED_TRACE(manifest); + f.Publish("manifest validation", 0); + ASSERT_EQ(f.dir.Entries().size(), 1u); + const auto entry = f.dir.Entries().at(0); + std::ofstream(entry / "manifest", std::ios::binary | std::ios::trunc) << manifest; + EXPECT_FALSE(f.Restore("manifest validation", 0)); + EXPECT_FALSE(std::filesystem::exists(entry)); + EXPECT_FALSE(std::filesystem::exists(f.restored)); + } + f.Publish("manifest validation", 0); + ASSERT_TRUE(f.Restore("manifest validation", 0)); + std::ifstream restored(f.restored, std::ios::binary); + EXPECT_EQ(std::string(std::istreambuf_iterator(restored), {}), "test artifact bytes"); +} + +TEST(jitter, gcc_cache_publish_io_failures_do_not_leave_partial_entries) { + CacheArtifactFixture f; + std::ifstream original_deps(f.deps); + const std::string dependency_rule(std::istreambuf_iterator(original_deps), {}); + original_deps.close(); + auto cfg = f.dir.Config().gcc_config; + { + GccCache cache(cfg, f.compiler, "publication failures", false); + cache.Publish(f.binary + ".missing", f.deps, f.source); + cache.Publish(f.binary, f.deps + ".missing", f.source); + cache.Publish(f.binary, f.deps, f.source + ".missing"); + std::ofstream(f.deps, std::ios::trunc) << "not a dependency rule"; + cache.Publish(f.binary, f.deps, f.source); + EXPECT_FALSE(cache.Restore(f.restored)); + } + EXPECT_TRUE(f.dir.Entries().empty()); + // A failed destination write is a miss, never a half-successful restore. + std::ofstream(f.deps, std::ios::trunc) << dependency_rule; + f.Publish("write failure", 0); + ASSERT_EQ(f.dir.Entries().size(), 1u); + std::filesystem::create_directory(f.restored); + { + GccCache cache(cfg, f.compiler, "write failure", false); + EXPECT_FALSE(cache.Restore(f.restored)); + } + EXPECT_TRUE(f.dir.Entries().empty()); + std::filesystem::remove(f.restored); + f.Publish("write failure", 0); + EXPECT_TRUE(f.Restore("write failure", 0)); +} + +TEST(jitter, gcc_cache_environment_and_debug_mode_separate_keys) { + CacheArtifactFixture f; + CacheTestEnvironment original_environment; + original_environment.Set("SOURCE_DATE_EPOCH", "111111111"); + f.Publish("key separation", 0); + ASSERT_TRUE(f.Restore("key separation", 0)); + { + CacheTestEnvironment env; + env.Set("SOURCE_DATE_EPOCH", "123456789"); + EXPECT_FALSE(f.Restore("key separation", 0)); + } + auto cfg = f.dir.Config().gcc_config; + { + GccCache debug(cfg, f.compiler, "key separation", true); + EXPECT_FALSE(debug.Restore(f.restored)); + } + EXPECT_TRUE(f.Restore("key separation", 0)); +} + +#if !defined(_WIN32) +TEST(jitter, gcc_cache_noncompiler_and_wrapper_are_not_persisted) { + CacheArtifactFixture f; + auto cfg = f.dir.Config().gcc_config; + const auto wrapper = f.dir.path / "gcc-wrapper"; + std::ofstream(wrapper) << "#!/bin/sh\nexit 99\n"; + std::filesystem::permissions(wrapper, std::filesystem::perms::owner_all); + for (const auto &compiler: {wrapper.string(), std::string("/bin/true")}) { + SCOPED_TRACE(compiler); + GccCache cache(cfg, compiler, "untrusted compiler", false); + cache.Publish(f.binary, f.deps, f.source); + EXPECT_FALSE(cache.Restore(f.restored)); + } + EXPECT_TRUE(f.dir.Entries().empty()); +} +#endif + TEST(jitter, gcc_cache_binary_literal_strings_all_backends) { JitCacheTestDir dir; std::string source = "function cache_all_bytes() return \""; @@ -4133,3 +4264,99 @@ function cache_collisions() return cache_collision("ab")*100+cache_collision("bA } } } + +TEST(jitter, fixed_prefix_vararg_expansion_and_missing_parameters) { + FakeluaStateGuard state; + CompileFile(state.GetState(), "./jit/test_vararg_expansion_boundaries.lua", {}); + for (auto backend: AllJitTypes()) { + int64_t result = 0; + Call(state.GetState(), backend, "test_vararg_expansion_boundaries", result); + EXPECT_EQ(result, 1) << JitTypeName(backend); + } +} + +TEST(jitter, nested_multivalue_returns_preserve_arity_when_math_specialization_is_ineligible) { + FakeluaStateGuard state; + CompileString(state.GetState(), R"( + function nested_multi_elseif(n) + if n < 0 then return 0 elseif n > 0 then return n, n + 1 end + return 0 + end + function nested_multi_else(n) + if n < 0 then return 0 else return n, n + 1 end + end + function nested_multi_while(n) + while n > 0 do return n, n + 1 end + return 0 + end + function nested_multi_repeat(n) + repeat return n, n + 1 until true + end + function nested_multi_numeric_for(n) + for i = 1, n do return n, n + 1 end + return 0 + end + function nested_multi_generic_for(n) + for _, value in ipairs({n}) do return value, value + 1 end + return 0 + end + function nested_multi_do(n) + do return n, n + 1 end + end + function nested_multivalue_contracts() + local a, b = nested_multi_elseif(1) assert(a == 1 and b == 2) + a, b = nested_multi_else(1) assert(a == 1 and b == 2) + a, b = nested_multi_while(1) assert(a == 1 and b == 2) + a, b = nested_multi_repeat(1) assert(a == 1 and b == 2) + a, b = nested_multi_numeric_for(1) assert(a == 1 and b == 2) + a, b = nested_multi_generic_for(1) assert(a == 1 and b == 2) + a, b = nested_multi_do(1) assert(a == 1 and b == 2) + local x, y = table.unpack({3, 4, 5}, 2) + assert(x == 4 and y == 5) + repeat until true + return 1 + end + )", + {}); + for (auto backend: AllJitTypes()) { + int64_t result = 0; + Call(state.GetState(), backend, "nested_multivalue_contracts", result); + EXPECT_EQ(result, 1) << JitTypeName(backend); + } +} + + +#if !defined(_WIN32) +TEST(jitter, gcc_cache_makefile_dependencies_with_escaped_names_and_line_endings) { + CacheArtifactFixture fixture; + std::vector headers; + for (const std::string name: {"space header.h", "tab\theader.h", "hash#header.h", "colon:header.h", "back\\slash.h"}) { + headers.push_back(fixture.dir.path / name); + std::ofstream(headers.back()) << "original dependency"; + } + auto escape = [](const std::string &path) { + std::string result; + for (char ch: path) { + if (ch == ' ' || ch == '\t' || ch == '#' || ch == ':' || ch == '\\') result += '\\'; + result += ch; + } + return result; + }; + { + std::ofstream dependencies(fixture.deps, std::ios::binary); + dependencies << "image: " << escape(fixture.source); + for (size_t i = 0; i < headers.size(); ++i) { + dependencies << (i % 2 ? " \\\r\n " : " \\\n ") << escape(headers[i].string()); + } + dependencies << '\n'; + } + for (size_t i = 0; i < headers.size(); ++i) { + const std::string key = "escaped-dependency-" + std::to_string(i); + fixture.Publish(key, 0); + ASSERT_TRUE(fixture.Restore(key, 0)); + std::ofstream(headers[i], std::ios::trunc) << "changed dependency"; + EXPECT_FALSE(fixture.Restore(key, 0)); + std::ofstream(headers[i], std::ios::trunc) << "original dependency"; + } +} +#endif diff --git a/test/test_math.cpp b/test/test_math.cpp index 77e48e70..c3340b37 100644 --- a/test/test_math.cpp +++ b/test/test_math.cpp @@ -1,6 +1,7 @@ #include #include "fakelua.h" +#include "jit/vm.h" #include "test_jit.h" using namespace fakelua; @@ -1344,3 +1345,32 @@ TEST(test_math, cov_math_inline_extra) { } FakeluaDeleteState(s); } + +TEST(test_math, integer_for_clamps_finite_and_infinite_float_limits) { + FakeluaStateGuard state; + CompileFile(state.GetState(), "./math/test_for_int64_overflow.lua", {}); + for (auto backend: AllJitTypes()) { + SCOPED_TRACE(JitTypeName(backend)); + int64_t result = 0; + Call(state.GetState(), backend, "test_for_clamped_float_limits", result); + EXPECT_EQ(result, 1); + } +} + +TEST(test_math, native_extrema_coerce_numeric_strings_and_compare_fractional_values) { + FakeluaStateGuard state; + auto *s = state.GetState(); + auto extrema = [&](const char *name, CVar first, CVar second) { + CVar args[] = {first, second}; + return inter::CVarToNumber(CallByNameArgs(s, JIT_INTERP, name, 2, args)); + }; + EXPECT_DOUBLE_EQ(extrema("math.max", inter::NativeToFakeluaString(s, "1"), inter::NativeToFakeluaString(s, "2")), 2); + EXPECT_DOUBLE_EQ(extrema("math.max", inter::NativeToFakeluaString(s, "1.25"), inter::NativeToFakeluaString(s, "2.5")), 2.5); + EXPECT_DOUBLE_EQ(extrema("math.min", inter::NativeToFakeluaString(s, "1"), inter::NativeToFakeluaString(s, "2")), 1); + EXPECT_DOUBLE_EQ(extrema("math.min", inter::NativeToFakeluaString(s, "1.25"), inter::NativeToFakeluaString(s, "2.5")), 1.25); + EXPECT_DOUBLE_EQ(extrema("math.max", inter::NativeToFakeluaInt(s, 1), inter::NativeToFakeluaDouble(s, 1.5)), 1.5); + EXPECT_DOUBLE_EQ(extrema("math.max", inter::NativeToFakeluaInt(s, 2), inter::NativeToFakeluaDouble(s, 1.5)), 2); + EXPECT_DOUBLE_EQ(extrema("math.min", inter::NativeToFakeluaDouble(s, 1.0), inter::NativeToFakeluaInt(s, 1)), 1); + CVar bounds[] = {inter::NativeToFakeluaInt(s, 1), inter::NativeToFakeluaInt(s, 2), inter::NativeToFakeluaInt(s, 0)}; + EXPECT_THROW(CallByNameArgs(s, JIT_INTERP, "math.clamp", 3, bounds), std::exception); +} diff --git a/test/test_mysql.cpp b/test/test_mysql.cpp index 63eeaa9c..0aae1f1c 100644 --- a/test/test_mysql.cpp +++ b/test/test_mysql.cpp @@ -1,9 +1,17 @@ #include "fakelua.h" +#include "jit/vm.h" +#include "native/mysql/mysql_connection_pool.h" #include "native/mysql/mysql_field_convert.h" #include "native/mysql/native_mysql.h" #include "native/native_common.h" +#include "native/net/net_event.h" +#include "native/object/native_object.h" +#include "native/table/native_table.h" +#include "state/state.h" #include "test_jit.h" #include "gtest/gtest.h" +#include +#include using namespace fakelua; using namespace fakelua::mysql; @@ -393,3 +401,337 @@ TEST(test_mysql, field_cell_to_cvar_type_conversion) { FakeluaDeleteState(s); } + +TEST(test_mysql, large_multi_results_and_queued_query_callbacks) { + FakeluaStateGuard state; + CompileFile(state.GetState(), "./mysql/test_mysql_streamed_results.lua", {}); + for (auto backend: AllJitTypes()) { + int64_t result = 0; + Call(state.GetState(), backend, "MysqlStream.test_large_and_queued_results", result); + EXPECT_EQ(result, 1) << JitTypeName(backend); + } +} + +TEST(test_mysql, pool_heartbeat_recovers_a_closed_idle_connection) { + FakeluaStateGuard state; + PoolConfig config; + config.host = "127.0.0.1"; + config.port = 3306; + config.user = "root"; + config.password = "root"; + config.database = "test"; + config.pool_size = 1; + config.connect_timeout_ms = 1000; + config.heartbeat_interval_ms = 1; + config.retry_base_ms = 1; + config.max_retries = 2; + MysqlConnectionPool pool(config, state.GetState()); + pool.Initialize(); + auto wait_healthy = [&] { + auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5); + do { + pool.Tick(); + if (pool.HealthyCount() == 1) return true; + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } while (std::chrono::steady_clock::now() < deadline); + return false; + }; + ASSERT_TRUE(wait_healthy()); + // Drive several real heartbeat request/response cycles before borrowing. + for (int i = 0; i < 20; ++i) { + pool.Tick(); + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + auto *connection = pool.Acquire(); + ASSERT_NE(connection, nullptr); + connection->Close(); + pool.Release(connection); + ASSERT_TRUE(wait_healthy()); + auto *reconnected = pool.Acquire(); + ASSERT_NE(reconnected, nullptr); + EXPECT_TRUE(reconnected->Connected()); + pool.Release(reconnected); + pool.Close(); + pool.Tick(); + EXPECT_EQ(pool.TotalCount(), 0u); + EXPECT_EQ(pool.Acquire(), nullptr); +} + +TEST(test_mysql, pool_close_inside_result_callback_defers_connection_destruction) { + FakeluaStateGuard state; + PoolConfig config; + config.host = "127.0.0.1"; + config.port = 3306; + config.user = "root"; + config.password = "root"; + config.database = "test"; + config.pool_size = 1; + config.connect_timeout_ms = 1000; + config.heartbeat_interval_ms = 0; + MysqlConnectionPool pool(config, state.GetState()); + bool callback_ran = false; + RegisterNativeFunction(state.GetState(), "close_pool_from_callback", 0, false, [&](State *s, CVar *, int) { + callback_ran = true; + pool.Close(); + // The active Tick frame still owns the connection until it unwinds. + EXPECT_EQ(pool.TotalCount(), 1u); + EXPECT_EQ(pool.Acquire(), nullptr); + return inter::NativeToFakeluaNil(s); + }); + CompileConfig compile; + DisableAllJit(compile); + compile.disable_jit[JIT_INTERP] = false; + compile.debug_mode = false; + CompileString(state.GetState(), R"( + function pool_close_on_result(conn, err, result) + assert(err == nil) + assert(result[3][1][1] == 42) + close_pool_from_callback() + end + )", + compile); + pool.Initialize(); + auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5); + while (pool.HealthyCount() != 1 && std::chrono::steady_clock::now() < deadline) { + pool.Tick(); + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + auto *connection = pool.Acquire(); + ASSERT_NE(connection, nullptr); + ResultCallback callback; + callback.name = "pool_close_on_result"; + callback.jit = JIT_INTERP; + connection->Query("SELECT 42", callback); + deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5); + while (!callback_ran && std::chrono::steady_clock::now() < deadline) { + pool.Tick(); + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + EXPECT_TRUE(callback_ran); + EXPECT_EQ(pool.TotalCount(), 0u); + pool.Reap(); + pool.Close(); + EXPECT_EQ(pool.HealthyCount(), 0u); +} + +TEST(test_mysql, pool_ssl_options_and_outstanding_wrapper_invalidation) { + for (auto backend: AllJitTypes()) { + SCOPED_TRACE(JitTypeName(backend)); + FakeluaStateGuard state; + CompileFile(state.GetState(), "./mysql/test_mysql_pool_lifecycle.lua", {}); + int64_t result = 0; + Call(state.GetState(), backend, "test_pool_lifecycle_contracts", result); + EXPECT_EQ(result, 1); + } +} + +TEST(test_mysql, statement_and_late_multi_result_errors_preserve_callback_and_connection) { + for (auto backend: AllJitTypes()) { + SCOPED_TRACE(JitTypeName(backend)); + FakeluaStateGuard state; + CompileFile(state.GetState(), "./mysql/test_mysql_streamed_results.lua", {}); + int64_t result = 0; + Call(state.GetState(), backend, "MysqlStream.test_statement_and_late_multi_result_errors", result); + EXPECT_EQ(result, 1); + } +} + +TEST(test_mysql, retryable_error_classification) { + for (auto type: {MysqlErrorType::None, MysqlErrorType::Connection, MysqlErrorType::Authentication, MysqlErrorType::Syntax, MysqlErrorType::Timeout, MysqlErrorType::Protocol, + MysqlErrorType::Server, MysqlErrorType::Unknown}) { + EXPECT_EQ(MysqlConnection::IsRetryable(type), type == MysqlErrorType::Connection || type == MysqlErrorType::Timeout); + } +} + +TEST(test_mysql, closed_cpp_statement_apis_report_errors_through_gcc_callback_fallback) { + FakeluaStateGuard state; + State *s = state.GetState(); + int callbacks = 0; + RegisterNativeFunction(s, "record_closed_mysql", 3, false, [&](State *st, CVar *args, int n) { + EXPECT_EQ(n, 3); + EXPECT_EQ(args[0].type_, static_cast(VarType::Nil)); + EXPECT_EQ(inter::CVarToString(args[1], ""), "connection closed"); + EXPECT_EQ(args[2].type_, static_cast(VarType::Nil)); + ++callbacks; + return inter::NativeToFakeluaNil(st); + }); + CompileConfig config; + config.disable_jit[JIT_TCC] = true; + CompileString(s, "function closed_mysql_result(conn, err, result) record_closed_mysql(conn, err, result) end", config); + MysqlConnection conn(s); + conn.SetResultCallback(ResultCallback{"closed_mysql_result"}); + conn.Query("SELECT 1"); + EXPECT_TRUE(conn.HasPendingWork()); + conn.Tick(); + conn.StmtPrepare("SELECT ?"); + EXPECT_TRUE(conn.HasPendingWork()); + conn.Tick(); + conn.StmtExecute(1, {}); + EXPECT_TRUE(conn.HasPendingWork()); + conn.Tick(); + EXPECT_EQ(callbacks, 3); + EXPECT_FALSE(conn.HasPendingWork()); + EXPECT_FALSE(conn.Connected()); +} + +TEST(test_mysql, streamed_rows_continue_between_packets_and_preserve_all_results) { + for (auto backend: AllJitTypes()) { + SCOPED_TRACE(JitTypeName(backend)); + FakeluaStateGuard state; + CompileFile(state.GetState(), "./mysql/test_mysql_streamed_results.lua", {}); + int64_t result = 0; + Call(state.GetState(), backend, "MysqlStream.test_row_stream_continuations", result); + EXPECT_EQ(result, 1); + } +} + +TEST(test_mysql, configuration_statement_parameters_and_single_stream) { + FakeluaStateGuard state; + CompileFile(state.GetState(), "./mysql/test_mysql_streamed_results.lua", {}); + int64_t result = 0; + CallAll(state.GetState(), "MysqlStream.test_configuration_and_statement_parameter_contracts", result); + EXPECT_EQ(result, 1); +} + +TEST(test_mysql, explicit_group_destruction_unregisters_live_wrapper) { + FakeluaStateGuard state; + CompileString(state.GetState(), R"(function live_wrapper_factory() return mysql.connect({host = "127.0.0.1", user = "root"}, "unused_callback") end)", {}); + CVar value = CallByNameArgs(state.GetState(), JIT_INTERP, "live_wrapper_factory", 0, nullptr); + auto *object = NativeObject::Unwrap(value); + ASSERT_NE(object, nullptr); + const auto group = object->GetGroupId(); + EXPECT_EQ(state.GetState()->GetNativeObjectManager().DestroyGroup(group), 1u); + EXPECT_EQ(state.GetState()->GetNativeObjectManager().DestroyGroup(group), 0u); +} + +TEST(test_mysql, cpp_legacy_queued_queries_and_connecting_statement_guards) { + FakeluaStateGuard state; + std::vector errors; + std::vector rows; + RegisterNativeFunction(state.GetState(), "record_cpp_mysql_result", 2, false, [&](State *s, CVar *args, int) { + if (args[0].type_ != static_cast(VarType::Nil)) { + errors.push_back(inter::CVarToString(args[0], "")); + } else { + auto all_rows = table::TableHelper::GetTableInt(s, args[1], 3); + auto row = table::TableHelper::GetTableInt(s, all_rows, 1); + rows.push_back(inter::CVarToInteger(table::TableHelper::GetTableInt(s, row, 1))); + } + return inter::NativeToFakeluaNil(s); + }); + CompileConfig config; + DisableAllJit(config); + config.disable_jit[JIT_INTERP] = false; + CompileString(state.GetState(), R"(function cpp_mysql_result(conn, err, result) record_cpp_mysql_result(err, result) end)", config); + ResultCallback callback; + callback.name = "cpp_mysql_result"; + callback.jit = JIT_INTERP; + for (bool prepare: {true, false}) { + MysqlConnection opening(state.GetState()); + opening.SetResultCallback(callback); + opening.Connect("127.0.0.1", 3306, "root", "root", "test", 1000); + ASSERT_TRUE(opening.Connecting()); + if (prepare) opening.StmtPrepare("SELECT 1"); + else + opening.StmtExecute(1, {}); + const auto expected = errors.size() + 1; + auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(3); + while (errors.size() < expected && std::chrono::steady_clock::now() < deadline) { + opening.Tick(); + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + ASSERT_EQ(errors.size(), expected); + EXPECT_NE(errors.back().find(prepare ? "not ready for prepare" : "not ready for execute"), std::string::npos); + opening.Close(); + } + MysqlConnection connection(state.GetState()); + connection.SetResultCallback(callback); + connection.Connect("127.0.0.1", 3306, "root", "root", "test", 1000); + auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(3); + while (!connection.Connected() && std::chrono::steady_clock::now() < deadline) { + connection.Tick(); + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + ASSERT_TRUE(connection.Connected()); + connection.Query("SELECT 41 AS value, SLEEP(0.02)"); + connection.Query("SELECT 42 AS value"); + deadline = std::chrono::steady_clock::now() + std::chrono::seconds(3); + while (rows.size() < 2 && std::chrono::steady_clock::now() < deadline) { + connection.Tick(); + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + EXPECT_EQ(rows, (std::vector{41, 42})); + connection.RequestClose(); + connection.Query("SELECT 43"); + connection.Tick(); + ASSERT_EQ(errors.size(), 3u); + EXPECT_NE(errors.back().find("closing"), std::string::npos); + connection.Close(); +} + +TEST(test_mysql, handshake_deadline_with_silent_local_tcp_peer) { + FakeluaStateGuard state; + net::NetConfig peer_config; + peer_config.ip = "127.0.0.1"; + peer_config.port = 19990; + peer_config.framer = net::FramerType::RawStream; + net::TcpServer peer(peer_config, state.GetState()); + peer.Start(); + ASSERT_TRUE(peer.Running()); + std::string error; + RegisterNativeFunction(state.GetState(), "record_mysql_deadline", 1, false, [&](State *s, CVar *args, int) { + error = inter::CVarToString(args[0], ""); + return inter::NativeToFakeluaNil(s); + }); + CompileConfig config; + DisableAllJit(config); + config.disable_jit[JIT_INTERP] = false; + CompileString(state.GetState(), "function mysql_deadline_callback(conn, err, success) record_mysql_deadline(err) end", config); + MysqlConnection connection(state.GetState()); + ResultCallback callback; + callback.name = "mysql_deadline_callback"; + callback.jit = JIT_INTERP; + connection.SetConnectCallback(callback); + connection.Connect("127.0.0.1", peer_config.port, "root", "root", "test", 10); + ASSERT_TRUE(connection.Connecting()); + std::this_thread::sleep_for(std::chrono::milliseconds(25)); + connection.Tick(); + EXPECT_FALSE(connection.Connected()); + EXPECT_FALSE(connection.Connecting()); + EXPECT_NE(error.find("timeout"), std::string::npos); + connection.Close(); + peer.Stop(); +} + +TEST(test_mysql, destroying_pool_group_invalidates_borrowed_wrapper_before_finalizer) { + FakeluaStateGuard state; + CompileString(state.GetState(), R"( + function pool_group_factory() + local pool = mysql_pool.create({host = "127.0.0.1", port = 3306, + user = "root", password = "root", db = "test", pool_size = 1, heartbeat_ms = 0}) + local conn = nil + for i = 1, 3000 do + runtime.tick() + conn = pool:acquire() + if conn then break end + os.sleep(1) + end + assert(conn ~= nil) + return pool, conn + end + function borrowed_after_pool_destruction(conn) + assert(conn:error() == nil) + assert(not pcall(function() conn:query("SELECT 1", "unused_pool_callback") end)) + conn:close() + return 1 + end + )", + {}); + CVar result = CallByNameArgs(state.GetState(), JIT_INTERP, "pool_group_factory", 0, nullptr); + auto *pool = NativeObject::Unwrap(inter::GetMultiCVarElement(result, 0)); + CVar borrowed = inter::GetMultiCVarElement(result, 1); + ASSERT_NE(pool, nullptr); + ASSERT_NE(NativeObject::Unwrap(borrowed), nullptr); + EXPECT_EQ(state.GetState()->GetNativeObjectManager().DestroyGroup(pool->GetGroupId()), 1u); + CVar success = CallByNameArgs(state.GetState(), JIT_INTERP, "borrowed_after_pool_destruction", 1, &borrowed); + EXPECT_EQ(inter::CVarToInteger(success), 1); +} diff --git a/test/test_native.cpp b/test/test_native.cpp index a4842227..9cdb0006 100644 --- a/test/test_native.cpp +++ b/test/test_native.cpp @@ -1,9 +1,12 @@ #include "fakelua.h" +#include "jit/vm.h" +#include "native/object/native_object.h" #include "state/state.h" #include "test_jit.h" #include "var/var_table.h" #include "var/var_type.h" #include "gtest/gtest.h" +#include #include #include @@ -1145,3 +1148,110 @@ TEST(native, gcc_cache_binds_native_callbacks_per_state) { Call(first.GetState(), JIT_GCC, "cache_native", value, 4); EXPECT_EQ(value, 14); } + +TEST(test_native, large_snapshot_growth_and_nil_removal) { + for (auto backend: AllJitTypes()) { + SCOPED_TRACE(JitTypeName(backend)); + FakeluaStateGuard state; + auto &manager = GetNativeObjectManager(state.GetState()); + auto *object = manager.Create(manager.CreateGroup(), "Snapshot", 701); + for (int i = 1; i <= 24; ++i) object->SetInt("field_" + std::to_string(i), i); + EXPECT_EQ(object->GetString("field_1", "fallback"), "fallback"); + RegisterNativeFunction(state.GetState(), "snapshot_object", 0, false, [object](State *s, CVar *, int) { return object->Wrap(s); }); + CompileFile(state.GetState(), "./native/test_native_snapshot_removal.lua", {}); + int64_t result = 0; + Call(state.GetState(), backend, "test_snapshot_removal", result); + EXPECT_EQ(result, 1); + EXPECT_EQ(object->Size(), 21); + EXPECT_FALSE(object->Has("field_1")); + EXPECT_FALSE(object->Has("field_12")); + EXPECT_FALSE(object->Has("field_24")); + } +} + +TEST(test_native, destroy_single_unlinks_global_index_and_empty_group) { + FakeluaStateGuard state; + auto &manager = GetNativeObjectManager(state.GetState()); + auto *first = manager.GlobalCreate("first", "Global", 401); + auto *second = manager.GlobalCreate("second", "Global", 402); + ASSERT_TRUE(manager.DestroySingle("Global", first->GetId())); + EXPECT_EQ(manager.GlobalGet("first"), nullptr); + EXPECT_EQ(manager.GlobalGet("second"), second); + EXPECT_EQ(manager.Get("Global", 401), nullptr); + EXPECT_FALSE(first->Alive()); + auto group = manager.CreateGroup(); + manager.Create(group, "Grouped", 403); + EXPECT_TRUE(manager.DestroySingle("Grouped", 403)); + EXPECT_EQ(manager.DestroyGroup(group), 0); + EXPECT_TRUE(manager.GlobalDestroy("second")); +} + +TEST(test_native, field_conversion_nullable_values_and_typed_fallbacks) { + FakeluaStateGuard state; + auto *s = state.GetState(); + NativeField field; + EXPECT_EQ(NativeFieldToCVar(field, s).type_, static_cast(VarType::Nil)); + field.kind = NativeField::Kind::Object; + EXPECT_EQ(NativeFieldToCVar(field, s).type_, static_cast(VarType::Nil)); + field.kind = NativeField::Kind::Table; + EXPECT_EQ(NativeFieldToCVar(field, s).type_, static_cast(VarType::Nil)); + EXPECT_EQ(CVarToNativeField(inter::NativeToFakeluaNil(s)).kind, NativeField::Kind::Nil); + for (auto type: {VarType::String, VarType::StringId}) { + CVar nullable{}; + nullable.type_ = static_cast(type); + EXPECT_EQ(CVarToNativeField(nullable).kind, NativeField::Kind::Nil); + } + auto &manager = GetNativeObjectManager(s); + auto group = manager.CreateGroup(); + auto *object = manager.Create(group, "TypedFallback"); + object->SetString("text", "not a number"); + EXPECT_EQ(object->GetInt("text", 71), 71); + EXPECT_EQ(object->GetFloat("text", 2.5), 2.5); + EXPECT_TRUE(object->GetBool("text", true)); + EXPECT_EQ(object->GetObject("missing"), nullptr); + EXPECT_EQ(object->GetString("missing", "absent"), "absent"); + manager.DestroyGroup(group); + EXPECT_EQ(object->GetInt("text", 81), 81); + EXPECT_DOUBLE_EQ(object->GetFloat("text", 3.5), 3.5); + EXPECT_TRUE(object->GetBool("text", true)); + EXPECT_EQ(object->GetObject("text"), nullptr); +} + +TEST(test_native, extracted_method_calls_and_destroyed_wrapper_contracts) { + FakeluaStateGuard state; + auto &manager = state.GetState()->GetNativeObjectManager(); + auto *object = manager.GlobalCreate("extracted_method_owner", "method_owner"); + ASSERT_NE(object, nullptr); + object->SetFloat("not_finite", std::numeric_limits::infinity()); + object->SetString("not_an_object", "text"); + EXPECT_EQ(object->GetInt("not_finite", 27), 27); + EXPECT_EQ(object->GetObject("not_an_object"), nullptr); + object->RegisterMethod("echo", [](NativeObject *, State *s, CVar *args, int n) { + EXPECT_EQ(n, 1); + return inter::GetNativeArg(s, args, n, 0); + }); + CompileString(state.GetState(), R"( + function extracted_method_contracts() + local owner = get_global_obj("extracted_method_owner") + local method = owner.echo + assert(method(17) == 17) + assert(method(owner, 19) == 19) + owner[2] = nil + assert(owner[2] == nil) + del_global_obj("extracted_method_owner") + assert(not pcall(function() return method(21) end)) + assert(owner.not_an_object == nil) + owner.new_field = 1 + assert(owner.new_field == nil) + local count = 0 + for key, value in pairs(owner) do count = count + 1 end + assert(count == 0) + assert(not pcall(function() new_native_obj(nil, "invalid", "invalid") end)) + return 1 + end + )", + {}); + int64_t result = 0; + Call(state.GetState(), JIT_INTERP, "extracted_method_contracts", result); + EXPECT_EQ(result, 1); +} diff --git a/test/test_net.cpp b/test/test_net.cpp index a9bea517..ed29b0ac 100644 --- a/test/test_net.cpp +++ b/test/test_net.cpp @@ -1,6 +1,15 @@ #include "fakelua.h" +#include "jit/vm.h" +#include "native/net/net_buffer.h" +#include "native/net/net_event.h" +#include "native/object/native_object.h" +#include "state/state.h" #include "test_jit.h" +#include "var/var.h" #include "gtest/gtest.h" +#include +#include +#include using namespace fakelua; @@ -402,3 +411,521 @@ TEST(test_net, test_send_in_callback) { FakeluaDeleteState(s); } + +TEST(test_net, circular_buffer_wrap_regions_and_zero_capacity) { + using namespace fakelua::net; + CircularBuffer buffer(8); + EXPECT_TRUE(buffer.Empty()); + EXPECT_EQ(buffer.ReadableRegion().second, 0u); + EXPECT_EQ(buffer.Write("abcdef", 6), 6u); + char bytes[8]{}; + ASSERT_EQ(buffer.Read(bytes, 3), 3u); + EXPECT_EQ(std::string(bytes, 3), "abc"); + ASSERT_EQ(buffer.Write("GHIJK", 5), 5u); + EXPECT_TRUE(buffer.Full()); + EXPECT_EQ(buffer.WritableRegion().second, 0u); + EXPECT_EQ(buffer.Write("x", 1), 0u); + ASSERT_EQ(buffer.Peek(bytes, sizeof(bytes)), 8u); + EXPECT_EQ(std::string(bytes, 8), "defGHIJK"); + EXPECT_EQ(buffer.Size(), 8u); + ASSERT_EQ(buffer.Read(bytes, sizeof(bytes)), 8u); + EXPECT_EQ(std::string(bytes, 8), "defGHIJK"); + EXPECT_EQ(buffer.Read(bytes, sizeof(bytes)), 0u); + auto writable = buffer.WritableRegion(); + ASSERT_GE(writable.second, 5u); + std::memcpy(writable.first, "12345", 5); + buffer.CommitWrite(5); + auto readable = buffer.ReadableRegion(); + ASSERT_EQ(readable.second, 5u); + EXPECT_EQ(std::string(readable.first, readable.second), "12345"); + buffer.CommitRead(readable.second); + EXPECT_TRUE(buffer.Empty()); + buffer.Clear(); + EXPECT_EQ(buffer.WritableRegion().second, buffer.Capacity()); + EXPECT_EQ(buffer.Peek(bytes, 1), 0u); + CircularBuffer zero(0); + EXPECT_EQ(zero.Write("x", 1), 0u); + EXPECT_EQ(zero.Read(bytes, 1), 0u); + EXPECT_EQ(zero.Peek(bytes, 1), 0u); + EXPECT_EQ(zero.WritableRegion().second, 0u); + EXPECT_EQ(zero.ReadableRegion().second, 0u); +} + +TEST(test_net, packet_framers_partial_input_and_binary_roundtrip) { + using namespace fakelua::net; + const std::string payload("a\0b\0c", 5); + for (auto framer: + {FramerType::Header4BigEndian, FramerType::Header4LittleEndian, FramerType::Header2BigEndian, FramerType::Header2LittleEndian, FramerType::LineDelimiter, FramerType::FixedLength}) { + SCOPED_TRACE(static_cast(framer)); + NetConfig config; + config.framer = framer; + config.fixed_packet_len = payload.size(); + config.max_packet_len = 64; + CircularBuffer output(64), input(64); + ASSERT_TRUE(WritePacket(output, config, payload.data(), payload.size())); + std::string encoded(output.Size(), '\0'); + ASSERT_EQ(output.Read(encoded.data(), encoded.size()), encoded.size()); + const char *data = nullptr; + uint32_t length = 0; + bool error = true; + EXPECT_FALSE(TryParsePacket(input, config, data, length, error)); + EXPECT_FALSE(error); + ASSERT_EQ(input.Write(encoded.data(), encoded.size() - 1), encoded.size() - 1); + EXPECT_FALSE(TryParsePacket(input, config, data, length, error)); + EXPECT_FALSE(error); + ASSERT_EQ(input.Write(encoded.data() + encoded.size() - 1, 1), 1u); + ASSERT_TRUE(TryParsePacket(input, config, data, length, error)); + EXPECT_FALSE(error); + EXPECT_EQ(std::string(data, length), payload); + EXPECT_TRUE(input.Empty()); + } +} + +TEST(test_net, packet_header_rejects_lengths_larger_than_limit_or_capacity) { + using namespace fakelua::net; + for (auto framer: {FramerType::Header4BigEndian, FramerType::Header4LittleEndian, FramerType::Header2BigEndian, FramerType::Header2LittleEndian}) { + NetConfig config; + config.framer = framer; + config.max_packet_len = 64; + CircularBuffer output(64); + ASSERT_TRUE(WritePacket(output, config, "12345678", 8)); + const size_t header = (framer == FramerType::Header4BigEndian || framer == FramerType::Header4LittleEndian) ? 4 : 2; + char bytes[4]{}; + ASSERT_EQ(output.Read(bytes, header), header); + for (const auto capacity: {size_t{4}, size_t{64}}) { + CircularBuffer input(capacity); + config.max_packet_len = capacity == 64 ? 3 : 64; + input.Write(bytes, header); + const char *data = nullptr; + uint32_t length = 0; + bool error = false; + EXPECT_FALSE(TryParsePacket(input, config, data, length, error)); + EXPECT_TRUE(error); + EXPECT_EQ(input.Size(), header); + } + } +} + +TEST(test_net, packet_line_fixed_and_raw_limits) { + using namespace fakelua::net; + NetConfig config; + config.framer = FramerType::LineDelimiter; + config.max_packet_len = 3; + const char *data = nullptr; + uint32_t length = 0; + bool error = false; + CircularBuffer input(64); + input.Write("a\r\n12345678", 11); + ASSERT_TRUE(TryParsePacket(input, config, data, length, error)); + EXPECT_EQ(std::string(data, length), "a"); + EXPECT_FALSE(TryParsePacket(input, config, data, length, error)); + EXPECT_TRUE(error); + input.Clear(); + config.framer = FramerType::FixedLength; + config.fixed_packet_len = 0; + EXPECT_FALSE(TryParsePacket(input, config, data, length, error)); + EXPECT_FALSE(error); + config.fixed_packet_len = 65; + EXPECT_FALSE(TryParsePacket(input, config, data, length, error)); + EXPECT_TRUE(error); + config.fixed_packet_len = 4; + config.max_packet_len = 64; + ASSERT_TRUE(WritePacket(input, config, "xy", 2)); + ASSERT_TRUE(TryParsePacket(input, config, data, length, error)); + EXPECT_EQ(std::string(data, length), std::string("xy\0\0", 4)); + ASSERT_TRUE(WritePacket(input, config, "abcdef", 6)); + ASSERT_TRUE(TryParsePacket(input, config, data, length, error)); + EXPECT_EQ(std::string(data, length), "abcd"); + config.framer = FramerType::RawStream; + config.max_packet_len = 2; + input.Write("123", 3); + ASSERT_TRUE(TryParsePacket(input, config, data, length, error)); + EXPECT_EQ(std::string(data, length), "12"); + ASSERT_TRUE(TryParsePacket(input, config, data, length, error)); + EXPECT_EQ(std::string(data, length), "3"); + EXPECT_FALSE(TryParsePacket(input, config, data, length, error)); +} + +TEST(test_net, custom_packet_encoder_atomicity_and_parser_progress) { + using namespace fakelua::net; + NetConfig config; + config.framer = FramerType::Custom; + config.custom_encoder_fn = [](CircularBuffer &buffer, const char *data, size_t length) { + buffer.Write("[", 1); + buffer.Write(data, length); + buffer.Write("]", 1); + }; + CircularBuffer too_small(3), enough(8); + EXPECT_FALSE(WritePacket(too_small, config, "abc", 3)); + EXPECT_TRUE(too_small.Empty()); + EXPECT_TRUE(WritePacket(enough, config, "abc", 3)); + char bytes[8]{}; + ASSERT_EQ(enough.Read(bytes, sizeof(bytes)), 5u); + EXPECT_EQ(std::string(bytes, 5), "[abc]"); + config.custom_parser_fn = [](CircularBuffer &, const char *&data, uint32_t &length) { + data = "x"; + length = 1; + return true; + }; + enough.Write("x", 1); + const char *data = nullptr; + uint32_t length = 0; + bool error = false; + EXPECT_FALSE(TryParsePacket(enough, config, data, length, error)); + EXPECT_TRUE(error); + EXPECT_EQ(enough.Size(), 1u); + config.custom_parser_fn = [](CircularBuffer &buffer, const char *&data, uint32_t &length) { + buffer.Skip(1); + data = "x"; + length = 1; + return true; + }; + EXPECT_TRUE(TryParsePacket(enough, config, data, length, error)); + EXPECT_FALSE(error); + EXPECT_EQ(std::string(data, length), "x"); + EXPECT_TRUE(enough.Empty()); +} + +TEST(test_net, native_udp_callbacks_and_explicit_destination) { + for (auto backend: AllJitTypes()) { + SCOPED_TRACE(JitTypeName(backend)); + FakeluaStateGuard state; + int server_receives = 0; + int client_receives = 0; + RegisterNativeFunction(state.GetState(), "cpp_udp_echo", 5, false, [&](State *s, CVar *args, int n) { + EXPECT_EQ(n, 5); + if (inter::CVarToString(args[0], "") != "recv") return inter::NativeToFakeluaNil(s); + ++server_receives; + EXPECT_EQ(inter::CVarToString(args[2], ""), std::string("a\0b", 3)); + EXPECT_EQ(inter::CVarToInteger(args[3]), 3); + CVar response = inter::AllocMultiCVar(s, 2); + inter::SetMultiCVarElement(response, 0, inter::NativeToFakeluaString(s, "echo")); + inter::SetMultiCVarElement(response, 1, args[2]); + return response; + }); + RegisterNativeFunction(state.GetState(), "cpp_udp_receive", 5, false, [&](State *s, CVar *args, int) { + if (inter::CVarToString(args[0], "") == "recv") { + ++client_receives; + EXPECT_EQ(inter::CVarToString(args[2], ""), std::string("a\0b", 3)); + } + return inter::NativeToFakeluaNil(s); + }); + CompileFile(state.GetState(), "./net/test_net_native_udp_callbacks.lua", {}); + int64_t result = 0; + Call(state.GetState(), backend, "test_native_udp_callbacks", result); + EXPECT_EQ(result, 1); + EXPECT_EQ(server_receives, 1); + EXPECT_EQ(client_receives, 1); + } +} + +TEST(test_net, configuration_ranges_tls_spellings_and_dispatch_contracts) { + for (auto backend: AllJitTypes()) { + SCOPED_TRACE(JitTypeName(backend)); + FakeluaStateGuard state; + CompileFile(state.GetState(), "./net/test_net_configuration_contracts.lua", {}); + int64_t result = 0; + Call(state.GetState(), backend, "test_net_configuration_contracts", result); + EXPECT_EQ(result, 1); + } +} + +TEST(test_net, native_custom_parser_gcc_callback_and_dispatch_failure_recovery) { + FakeluaStateGuard state; + std::vector received; + RegisterNativeFunction(state.GetState(), "native_three_byte_parser", 1, false, [](State *s, CVar *args, int) { + const std::string input = inter::CVarToString(args[0], ""); + if (input.size() < 3) return inter::NativeToFakeluaNil(s); + return inter::NativeToFakeluaString(s, input.substr(0, 3)); + }); + RegisterNativeFunction(state.GetState(), "native_parser_host_check", 1, false, [](State *s, CVar *args, int) { + if (inter::CVarToString(args[0], "") == "err") throw std::runtime_error("network dispatch failure"); + return inter::NativeToFakeluaNil(s); + }); + RegisterNativeFunction(state.GetState(), "native_parser_client_event", 5, false, [&](State *s, CVar *args, int) { + if (inter::CVarToString(args[0], "") == "recv") received.push_back(inter::CVarToString(args[2], "")); + else { + EXPECT_EQ(args[2].type_, static_cast(VarType::Nil)); + EXPECT_EQ(args[3].type_, static_cast(VarType::Nil)); + } + return inter::NativeToFakeluaNil(s); + }); + RegisterNativeFunction(state.GetState(), "native_parser_received_count", 0, false, [&](State *s, CVar *, int) { return inter::NativeToFakeluaInt(s, received.size()); }); + CompileConfig config; + config.disable_jit[JIT_TCC] = true; + CompileFile(state.GetState(), "./net/test_net_native_parser.lua", config); + int64_t result = 0; + Call(state.GetState(), JIT_GCC, "test_native_parser_and_dispatch_recovery", result); + EXPECT_EQ(result, 1); + EXPECT_EQ(received, (std::vector{"abc", "def", "ghi"})); +} + +namespace { +bool PollNetPair(net::TcpServer &server, net::TcpClient &client, std::vector &server_events, std::vector &client_events, const std::function &done) { + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5); + do { + server.DrainEventsWith([&](const auto &event) { server_events.push_back(event); }); + client.DrainEventsWith([&](const auto &event) { client_events.push_back(event); }); + if (done()) return true; + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } while (std::chrono::steady_clock::now() < deadline); + return false; +} + +bool HasNetEvent(const std::vector &events, net::EventKind kind) { + return std::any_of(events.begin(), events.end(), [&](const auto &event) { return event.kind == kind; }); +} + +const std::string kWebSocketRequest = + "GET /socket HTTP/1.1\r\nHost: localhost\r\nUpgrade: websocket\r\nConnection: keep-alive, Upgrade\r\nSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\n\r\n"; +}// namespace + +TEST(test_net, websocket_rejects_invalid_upgrade_path_key_tokens_and_version) { + const std::vector> replacements{{"/socket", "/wrong"}, + {"Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n", ""}, + {"Upgrade: websocket", "Upgrade: h2c"}, + {"Connection: keep-alive, Upgrade", "Connection: keep-alive, invalid"}, + {"Version: 13", "Version: 12"}}; + for (const auto &[from, to]: replacements) { + SCOPED_TRACE(from); + FakeluaStateGuard state; + net::NetConfig server_config; + server_config.port = 19972; + server_config.framer = net::FramerType::WebSocket; + server_config.ws_path = "/socket"; + net::TcpServer server(server_config, state.GetState()); + server.Start(); + ASSERT_TRUE(server.Running()); + auto client_config = server_config; + client_config.framer = net::FramerType::RawStream; + net::TcpClient client(client_config, state.GetState()); + EXPECT_FALSE(client.Connected()); + client.Connect(); + std::vector server_events, client_events; + ASSERT_TRUE(PollNetPair(server, client, server_events, client_events, [&] { return client.Connected(); })); + std::string request = kWebSocketRequest; + request.replace(request.find(from), from.size(), to); + ASSERT_TRUE(client.Send(request.data(), request.size())); + ASSERT_TRUE(PollNetPair(server, client, server_events, client_events, [&] { return HasNetEvent(client_events, net::EventKind::Close); })); + EXPECT_FALSE(HasNetEvent(server_events, net::EventKind::Connect)); + EXPECT_FALSE(client.Connected()); + } +} + +TEST(test_net, websocket_fragmented_extended_frame_control_frame_and_close) { + FakeluaStateGuard state; + net::NetConfig server_config; + server_config.port = 19973; + server_config.framer = net::FramerType::WebSocket; + server_config.ws_path = "/socket"; + net::TcpServer server(server_config, state.GetState()); + server.Start(); + ASSERT_TRUE(server.Running()); + auto client_config = server_config; + client_config.framer = net::FramerType::RawStream; + net::TcpClient client(client_config, state.GetState()); + client.Connect(); + std::vector server_events, client_events; + ASSERT_TRUE(PollNetPair(server, client, server_events, client_events, [&] { return client.Connected(); })); + ASSERT_TRUE(client.Send(kWebSocketRequest.data(), kWebSocketRequest.size())); + ASSERT_TRUE(PollNetPair(server, client, server_events, client_events, [&] { return HasNetEvent(server_events, net::EventKind::Connect) && HasNetEvent(client_events, net::EventKind::Recv); })); + std::string handshake; + for (const auto &event: client_events) + if (event.kind == net::EventKind::Recv) handshake += event.data; + ASSERT_NE(handshake.find("HTTP/1.1 101"), std::string::npos); + client_events.clear(); + server_events.clear(); + const std::string ping("\x89\x80\x01\x02\x03\x04", 6); + const std::string payload(300, 'x'); + std::string frame("\x81\xfe\x01\x2c\x01\x02\x03\x04", 8); + for (size_t i = 0; i < payload.size(); ++i) frame.push_back(payload[i] ^ static_cast(i % 4 + 1)); + ASSERT_TRUE(client.Send(ping.data(), ping.size())); + ASSERT_TRUE(client.Send(frame.data(), 2)); + // No complete data frame is available yet; polling must retain its prefix. + for (int i = 0; i < 3; ++i) { + server.DrainEventsWith([&](const auto &event) { server_events.push_back(event); }); + client.DrainEventsWith([&](const auto &event) { client_events.push_back(event); }); + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + EXPECT_FALSE(HasNetEvent(server_events, net::EventKind::Recv)); + ASSERT_TRUE(client.Send(frame.data() + 2, frame.size() - 2)); + ASSERT_TRUE(PollNetPair(server, client, server_events, client_events, [&] { return HasNetEvent(server_events, net::EventKind::Recv); })); + for (const auto &event: server_events) + if (event.kind == net::EventKind::Recv) EXPECT_EQ(event.data, payload); + ASSERT_TRUE(server.Send(0, payload.data(), payload.size())); + ASSERT_TRUE(PollNetPair(server, client, server_events, client_events, [&] { + size_t bytes = 0; + for (const auto &event: client_events) + if (event.kind == net::EventKind::Recv) bytes += event.data.size(); + return bytes >= payload.size() + 4; + })); + std::string response; + for (const auto &event: client_events) + if (event.kind == net::EventKind::Recv) response += event.data; + EXPECT_EQ(response, std::string("\x81\x7e\x01\x2c", 4) + payload); + std::string too_large(65536, 'x'); + EXPECT_FALSE(server.Send(0, too_large.data(), too_large.size())); + const std::string close("\x88\x80\x01\x02\x03\x04", 6); + ASSERT_TRUE(client.Send(close.data(), close.size())); + ASSERT_TRUE(PollNetPair(server, client, server_events, client_events, [&] { return HasNetEvent(client_events, net::EventKind::Close); })); + EXPECT_FALSE(client.Connected()); +} + +TEST(test_net, websocket_client_rejects_status_and_missing_accept_header) { + for (const std::string response: {"HTTP/1.1 400 Bad Request\r\n\r\n", "HTTP/1.1 101 Switching Protocols\r\n\r\n"}) { + FakeluaStateGuard state; + net::NetConfig server_config; + server_config.port = 19974; + server_config.framer = net::FramerType::RawStream; + net::TcpServer server(server_config, state.GetState()); + server.Start(); + ASSERT_TRUE(server.Running()); + auto client_config = server_config; + client_config.framer = net::FramerType::WebSocket; + net::TcpClient client(client_config, state.GetState()); + client.Connect(); + std::vector server_events, client_events; + ASSERT_TRUE(PollNetPair(server, client, server_events, client_events, [&] { return HasNetEvent(server_events, net::EventKind::Recv); })); + ASSERT_TRUE(server.Send(0, response.data(), response.size())); + ASSERT_TRUE(PollNetPair(server, client, server_events, client_events, [&] { return HasNetEvent(client_events, net::EventKind::Close); })); + EXPECT_FALSE(client.Connected()); + EXPECT_FALSE(HasNetEvent(client_events, net::EventKind::Connect)); + } +} + +TEST(test_net, tls_client_reports_invalid_ca_without_starting_connection) { + FakeluaStateGuard state; + net::NetConfig config; + config.tls = true; + config.tls_ca = "./tls/nonexistent_validation_ca.pem"; + net::TcpClient client(config, state.GetState()); + client.Connect(); + int closed = 0; + client.DrainEventsWith([&](const auto &event) { + if (event.kind == net::EventKind::Close) ++closed; + }); + EXPECT_EQ(closed, 1); + EXPECT_FALSE(client.Connected()); +} + +TEST(test_net, explicit_group_destruction_unregisters_live_wrapper) { + FakeluaStateGuard state; + CompileString(state.GetState(), R"(function live_wrapper_factory() return net.server({ip = "127.0.0.1", port = 19979}) end)", {}); + CVar value = CallByNameArgs(state.GetState(), JIT_INTERP, "live_wrapper_factory", 0, nullptr); + auto *object = NativeObject::Unwrap(value); + ASSERT_NE(object, nullptr); + const auto group = object->GetGroupId(); + EXPECT_EQ(state.GetState()->GetNativeObjectManager().DestroyGroup(group), 1u); + EXPECT_EQ(state.GetState()->GetNativeObjectManager().DestroyGroup(group), 0u); +} + +TEST(test_net, custom_parser_return_contracts_and_multivalue_close_with_gcc_callbacks) { + FakeluaStateGuard state; + int received = 0; + RegisterNativeFunction(state.GetState(), "custom_contract_seen", 1, false, [&](State *s, CVar *args, int) { + EXPECT_EQ(inter::CVarToString(args[0], ""), "abc"); + ++received; + return inter::NativeToFakeluaNil(s); + }); + RegisterNativeFunction(state.GetState(), "custom_contract_received", 0, false, [&](State *s, CVar *, int) { return inter::NativeToFakeluaInt(s, received); }); + CompileConfig config; + config.disable_jit[JIT_TCC] = true; + CompileFile(state.GetState(), "./net/test_net_native_parser.lua", config); + int64_t result = 0; + Call(state.GetState(), JIT_GCC, "test_custom_parser_return_contracts", result); + EXPECT_EQ(result, 1); + EXPECT_EQ(received, 2); +} + +TEST(test_net, callback_send_queue_limit_and_deferred_invalid_destination) { + FakeluaStateGuard state; + CVar server; + bool dispatched = false; + RegisterNativeFunction(state.GetState(), "cpp_queue_pressure", 5, false, [&](State *s, CVar *args, int) { + if (inter::CVarToString(args[0], "") == "conn") { + CVar parameters[] = {server, args[1]}; + CallByNameArgs(s, JIT_INTERP, "queue_limit_contract", 2, parameters); + dispatched = true; + } + return inter::NativeToFakeluaNil(s); + }); + RegisterNativeFunction(state.GetState(), "queue_pressure_done", 0, false, [&](State *s, CVar *, int) { return inter::NativeToFakeluaBool(s, dispatched); }); + CompileString(state.GetState(), R"( + function queue_limit_contract(server, connid) + assert(server:send(999999, "invalid destination")) + for i = 1, 4095 do assert(server:send(connid, "")) end + assert(not server:send(connid, "queue is bounded")) + end + function queue_server_factory() + local server = net.server({ip = "127.0.0.1", port = 19989, framer = "raw"}) + server:dispatch("cpp_queue_pressure") + return server + end + function queue_client_contract() + local client = net.client({ip = "127.0.0.1", port = 19989, framer = "raw"}) + for i = 1, 1000 do + runtime.tick() + if queue_pressure_done() then break end + os.sleep(1) + end + client:close() + assert(queue_pressure_done()) + return 1 + end + )", + {}); + server = CallByNameArgs(state.GetState(), JIT_INTERP, "queue_server_factory", 0, nullptr); + int64_t result = 0; + Call(state.GetState(), JIT_INTERP, "queue_client_contract", result); + EXPECT_EQ(result, 1); + EXPECT_TRUE(dispatched); +} + +TEST(test_net, connected_udp_callback_echo_directive) { + FakeluaStateGuard state; + bool received = false; + RegisterNativeFunction(state.GetState(), "connected_udp_seen", 0, false, [&](State *s, CVar *, int) { + received = true; + return inter::NativeToFakeluaNil(s); + }); + RegisterNativeFunction(state.GetState(), "connected_udp_done", 0, false, [&](State *s, CVar *, int) { return inter::NativeToFakeluaBool(s, received); }); + CompileString(state.GetState(), R"( + function udp_server_directive(kind, connid, data, length, reason) + if kind == "recv" then + if data == "start" then return "echo", "server-reply" end + assert(data == "client-echo") + connected_udp_seen() + return "close", nil + end + return nil + end + function udp_client_directive(kind, connid, data, length, reason) + if kind == "recv" then + assert(data == "server-reply") + return "echo", "client-echo" + end + return nil + end + function connected_udp_directive_contract() + local server = net.udp_server({ip = "127.0.0.1", port = 0}) + local client = net.udp_client({ip = "127.0.0.1", port = server:get_port()}) + server:dispatch("udp_server_directive") + client:dispatch("udp_client_directive") + assert(client:send("start")) + for i = 1, 1000 do + runtime.tick() + if connected_udp_done() then break end + os.sleep(1) + end + client:close() + server:close() + assert(connected_udp_done()) + return 1 + end + )", + {}); + int64_t result = 0; + Call(state.GetState(), JIT_INTERP, "connected_udp_directive_contract", result); + EXPECT_EQ(result, 1); + EXPECT_TRUE(received); +} diff --git a/test/test_os.cpp b/test/test_os.cpp index e992eaf1..103abd43 100644 --- a/test/test_os.cpp +++ b/test/test_os.cpp @@ -367,3 +367,22 @@ TEST(test_os, test_os_filesystem) { EXPECT_EQ(ret, 1); FakeluaDeleteState(s); } + +#if !defined(_WIN32) +TEST(test_os, execute_reports_shell_termination_signal) { + FakeluaStateGuard state; + CompileString(state.GetState(), R"( + function test_shell_signal_status() + local success, reason, signal = os.execute("kill -TERM $$") + assert(success == nil and reason == "signal" and signal == 15) + return 1 + end + )", + {}); + for (auto backend: AllJitTypes()) { + int64_t result = 0; + Call(state.GetState(), backend, "test_shell_signal_status", result); + EXPECT_EQ(result, 1); + } +} +#endif diff --git a/test/test_process.cpp b/test/test_process.cpp index 74be585f..337dc50c 100644 --- a/test/test_process.cpp +++ b/test/test_process.cpp @@ -75,3 +75,36 @@ TEST(test_process, output_over_8mb) { CallThrow(s, "ProcessTest.test_output_over_8mb", ret); FakeluaDeleteState(s); } + +TEST(test_process, argument_validation_environment_override_and_working_directory) { + FakeluaStateGuard state; + CompileFile(state.GetState(), "./process/test_process_options.lua", {}); + for (auto backend: AllJitTypes()) { + SCOPED_TRACE(JitTypeName(backend)); + int64_t result = 0; + Call(state.GetState(), backend, "test_process_options", result); + EXPECT_EQ(result, 1); + } +} + + +#if !defined(_WIN32) +TEST(test_process, completed_and_signaled_children_with_and_without_deadlines) { + FakeluaStateGuard state; + CompileString(state.GetState(), R"( + function child_exit_contracts() + local output, errors, code = process.run({"sh", "-c", "exit 7"}, {timeout_ms = 1000}) + assert(output == "" and errors == "" and code == 7) + output, errors, code = process.run({"sh", "-c", "kill -TERM $$"}, {timeout_ms = 1000}) + assert(output == "" and errors == "" and code == 143) + output, errors, code = process.run({"sh", "-c", "sleep 0.05; kill -TERM $$"}, {timeout_ms = 0}) + assert(output == "" and errors == "" and code == 143) + return 1 + end + )", + {}); + int64_t result = 0; + CallAll(state.GetState(), "child_exit_contracts", result); + EXPECT_EQ(result, 1); +} +#endif diff --git a/test/test_protobuf.cpp b/test/test_protobuf.cpp index 8861b3f7..e7ba5fab 100644 --- a/test/test_protobuf.cpp +++ b/test/test_protobuf.cpp @@ -1,6 +1,9 @@ #include "fakelua.h" +#include "native/protobuf/protobuf_parser.h" +#include "native/protobuf/protobuf_schema.h" #include "test_jit.h" #include "gtest/gtest.h" +#include using namespace fakelua; @@ -124,3 +127,203 @@ TEST(test_protobuf, test_optional_nil) { EXPECT_EQ(ret, 1); FakeluaDeleteState(s); } + +TEST(test_protobuf, parser_nested_options_and_type_resolution) { + FakeluaStateGuard state; + auto *s = state.GetState(); + const std::string schema = R"proto( + // Imports are declarations; callers load dependencies explicitly. + syntax = 'proto3'; package coverage.proto; + import public "public.proto"; import weak 'weak.proto'; ; + option java_package = "a\n\t\r\\\'\"\0\x"; + option (custom.(nested)) = 1.25; + /* A multi-line comment + must not alter declaration parsing. */ + enum Status { ; option allow_alias = 1; OK = 0 [deprecated = true]; }; + message Outer { + ; option deprecated = 1; + reserved 20 to 29, "old"; extensions 100 to 199; + message Inner { string text = 1; }; + enum Kind { ; ZERO = 0; ONE = 0x1; } + optional Inner child = 1 [deprecated = true]; + repeated coverage.proto.Outer.Inner children = 2; + Status status = 3; + Kind kind = 4; + map by_name = 5 [deprecated = true]; + map flags = 6; + oneof choice { + ; option (custom.choice) = "selected"; + string title = 7 [deprecated = true]; + Inner selected = 8; + } + }; + )proto"; + ASSERT_TRUE(protobuf::ParseProto(s, schema, "nested.proto").empty()); + auto ®istry = protobuf::GetProtobufState(s); + const auto *outer = registry.FindMessage("coverage.proto.Outer"); + ASSERT_NE(outer, nullptr); + ASSERT_EQ(outer->fields.size(), 8u); + EXPECT_TRUE(outer->fields[0].optional); + EXPECT_EQ(outer->fields[0].type_name, "coverage.proto.Outer.Inner"); + EXPECT_TRUE(outer->fields[1].repeated); + EXPECT_EQ(outer->fields[1].type_name, "coverage.proto.Outer.Inner"); + EXPECT_EQ(outer->fields[2].type, protobuf::TYPE_ENUM); + EXPECT_EQ(outer->fields[3].type, protobuf::TYPE_ENUM); + EXPECT_TRUE(outer->fields[4].is_map); + EXPECT_EQ(outer->fields[4].map_value_type_name, "coverage.proto.Outer.Inner"); + EXPECT_EQ(outer->fields[5].map_value_type, protobuf::TYPE_BOOL); + EXPECT_GE(outer->fields[6].oneof_index, 0); + EXPECT_EQ(outer->fields[6].oneof_index, outer->fields[7].oneof_index); + ASSERT_NE(registry.FindEnum("coverage.proto.Outer.Kind"), nullptr); + EXPECT_EQ(registry.FindEnum("coverage.proto.Outer.Kind")->number_to_name.at(1), "ONE"); +} + +TEST(test_protobuf, parser_reports_malformed_declarations) { + struct InvalidSchema { + const char *text; + const char *message; + }; + + const InvalidSchema cases[] = { + {"@", "unexpected character"}, + {"syntax = 3;", "expected syntax string"}, + {"syntax 'proto3';", "expected '='"}, + {"optional", "unexpected token"}, + {"message {}", "expected message name"}, + {"message M { 1 x = 1; }", "expected field type"}, + {"message M { string = 1; }", "expected field name"}, + {"message M { string x = name; }", "expected field number"}, + {"message M { string x = 99999999999999999999999999; }", "invalid field number"}, + {"message M { foo. = 1; }", "expected identifier after '.'"}, + {"message M { map<1, string> x = 1; }", "expected map key type"}, + {"message M { map x = 1; }", "expected type name"}, + {"message M { map = 1; }", "expected map field name"}, + {"message M { map x = 1; }", "unknown proto scalar type"}, + {"message M { oneof { } }", "expected oneof name"}, + {"message M { oneof choice { int32 = 1; } }", "expected field name"}, + {"enum {}", "expected enum name"}, + {"enum E { 1 = 2; }", "expected enum value name"}, + {"message M { string x = 1 [", "expected ';'"}, + {"message M { map x = 1 [", "expected ';'"}, + {"message M { oneof choice { string x = 1 [", "expected ';'"}, + {"enum E { X = 1 [", "expected ';'"}, + {"message M { reserved 2", "expected ';'"}, + {"message M { extensions 2", "expected ';'"}, + {"option (unfinished", "expected ';'"}, + }; + for (const auto &test: cases) { + SCOPED_TRACE(test.text); + FakeluaStateGuard state; + const auto error = protobuf::ParseProto(state.GetState(), test.text, "invalid.proto"); + EXPECT_NE(error.find(test.message), std::string::npos) << error; + } +} + +TEST(test_protobuf, schema_registry_replacement_and_state_isolation) { + FakeluaStateGuard first, second; + auto &a = protobuf::GetProtobufState(first.GetState()); + auto &b = protobuf::GetProtobufState(second.GetState()); + ASSERT_TRUE(protobuf::ParseProto(first.GetState(), "message M { string later = 3; int32 earlier = 1; }", "first.proto").empty()); + ASSERT_NE(a.FindMessage("M"), nullptr); + EXPECT_EQ(a.FindMessage("M")->number_to_field.at(1)->name, "earlier"); + EXPECT_EQ(a.FindMessage("M")->number_to_field.at(3)->name, "later"); + EXPECT_EQ(b.FindMessage("M"), nullptr); + EXPECT_EQ(b.FindEnum("E"), nullptr); + ASSERT_TRUE(protobuf::ParseProto(first.GetState(), "enum E { ZERO = 0; } message M { E status = 2; }", "replacement.proto").empty()); + ASSERT_NE(a.FindMessage("M"), nullptr); + ASSERT_EQ(a.FindMessage("M")->fields.size(), 1u); + EXPECT_EQ(a.FindMessage("M")->fields[0].type, protobuf::TYPE_ENUM); + EXPECT_EQ(a.MessageNames(), std::vector{"M"}); + a.Clear(); + EXPECT_TRUE(a.MessageNames().empty()); + EXPECT_EQ(a.FindEnum("E"), nullptr); +} + +TEST(test_protobuf, wire_scalar_boundaries_and_truncated_inputs) { + using namespace fakelua::protobuf; + for (uint64_t value: {uint64_t{0}, uint64_t{127}, uint64_t{128}, uint64_t{16384}, std::numeric_limits::max()}) { + std::string encoded; + WriteVarint(encoded, value); + size_t position = 0; + EXPECT_EQ(ReadVarint(encoded, position), value); + EXPECT_EQ(position, encoded.size()); + position = 0; + SkipValue(encoded, position, WIRE_VARINT); + EXPECT_EQ(position, encoded.size()); + } + for (const auto &truncated: {std::string{}, std::string(1, '\x80'), std::string(10, '\x80')}) { + size_t position = 0; + EXPECT_THROW(ReadVarint(truncated, position), std::exception); + } + for (size_t length = 0; length < 8; ++length) { + const std::string data(length, '\0'); + size_t position = 0; + EXPECT_THROW(ReadFixed64(data, position), std::exception); + position = 0; + EXPECT_THROW(SkipValue(data, position, WIRE_64BIT), std::exception); + if (length < 4) { + position = 0; + EXPECT_THROW(ReadFixed32(data, position), std::exception); + position = 0; + EXPECT_THROW(SkipValue(data, position, WIRE_32BIT), std::exception); + } + } + for (uint8_t wire: {uint8_t{3}, uint8_t{4}, uint8_t{6}, uint8_t{7}}) { + size_t position = 0; + EXPECT_THROW(SkipValue("", position, wire), std::exception); + } + size_t position = std::numeric_limits::max(); + EXPECT_THROW(ReadFixed32("data", position), std::exception); + position = std::numeric_limits::max(); + EXPECT_THROW(ReadFixed64("data", position), std::exception); + for (auto wire: {WIRE_32BIT, WIRE_64BIT}) { + std::string encoded; + if (wire == WIRE_32BIT) WriteFixed32(encoded, 0x12345678); + else + WriteFixed64(encoded, 0x123456789abcdef0ull); + position = 0; + SkipValue(encoded, position, wire); + EXPECT_EQ(position, encoded.size()); + } + const std::string length_delimited("\x03" + "abc", + 4); + position = 0; + EXPECT_EQ(ReadLengthDelimited(length_delimited, position), "abc"); + EXPECT_EQ(position, length_delimited.size()); + position = 0; + SkipValue(length_delimited, position, WIRE_LEN); + EXPECT_EQ(position, length_delimited.size()); + position = 0; + EXPECT_THROW(ReadLengthDelimited(std::string("\x04" + "abc", + 4), + position), + std::exception); + position = 0; + EXPECT_THROW(SkipValue(std::string("\x04" + "abc", + 4), + position, WIRE_LEN), + std::exception); +} + +TEST(test_protobuf, nested_message_containers_and_complete_field_metadata) { + FakeluaStateGuard state; + CompileFile(state.GetState(), "./protobuf/test_protobuf_nested_containers.lua", {}); + for (auto backend: AllJitTypes()) { + int64_t result = 0; + Call(state.GetState(), backend, "test_protobuf_nested_containers", result); + EXPECT_EQ(result, 1) << JitTypeName(backend); + Call(state.GetState(), backend, "test_protobuf_metadata_contracts", result); + EXPECT_EQ(result, 1) << JitTypeName(backend); + } +} + +TEST(test_protobuf, scalar_repeated_compatibility_unknown_map_fields_and_nesting_limit) { + FakeluaStateGuard state; + CompileFile(state.GetState(), "./protobuf/test_protobuf_wire_compatibility.lua", {}); + int64_t result = 0; + CallAll(state.GetState(), "test_protobuf_wire_compatibility", result); + EXPECT_EQ(result, 1); +} diff --git a/test/test_random.cpp b/test/test_random.cpp index f0faac4e..ff7674ac 100644 --- a/test/test_random.cpp +++ b/test/test_random.cpp @@ -91,3 +91,12 @@ TEST(test_random, destroy) { EXPECT_EQ(ret, 1); FakeluaDeleteState(s); } + +TEST(test_random, full_signed_range_state_spelling_and_overflow_validation) { + FakeluaStateGuard state; + CompileConfig config; + CompileFile(state.GetState(), "./random/test_random_additional_contracts.lua", config); + int64_t result = 0; + CallAll(state.GetState(), "test_random_contracts", result); + EXPECT_EQ(result, 1); +} diff --git a/test/test_redis.cpp b/test/test_redis.cpp index 8aba3e53..3b2d1c50 100644 --- a/test/test_redis.cpp +++ b/test/test_redis.cpp @@ -1,4 +1,7 @@ #include "fakelua.h" +#include "jit/vm.h" +#include "native/object/native_object.h" +#include "state/state.h" #include "test_jit.h" #include "gtest/gtest.h" @@ -134,3 +137,34 @@ TEST(test_redis, subscribe_rejected) { EXPECT_EQ(ret, 1); FakeluaDeleteState(s); } + +TEST(test_redis, authentication_errors_database_selection_and_resp3_scalars) { + FakeluaStateGuard state; + CompileFile(state.GetState(), "./redis/test_redis_handshake_contracts.lua", {}); + for (auto backend: AllJitTypes()) { + int64_t result = 0; + Call(state.GetState(), backend, "RedisHandshake.test_handshake_contracts", result); + EXPECT_EQ(result, 1) << JitTypeName(backend); + } +} + +TEST(test_redis, pending_connection_and_deep_reply_contracts) { + CompileConfig config; + config.disable_jit[JIT_TCC] = true; + FakeluaStateGuard state; + CompileFile(state.GetState(), "./redis/test_redis_handshake_contracts.lua", config); + int64_t result = 0; + Call(state.GetState(), JIT_GCC, "RedisHandshake.test_pending_connection_and_deep_reply_contracts", result); + EXPECT_EQ(result, 1); +} + +TEST(test_redis, explicit_group_destruction_unregisters_live_wrapper) { + FakeluaStateGuard state; + CompileString(state.GetState(), R"(function live_wrapper_factory() return redis.connect({host = "127.0.0.1", port = 6379}, "unused_callback") end)", {}); + CVar value = CallByNameArgs(state.GetState(), JIT_INTERP, "live_wrapper_factory", 0, nullptr); + auto *object = NativeObject::Unwrap(value); + ASSERT_NE(object, nullptr); + const auto group = object->GetGroupId(); + EXPECT_EQ(state.GetState()->GetNativeObjectManager().DestroyGroup(group), 1u); + EXPECT_EQ(state.GetState()->GetNativeObjectManager().DestroyGroup(group), 0u); +} diff --git a/test/test_runtime.cpp b/test/test_runtime.cpp index badf1562..ca4555ac 100644 --- a/test/test_runtime.cpp +++ b/test/test_runtime.cpp @@ -1,5 +1,6 @@ #include "compile/compiler.h" #include "fakelua.h" +#include "interp/func_proto.h" #include "interp/runtime.h" #include "interp/vm_ops.h" #include "jit/vm.h" @@ -830,3 +831,193 @@ TEST(runtime, vm_ops_for_and_arith_edges) { step = Float(0.0); EXPECT_THROW(ForPrep(idx, limit, step, loopvar), std::exception); } + +TEST(runtime, multireturn_argument_limit_is_checked_for_named_and_closure_calls) { + FakeluaStateGuard state; + auto *s = state.GetState(); + RegisterNativeFunction(s, "runtime_opaque_closure", 1, false, [](State *, CVar *args, int) { return args[0]; }); + RegisterNativeFunction(s, "runtime_arg_count", 0, true, [](State *s, CVar *, int n) { return inter::NativeToFakeluaInt(s, n); }); + RegisterNativeFunction(s, "runtime_expanded_values", 1, false, [](State *s, CVar *args, int) { + const int count = static_cast(inter::CVarToInteger(args[0])); + CVar result = inter::AllocMultiCVar(s, count); + for (int i = 0; i < count; ++i) inter::SetMultiCVarElement(result, i, inter::NativeToFakeluaInt(s, 1)); + return result; + }); + std::string prefix; + for (size_t i = 1; i < kMaxFunctionInputParams; ++i) prefix += "1,"; + std::string source = "function named_arity_target(...) return runtime_arg_count(...) end\n"; + for (bool closure: {false, true}) { + for (bool tail: {false, true}) { + const std::string name = std::string(closure ? "closure" : "named") + (tail ? "_tail" : "_regular"); + source += "function limit_" + name + "(count)\n"; + if (closure) source += "local target = runtime_opaque_closure(function(...) return runtime_arg_count(...) end)\n"; + const std::string call = (closure ? "target(" : "named_arity_target(") + prefix + "runtime_expanded_values(count))"; + source += tail ? "return " + call + "\n" : "local result = " + call + "\nreturn result\n"; + source += "end\n"; + } + } + CompileString(s, source, {}); + for (auto backend: AllJitTypes()) { + for (const char *suffix: {"named_regular", "named_tail", "closure_regular", "closure_tail"}) { + SCOPED_TRACE(::testing::Message() << JitTypeName(backend) << " " << suffix); + const std::string name = std::string("limit_") + suffix; + int64_t result = 0; + Call(s, backend, name, result, 1); + EXPECT_EQ(result, kMaxFunctionInputParams); + EXPECT_THROW(Call(s, backend, name, result, 2), std::exception); + } + } +} + +TEST(runtime, interpreter_bytecode_globals_and_explicit_throw_locations) { + FakeluaStateGuard state; + auto *s = state.GetState(); + InterpUnit unit; + unit.state = s; + unit.file_name = "bytecode-contract.lua"; + FuncProto function; + function.unit = &unit; + function.max_stack = 1; + // Constant-pool names may use ordinary runtime strings as well as intern IDs. + function.constants = {inter::NativeToFakeluaString(s, "_VERSION")}; + function.code = {{Op::GETGLOBAL, 0, 0, 0, 0}, {Op::RETURN, 0, 1}}; + EXPECT_TRUE(inter::CVarToString(InterpreterExecute(s, &function, nullptr, 0, nullptr), "").starts_with("Fakelua ")); + function.constants[0] = inter::NativeToFakeluaString(s, "missing_global"); + EXPECT_EQ(InterpreterExecute(s, &function, nullptr, 0, nullptr).type_, static_cast(VarType::Nil)); + function.constants.push_back(inter::NativeToFakeluaInt(s, 19)); + function.code = {{Op::LOADK, 0, 0, 0, 1}, {Op::SETGLOBAL, 0, 0, 0, 0}, {Op::GETGLOBAL, 0, 0, 0, 0}, {Op::RETURN, 0, 1}}; + EXPECT_EQ(inter::CVarToInteger(InterpreterExecute(s, &function, nullptr, 0, nullptr)), 19); + EXPECT_EQ(inter::CVarToInteger(unit.globals.at("missing_global")), 19); + function.constants[0] = inter::NativeToFakeluaString(s, "explicit bytecode error"); + function.code = {{Op::THROW, 0, 0, 0, 0}}; + function.lineinfo = {41}; + try { + (void) InterpreterExecute(s, &function, nullptr, 0, nullptr); + FAIL() << "THROW opcode did not throw"; + } catch (const std::exception &error) { + EXPECT_NE(std::string(error.what()).find("explicit bytecode error"), std::string::npos); + EXPECT_NE(std::string(error.what()).find("bytecode-contract.lua:41"), std::string::npos); + } +} + +TEST(runtime, interpreter_bytecode_empty_table_entry_returns_nil_pair) { + FakeluaStateGuard state; + InterpUnit unit; + unit.state = state.GetState(); + FuncProto function; + function.unit = &unit; + function.max_stack = 4; + function.constants = {inter::NativeToFakeluaInt(state.GetState(), 0)}; + function.code = {{Op::NEWTABLE, 0}, {Op::LOADK, 3, 0, 0, 0}, {Op::TABENT, 0, 1, 2, 3}, {Op::MAKEMULTI, 1, 2}, {Op::RETURN, 1}}; + CVar result = InterpreterExecute(state.GetState(), &function, nullptr, 0, nullptr); + ASSERT_EQ(result.type_, static_cast(VarType::Multi)); + ASSERT_EQ(inter::GetMultiCVarCount(result), 2); + EXPECT_EQ(inter::GetMultiCVarElement(result, 0).type_, static_cast(VarType::Nil)); + EXPECT_EQ(inter::GetMultiCVarElement(result, 1).type_, static_cast(VarType::Nil)); +} + +TEST(runtime, interpreter_bytecode_lazy_capture_cell_remains_shared) { + FakeluaStateGuard state; + InterpUnit unit; + unit.state = state.GetState(); + FuncProto child; + child.unit = &unit; + child.max_stack = 1; + child.upvalues = {{true, 0}}; + child.code = {{Op::GETUPVAL, 0, 0}, {Op::RETURN, 0, 1}}; + FuncProto parent; + parent.unit = &unit; + parent.max_stack = 2; + parent.uses_boxes = true; + parent.constants = {inter::NativeToFakeluaInt(state.GetState(), 42), inter::NativeToFakeluaInt(state.GetState(), 7)}; + parent.child_protos = {&child}; + parent.code = {{Op::LOADK, 0, 0, 0, 0}, {Op::CLOSURE, 1, 0, 0, 0}, {Op::LOADK, 0, 0, 0, 1}, {Op::RETURN, 1, 1}}; + CVar closure = InterpreterExecute(state.GetState(), &parent, nullptr, 0, nullptr); + ASSERT_EQ(closure.type_, static_cast(VarType::Closure)); + EXPECT_EQ(inter::CVarToInteger(InterpreterExecute(state.GetState(), &child, nullptr, 0, closure.data_.cl)), 7); + // A bytecode producer that forgets the capture-storage flag must get a + // deterministic validation error, not an invalid box-pointer dereference. + parent.uses_boxes = false; + EXPECT_THROW(InterpreterExecute(state.GetState(), &parent, nullptr, 0, nullptr), std::exception); +} + +TEST(runtime, interpreter_bytecode_empty_functions_upvalues_and_box_validation) { + FakeluaStateGuard state; + InterpUnit unit; + unit.state = state.GetState(); + FuncProto function; + function.unit = &unit; + function.max_stack = 1; + EXPECT_EQ(InterpreterExecute(state.GetState(), &function, nullptr, 0, nullptr).type_, static_cast(VarType::Nil)); + function.code = {{Op::GETUPVAL, 0, 0}, {Op::RETURN, 0, 1}}; + EXPECT_EQ(InterpreterExecute(state.GetState(), &function, nullptr, 0, nullptr).type_, static_cast(VarType::Nil)); + function.code = {{Op::NEWBOX, 0}, {Op::RETURN, 0, 1}}; + EXPECT_THROW(InterpreterExecute(state.GetState(), &function, nullptr, 0, nullptr), std::exception); + function.uses_boxes = true; + EXPECT_EQ(InterpreterExecute(state.GetState(), &function, nullptr, 0, nullptr).type_, static_cast(VarType::Nil)); + function.uses_boxes = false; + function.constants = {inter::NativeToFakeluaString(state.GetState(), "unresolved_bytecode_target")}; + for (const auto operation: {Op::CALLNAME, Op::TAILNAME, Op::TAIL}) { + function.code = {{operation, 0, 33}}; + EXPECT_THROW(InterpreterExecute(state.GetState(), &function, nullptr, 0, nullptr), std::exception); + } +} + +TEST(runtime, interpreter_tail_call_flattens_nonfinal_multi_and_missing_named_backend) { + FakeluaStateGuard state; + CompileString(state.GetState(), "function tail_abi_target(first, second) return first, second end", {}); + InterpUnit unit; + unit.state = state.GetState(); + FuncProto function; + function.unit = &unit; + function.param_count = 2; + function.max_stack = 2; + function.constants = {inter::NativeToFakeluaString(state.GetState(), "tail_abi_target")}; + function.code = {{Op::TAILNAME, 0, 2, 0, 0}}; + CVar values[] = {inter::AllocMultiCVar(state.GetState(), 2), inter::NativeToFakeluaInt(state.GetState(), 9)}; + inter::SetMultiCVarElement(values[0], 0, inter::NativeToFakeluaInt(state.GetState(), 7)); + inter::SetMultiCVarElement(values[0], 1, inter::NativeToFakeluaInt(state.GetState(), 8)); + CVar result = InterpreterExecute(state.GetState(), &function, values, 2, nullptr); + EXPECT_EQ(inter::CVarToInteger(inter::GetMultiCVarElement(result, 0)), 7); + EXPECT_EQ(inter::CVarToInteger(inter::GetMultiCVarElement(result, 1)), 9); + values[0] = inter::AllocMultiCVar(state.GetState(), 0); + result = InterpreterExecute(state.GetState(), &function, values, 2, nullptr); + EXPECT_EQ(inter::GetMultiCVarElement(result, 0).type_, static_cast(VarType::Nil)); + EXPECT_EQ(inter::CVarToInteger(inter::GetMultiCVarElement(result, 1)), 9); + values[0] = inter::NativeToFakeluaInt(state.GetState(), 7); + function.code[0].b = 1; + EXPECT_THROW(InterpreterExecute(state.GetState(), &function, values, 2, nullptr), std::exception); + CompileConfig config; + DisableAllJit(config); + config.disable_jit[JIT_GCC] = false; + CompileString(state.GetState(), "function gcc_only_tail_target(value) return value end", config); + function.constants[0] = inter::NativeToFakeluaString(state.GetState(), "gcc_only_tail_target"); + EXPECT_THROW(InterpreterExecute(state.GetState(), &function, values, 2, nullptr), std::exception); +} + +TEST(runtime, generated_call_abi_rejects_out_of_range_argument_metadata) { + FakeluaStateGuard state; + CompileString(state.GetState(), "function host_abi_target() return 7 end", {}); + void *address = state.GetState()->GetVM().GetFunction("host_abi_target").GetAddr(JIT_GCC); + ASSERT_NE(address, nullptr); + EXPECT_THROW(inter::DispatchCall(state.GetState(), address, nullptr, 33, JIT_GCC), std::exception); + CVar closure = interp_rt::MakeClosure(state.GetState(), address, 0, 33, false, nullptr); + EXPECT_THROW(inter::DispatchCallClosure(state.GetState(), closure.data_.cl, nullptr, 0, JIT_GCC), std::exception); +} + +TEST(runtime, host_native_call_flattens_nonfinal_multi_and_nested_empty_values) { + FakeluaStateGuard state; + RegisterNativeFunction(state.GetState(), "host_multi_pair", 2, false, [](State *s, CVar *args, int count) { + EXPECT_EQ(count, 2); + EXPECT_EQ(inter::CVarToInteger(args[1]), 9); + return args[0]; + }); + CVar args[] = {inter::AllocMultiCVar(state.GetState(), 2), inter::NativeToFakeluaInt(state.GetState(), 9)}; + inter::SetMultiCVarElement(args[0], 0, inter::NativeToFakeluaInt(state.GetState(), 7)); + inter::SetMultiCVarElement(args[0], 1, inter::NativeToFakeluaInt(state.GetState(), 8)); + EXPECT_EQ(inter::CVarToInteger(CallByNameArgs(state.GetState(), JIT_INTERP, "host_multi_pair", 2, args)), 7); + args[0] = inter::AllocMultiCVar(state.GetState(), 0); + EXPECT_EQ(CallByNameArgs(state.GetState(), JIT_INTERP, "host_multi_pair", 2, args).type_, static_cast(VarType::Nil)); + CVar nested[] = {inter::NativeToFakeluaInt(state.GetState(), 1), args[0]}; + EXPECT_EQ(inter::GetNativeArg(state.GetState(), nested, 2, 1).type_, static_cast(VarType::Nil)); +} diff --git a/test/test_serialize.cpp b/test/test_serialize.cpp index 0ddd5faf..8e159389 100644 --- a/test/test_serialize.cpp +++ b/test/test_serialize.cpp @@ -1,4 +1,8 @@ #include "fakelua.h" +#include "jit/vm.h" +#include "native/native_common.h" +#include "native/serialize/wire_codec.h" +#include "native/table/native_table.h" #include "test_jit.h" #include "gtest/gtest.h" @@ -154,3 +158,112 @@ TEST(test_serialize, test_text_bad) { CallThrow(s, "SerializeTest.test_text_bad", ret); FakeluaDeleteState(s); } + +TEST(test_serialize, wire_rejects_truncated_overlong_and_unknown_encodings) { + FakeluaStateGuard state; + const std::vector malformed{{}, + std::string("\x03\x80", 2), + std::string("\x03", 1) + std::string(10, '\x80'), + std::string("\x04", 1) + std::string(7, '\0'), + std::string("\x05\x04x", 3), + std::string("\x06\0", 2), + std::string("\xff", 1), + std::string("\0\0", 2)}; + for (const auto &input: malformed) { + SCOPED_TRACE(::testing::PrintToString(input)); + EXPECT_THROW(serialize::WireDecode(state.GetState(), input), std::exception); + } + EXPECT_THROW(serialize::WireDecodeCallbackArgs(state.GetState(), std::string("\0\0", 2)), std::exception); + EXPECT_TRUE(serialize::WireDecodeCallbackArgs(state.GetState(), {}).vars.empty()); +} + +TEST(test_serialize, callback_tuple_owns_binary_strings_and_preserves_nil_slots) { + FakeluaStateGuard state; + auto *s = state.GetState(); + const std::string binary("a\0b", 3); + std::vector args{inter::NativeToFakeluaNil(s), inter::NativeToFakeluaBool(s, false), inter::NativeToFakeluaInt(s, -42), + inter::NativeToFakeluaDouble(s, 1.25), inter::NativeToFakeluaString(s, binary), inter::NativeToFakeluaString(s, binary)}; + auto encoded = serialize::WireEncodeCallbackArgs(s, args.data(), 0, args.size(), "test_callback", 1); + auto decoded = serialize::WireDecodeCallbackArgs(s, encoded); + encoded.assign(encoded.size(), '?'); + ASSERT_EQ(decoded.vars.size(), args.size()); + EXPECT_EQ(decoded.vars[0].type_, static_cast(VarType::Nil)); + EXPECT_FALSE(inter::CVarToBool(decoded.vars[1], true)); + EXPECT_EQ(inter::CVarToInteger(decoded.vars[2]), -42); + EXPECT_DOUBLE_EQ(inter::CVarToNumber(decoded.vars[3]), 1.25); + EXPECT_EQ(inter::CVarToString(decoded.vars[4], ""), binary); + EXPECT_EQ(inter::CVarToString(decoded.vars[5], ""), binary); + EXPECT_EQ(serialize::WireDecode(s, serialize::WireEncode(args[0])).type_, static_cast(VarType::Nil)); +} + +TEST(test_serialize, callback_graph_rejects_cycles_depth_and_nested_closures) { + FakeluaStateGuard state; + auto *s = state.GetState(); + CVar cycle = table::TableHelper::CreateTable(s); + table::TableHelper::SetTableStrId(s, cycle, "self", cycle); + EXPECT_THROW(serialize::WireEncodeCallbackArgs(s, &cycle, 0, 1, "callback", 1), std::exception); + EXPECT_THROW(serialize::WireEncode(cycle), std::exception); + CVar root = table::TableHelper::CreateTable(s); + CVar tail = root; + for (int i = 0; i < 65; ++i) { + CVar next = table::TableHelper::CreateTable(s); + table::TableHelper::SetTableStrId(s, tail, "next", next); + tail = next; + } + EXPECT_THROW(serialize::WireEncodeCallbackArgs(s, &root, 0, 1, "callback", 1), std::exception); + CompileConfig config; + DisableAllJit(config); + config.disable_jit[JIT_INTERP] = false; + config.debug_mode = false; + CompileString(s, "function wire_closure_factory() return function() return 1 end end", config); + CVar closure = CallByNameArgs(s, JIT_INTERP, "wire_closure_factory", 0, nullptr); + EXPECT_FALSE(serialize::WireIsSerializable(closure)); + EXPECT_THROW(serialize::WireEncode(closure), std::exception); + CVar nested = table::TableHelper::CreateTable(s); + table::TableHelper::SetTableStrId(s, nested, "callback", closure); + EXPECT_THROW(serialize::WireEncodeCallbackArgs(s, &nested, 0, 1, "callback", 1), std::exception); +} + +TEST(test_serialize, unsupported_values_depth_and_malformed_xml_contracts) { + FakeluaStateGuard state; + CompileString(state.GetState(), R"( + function serialization_boundary_contracts() + local unsupported = function() return 1 end + for _, encode in ipairs({function(v) return serialize.encode(v) end, function(v) return serialize.text_encode(v) end, function(v) return serialize.xml_encode(v) end}) do + local ok, message = pcall(encode, unsupported) + assert(not ok and string.find(message, "unsupported", 1, true)) + end + local deep = {} + local cursor = deep + for i = 1, 65 do local child = {} cursor.next = child cursor = child end + for _, encode in ipairs({function(v) return serialize.encode(v) end, function(v) return serialize.text_encode(v) end, function(v) return serialize.xml_encode(v) end}) do + local ok, message = pcall(encode, deep) + assert(not ok and string.find(message, "nesting too deep", 1, true)) + end + assert(not pcall(function() return serialize.xml_decode("") end)) + local xml = serialize.xml_encode(7) + local unknown, replacements = string.gsub(xml, "2", "99") + assert(replacements == 1) + local ok, message = pcall(function() return serialize.xml_decode(unknown) end) + assert(not ok and string.find(message, "unknown kind", 1, true)) + return 1 + end + )", + {}); + int64_t result = 0; + CallAll(state.GetState(), "serialization_boundary_contracts", result); + EXPECT_EQ(result, 1); +} + +TEST(test_serialize, nullable_host_table_encodes_as_empty_table) { + FakeluaStateGuard state; + CVar empty{static_cast(VarType::Table)}; + empty.data_.t = nullptr; + ASSERT_TRUE(serialize::WireIsSerializable(empty)); + CVar decoded = serialize::WireDecode(state.GetState(), serialize::WireEncode(empty)); + ASSERT_EQ(decoded.type_, static_cast(VarType::Table)); + EXPECT_EQ(table::TableHelper::GetTableLen(decoded), 0); + size_t entries = 0; + table::TableHelper::ForEachKV(decoded, [&](CVar, CVar) { ++entries; }); + EXPECT_EQ(entries, 0u); +} diff --git a/test/test_sqlite.cpp b/test/test_sqlite.cpp index e5aee02a..94febdd0 100644 --- a/test/test_sqlite.cpp +++ b/test/test_sqlite.cpp @@ -1,6 +1,8 @@ #include "fakelua.h" #include "test_jit.h" #include "gtest/gtest.h" +#include +#include using namespace fakelua; @@ -278,3 +280,16 @@ TEST(test_sqlite, exec_nul) { EXPECT_EQ(ret, 1); FakeluaDeleteState(s); } + +TEST(test_sqlite, constraint_bind_reset_and_open_error_contracts) { + FakeluaStateGuard state; + CompileFile(state.GetState(), "./sqlite/test_sqlite_error_contracts.lua", {}); + const auto missing = std::filesystem::temp_directory_path() / ("fakelua-sqlite-missing-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count())) / "db.sqlite"; + ASSERT_FALSE(std::filesystem::exists(missing.parent_path())); + for (auto backend: AllJitTypes()) { + int64_t result = 0; + Call(state.GetState(), backend, "test_sqlite_error_contracts", result, missing.string()); + EXPECT_EQ(result, 1) << JitTypeName(backend); + EXPECT_FALSE(std::filesystem::exists(missing)); + } +} diff --git a/test/test_string.cpp b/test/test_string.cpp index 4d948c21..572790b0 100644 --- a/test/test_string.cpp +++ b/test/test_string.cpp @@ -1,6 +1,7 @@ #include #include "fakelua.h" +#include "native/native_common.h" #include "native/string/lua_pattern.h" #include "test_jit.h" @@ -975,3 +976,69 @@ TEST(test_string, cov_string_escapes_and_ops) { } FakeluaDeleteState(s); } + +TEST(test_string, argument_arity_contracts) { + FakeluaStateGuard state; + CompileFile(state.GetState(), "./string/test_string_argument_contracts.lua", {}); + int64_t result = 0; + CallAll(state.GetState(), "test_string_missing_arguments", result); + EXPECT_EQ(result, 1); +} + +TEST(test_string, integer_and_format_contracts) { + FakeluaStateGuard state; + CompileFile(state.GetState(), "./string/test_string_argument_contracts.lua", {}); + int64_t result = 0; + CallAll(state.GetState(), "test_string_integer_and_format_contracts", result); + EXPECT_EQ(result, 1); +} + +TEST(test_string, binary_roundtrips_all_integer_widths) { + FakeluaStateGuard state; + CompileFile(state.GetState(), "./string/test_string_binary_boundaries.lua", {}); + int64_t result = 0; + CallAll(state.GetState(), "test_string_binary_roundtrips", result); + EXPECT_EQ(result, 1); +} + +TEST(test_string, binary_format_validation) { + FakeluaStateGuard state; + CompileFile(state.GetState(), "./string/test_string_binary_boundaries.lua", {}); + int64_t result = 0; + CallAll(state.GetState(), "test_string_binary_rejects_invalid_formats", result); + EXPECT_EQ(result, 1); +} + +TEST(test_string, runtime_string_intrinsics_accept_host_strings_and_numeric_coercion) { + FakeluaStateGuard state; + RegisterNativeFunction(state.GetState(), "runtime_string_value", 1, false, [](State *s, CVar *args, int) { + if (args[0].type_ == static_cast(VarType::String) || args[0].type_ == static_cast(VarType::StringId)) return inter::NativeToFakeluaString(s, inter::CVarToString(args[0], "")); + return args[0]; + }); + CompileFile(state.GetState(), "./string/test_string_runtime_intrinsics.lua", {}); + for (auto backend: AllJitTypes()) { + SCOPED_TRACE(JitTypeName(backend)); + int64_t result = 0; + Call(state.GetState(), backend, "test_runtime_string_intrinsics", result); + EXPECT_EQ(result, 1); + } +} + +TEST(test_string, dump_load_preserves_scalar_captures_and_loaded_error_handlers) { + for (auto backend: AllJitTypes()) { + SCOPED_TRACE(JitTypeName(backend)); + FakeluaStateGuard state; + CompileFile(state.GetState(), "./string/test_string_dump_scalar_captures.lua", {}); + int64_t result = 0; + Call(state.GetState(), backend, "test_dump_scalar_captures", result); + EXPECT_EQ(result, 1); + } +} + +TEST(test_string, alignment_lookahead_zero_hex_and_position_capture_replacements) { + FakeluaStateGuard state; + CompileFile(state.GetState(), "./string/test_string_binary_boundaries.lua", {}); + int64_t result = 0; + CallAll(state.GetState(), "test_additional_format_and_capture_contracts", result); + EXPECT_EQ(result, 1); +} diff --git a/test/test_table.cpp b/test/test_table.cpp index 731e0646..c57051c0 100644 --- a/test/test_table.cpp +++ b/test/test_table.cpp @@ -1,4 +1,11 @@ +#include "jit/vm.h" +#include "state/const_string.h" +#include "state/state.h" +#include "var/var_string.h" +#include "var/var_table.h" +#include #include +#include #include "fakelua.h" #include "native/table/native_table.h" @@ -506,3 +513,203 @@ TEST(test_table, test_table_move_unpack_limits) { FakeluaDeleteState(s); } + +namespace { +void RegisterOpaqueTableKeys(State *s) { + RegisterNativeFunction(s, "opaque_table_key", 1, false, [](State *, CVar *args, int) { return args[0]; }); + RegisterNativeFunction(s, "opaque_string_key", 1, false, [](State *state, CVar *args, int) { return inter::NativeToFakeluaStringView(state, AsVar(args[0]).ToString(false, false)); }); +} +}// namespace + +TEST(test_table, dynamic_quick_keys_and_cross_string_representations) { + FakeluaStateGuard state; + RegisterOpaqueTableKeys(state.GetState()); + CompileFile(state.GetState(), "./table/test_table_dynamic_keys.lua", {}); + int64_t result = 0; + CallAll(state.GetState(), "test_dynamic_quick_keys", result); + EXPECT_EQ(result, 1); +} + +TEST(test_table, dynamic_hash_collision_insert_update_remove) { + FakeluaStateGuard state; + RegisterOpaqueTableKeys(state.GetState()); + CompileFile(state.GetState(), "./table/test_table_dynamic_keys.lua", {}); + int64_t result = 0; + CallAll(state.GetState(), "test_dynamic_collision_chains", result); + EXPECT_EQ(result, 1); +} + +TEST(test_table, host_sparse_hash_promotes_dense_prefix_without_losing_keys) { + FakeluaStateGuard state; + auto *s = state.GetState(); + CVar value = table::TableHelper::CreateTable(s); + for (int64_t key: {2, 3, 4, 5, 50, 60, 70, 80, 100}) table::TableHelper::SetTableInt(s, value, key, inter::NativeToFakeluaInt(s, key * 10)); + for (int64_t key: {2, 3, 4, 5, 50, 60, 70, 80, 100}) EXPECT_EQ(inter::CVarToInteger(table::TableHelper::GetTableInt(s, value, key)), key * 10); + EXPECT_EQ(table::TableHelper::GetTableLen(value), 0); + table::TableHelper::SetTableInt(s, value, 1, inter::NativeToFakeluaInt(s, 10)); + EXPECT_EQ(table::TableHelper::GetTableLen(value), 5); + EXPECT_EQ(table::TableHelper::CollectKVPairs(value).size(), 10u); + CVar nan{}; + nan.type_ = static_cast(VarType::Float); + nan.data_.f = std::numeric_limits::quiet_NaN(); + EXPECT_THROW(table::TableHelper::SetTable(s, value, nan, inter::NativeToFakeluaInt(s, 1)), std::exception); +} + +TEST(test_table, host_table_and_closure_keys_use_reference_identity) { + FakeluaStateGuard state; + auto *s = state.GetState(); + CompileString(s, "function table_key_factory() return function() return 1 end end", {}); + CVar value = table::TableHelper::CreateTable(s); + std::vector keys; + for (int i = 0; i < 12; ++i) { + keys.push_back(table::TableHelper::CreateTable(s)); + keys.push_back(CallByNameArgs(s, JIT_INTERP, "table_key_factory", 0, nullptr)); + } + for (size_t i = 0; i < keys.size(); ++i) table::TableHelper::SetTable(s, value, keys[i], inter::NativeToFakeluaInt(s, i + 10)); + for (size_t i = 0; i < keys.size(); ++i) EXPECT_EQ(inter::CVarToInteger(table::TableHelper::GetTable(s, value, keys[i])), i + 10); + for (size_t i = 0; i < keys.size(); i += 3) table::TableHelper::SetTable(s, value, keys[i], inter::NativeToFakeluaNil(s)); + for (size_t i = 0; i < keys.size(); ++i) { + const auto found = table::TableHelper::GetTable(s, value, keys[i]); + if (i % 3 == 0) EXPECT_EQ(found.type_, static_cast(VarType::Nil)); + else + EXPECT_EQ(inter::CVarToInteger(found), i + 10); + } + EXPECT_EQ(table::TableHelper::CollectKVPairs(value).size(), 16u); +} + +TEST(test_table, abi_spec_key_fallback_read_write_and_length) { + FakeluaStateGuard state; + auto *s = state.GetState(); + CVar value = table::TableHelper::CreateTable(s); + std::array keys{inter::NativeToFakeluaDouble(s, 1.0), inter::NativeToFakeluaInt(s, 2), inter::NativeToFakeluaString(s, "label")}; + std::array values{inter::NativeToFakeluaInt(s, 10), inter::NativeToFakeluaInt(s, 20), inter::NativeToFakeluaInt(s, 30)}; + value.data_.t->spec_keys = keys.data(); + value.data_.t->spec_vals = values.data(); + value.data_.t->spec_count = keys.size(); + value.data_.t->seq_len_valid_ = 0; + EXPECT_EQ(inter::CVarToInteger(table::TableHelper::GetTableInt(s, value, 1)), 10); + EXPECT_EQ(inter::CVarToInteger(table::TableHelper::GetTable(s, value, keys[2])), 30); + EXPECT_EQ(inter::CVarToInteger(table::TableHelper::GetTableStrId(s, value, "label")), 30); + EXPECT_EQ(table::TableHelper::GetTableLen(value), 2); + table::TableHelper::SetTableInt(s, value, 2, inter::NativeToFakeluaInt(s, 99)); + EXPECT_EQ(inter::CVarToInteger(values[1]), 99); + EXPECT_EQ(table::TableHelper::GetTableInt(s, value, 4).type_, static_cast(VarType::Nil)); + EXPECT_TRUE(table::TableHelper::VarKeyEqualInt(keys[0], 1)); + EXPECT_FALSE(table::TableHelper::VarKeyEqualInt(keys[2], 1)); +} + +TEST(test_table, presized_move_and_mixed_numeric_sort_contracts) { + FakeluaStateGuard state; + CompileFile(state.GetState(), "./table/test_table_dynamic_keys.lua", {}); + for (auto backend: AllJitTypes()) { + int64_t result = 0; + Call(state.GetState(), backend, "test_presized_move_and_mixed_sort", result); + EXPECT_EQ(result, 1) << JitTypeName(backend); + } +} + +TEST(test_table, zero_initialized_abi_table_rebuilds_sequence_cache) { + FakeluaStateGuard state; + auto *s = state.GetState(); + // Generated C also allocates zero-initialized ABI tables without calling + // TableHelper::CreateTable; their initial sequence cache is invalid. + VarTable raw{}; + raw.free_list_idx_ = VarTable::INVALID_INDEX; + CVar value{}; + value.type_ = static_cast(VarType::Table); + value.data_.t = &raw; + table::TableHelper::SetTableInt(s, value, 1, inter::NativeToFakeluaInt(s, 10)); + table::TableHelper::SetTableInt(s, value, 2, inter::NativeToFakeluaInt(s, 20)); + EXPECT_EQ(table::TableHelper::GetTableLen(value), 2); + EXPECT_EQ(raw.seq_len_valid_, 1u); + table::TableHelper::SetTableInt(s, value, 1, inter::NativeToFakeluaNil(s)); + EXPECT_EQ(table::TableHelper::GetTableLen(value), 0); + table::TableHelper::SetTableInt(s, value, 1, inter::NativeToFakeluaInt(s, 30)); + EXPECT_EQ(table::TableHelper::GetTableLen(value), 2); +} + +TEST(test_table, abi_string_keys_use_bytes_across_quick_and_bucket_storage) { + FakeluaStateGuard string_owner; + const int64_t string_id = string_owner.GetState()->GetConstString().Alloc("ab"); + for (bool bucketed: {false, true}) { + for (auto representation: {VarType::String, VarType::StringId}) { + for (auto backend: AllJitTypes()) { + SCOPED_TRACE(::testing::Message() << bucketed << " " << static_cast(representation) << " " << JitTypeName(backend)); + FakeluaStateGuard state; + VarTable raw{}; + raw.count_ = 1; + raw.free_list_idx_ = VarTable::INVALID_INDEX; + std::array nodes{}; + std::array active{}; + const auto hash = VarString::HashOf("ab"); + auto *entry = &raw.quick_data_[0]; + if (bucketed) { + raw.bucket_count_ = 2; + raw.nodes_ = nodes.data(); + raw.active_list_ = active.data(); + active[0] = hash & (raw.bucket_count_ - 1); + entry = &nodes[active[0]].entry; + for (auto &node: nodes) { + node.next = VarTable::INVALID_INDEX; + node.active_pos = VarTable::INVALID_INDEX; + } + nodes[active[0]].active_pos = 0; + raw.free_list_idx_ = 2; + } + // Host-provided ABI tables can retain their own string storage. + // The owning State outlives every consumer and owns the bytes. + entry->key.type_ = static_cast(representation); + if (representation == VarType::String) entry->key.data_.s = reinterpret_cast(string_id); + else + entry->key.data_.i = string_id; + entry->val.SetInt(42); + entry->hash = hash; + CVar wrapped{}; + wrapped.type_ = static_cast(VarType::Table); + wrapped.data_.t = &raw; + EXPECT_EQ(inter::CVarToInteger(table::TableHelper::GetTableStrId(state.GetState(), wrapped, "ab")), 42); + RegisterNativeFunction(state.GetState(), "legacy_abi_table", 0, false, [wrapped](State *, CVar *, int) { return wrapped; }); + CompileString(state.GetState(), R"( + function test_legacy_abi_table() + local value = legacy_abi_table() + assert(value.ab == 42) + assert(value.bA == nil and value.zz == nil) + value.ab = 99 + assert(value.ab == 99) + return 1 + end + )", + {}); + int64_t result = 0; + Call(state.GetState(), backend, "test_legacy_abi_table", result); + EXPECT_EQ(result, 1); + EXPECT_EQ(entry->val.GetInt(), 99); + EXPECT_EQ(inter::CVarToInteger(table::TableHelper::GetTableStrId(state.GetState(), wrapped, "ab")), 99); + } + } + } +} + +TEST(test_table, sparse_prefix_hash_resize_keeps_integer_and_string_entries) { + FakeluaStateGuard state; + CompileFile(state.GetState(), "./table/test_table_sparse_prefix_resize.lua", {}); + int64_t result = 0; + CallAll(state.GetState(), "test_sparse_prefix_resize", result); + EXPECT_EQ(result, 1); +} + +TEST(test_table, mixed_constructor_and_dynamic_store_contracts) { + FakeluaStateGuard state; + CompileFile(state.GetState(), "./table/test_table_dynamic_keys.lua", {}); + int64_t result = 0; + CallAll(state.GetState(), "test_mixed_constructor_and_dynamic_store_contracts", result); + EXPECT_EQ(result, 1); +} + +TEST(test_table, loaded_source_comparator_and_unpack_type_contract) { + FakeluaStateGuard state; + CompileFile(state.GetState(), "./table/test_table_dynamic_keys.lua", {}); + int64_t result = 0; + CallAll(state.GetState(), "test_loaded_sort_comparator", result); + EXPECT_EQ(result, 1); +} diff --git a/test/test_timer.cpp b/test/test_timer.cpp index 30307280..41a1c8ad 100644 --- a/test/test_timer.cpp +++ b/test/test_timer.cpp @@ -1,6 +1,11 @@ #include "fakelua.h" +#include "jit/vm.h" +#include "native/timer/heap_timer.h" +#include "native/timer/native_timer.h" #include "test_jit.h" +#include "var/var.h" #include "gtest/gtest.h" +#include using namespace fakelua; @@ -48,3 +53,90 @@ TEST(test_timer, test_heartbeat_nested) { TEST(test_timer, test_nested_tick_noop) { RunTimerScript("./timer/test_timer_reenter.lua", "TimerTest.test_nested_tick_noop"); } + +TEST(test_timer, heap_timer_growth_deletion_and_deadline_order) { + timer::HeapTimer heap; + const auto past = timer::HeapTimer::Clock::now() - std::chrono::hours(1); + std::vector ids; + for (int i = 127; i >= 0; --i) ids.push_back(heap.AddAt(past + std::chrono::milliseconds(i))); + ASSERT_EQ(heap.Size(), 128u); + EXPECT_FALSE(heap.Del(0)); + std::vector expected; + for (size_t i = 0; i < ids.size(); ++i) { + if (i % 3 == 0) { + EXPECT_TRUE(heap.Del(ids[i])); + EXPECT_FALSE(heap.Del(ids[i])); + } else + expected.push_back(ids[i]); + } + std::reverse(expected.begin(), expected.end()); + EXPECT_EQ(heap.Update(), expected); + EXPECT_EQ(heap.Size(), 0u); + EXPECT_TRUE(heap.Update().empty()); + const auto future = heap.AddAt(timer::HeapTimer::Clock::now() + std::chrono::hours(24)); + EXPECT_TRUE(heap.Update().empty()); + EXPECT_EQ(heap.Size(), 1u); + EXPECT_TRUE(heap.Del(future)); + EXPECT_EQ(heap.Size(), 0u); +} + +TEST(test_timer, heap_timer_move_preserves_pending_ids_and_reuses_source) { + timer::HeapTimer source; + const auto past = timer::HeapTimer::Clock::now() - std::chrono::hours(1); + const auto first = source.AddAt(past); + const auto second = source.AddAt(past + std::chrono::seconds(1)); + timer::HeapTimer moved(std::move(source)); + EXPECT_EQ(source.Size(), 0u); + EXPECT_EQ(moved.Size(), 2u); + EXPECT_TRUE(moved.Del(first)); + timer::HeapTimer assigned; + assigned.AddAt(past); + assigned = std::move(moved); + EXPECT_EQ(moved.Size(), 0u); + EXPECT_EQ(assigned.Update(), std::vector{second}); + const auto reused = source.AddAt(past); + EXPECT_EQ(source.Update(), std::vector{reused}); +} + +TEST(test_timer, native_callbacks_validation_and_exception_recovery) { + FakeluaStateGuard state; + State *s = state.GetState(); + int calls = 0; + RegisterNativeFunction(s, "cpp_timer_record", 2, false, [&](State *st, CVar *args, int n) { + EXPECT_EQ(n, 2); + EXPECT_EQ(inter::CVarToString(args[0], ""), "timer"); + EXPECT_GT(inter::CVarToInteger(args[1]), 0); + ++calls; + return inter::NativeToFakeluaNil(st); + }); + RegisterNativeFunction(s, "cpp_timer_throw", 2, false, [](State *, CVar *, int) -> CVar { throw std::runtime_error("timer dispatch failure"); }); + auto set = [&](const char *name) { + CVar args[] = {inter::NativeToFakeluaInt(s, 0), inter::NativeToFakeluaString(s, name)}; + return CallByNameArgs(s, JIT_INTERP, "timer.set", 2, args); + }; + set("cpp_timer_throw"); + EXPECT_THROW(timer::TickAll(s), std::runtime_error); + set("cpp_timer_record"); + timer::TickAll(s); + EXPECT_EQ(calls, 1); + set("missing_timer_callback"); + EXPECT_NO_THROW(timer::TickAll(s)); + CompileConfig config; + config.disable_jit[JIT_TCC] = true; + CompileString(s, "function gcc_timer_callback(kind, id) cpp_timer_record(kind, id) end", config); + set("gcc_timer_callback"); + timer::TickAll(s); + EXPECT_EQ(calls, 2); + for (const char *name: {"timer.set", "timer.set_heartbeat"}) { + CVar args[] = {inter::NativeToFakeluaInt(s, -1), inter::NativeToFakeluaString(s, "cpp_timer_record")}; + EXPECT_THROW(CallByNameArgs(s, JIT_INTERP, name, 2, args), std::exception); + args[0] = inter::NativeToFakeluaInt(s, 4294967296LL); + EXPECT_THROW(CallByNameArgs(s, JIT_INTERP, name, 2, args), std::exception); + args[0] = inter::NativeToFakeluaInt(s, 1); + args[1] = inter::NativeToFakeluaBool(s, false); + EXPECT_THROW(CallByNameArgs(s, JIT_INTERP, name, 2, args), std::exception); + } + CVar invalid = inter::NativeToFakeluaInt(s, -1); + EXPECT_THROW(CallByNameArgs(s, JIT_INTERP, "timer.del", 1, &invalid), std::exception); + EXPECT_THROW(CallByNameArgs(s, JIT_INTERP, "timer.register_obj_methods", 1, &invalid), std::exception); +} diff --git a/test/test_toml.cpp b/test/test_toml.cpp index 722e0b2a..87b3e413 100644 --- a/test/test_toml.cpp +++ b/test/test_toml.cpp @@ -1,4 +1,5 @@ #include "fakelua.h" +#include "test_jit.h" #include "gtest/gtest.h" using namespace fakelua; @@ -236,3 +237,12 @@ TEST(test_toml, encode_cyclic) { FakeluaDeleteState(s); } } + +TEST(test_toml, unsupported_fields_are_skipped_and_nested_depth_is_bounded) { + FakeluaStateGuard state; + CompileConfig config; + CompileFile(state.GetState(), "./toml/test_toml_additional_contracts.lua", config); + int64_t result = 0; + CallAll(state.GetState(), "test_toml_contracts", result); + EXPECT_EQ(result, 1); +} diff --git a/test/test_url.cpp b/test/test_url.cpp index 8ca93780..6d0ae4eb 100644 --- a/test/test_url.cpp +++ b/test/test_url.cpp @@ -47,3 +47,12 @@ TEST(test_url, format_bad_port) { EXPECT_EQ(ret, 1); FakeluaDeleteState(s); } + +TEST(test_url, authority_optional_query_values_and_malformed_escapes) { + FakeluaStateGuard state; + CompileConfig config; + CompileFile(state.GetState(), "./url/test_url_additional_contracts.lua", config); + int64_t result = 0; + CallAll(state.GetState(), "test_url_contracts", result); + EXPECT_EQ(result, 1); +} diff --git a/test/test_utf8.cpp b/test/test_utf8.cpp index e25e818c..139d951b 100644 --- a/test/test_utf8.cpp +++ b/test/test_utf8.cpp @@ -216,3 +216,14 @@ TEST(test_utf8, test_utf8_bounds) { FakeluaDeleteState(s); } + +TEST(test_utf8, rejects_overlong_surrogate_out_of_range_and_truncated_sequences) { + FakeluaStateGuard state; + CompileFile(state.GetState(), "./utf8/test_utf8_invalid_sequences.lua", {}); + for (auto backend: AllJitTypes()) { + SCOPED_TRACE(JitTypeName(backend)); + int64_t result = 0; + Call(state.GetState(), backend, "test_utf8_invalid_sequences", result); + EXPECT_EQ(result, 1); + } +} diff --git a/test/test_xml.cpp b/test/test_xml.cpp index 2b789f5f..da9cae11 100644 --- a/test/test_xml.cpp +++ b/test/test_xml.cpp @@ -197,3 +197,13 @@ TEST(test_xml, decode_too_deep) { FakeluaDeleteState(s); } } + +TEST(test_xml, repeated_siblings_nested_arrays_and_scalar_roots) { + FakeluaStateGuard state; + CompileFile(state.GetState(), "./xml/test_xml_structure_contracts.lua", {}); + for (auto backend: AllJitTypes()) { + int64_t result = 0; + Call(state.GetState(), backend, "test_xml_structure_contracts", result); + EXPECT_EQ(result, 1) << JitTypeName(backend); + } +} diff --git a/test/test_yaml.cpp b/test/test_yaml.cpp index 7f75cd94..b571a131 100644 --- a/test/test_yaml.cpp +++ b/test/test_yaml.cpp @@ -184,3 +184,23 @@ TEST(test_yaml, decode_too_deep) { FakeluaDeleteState(s); } } + +TEST(test_yaml, scalar_encoding_and_quoted_nesting_tokens) { + FakeluaStateGuard state; + CompileFile(state.GetState(), "./yaml/test_yaml_encoding_boundaries.lua", {}); + for (auto backend: AllJitTypes()) { + int64_t result = 0; + Call(state.GetState(), backend, "test_yaml_scalar_encoding", result); + EXPECT_EQ(result, 1) << JitTypeName(backend); + } +} + +TEST(test_yaml, encode_cycles_depth_and_unsupported_values) { + FakeluaStateGuard state; + CompileFile(state.GetState(), "./yaml/test_yaml_encoding_boundaries.lua", {}); + for (auto backend: AllJitTypes()) { + int64_t result = 0; + Call(state.GetState(), backend, "test_yaml_encoding_rejections", result); + EXPECT_EQ(result, 1) << JitTypeName(backend); + } +}