From 7f88aedbc3b53496bc99d8e0e64a818c7a3f6d6f Mon Sep 17 00:00:00 2001 From: Alexander Gavriliuk Date: Fri, 24 Jan 2025 00:26:00 +0100 Subject: #3423 Add Lua as Compile Target in Viewer Script Editor --- indra/llmessage/message_prehash.cpp | 2 ++ indra/llmessage/message_prehash.h | 2 ++ 2 files changed, 4 insertions(+) (limited to 'indra/llmessage') diff --git a/indra/llmessage/message_prehash.cpp b/indra/llmessage/message_prehash.cpp index c264a9f086..df16184e76 100644 --- a/indra/llmessage/message_prehash.cpp +++ b/indra/llmessage/message_prehash.cpp @@ -714,6 +714,8 @@ char const* const _PREHASH_FirstName = LLMessageStringTable::getInstance()->getS char const* const _PREHASH_AttachedSoundGainChange = LLMessageStringTable::getInstance()->getString("AttachedSoundGainChange"); char const* const _PREHASH_LocationID = LLMessageStringTable::getInstance()->getString("LocationID"); char const* const _PREHASH_Running = LLMessageStringTable::getInstance()->getString("Running"); +char const* const _PREHASH_Mono = LLMessageStringTable::getInstance()->getString("Mono"); +char const* const _PREHASH_CompileTarget = LLMessageStringTable::getInstance()->getString("CompileTarget"); char const* const _PREHASH_AgentThrottle = LLMessageStringTable::getInstance()->getString("AgentThrottle"); char const* const _PREHASH_NeighborList = LLMessageStringTable::getInstance()->getString("NeighborList"); char const* const _PREHASH_PathTaperX = LLMessageStringTable::getInstance()->getString("PathTaperX"); diff --git a/indra/llmessage/message_prehash.h b/indra/llmessage/message_prehash.h index 1d30b69b67..0feb6ecad8 100644 --- a/indra/llmessage/message_prehash.h +++ b/indra/llmessage/message_prehash.h @@ -714,6 +714,8 @@ extern char const* const _PREHASH_FirstName; extern char const* const _PREHASH_AttachedSoundGainChange; extern char const* const _PREHASH_LocationID; extern char const* const _PREHASH_Running; +extern char const* const _PREHASH_Mono; +extern char const* const _PREHASH_CompileTarget; extern char const* const _PREHASH_AgentThrottle; extern char const* const _PREHASH_NeighborList; extern char const* const _PREHASH_PathTaperX; -- cgit v1.3 From fd82aa010c4ff369484304d00822dc286d9c720e Mon Sep 17 00:00:00 2001 From: Andrey Lihatskiy Date: Wed, 5 Feb 2025 14:29:45 +0200 Subject: #3423 Adapt the code to the changes on a server --- indra/llmessage/message_prehash.cpp | 3 +- indra/llmessage/message_prehash.h | 3 +- indra/newview/llpreviewscript.cpp | 34 +++++++++++++++------- .../default/xui/en/floater_live_lsleditor.xml | 4 +++ 4 files changed, 32 insertions(+), 12 deletions(-) (limited to 'indra/llmessage') diff --git a/indra/llmessage/message_prehash.cpp b/indra/llmessage/message_prehash.cpp index df16184e76..fab07c018c 100644 --- a/indra/llmessage/message_prehash.cpp +++ b/indra/llmessage/message_prehash.cpp @@ -715,7 +715,8 @@ char const* const _PREHASH_AttachedSoundGainChange = LLMessageStringTable::getIn char const* const _PREHASH_LocationID = LLMessageStringTable::getInstance()->getString("LocationID"); char const* const _PREHASH_Running = LLMessageStringTable::getInstance()->getString("Running"); char const* const _PREHASH_Mono = LLMessageStringTable::getInstance()->getString("Mono"); -char const* const _PREHASH_CompileTarget = LLMessageStringTable::getInstance()->getString("CompileTarget"); +char const* const _PREHASH_Luau = LLMessageStringTable::getInstance()->getString("Luau"); +char const* const _PREHASH_LuauLanguage = LLMessageStringTable::getInstance()->getString("LuauLanguage"); char const* const _PREHASH_AgentThrottle = LLMessageStringTable::getInstance()->getString("AgentThrottle"); char const* const _PREHASH_NeighborList = LLMessageStringTable::getInstance()->getString("NeighborList"); char const* const _PREHASH_PathTaperX = LLMessageStringTable::getInstance()->getString("PathTaperX"); diff --git a/indra/llmessage/message_prehash.h b/indra/llmessage/message_prehash.h index 0feb6ecad8..83b480392c 100644 --- a/indra/llmessage/message_prehash.h +++ b/indra/llmessage/message_prehash.h @@ -715,7 +715,8 @@ extern char const* const _PREHASH_AttachedSoundGainChange; extern char const* const _PREHASH_LocationID; extern char const* const _PREHASH_Running; extern char const* const _PREHASH_Mono; -extern char const* const _PREHASH_CompileTarget; +extern char const* const _PREHASH_Luau; +extern char const* const _PREHASH_LuauLanguage; extern char const* const _PREHASH_AgentThrottle; extern char const* const _PREHASH_NeighborList; extern char const* const _PREHASH_PathTaperX; diff --git a/indra/newview/llpreviewscript.cpp b/indra/newview/llpreviewscript.cpp index 432aaa8f18..300fa30420 100644 --- a/indra/newview/llpreviewscript.cpp +++ b/indra/newview/llpreviewscript.cpp @@ -2451,26 +2451,40 @@ void LLLiveLSLEditor::processScriptRunningReply(LLMessageSystem* msg, void**) msg->getBOOLFast(_PREHASH_Script, _PREHASH_Running, running); instance->mRunningCheckbox->set(running); + bool mono = false, luau = false, luau_language = false; + msg->getBOOLFast(_PREHASH_Script, _PREHASH_Mono, mono); + msg->getBOOLFast(_PREHASH_Script, _PREHASH_Luau, luau); + msg->getBOOLFast(_PREHASH_Script, _PREHASH_LuauLanguage, luau_language); + std::string compile_target; - msg->getStringFast(_PREHASH_Script, _PREHASH_CompileTarget, compile_target); - if (compile_target.empty()) // Old sim not providing CompileTarget field + if (luau) { - bool mono; - msg->getBOOLFast(_PREHASH_Script, _PREHASH_Mono, mono); // Use Mono field - instance->mCompileTarget->setValue(mono ? "mono" : "lso2"); + if (luau_language) + { + compile_target = "luau"; + } + else + { + compile_target = "lsl_luau"; + } } - else if (instance->mCompileTarget->valueExists(compile_target)) + else if (mono) { - instance->mCompileTarget->setValue(compile_target); // Use CompileTarget field + compile_target = "mono"; } else { - instance->mCompileTarget->setValue("mono"); // Use default value + compile_target = "lsl2"; } - if (LLScrollListItem* item = instance->mCompileTarget->findItemByValue("luau")) + instance->mCompileTarget->setValue(compile_target); + if (LLScrollListItem* luau_item = instance->mCompileTarget->findItemByValue("luau")) + { + luau_item->setEnabled(luau); + } + if (LLScrollListItem* lsl_luau_item = instance->mCompileTarget->findItemByValue("lsl_luau")) { - item->setEnabled(!compile_target.empty()); + lsl_luau_item->setEnabled(luau); } instance->mCompileTarget->setEnabled(instance->getIsModifiable() && have_script_upload_cap(object_id)); diff --git a/indra/newview/skins/default/xui/en/floater_live_lsleditor.xml b/indra/newview/skins/default/xui/en/floater_live_lsleditor.xml index 4d15522c76..c5124e2119 100644 --- a/indra/newview/skins/default/xui/en/floater_live_lsleditor.xml +++ b/indra/newview/skins/default/xui/en/floater_live_lsleditor.xml @@ -145,5 +145,9 @@ label="Lua" name="compile_target_luau" value="luau" /> + -- cgit v1.3 From 8890372a116cd6db0a1a43dcce753b9070d86b49 Mon Sep 17 00:00:00 2001 From: Rye Date: Sun, 19 Oct 2025 23:16:49 -0400 Subject: Fix numerous compiler warnings from GCC under Ubuntu 22.04 Signed-off-by: Rye --- indra/llcommon/classic_callback.h | 4 ++-- indra/llcommon/llerror.h | 7 +------ indra/llcommon/llkeybind.cpp | 9 --------- indra/llcommon/llkeybind.h | 1 - indra/llcommon/llsdserialize.cpp | 1 + indra/llcommon/tests/llerror_test.cpp | 2 ++ indra/llinventory/llsettingsbase.cpp | 4 +++- indra/llinventory/llsettingsdaycycle.cpp | 2 ++ indra/llinventory/llsettingssky.cpp | 2 ++ indra/llinventory/llsettingswater.cpp | 1 + indra/llmessage/llavatarname.h | 2 +- indra/llmessage/llexperiencecache.cpp | 2 ++ indra/llmessage/llstoredmessage.cpp | 2 ++ indra/llmessage/lltemplatemessagedispatcher.cpp | 1 + indra/llprimitive/llmodelloader.cpp | 2 ++ indra/llrender/llglcommonfunc.cpp | 2 ++ indra/llrender/lltexturemanagerbridge.cpp | 2 ++ indra/llwindow/llwindowmesaheadless.h | 1 + indra/newview/llappviewerlinux.cpp | 27 ------------------------- indra/newview/llinventorygallerymenu.cpp | 4 ++-- 20 files changed, 29 insertions(+), 49 deletions(-) (limited to 'indra/llmessage') diff --git a/indra/llcommon/classic_callback.h b/indra/llcommon/classic_callback.h index 009c25d67c..8a6ac7f7ff 100644 --- a/indra/llcommon/classic_callback.h +++ b/indra/llcommon/classic_callback.h @@ -184,8 +184,8 @@ protected: template auto makeClassicCallback(CALLABLE&& callable) { - return std::move(ClassicCallback - (std::forward(callable))); + return ClassicCallback + (std::forward(callable)); } /***************************************************************************** diff --git a/indra/llcommon/llerror.h b/indra/llcommon/llerror.h index 41893a35e5..343cc47e4c 100644 --- a/indra/llcommon/llerror.h +++ b/indra/llcommon/llerror.h @@ -91,13 +91,8 @@ const int LL_ERR_NOERR = 0; #define llverify(func) do {if (func) {}} while(0) #endif -#ifdef LL_WINDOWS #define LL_STATIC_ASSERT(func, msg) static_assert(func, msg) -#define LL_BAD_TEMPLATE_INSTANTIATION(type, msg) static_assert(false, msg) -#else -#define LL_STATIC_ASSERT(func, msg) BOOST_STATIC_ASSERT(func) -#define LL_BAD_TEMPLATE_INSTANTIATION(type, msg) BOOST_STATIC_ASSERT(sizeof(type) != 0 && false); -#endif +#define LL_BAD_TEMPLATE_INSTANTIATION(type, msg) static_assert(sizeof(type) != 0 && false, msg) /** Error Logging Facility diff --git a/indra/llcommon/llkeybind.cpp b/indra/llcommon/llkeybind.cpp index e36c1d0a4c..abb0df0b87 100644 --- a/indra/llcommon/llkeybind.cpp +++ b/indra/llcommon/llkeybind.cpp @@ -114,15 +114,6 @@ void LLKeyData::reset() mIgnoreMasks = false; } -LLKeyData& LLKeyData::operator=(const LLKeyData& rhs) -{ - mMouse = rhs.mMouse; - mKey = rhs.mKey; - mMask = rhs.mMask; - mIgnoreMasks = rhs.mIgnoreMasks; - return *this; -} - bool LLKeyData::operator==(const LLKeyData& rhs) { if (mMouse != rhs.mMouse) return false; diff --git a/indra/llcommon/llkeybind.h b/indra/llcommon/llkeybind.h index 1bbb2fadb5..0a9d4600cc 100644 --- a/indra/llcommon/llkeybind.h +++ b/indra/llcommon/llkeybind.h @@ -43,7 +43,6 @@ public: bool isEmpty() const; bool empty() const { return isEmpty(); }; void reset(); - LLKeyData& operator=(const LLKeyData& rhs); bool operator==(const LLKeyData& rhs); bool operator!=(const LLKeyData& rhs); diff --git a/indra/llcommon/llsdserialize.cpp b/indra/llcommon/llsdserialize.cpp index 37af366a20..c42eebebd1 100644 --- a/indra/llcommon/llsdserialize.cpp +++ b/indra/llcommon/llsdserialize.cpp @@ -2397,6 +2397,7 @@ U8* unzip_llsdNavMesh( bool& valid, size_t& outsize, std::istream& is, S32 size { case Z_NEED_DICT: ret = Z_DATA_ERROR; + [[fallthrough]]; case Z_DATA_ERROR: case Z_MEM_ERROR: inflateEnd(&strm); diff --git a/indra/llcommon/tests/llerror_test.cpp b/indra/llcommon/tests/llerror_test.cpp index 3ec429530c..e39c402972 100644 --- a/indra/llcommon/tests/llerror_test.cpp +++ b/indra/llcommon/tests/llerror_test.cpp @@ -61,6 +61,8 @@ namespace { #ifdef __clang__ # pragma clang diagnostic ignored "-Wunused-function" +#elif defined(LL_GNUC) +# pragma GCC diagnostic ignored "-Wunused-function" #endif void test_that_error_h_includes_enough_things_to_compile_a_message() { diff --git a/indra/llinventory/llsettingsbase.cpp b/indra/llinventory/llsettingsbase.cpp index d7a94d61a5..fe2503966e 100644 --- a/indra/llinventory/llsettingsbase.cpp +++ b/indra/llinventory/llsettingsbase.cpp @@ -25,6 +25,8 @@ * $/LicenseInfo$ */ +#include "linden_common.h" + #include "llsettingsbase.h" #include "llmath.h" @@ -757,7 +759,7 @@ void LLSettingsBlender::update(const LLSettingsBase::BlendFactor& blendf) F64 LLSettingsBlender::setBlendFactor(const LLSettingsBase::BlendFactor& blendf_in) { LLSettingsBase::TrackPosition blendf = (F32)blendf_in; - llassert(!isnan(blendf)); + llassert(!std::isnan(blendf)); if (blendf >= 1.0) { triggerComplete(); diff --git a/indra/llinventory/llsettingsdaycycle.cpp b/indra/llinventory/llsettingsdaycycle.cpp index 2baf140e6a..ebd8602c8d 100644 --- a/indra/llinventory/llsettingsdaycycle.cpp +++ b/indra/llinventory/llsettingsdaycycle.cpp @@ -25,6 +25,8 @@ * $/LicenseInfo$ */ +#include "linden_common.h" + #include "llsettingsdaycycle.h" #include "llerror.h" #include diff --git a/indra/llinventory/llsettingssky.cpp b/indra/llinventory/llsettingssky.cpp index 4957cf3c02..fd3e49041c 100644 --- a/indra/llinventory/llsettingssky.cpp +++ b/indra/llinventory/llsettingssky.cpp @@ -25,6 +25,8 @@ * $/LicenseInfo$ */ +#include "linden_common.h" + #include "llsettingssky.h" #include "indra_constants.h" #include diff --git a/indra/llinventory/llsettingswater.cpp b/indra/llinventory/llsettingswater.cpp index b5d59dc497..427f06457f 100644 --- a/indra/llinventory/llsettingswater.cpp +++ b/indra/llinventory/llsettingswater.cpp @@ -24,6 +24,7 @@ * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ +#include "linden_common.h" #include "llsettingswater.h" #include diff --git a/indra/llmessage/llavatarname.h b/indra/llmessage/llavatarname.h index eec966d51b..86b2931ed9 100644 --- a/indra/llmessage/llavatarname.h +++ b/indra/llmessage/llavatarname.h @@ -32,7 +32,7 @@ class LLSD; -class LL_COMMON_API LLAvatarName +class LLAvatarName { public: LLAvatarName(); diff --git a/indra/llmessage/llexperiencecache.cpp b/indra/llmessage/llexperiencecache.cpp index 78cca47456..9d940d8d71 100644 --- a/indra/llmessage/llexperiencecache.cpp +++ b/indra/llmessage/llexperiencecache.cpp @@ -23,6 +23,8 @@ * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ +#include "linden_common.h" + #include "llexperiencecache.h" #include "llavatarname.h" diff --git a/indra/llmessage/llstoredmessage.cpp b/indra/llmessage/llstoredmessage.cpp index 39696ea235..ff8afde657 100644 --- a/indra/llmessage/llstoredmessage.cpp +++ b/indra/llmessage/llstoredmessage.cpp @@ -24,6 +24,8 @@ * $/LicenseInfo$ */ +#include "linden_common.h" + #include "llstoredmessage.h" LLStoredMessage::LLStoredMessage(const std::string& name, const LLSD& message) : mMessage(message), mName(name) diff --git a/indra/llmessage/lltemplatemessagedispatcher.cpp b/indra/llmessage/lltemplatemessagedispatcher.cpp index edbeb4acc1..02e5b56c8d 100644 --- a/indra/llmessage/lltemplatemessagedispatcher.cpp +++ b/indra/llmessage/lltemplatemessagedispatcher.cpp @@ -24,6 +24,7 @@ * $/LicenseInfo$ */ +#include "linden_common.h" #include "lltemplatemessagedispatcher.h" diff --git a/indra/llprimitive/llmodelloader.cpp b/indra/llprimitive/llmodelloader.cpp index 0383659f62..bce5f6adce 100644 --- a/indra/llprimitive/llmodelloader.cpp +++ b/indra/llprimitive/llmodelloader.cpp @@ -24,6 +24,8 @@ * $/LicenseInfo$ */ +#include "linden_common.h" + #include "llmodelloader.h" #include "llapp.h" diff --git a/indra/llrender/llglcommonfunc.cpp b/indra/llrender/llglcommonfunc.cpp index 13b08de7cc..bf4d337b50 100644 --- a/indra/llrender/llglcommonfunc.cpp +++ b/indra/llrender/llglcommonfunc.cpp @@ -24,6 +24,8 @@ * $/LicenseInfo$ */ +#include "linden_common.h" + #include "llglheaders.h" #include "llglcommonfunc.h" diff --git a/indra/llrender/lltexturemanagerbridge.cpp b/indra/llrender/lltexturemanagerbridge.cpp index c243f0697a..67838418bf 100644 --- a/indra/llrender/lltexturemanagerbridge.cpp +++ b/indra/llrender/lltexturemanagerbridge.cpp @@ -24,6 +24,8 @@ * $/LicenseInfo$ */ +#include "linden_common.h" + #include "lltexturemanagerbridge.h" // Define a null texture manager bridge. Applications must provide their own bridge implementaton. diff --git a/indra/llwindow/llwindowmesaheadless.h b/indra/llwindow/llwindowmesaheadless.h index ad08c4f065..47cd6320b1 100644 --- a/indra/llwindow/llwindowmesaheadless.h +++ b/indra/llwindow/llwindowmesaheadless.h @@ -53,6 +53,7 @@ public: bool switchContext(bool fullscreen, const LLCoordScreen &size, bool disable_vsync, const LLCoordScreen * const posp = NULL) override {return false;}; bool setCursorPosition(LLCoordWindow position) override {return false;}; bool getCursorPosition(LLCoordWindow *position) override {return false;}; + bool isWrapMouse() const override { return true; } void showCursor() override {}; void hideCursor() override {}; void showCursorFromMouseMove() override {}; diff --git a/indra/newview/llappviewerlinux.cpp b/indra/newview/llappviewerlinux.cpp index 4a96c45c69..c924771816 100644 --- a/indra/newview/llappviewerlinux.cpp +++ b/indra/newview/llappviewerlinux.cpp @@ -51,27 +51,6 @@ #ifdef LL_GLIB #include #endif -#include - -#if (__GLIBC__*1000 + __GLIBC_MINOR__) >= 2034 -extern "C" -{ - int __res_nquery(res_state statep, - const char *dname, int qclass, int type, - unsigned char *answer, int anslen) - { - return res_nquery( statep, dname, qclass, type, answer, anslen ); - } - - int __dn_expand(const unsigned char *msg, - const unsigned char *eomorig, - const unsigned char *comp_dn, char *exp_dn, - int length) - { - return dn_expand( msg,eomorig,comp_dn,exp_dn,length); - } -} -#endif #define VIEWERAPI_SERVICE "com.secondlife.ViewerAppAPIService" #define VIEWERAPI_PATH "/com/secondlife/ViewerAppAPI" @@ -299,12 +278,6 @@ void SDL_AppQuit(void *appstate, SDL_AppResult result) bool LLAppViewerLinux::init() { - // g_thread_init() must be called before *any* use of glib, *and* - // before any mutexes are held, *and* some of our third-party - // libraries likes to use glib functions; in short, do this here - // really early in app startup! - if (!g_thread_supported ()) g_thread_init (NULL); - bool success = LLAppViewer::init(); #if LL_SEND_CRASH_REPORTS diff --git a/indra/newview/llinventorygallerymenu.cpp b/indra/newview/llinventorygallerymenu.cpp index eda93e3e79..b63aa0997b 100644 --- a/indra/newview/llinventorygallerymenu.cpp +++ b/indra/newview/llinventorygallerymenu.cpp @@ -334,11 +334,11 @@ void LLInventoryGalleryContextMenu::doToSelected(const LLSD& userdata) } else if ("copy_slurl" == action) { - boost::function copy_slurl_cb = [](LLLandmark* landmark) + std::function copy_slurl_cb = [](LLLandmark* landmark) { LLVector3d global_pos; landmark->getGlobalPos(global_pos); - boost::function copy_slurl_to_clipboard_cb = [](const std::string& slurl) + std::function copy_slurl_to_clipboard_cb = [](const std::string& slurl) { gViewerWindow->getWindow()->copyTextToClipboard(utf8str_to_wstring(slurl)); LLSD args; -- cgit v1.3 From 37f89080ba5ce1ddd7848d2029794a5f5aabb7be Mon Sep 17 00:00:00 2001 From: Rye Date: Thu, 23 Oct 2025 09:15:38 -0400 Subject: Introduce global precompiled header to accelerate build Signed-off-by: Rye --- indra/CMakeLists.txt | 3 ++ indra/cmake/LLAddBuildTest.cmake | 14 +++++++- indra/llappearance/CMakeLists.txt | 8 +++++ indra/llappearanceutility/CMakeLists.txt | 8 +++++ indra/llaudio/CMakeLists.txt | 4 +++ indra/llcharacter/CMakeLists.txt | 4 +++ indra/llcommon/CMakeLists.txt | 28 +++++++++++++--- indra/llcommon/llsd.cpp | 5 ++- indra/llcommon/llsdjson.cpp | 1 - indra/llcorehttp/CMakeLists.txt | 8 ++++- indra/llcrashlogger/CMakeLists.txt | 4 +++ indra/llfilesystem/CMakeLists.txt | 11 +++++++ indra/llimage/CMakeLists.txt | 4 +++ indra/llimagej2coj/CMakeLists.txt | 3 ++ indra/llinventory/CMakeLists.txt | 4 +++ indra/llmath/CMakeLists.txt | 8 +++-- indra/llmeshoptimizer/CMakeLists.txt | 4 +++ indra/llmessage/CMakeLists.txt | 4 +++ indra/llphysicsextensionsos/CMakeLists.txt | 4 +++ indra/llplugin/CMakeLists.txt | 5 +++ indra/llplugin/slplugin/CMakeLists.txt | 10 ++++++ indra/llprecompiled/CMakeLists.txt | 53 ++++++++++++++++++++++++++++++ indra/llprecompiled/cmake_dummy.cpp | 24 ++++++++++++++ indra/llprimitive/CMakeLists.txt | 4 +++ indra/llrender/CMakeLists.txt | 7 ++++ indra/llui/CMakeLists.txt | 4 +++ indra/llwindow/CMakeLists.txt | 15 +++++++++ indra/llxml/CMakeLists.txt | 3 ++ 28 files changed, 241 insertions(+), 13 deletions(-) create mode 100644 indra/llprecompiled/CMakeLists.txt create mode 100644 indra/llprecompiled/cmake_dummy.cpp (limited to 'indra/llmessage') diff --git a/indra/CMakeLists.txt b/indra/CMakeLists.txt index 571465c707..a7f0ab0486 100644 --- a/indra/CMakeLists.txt +++ b/indra/CMakeLists.txt @@ -58,6 +58,9 @@ endif (NOT CMAKE_BUILD_TYPE) add_subdirectory(cmake) +if (USE_PRECOMPILED_HEADERS) + add_subdirectory(${LIBS_OPEN_PREFIX}llprecompiled) +endif () add_subdirectory(${LIBS_OPEN_PREFIX}llaudio) add_subdirectory(${LIBS_OPEN_PREFIX}llappearance) add_subdirectory(${LIBS_OPEN_PREFIX}llcharacter) diff --git a/indra/cmake/LLAddBuildTest.cmake b/indra/cmake/LLAddBuildTest.cmake index 83725ffd1b..4959051617 100644 --- a/indra/cmake/LLAddBuildTest.cmake +++ b/indra/cmake/LLAddBuildTest.cmake @@ -100,6 +100,10 @@ MACRO(LL_ADD_PROJECT_UNIT_TESTS project sources) ) endif(DARWIN) + if (USE_PRECOMPILED_HEADERS) + target_precompile_headers(PROJECT_${project}_TEST_${name} REUSE_FROM llprecompiled) + endif () + # # Per-codefile additional / external project dep and lib dep property extraction # @@ -122,7 +126,9 @@ MACRO(LL_ADD_PROJECT_UNIT_TESTS project sources) set_target_properties(PROJECT_${project}_TEST_${name} PROPERTIES COMPILE_FLAGS "${${name}_test_additional_CFLAGS}" - COMPILE_DEFINITIONS "LL_TEST=${name};LL_TEST_${name}") + COMPILE_DEFINITIONS "LL_TEST=${name};LL_TEST_${name}" + FOLDER "Tests" + ) if(LL_TEST_VERBOSE) message("LL_ADD_PROJECT_UNIT_TESTS ${name}_test_additional_CFLAGS ${${name}_test_additional_CFLAGS}") endif() @@ -217,6 +223,7 @@ FUNCTION(LL_ADD_INTEGRATION_TEST PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${EXE_STAGING_DIR}" COMPILE_DEFINITIONS "LL_TEST=${testname};LL_TEST_${testname}" + FOLDER "Tests" ) # The following was copied to llcorehttp/CMakeLists.txt's texture_load target. @@ -246,6 +253,11 @@ FUNCTION(LL_ADD_INTEGRATION_TEST target_link_libraries(INTEGRATION_TEST_${testname} ${libraries}) target_include_directories (INTEGRATION_TEST_${testname} PRIVATE ${LIBS_OPEN_DIR}/test ) + if (USE_PRECOMPILED_HEADERS) + target_include_directories (INTEGRATION_TEST_${testname} PRIVATE ${LIBS_OPEN_DIR}/llmath ) + target_precompile_headers(INTEGRATION_TEST_${testname} REUSE_FROM llprecompiled) + endif () + # Create the test running command set(test_command ${ARGN}) set(TEST_EXE $) diff --git a/indra/llappearance/CMakeLists.txt b/indra/llappearance/CMakeLists.txt index 40a1036597..5b6d68fa37 100644 --- a/indra/llappearance/CMakeLists.txt +++ b/indra/llappearance/CMakeLists.txt @@ -69,6 +69,10 @@ target_link_libraries(llappearance ) target_include_directories( llappearance INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}) +if (USE_PRECOMPILED_HEADERS) + target_precompile_headers(llappearance REUSE_FROM llprecompiled) +endif () + if (BUILD_HEADLESS) add_library (llappearanceheadless ${llappearance_SOURCE_FILES}) target_include_directories( llappearanceheadless INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}) @@ -85,4 +89,8 @@ if (BUILD_HEADLESS) llcorehttp llcommon ) + + if (USE_PRECOMPILED_HEADERS) + target_precompile_headers(llappearanceheadless REUSE_FROM llprecompiled) + endif () endif (BUILD_HEADLESS) diff --git a/indra/llappearanceutility/CMakeLists.txt b/indra/llappearanceutility/CMakeLists.txt index 1d4e5309ba..53b5ce1cbe 100644 --- a/indra/llappearanceutility/CMakeLists.txt +++ b/indra/llappearanceutility/CMakeLists.txt @@ -63,6 +63,10 @@ target_link_libraries(appearance-utility-bin llxml ) +if (USE_PRECOMPILED_HEADERS) + target_precompile_headers(appearance-utility-bin REUSE_FROM llprecompiled) +endif () + if (BUILD_HEADLESS) add_executable(appearance-utility-headless-bin ${appearance_utility_SOURCE_FILES}) @@ -74,5 +78,9 @@ if (BUILD_HEADLESS) llrenderheadless llxml ) + + if (USE_PRECOMPILED_HEADERS) + target_precompile_headers(appearance-utility-headless-bin REUSE_FROM llprecompiled) + endif () endif (BUILD_HEADLESS) diff --git a/indra/llaudio/CMakeLists.txt b/indra/llaudio/CMakeLists.txt index 9278d3c488..18e29fb194 100644 --- a/indra/llaudio/CMakeLists.txt +++ b/indra/llaudio/CMakeLists.txt @@ -54,3 +54,7 @@ endif() if( TARGET ll::fmodstudio ) target_link_libraries( llaudio ll::fmodstudio ) endif() + +if (USE_PRECOMPILED_HEADERS) + target_precompile_headers(llaudio REUSE_FROM llprecompiled) +endif () diff --git a/indra/llcharacter/CMakeLists.txt b/indra/llcharacter/CMakeLists.txt index bc45eb474a..1f019e6aef 100644 --- a/indra/llcharacter/CMakeLists.txt +++ b/indra/llcharacter/CMakeLists.txt @@ -70,3 +70,7 @@ target_link_libraries( llfilesystem llxml ) + +if (USE_PRECOMPILED_HEADERS) + target_precompile_headers(llcharacter REUSE_FROM llprecompiled) +endif () diff --git a/indra/llcommon/CMakeLists.txt b/indra/llcommon/CMakeLists.txt index 2de9deea70..c3b892b204 100644 --- a/indra/llcommon/CMakeLists.txt +++ b/indra/llcommon/CMakeLists.txt @@ -68,7 +68,7 @@ set(llcommon_SOURCE_FILES llmetricperformancetester.cpp llmortician.cpp llmutex.cpp - llptrto.cpp + llptrto.cpp llpredicate.cpp llprocess.cpp llprocessor.cpp @@ -108,7 +108,7 @@ set(llcommon_SOURCE_FILES workqueue.cpp StackWalker.cpp ) - + set(llcommon_HEADER_FILES CMakeLists.txt @@ -255,14 +255,28 @@ set(llcommon_HEADER_FILES workqueue.h StackWalker.h ) - + if (DARWIN) list(APPEND llcommon_HEADER_FILES llsys_objc.h) list(APPEND llcommon_SOURCE_FILES llsys_objc.mm) + + set_source_files_properties( + llsys_objc.mm + PROPERTIES + SKIP_PRECOMPILE_HEADERS TRUE + ) endif (DARWIN) if (USE_TRACY) list(APPEND llcommon_SOURCE_FILES llprofiler.cpp) + + # Skip precompiled headers on these files due to special compilation needs + set_source_files_properties( + llfasttimer.cpp + llprofiler.cpp + PROPERTIES + SKIP_PRECOMPILE_HEADERS TRUE + ) endif () list(APPEND llcommon_SOURCE_FILES ${llcommon_HEADER_FILES}) @@ -280,8 +294,12 @@ target_link_libraries( ll::sse2neon ) -target_include_directories(llcommon INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}) -target_include_directories(llcommon PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}) +target_include_directories(llcommon PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) +target_include_directories(llcommon PRIVATE ${CMAKE_SOURCE_DIR}/llmath) + +if (USE_PRECOMPILED_HEADERS) + target_precompile_headers(llcommon REUSE_FROM llprecompiled) +endif () add_dependencies(llcommon stage_third_party_libs) diff --git a/indra/llcommon/llsd.cpp b/indra/llcommon/llsd.cpp index 77fe545c3f..ea6d6a308a 100644 --- a/indra/llcommon/llsd.cpp +++ b/indra/llcommon/llsd.cpp @@ -32,7 +32,6 @@ #include "llbase64.h" #include "llerror.h" -#include "../llmath/llmath.h" #include "llformat.h" #include "llsdserialize.h" #include "stringize.h" @@ -291,10 +290,10 @@ namespace }; LLSD::Boolean ImplReal::asBoolean() const - { return !llisnan(mValue) && mValue != 0.0; } + { return !std::isnan(mValue) && mValue != 0.0; } LLSD::Integer ImplReal::asInteger() const - { return !llisnan(mValue) ? (LLSD::Integer)mValue : 0; } + { return !std::isnan(mValue) ? (LLSD::Integer)mValue : 0; } LLSD::String ImplReal::asString() const { return llformat("%lg", mValue); } diff --git a/indra/llcommon/llsdjson.cpp b/indra/llcommon/llsdjson.cpp index 655869a704..542a3c26e3 100644 --- a/indra/llcommon/llsdjson.cpp +++ b/indra/llcommon/llsdjson.cpp @@ -33,7 +33,6 @@ #include "llsdutil.h" #include "llerror.h" -#include "../llmath/llmath.h" #include diff --git a/indra/llcorehttp/CMakeLists.txt b/indra/llcorehttp/CMakeLists.txt index 05b788a433..46503a8a4b 100644 --- a/indra/llcorehttp/CMakeLists.txt +++ b/indra/llcorehttp/CMakeLists.txt @@ -81,6 +81,7 @@ list(APPEND llcorehttp_SOURCE_FILES ${llcorehttp_HEADER_FILES}) add_library (llcorehttp ${llcorehttp_SOURCE_FILES}) target_link_libraries( llcorehttp + llmath llcommon ll::libcurl ll::openssl @@ -92,6 +93,10 @@ target_include_directories( llcorehttp INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}) # lead to circular dependencies (or in case of cmake, the first project declaring it's dependencies wins) target_include_directories( llcorehttp PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../llmessage) +if (USE_PRECOMPILED_HEADERS) + target_precompile_headers(llcorehttp REUSE_FROM llprecompiled) +endif () + # tests set(LLCOREHTTP_TESTS ON CACHE BOOL "Build and run llcorehttp integration tests specifically") @@ -131,7 +136,7 @@ if (LL_TESTS AND LLCOREHTTP_TESTS) ${PYTHON_EXECUTABLE} "${CMAKE_CURRENT_SOURCE_DIR}/tests/test_llcorehttp_peer.py" ) - + # # Example Programs # @@ -151,6 +156,7 @@ if (LL_TESTS AND LLCOREHTTP_TESTS) set_target_properties(http_texture_load PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${EXE_STAGING_DIR}" + FOLDER "Tests" ) if (WINDOWS) diff --git a/indra/llcrashlogger/CMakeLists.txt b/indra/llcrashlogger/CMakeLists.txt index 6ac73c0d32..7a1c3eef54 100644 --- a/indra/llcrashlogger/CMakeLists.txt +++ b/indra/llcrashlogger/CMakeLists.txt @@ -21,3 +21,7 @@ list(APPEND llcrashlogger_SOURCE_FILES ${llcrashlogger_HEADER_FILES}) add_library(llcrashlogger ${llcrashlogger_SOURCE_FILES}) target_link_libraries( llcrashlogger llcommon llmessage llcorehttp llxml llfilesystem ) + +if (USE_PRECOMPILED_HEADERS) + target_precompile_headers(llcrashlogger REUSE_FROM llprecompiled) +endif () diff --git a/indra/llfilesystem/CMakeLists.txt b/indra/llfilesystem/CMakeLists.txt index 9f24f75eab..a552e4bdbc 100644 --- a/indra/llfilesystem/CMakeLists.txt +++ b/indra/llfilesystem/CMakeLists.txt @@ -28,6 +28,12 @@ if (DARWIN) LIST(APPEND llfilesystem_SOURCE_FILES lldir_utils_objc.h) LIST(APPEND llfilesystem_SOURCE_FILES lldir_mac.cpp) LIST(APPEND llfilesystem_HEADER_FILES lldir_mac.h) + + set_source_files_properties( + lldir_utils_objc.mm + PROPERTIES + SKIP_PRECOMPILE_HEADERS TRUE + ) endif (DARWIN) if (LINUX) @@ -52,10 +58,15 @@ list(APPEND llfilesystem_SOURCE_FILES ${llfilesystem_HEADER_FILES}) add_library (llfilesystem ${llfilesystem_SOURCE_FILES}) target_link_libraries(llfilesystem + llmath llcommon ) target_include_directories( llfilesystem INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}) +if (USE_PRECOMPILED_HEADERS) + target_precompile_headers(llfilesystem REUSE_FROM llprecompiled) +endif () + # Add tests if (LL_TESTS) include(LLAddBuildTest) diff --git a/indra/llimage/CMakeLists.txt b/indra/llimage/CMakeLists.txt index cc75c463bc..a81808343f 100644 --- a/indra/llimage/CMakeLists.txt +++ b/indra/llimage/CMakeLists.txt @@ -63,6 +63,10 @@ target_link_libraries(llimage ll::libjpeg ) +if (USE_PRECOMPILED_HEADERS) + target_precompile_headers(llimage REUSE_FROM llprecompiled) +endif () + # Add tests if (LL_TESTS) SET(llimage_TEST_SOURCE_FILES diff --git a/indra/llimagej2coj/CMakeLists.txt b/indra/llimagej2coj/CMakeLists.txt index 93e85668dd..b7ef696b20 100644 --- a/indra/llimagej2coj/CMakeLists.txt +++ b/indra/llimagej2coj/CMakeLists.txt @@ -27,3 +27,6 @@ target_link_libraries( llimagej2coj ll::openjpeg ) +if (USE_PRECOMPILED_HEADERS) + target_precompile_headers(llimagej2coj REUSE_FROM llprecompiled) +endif () diff --git a/indra/llinventory/CMakeLists.txt b/indra/llinventory/CMakeLists.txt index 93a586759f..22966bc55b 100644 --- a/indra/llinventory/CMakeLists.txt +++ b/indra/llinventory/CMakeLists.txt @@ -59,6 +59,10 @@ add_library (llinventory ${llinventory_SOURCE_FILES}) target_link_libraries( llinventory llcommon llmath llmessage llxml ) target_include_directories( llinventory INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}) +if (USE_PRECOMPILED_HEADERS) + target_precompile_headers(llinventory REUSE_FROM llprecompiled) +endif () + #add unit tests if (LL_TESTS) INCLUDE(LLAddBuildTest) diff --git a/indra/llmath/CMakeLists.txt b/indra/llmath/CMakeLists.txt index bd860adc31..fb57e5db11 100644 --- a/indra/llmath/CMakeLists.txt +++ b/indra/llmath/CMakeLists.txt @@ -99,10 +99,14 @@ set(llmath_HEADER_FILES list(APPEND llmath_SOURCE_FILES ${llmath_HEADER_FILES}) -add_library (llmath ${llmath_SOURCE_FILES}) +add_library(llmath ${llmath_SOURCE_FILES}) target_link_libraries(llmath llcommon llmeshoptimizer ll::sse2neon) -target_include_directories( llmath INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}) +target_include_directories(llmath INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}) + +if (USE_PRECOMPILED_HEADERS) + target_precompile_headers(llmath REUSE_FROM llprecompiled) +endif () # Add tests if (LL_TESTS) diff --git a/indra/llmeshoptimizer/CMakeLists.txt b/indra/llmeshoptimizer/CMakeLists.txt index dfac44c296..5b1ab9d8e4 100644 --- a/indra/llmeshoptimizer/CMakeLists.txt +++ b/indra/llmeshoptimizer/CMakeLists.txt @@ -30,5 +30,9 @@ target_link_libraries(llmeshoptimizer llmath ll::meshoptimizer) +if (USE_PRECOMPILED_HEADERS) + target_precompile_headers(llmeshoptimizer REUSE_FROM llprecompiled) +endif () + # Add tests diff --git a/indra/llmessage/CMakeLists.txt b/indra/llmessage/CMakeLists.txt index b2757a7306..46f28abc9c 100644 --- a/indra/llmessage/CMakeLists.txt +++ b/indra/llmessage/CMakeLists.txt @@ -194,6 +194,10 @@ target_link_libraries( ) target_include_directories( llmessage INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}) +if (USE_PRECOMPILED_HEADERS) + target_precompile_headers(llmessage REUSE_FROM llprecompiled) +endif () + # tests if (LL_TESTS) SET(llmessage_TEST_SOURCE_FILES diff --git a/indra/llphysicsextensionsos/CMakeLists.txt b/indra/llphysicsextensionsos/CMakeLists.txt index c04115ef26..ff1b703dc7 100644 --- a/indra/llphysicsextensionsos/CMakeLists.txt +++ b/indra/llphysicsextensionsos/CMakeLists.txt @@ -43,5 +43,9 @@ if(WINDOWS) target_compile_options(llphysicsextensionsos PRIVATE /bigobj) endif() +if (USE_PRECOMPILED_HEADERS) + target_precompile_headers(llphysicsextensionsos REUSE_FROM llprecompiled) +endif () + # Add tests diff --git a/indra/llplugin/CMakeLists.txt b/indra/llplugin/CMakeLists.txt index e008a4093e..f67975365a 100644 --- a/indra/llplugin/CMakeLists.txt +++ b/indra/llplugin/CMakeLists.txt @@ -36,5 +36,10 @@ list(APPEND llplugin_SOURCE_FILES ${llplugin_HEADER_FILES}) add_library (llplugin ${llplugin_SOURCE_FILES}) target_include_directories( llplugin INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}) target_link_libraries( llplugin llcommon llmath llmessage llxml ) + +if (USE_PRECOMPILED_HEADERS) + target_precompile_headers(llplugin REUSE_FROM llprecompiled) +endif () + add_subdirectory(slplugin) diff --git a/indra/llplugin/slplugin/CMakeLists.txt b/indra/llplugin/slplugin/CMakeLists.txt index 4df3e306cb..f746160ada 100644 --- a/indra/llplugin/slplugin/CMakeLists.txt +++ b/indra/llplugin/slplugin/CMakeLists.txt @@ -18,6 +18,12 @@ if (DARWIN) list(APPEND SLPlugin_HEADER_FILES slplugin-objc.h ) + + set_source_files_properties( + slplugin-objc.mm + PROPERTIES + SKIP_PRECOMPILE_HEADERS TRUE + ) endif (DARWIN) if (SLPlugin_HEADER_FILES) @@ -37,6 +43,10 @@ target_link_libraries(SLPlugin ll::pluginlibraries ) +if (USE_PRECOMPILED_HEADERS) + target_precompile_headers(SLPlugin REUSE_FROM llprecompiled) +endif () + if (WINDOWS) set_target_properties(SLPlugin PROPERTIES diff --git a/indra/llprecompiled/CMakeLists.txt b/indra/llprecompiled/CMakeLists.txt new file mode 100644 index 0000000000..ea230f4a98 --- /dev/null +++ b/indra/llprecompiled/CMakeLists.txt @@ -0,0 +1,53 @@ +# -*- cmake -*- + +project(llprecompiled) + +include(00-Common) +include(APR) +include(bugsplat) +include(Linking) +include(Boost) +include(LLSharedLibs) +include(ZLIBNG) +include(Tracy) +include(EXPAT) +include(SSE2NEON) + +set(llprecompiled_SOURCE_FILES + cmake_dummy.cpp + ) + +add_library (llprecompiled ${llprecompiled_SOURCE_FILES}) + +target_include_directories(llprecompiled PRIVATE + ${CMAKE_SOURCE_DIR}/${LIBS_OPEN_PREFIX}llmath + ) + +target_link_libraries(llprecompiled + llcommon + ll::apr + ll::expat + ll::zlib-ng + ll::boost + ll::oslibraries + ll::tracy + ll::sse2neon + ) + +target_precompile_headers(llprecompiled PRIVATE + [["linden_common.h"]] + [["llwin32headers.h"]] + [["llprofiler.h"]] + [["llmath.h"]] + + + + + + + + + + + + ) diff --git a/indra/llprecompiled/cmake_dummy.cpp b/indra/llprecompiled/cmake_dummy.cpp new file mode 100644 index 0000000000..21a47a9b14 --- /dev/null +++ b/indra/llprecompiled/cmake_dummy.cpp @@ -0,0 +1,24 @@ +/** + * @file cmake_dummy.cpp + * + * $LicenseInfo:firstyear=2008&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2010, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ diff --git a/indra/llprimitive/CMakeLists.txt b/indra/llprimitive/CMakeLists.txt index ff0cad58d6..f05be03034 100644 --- a/indra/llprimitive/CMakeLists.txt +++ b/indra/llprimitive/CMakeLists.txt @@ -79,6 +79,10 @@ else() ) endif () +if (USE_PRECOMPILED_HEADERS) + target_precompile_headers(llprimitive REUSE_FROM llprecompiled) +endif () + #add unit tests if (LL_TESTS) INCLUDE(LLAddBuildTest) diff --git a/indra/llrender/CMakeLists.txt b/indra/llrender/CMakeLists.txt index d0ae2d6b93..77af0693f3 100644 --- a/indra/llrender/CMakeLists.txt +++ b/indra/llrender/CMakeLists.txt @@ -86,6 +86,10 @@ if (BUILD_HEADLESS) ll::freetype OpenGL::GL ) + + if (USE_PRECOMPILED_HEADERS) + target_precompile_headers(llrenderheadless REUSE_FROM llprecompiled) + endif() endif (BUILD_HEADLESS) add_library (llrender ${llrender_SOURCE_FILES}) @@ -104,3 +108,6 @@ target_link_libraries(llrender OpenGL::GL ) +if (USE_PRECOMPILED_HEADERS) + target_precompile_headers(llrender REUSE_FROM llprecompiled) +endif () diff --git a/indra/llui/CMakeLists.txt b/indra/llui/CMakeLists.txt index 908e94b24c..b543a12281 100644 --- a/indra/llui/CMakeLists.txt +++ b/indra/llui/CMakeLists.txt @@ -272,6 +272,10 @@ target_link_libraries(llui llcommon ) +if (USE_PRECOMPILED_HEADERS) + target_precompile_headers(llui REUSE_FROM llprecompiled) +endif () + # Add tests if(LL_TESTS) include(LLAddBuildTest) diff --git a/indra/llwindow/CMakeLists.txt b/indra/llwindow/CMakeLists.txt index fe45df4021..1f846de35d 100644 --- a/indra/llwindow/CMakeLists.txt +++ b/indra/llwindow/CMakeLists.txt @@ -101,6 +101,13 @@ if (DARWIN) PROPERTIES COMPILE_FLAGS "-fpascal-strings" ) + + set_source_files_properties( + llwindowmacosx-objc.mm + llopenglview-objc.mm + PROPERTIES + SKIP_PRECOMPILE_HEADERS TRUE + ) endif (DARWIN) @@ -170,6 +177,10 @@ if (BUILD_HEADLESS) dl ) target_include_directories(llwindowheadless INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}) + + if (USE_PRECOMPILED_HEADERS) + target_precompile_headers(llwindowheadless REUSE_FROM llprecompiled) + endif () endif (BUILD_HEADLESS) if (llwindow_HEADER_FILES) @@ -190,6 +201,10 @@ if (USE_SDL_WINDOW) target_compile_definitions( llwindow PUBLIC LL_SDL_WINDOW=1 ) endif() +if (USE_PRECOMPILED_HEADERS) + target_precompile_headers(llwindow REUSE_FROM llprecompiled) +endif () + if (DARWIN) target_link_libraries(llwindow ${CARBON_LIBRARY}) endif (DARWIN) diff --git a/indra/llxml/CMakeLists.txt b/indra/llxml/CMakeLists.txt index 508c2b919b..bc79e2ef19 100644 --- a/indra/llxml/CMakeLists.txt +++ b/indra/llxml/CMakeLists.txt @@ -34,6 +34,9 @@ target_link_libraries( llxml ) target_include_directories( llxml INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}) +if (USE_PRECOMPILED_HEADERS) + target_precompile_headers(llxml REUSE_FROM llprecompiled) +endif () # tests -- cgit v1.3 From 5964e02894f2d9387080fbd848f0db02abd06356 Mon Sep 17 00:00:00 2001 From: Rye Date: Sun, 26 Oct 2025 02:53:52 -0400 Subject: Fix memcpy of 0 being reported as undefined behavior by ubsan Signed-off-by: Rye --- indra/llcommon/llmd5.cpp | 2 ++ indra/llmessage/lltemplatemessagereader.cpp | 3 +++ 2 files changed, 5 insertions(+) (limited to 'indra/llmessage') diff --git a/indra/llcommon/llmd5.cpp b/indra/llcommon/llmd5.cpp index c8ca586e7f..ae7468aa22 100644 --- a/indra/llcommon/llmd5.cpp +++ b/indra/llcommon/llmd5.cpp @@ -262,6 +262,8 @@ void LLMD5::raw_digest(unsigned char* s) const void LLMD5::hex_digest(char* s) const { + if(!s) return; + if (!finalized) { std::cerr << "LLMD5::hex_digest: Can't get digest if you haven't " diff --git a/indra/llmessage/lltemplatemessagereader.cpp b/indra/llmessage/lltemplatemessagereader.cpp index b62288590e..850d73e910 100644 --- a/indra/llmessage/lltemplatemessagereader.cpp +++ b/indra/llmessage/lltemplatemessagereader.cpp @@ -118,6 +118,9 @@ void LLTemplateMessageReader::getData(const char *blockname, const char *varname { switch( vardata_size ) { + case 0: + // This is here to prevent a memcpy from a null value which is undefined behavior. + break; case 1: *((U8*)datap) = *((U8*)vardata.getData()); break; -- cgit v1.3 From d2e80039df1712734a6e3b0d811d73f850345157 Mon Sep 17 00:00:00 2001 From: Rye Date: Sun, 2 Nov 2025 13:20:01 -0500 Subject: Fix building with clang on non-darwin platforms Signed-off-by: Rye --- indra/cmake/00-Common.cmake | 4 +++ indra/cmake/UI.cmake | 1 + indra/llcommon/StackWalker.cpp | 2 ++ indra/llcommon/llapr.cpp | 4 +-- indra/llcommon/lldate.cpp | 4 --- indra/llcommon/llfindlocale.cpp | 4 +-- indra/llcommon/llinstancetracker.h | 8 ++--- indra/llcommon/llmd5.cpp | 4 +-- indra/llcommon/llmemory.cpp | 3 -- indra/llcommon/llpreprocessor.h | 52 ++++++++++++++-------------- indra/llcommon/llsdserialize.cpp | 4 --- indra/llcommon/llstl.h | 10 ------ indra/llcommon/stdtypes.h | 24 +++---------- indra/llcommon/tests/commonmisc_test.cpp | 4 +-- indra/llcommon/tests/lldependencies_test.cpp | 12 ------- indra/llcommon/tests/llerror_test.cpp | 2 +- indra/llcommon/tests/llstring_test.cpp | 4 +-- indra/llcorehttp/llhttpconstants.h | 2 ++ indra/llkdu/include_kdu_xxxx.h | 2 +- indra/llkdu/tests/llimagej2ckdu_test.cpp | 2 +- indra/llmessage/llbufferstream.cpp | 11 ------ indra/llmessage/llbufferstream.h | 9 ----- indra/llmessage/llpartdata.cpp | 8 ++--- indra/newview/llappviewerlinux.h | 2 +- indra/newview/llface.cpp | 6 ---- indra/newview/llviewermessage.cpp | 4 --- indra/newview/llviewerwindow.cpp | 9 ++--- indra/newview/llvoicewebrtc.cpp | 6 ++-- indra/newview/pipeline.cpp | 17 +++++++-- indra/test/lltut.h | 4 +-- 30 files changed, 81 insertions(+), 147 deletions(-) (limited to 'indra/llmessage') diff --git a/indra/cmake/00-Common.cmake b/indra/cmake/00-Common.cmake index 24402f03ee..1ab94e13df 100644 --- a/indra/cmake/00-Common.cmake +++ b/indra/cmake/00-Common.cmake @@ -216,6 +216,10 @@ endif(DARWIN) if (LINUX OR DARWIN) add_compile_options(-Wall -Wno-sign-compare -Wno-trigraphs -Wno-reorder -Wno-unused-but-set-variable -Wno-unused-variable) + if(CMAKE_CXX_COMPILER_ID STREQUAL "Clang") + add_compile_options(-Wno-unused-private-field) + endif() + if (CMAKE_CXX_COMPILER_ID STREQUAL "Clang" OR CMAKE_CXX_COMPILER_ID STREQUAL "AppleClang") add_compile_options(-Wno-unused-local-typedef) endif() diff --git a/indra/cmake/UI.cmake b/indra/cmake/UI.cmake index 8e6382ceeb..f2776b21e1 100644 --- a/indra/cmake/UI.cmake +++ b/indra/cmake/UI.cmake @@ -15,6 +15,7 @@ if (LINUX) pkg_check_modules(WAYLAND_CLIENT wayland-client) if(WAYLAND_CLIENT_FOUND) + target_include_directories(ll::uilibraries INTERFACE ${WAYLAND_CLIENT_INCLUDE_DIRS}) target_compile_definitions(ll::uilibraries INTERFACE LL_WAYLAND=1) else() message("pkgconfig could not find wayland client, compiling without full wayland support") diff --git a/indra/llcommon/StackWalker.cpp b/indra/llcommon/StackWalker.cpp index e9ae1723fb..77ae4db4bd 100644 --- a/indra/llcommon/StackWalker.cpp +++ b/indra/llcommon/StackWalker.cpp @@ -785,6 +785,8 @@ private: case 8: //SymVirtual: szSymType = "Virtual"; break; + case NumSymTypes: + break; } } LPCSTR pdbName = Module.LoadedImageName; diff --git a/indra/llcommon/llapr.cpp b/indra/llcommon/llapr.cpp index 01763c49aa..ff5f262036 100644 --- a/indra/llcommon/llapr.cpp +++ b/indra/llcommon/llapr.cpp @@ -230,11 +230,11 @@ bool LLVolatileAPRPool::isFull() bool _ll_apr_warn_status(apr_status_t status, const char* file, int line) { if(APR_SUCCESS == status) return false; -#if !LL_LINUX + char buf[MAX_STRING]; /* Flawfinder: ignore */ apr_strerror(status, buf, sizeof(buf)); LL_WARNS("APR") << "APR: " << file << ":" << line << " " << buf << LL_ENDL; -#endif + return true; } diff --git a/indra/llcommon/lldate.cpp b/indra/llcommon/lldate.cpp index 5205699b92..b4cdf3cbda 100644 --- a/indra/llcommon/lldate.cpp +++ b/indra/llcommon/lldate.cpp @@ -131,11 +131,7 @@ void LLDate::toStream(std::ostream& s) const } s << std::dec << std::setfill('0'); -#if( LL_WINDOWS || __GNUC__ > 2) s << std::right; -#else - s.setf(ios::right); -#endif s << std::setw(4) << (exp_time.tm_year + 1900) << '-' << std::setw(2) << (exp_time.tm_mon + 1) << '-' << std::setw(2) << (exp_time.tm_mday) diff --git a/indra/llcommon/llfindlocale.cpp b/indra/llcommon/llfindlocale.cpp index b4bcc80ac4..d606a6fdb9 100644 --- a/indra/llcommon/llfindlocale.cpp +++ b/indra/llcommon/llfindlocale.cpp @@ -134,7 +134,7 @@ accumulate_locstring(const char *str, FL_Locale *l) { return 0; } - +#ifndef LL_WINDOWS static int accumulate_env(const char *name, FL_Locale *l) { char *env; @@ -148,7 +148,7 @@ accumulate_env(const char *name, FL_Locale *l) { free(lang); free(country); free(variant); return 0; } - +#endif static void canonise_fl(FL_Locale *l) { diff --git a/indra/llcommon/llinstancetracker.h b/indra/llcommon/llinstancetracker.h index 6692d6a697..5a7f27e688 100644 --- a/indra/llcommon/llinstancetracker.h +++ b/indra/llcommon/llinstancetracker.h @@ -246,9 +246,7 @@ public: } protected: -#if LL_CLANG || LL_GNUC - __attribute__((no_sanitize("vptr"))) -#endif + LL_UBSAN_SUPRESS_VPTR LLInstanceTracker(const KEY& key) { // We do not intend to manage the lifespan of this object with @@ -487,9 +485,7 @@ public: using key_snapshot_of = instance_snapshot_of; protected: -#if LL_CLANG || LL_GNUC - __attribute__((no_sanitize("vptr"))) -#endif + LL_UBSAN_SUPRESS_VPTR LLInstanceTracker() { // Since we do not intend for this shared_ptr to manage lifespan, give diff --git a/indra/llcommon/llmd5.cpp b/indra/llcommon/llmd5.cpp index ae7468aa22..b05fd2e21b 100644 --- a/indra/llcommon/llmd5.cpp +++ b/indra/llcommon/llmd5.cpp @@ -255,7 +255,7 @@ void LLMD5::raw_digest(unsigned char* s) const memcpy(s, digest, 16); /* Flawfinder: ignore */ } -#if LL_DARWIN +#if LL_CLANG #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" #endif @@ -280,7 +280,7 @@ void LLMD5::hex_digest(char* s) const s[32] = '\0'; } -#if LL_DARWIN +#if LL_CLANG #pragma clang diagnostic pop #endif diff --git a/indra/llcommon/llmemory.cpp b/indra/llcommon/llmemory.cpp index ba48319a16..9617e30f0b 100644 --- a/indra/llcommon/llmemory.cpp +++ b/indra/llcommon/llmemory.cpp @@ -146,9 +146,6 @@ void LLMemory::updateMemoryInfo() LL_WARNS() << "task_info failed" << LL_ENDL; } #elif defined(LL_LINUX) - // Use sysinfo() to get the total physical memory. - struct sysinfo info; - sysinfo(&info); sAllocatedMemInKB = U32Kilobytes::convert(U64Bytes(LLMemory::getCurrentRSS())); // represents the RAM allocated by this process only (in line with the windows implementation) #else //not valid for other systems for now. diff --git a/indra/llcommon/llpreprocessor.h b/indra/llcommon/llpreprocessor.h index 5269fb2282..104d3cc186 100644 --- a/indra/llcommon/llpreprocessor.h +++ b/indra/llcommon/llpreprocessor.h @@ -61,18 +61,25 @@ # define LL_UNLIKELY(EXPR) (EXPR) #endif - // Figure out differences between compilers -#if defined(__clang__) - #define GCC_VERSION (__GNUC__ * 10000 \ - + __GNUC_MINOR__ * 100 \ - + __GNUC_PATCHLEVEL__) +#if defined(__MSVC_VER__) || defined(_MSC_VER) + #ifndef LL_MSVC + #define LL_MSVC 1 + #endif + + // Clang CL is MSVC-like but also supports its own macros + #if defined(__clang__) + #ifndef LL_CLANG + #define LL_CLANG 1 + #endif + #endif +#elif defined(__clang__) + #define CLANG_VERSION (__clang_major__ * 10000 \ + + __clang_minor__ * 100 \ + + __clang_patchlevel__) #ifndef LL_CLANG #define LL_CLANG 1 #endif - #ifndef LL_GNUC - #define LL_GNUC 1 - #endif #elif defined(__GNUC__) #define GCC_VERSION (__GNUC__ * 10000 \ + __GNUC_MINOR__ * 100 \ @@ -80,26 +87,22 @@ #ifndef LL_GNUC #define LL_GNUC 1 #endif -#elif defined(__MSVC_VER__) || defined(_MSC_VER) - #ifndef LL_MSVC - #define LL_MSVC 1 - #endif #endif // Set up CPU architecture defines #if LL_MSVC && defined(_M_ARM64) # define LL_ARM64 1 -#elif LL_GNUC && (defined(__arm64__) || defined(__aarch64__)) +#elif (LL_GNUC || LL_CLANG) && (defined(__arm64__) || defined(__aarch64__)) # define LL_ARM64 1 #elif LL_MSVC && _M_X64 # define LL_X86_64 1 # define LL_X86 1 #elif LL_MSVC && _M_IX86 # define LL_X86 1 -#elif LL_GNUC && ( defined(__amd64__) || defined(__x86_64__) ) +#elif (LL_GNUC || LL_CLANG) && ( defined(__amd64__) || defined(__x86_64__) ) # define LL_X86_64 1 # define LL_X86 1 -#elif LL_GNUC && ( defined(__i386__) ) +#elif (LL_GNUC || LL_CLANG) && ( defined(__i386__) ) # define LL_X86 1 #endif @@ -116,16 +119,6 @@ #endif -// Although thread_local is now a standard storage class, we can't just -// #define LL_THREAD_LOCAL as thread_local because the *usage* is different. -// We'll have to take the time to change LL_THREAD_LOCAL declarations by hand. -#if LL_WINDOWS -# define LL_THREAD_LOCAL __declspec(thread) -#else -# define LL_THREAD_LOCAL __thread -#endif - - #if defined(LL_WINDOWS) #define BOOST_REGEX_NO_LIB 1 #define CURL_STATICLIB 1 @@ -150,7 +143,7 @@ #define LL_DLLIMPORT #endif // LL_WINDOWS -#if __clang__ || ! defined(LL_WINDOWS) +#if LL_CLANG || ! defined(LL_WINDOWS) // Only on Windows, and only with the Microsoft compiler (vs. clang) is // wchar_t potentially not a distinct type. #define LL_WCHAR_T_NATIVE 1 @@ -211,6 +204,13 @@ #define LL_PRETTY_FUNCTION __PRETTY_FUNCTION__ #endif +// vptr warning supression funtionality for undefined behavior sanitizer +#if LL_CLANG || LL_GNUC +# define LL_UBSAN_SUPRESS_VPTR __attribute__((no_sanitize("vptr"))) +#else +# define LL_UBSAN_SUPRESS_VPTR +#endif + #if LL_ARM64 #define GLM_FORCE_NEON 1 #else diff --git a/indra/llcommon/llsdserialize.cpp b/indra/llcommon/llsdserialize.cpp index c42eebebd1..3cc960698e 100644 --- a/indra/llcommon/llsdserialize.cpp +++ b/indra/llcommon/llsdserialize.cpp @@ -1424,11 +1424,7 @@ S32 LLSDNotationFormatter::format_impl(const LLSD& data, std::ostream& ostr, case LLSD::TypeBoolean: if(mBoolAlpha || -#if( LL_WINDOWS || __GNUC__ > 2) (ostr.flags() & std::ios::boolalpha) -#else - (ostr.flags() & 0x0100) -#endif ) { ostr << (data.asBoolean() diff --git a/indra/llcommon/llstl.h b/indra/llcommon/llstl.h index 7d41c42ba7..fb387a7b52 100644 --- a/indra/llcommon/llstl.h +++ b/indra/llcommon/llstl.h @@ -522,18 +522,8 @@ llbind2nd(const _Operation& __oper, const _Tp& __x) inline bool before(const std::type_info* lhs, const std::type_info* rhs) { -#if LL_LINUX && defined(__GNUC__) && ((__GNUC__ < 4) || (__GNUC__ == 4 && __GNUC_MINOR__ < 4)) - // If we're building on Linux with gcc, and it's either gcc 3.x or - // 4.{0,1,2,3}, then we have to use a workaround. Note that we use gcc on - // Mac too, and some people build with gcc on Windows (cygwin or mingw). - // On Linux, different load modules may produce different type_info* - // pointers for the same type. Have to compare name strings to get good - // results. - return strcmp(lhs->name(), rhs->name()) < 0; -#else // not Linux, or gcc 4.4+ // Just use before(), as we normally would return lhs->before(*rhs); -#endif } /** diff --git a/indra/llcommon/stdtypes.h b/indra/llcommon/stdtypes.h index f1e4c2bc78..6b98a6bc49 100644 --- a/indra/llcommon/stdtypes.h +++ b/indra/llcommon/stdtypes.h @@ -38,6 +38,11 @@ typedef signed short S16; typedef unsigned short U16; typedef signed int S32; typedef unsigned int U32; +typedef long long int S64; +typedef long long unsigned int U64; + +#define S64L(a) (a##LL) +#define U64L(a) (a##ULL) // to express an index that might go negative // (ssize_t is provided by SOME compilers, don't collide) @@ -62,21 +67,6 @@ typedef wchar_t llwchar; #define LLWCHAR_IS_WCHAR_T 1 #endif -#if LL_WINDOWS -typedef signed __int64 S64; -// probably should be 'hyper' or similiar -#define S64L(a) (a) -typedef unsigned __int64 U64; -#define U64L(a) (a) -#else -typedef long long int S64; -typedef long long unsigned int U64; -#if LL_DARWIN || LL_LINUX -#define S64L(a) (a##LL) -#define U64L(a) (a##ULL) -#endif -#endif - typedef float F32; typedef double F64; @@ -121,10 +111,6 @@ typedef U8 LLPCode; #define LL_ARRAY_SIZE( _kArray ) ( sizeof( (_kArray) ) / sizeof( _kArray[0] ) ) -#if LL_LINUX && __GNUC__ <= 2 -typedef int intptr_t; -#endif - /***************************************************************************** * Narrowing *****************************************************************************/ diff --git a/indra/llcommon/tests/commonmisc_test.cpp b/indra/llcommon/tests/commonmisc_test.cpp index b1a284225e..80be26dfeb 100644 --- a/indra/llcommon/tests/commonmisc_test.cpp +++ b/indra/llcommon/tests/commonmisc_test.cpp @@ -503,7 +503,7 @@ namespace tut result_str = (const char*) result; ensure_equals("U64_to_str converted 1.4", val_str, result_str); - val = U64L(-1); // 0xFFFFFFFFFFFFFFFF == 18446744073709551615 + val = U64(-1); // 0xFFFFFFFFFFFFFFFF == 18446744073709551615 val_str = "18446744073709551615"; U64_to_str(val, result, sizeof(result)); result_str = (const char*) result; @@ -619,7 +619,7 @@ namespace tut val = U64_to_F64(U64L(2)); ensure_equals("U64_to_F64 converted 3.6", val, result); - result = U64L(0x7FFFFFFFFFFFFFFF) * 1.0L; // 0x7FFFFFFFFFFFFFFF + result = F64(0x7FFFFFFFFFFFFFFF) * 1.0; // 0x7FFFFFFFFFFFFFFF val = U64_to_F64(U64L(0x7FFFFFFFFFFFFFFF)); ensure_equals("U64_to_F64 converted 3.7", val, result); } diff --git a/indra/llcommon/tests/lldependencies_test.cpp b/indra/llcommon/tests/lldependencies_test.cpp index 84eb41b5fe..0a4f0f38da 100644 --- a/indra/llcommon/tests/lldependencies_test.cpp +++ b/indra/llcommon/tests/lldependencies_test.cpp @@ -233,19 +233,7 @@ namespace tut StringList keys(make(list_of("The")("brown")("dog.")("fox")("jumps")("lazy")("over")("quick")("the")("yellow"))); ensure_equals(instance_from_range(deps.get_key_range()), keys); -#if (! defined(__GNUC__)) || (__GNUC__ > 3) || (__GNUC__ == 3 && __GNUC_MINOR__ > 3) - // This is the succinct way, works on modern compilers ensure_equals(instance_from_range(make_transform_range(deps.get_range(), extract_key)), keys); -#else // gcc 3.3 - StringDeps::range got_range(deps.get_range()); - StringDeps::iterator kni = got_range.begin(), knend = got_range.end(); - StringList::iterator ki = keys.begin(), kend = keys.end(); - for ( ; kni != knend && ki != kend; ++kni, ++ki) - { - ensure_equals(kni->first, *ki); - } - ensure("get_range() returns proper length", kni == knend && ki == kend); -#endif // gcc 3.3 // blow off get_node_range() because they're all LLDependenciesEmpty instances } diff --git a/indra/llcommon/tests/llerror_test.cpp b/indra/llcommon/tests/llerror_test.cpp index e39c402972..653f64f1b6 100644 --- a/indra/llcommon/tests/llerror_test.cpp +++ b/indra/llcommon/tests/llerror_test.cpp @@ -59,7 +59,7 @@ static const char* FieldName[] = namespace { -#ifdef __clang__ +#if defined(LL_CLANG) # pragma clang diagnostic ignored "-Wunused-function" #elif defined(LL_GNUC) # pragma GCC diagnostic ignored "-Wunused-function" diff --git a/indra/llcommon/tests/llstring_test.cpp b/indra/llcommon/tests/llstring_test.cpp index b18712b8e9..f4366b2059 100644 --- a/indra/llcommon/tests/llstring_test.cpp +++ b/indra/llcommon/tests/llstring_test.cpp @@ -377,7 +377,7 @@ namespace tut { F32 value; std::string str_val("2147483647"); //0x7FFFFFFF - ensure("1: convertToF32 failed", LLStringUtil::convertToF32(str_val, value) && value == 2147483647); + ensure("1: convertToF32 failed", LLStringUtil::convertToF32(str_val, value) && value == 2147483647.f); str_val = "0"; ensure("2: convertToF32 failed", LLStringUtil::convertToF32(str_val, value) && value == 0); @@ -399,7 +399,7 @@ namespace tut { F64 value; std::string str_val("9223372036854775807"); //0x7FFFFFFFFFFFFFFF - ensure("1: convertToF64 failed", LLStringUtil::convertToF64(str_val, value) && value == 9223372036854775807LL); + ensure("1: convertToF64 failed", LLStringUtil::convertToF64(str_val, value) && value == 9223372036854775807.0); str_val = "0"; ensure("2: convertToF64 failed", LLStringUtil::convertToF64(str_val, value) && value == 0.0F); diff --git a/indra/llcorehttp/llhttpconstants.h b/indra/llcorehttp/llhttpconstants.h index 71c1dfa173..d05d0f1af1 100755 --- a/indra/llcorehttp/llhttpconstants.h +++ b/indra/llcorehttp/llhttpconstants.h @@ -100,6 +100,8 @@ extern const std::string HTTP_VERB_POST; extern const std::string HTTP_VERB_DELETE; extern const std::string HTTP_VERB_MOVE; extern const std::string HTTP_VERB_OPTIONS; +extern const std::string HTTP_VERB_PATCH; +extern const std::string HTTP_VERB_COPY; enum EHTTPMethod { diff --git a/indra/llkdu/include_kdu_xxxx.h b/indra/llkdu/include_kdu_xxxx.h index 3db417a6cb..acd23fa6c0 100644 --- a/indra/llkdu/include_kdu_xxxx.h +++ b/indra/llkdu/include_kdu_xxxx.h @@ -16,7 +16,7 @@ // #include "include_kdu_xxxx.h" // // kdu_xxxx #undef'ed by include_kdu_xxxx.h -#if __clang__ +#if LL_CLANG // don't *really* want to rebuild KDU so turn off specific warnings for this header #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wself-assign-field" diff --git a/indra/llkdu/tests/llimagej2ckdu_test.cpp b/indra/llkdu/tests/llimagej2ckdu_test.cpp index bc52a15c4a..09425fc001 100644 --- a/indra/llkdu/tests/llimagej2ckdu_test.cpp +++ b/indra/llkdu/tests/llimagej2ckdu_test.cpp @@ -29,7 +29,7 @@ // Class to test #include "llimagej2ckdu.h" -#if __clang__ +#if LL_CLANG // For this source, it's true that private fields in llkdumem.h are unused. #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-private-field" diff --git a/indra/llmessage/llbufferstream.cpp b/indra/llmessage/llbufferstream.cpp index 2c745f6fe4..cb5a4c1824 100644 --- a/indra/llmessage/llbufferstream.cpp +++ b/indra/llmessage/llbufferstream.cpp @@ -234,17 +234,10 @@ int LLBufferStreamBuf::sync() } // virtual -#if( LL_WINDOWS || __GNUC__ > 2) LLBufferStreamBuf::pos_type LLBufferStreamBuf::seekoff( LLBufferStreamBuf::off_type off, std::ios::seekdir way, std::ios::openmode which) -#else -streampos LLBufferStreamBuf::seekoff( - streamoff off, - std::ios::seekdir way, - std::ios::openmode which) -#endif { if(!mBuffer || ((way == std::ios::beg) && (off < 0)) @@ -319,12 +312,8 @@ streampos LLBufferStreamBuf::seekoff( } } -#if( LL_WINDOWS || __GNUC__ > 2 ) S32 rv = (S32)(intptr_t)address; return (pos_type)rv; -#else - return (streampos)address; -#endif } diff --git a/indra/llmessage/llbufferstream.h b/indra/llmessage/llbufferstream.h index ac1aa49e81..e0a7d8c642 100644 --- a/indra/llmessage/llbufferstream.h +++ b/indra/llmessage/llbufferstream.h @@ -48,10 +48,8 @@ public: virtual ~LLBufferStreamBuf(); protected: -#if( LL_WINDOWS || __GNUC__ > 2 ) typedef std::streambuf::pos_type pos_type; typedef std::streambuf::off_type off_type; -#endif /* @name streambuf vrtual implementations */ @@ -87,17 +85,10 @@ protected: * or both masked together. * @return Returns the new position or an invalid position on failure. */ -#if( LL_WINDOWS || __GNUC__ > 2) virtual pos_type seekoff( off_type off, std::ios::seekdir way, std::ios::openmode which); -#else - virtual streampos seekoff( - streamoff off, - std::ios::seekdir way, - std::ios::openmode which); -#endif /* * @brief Get s sequence of characters from the input diff --git a/indra/llmessage/llpartdata.cpp b/indra/llmessage/llpartdata.cpp index d4cf95c1e3..b626637862 100644 --- a/indra/llmessage/llpartdata.cpp +++ b/indra/llmessage/llpartdata.cpp @@ -331,7 +331,7 @@ bool LLPartSysData::isNullPS(const S32 block_num) S32 size; // Check size of block - size = gMessageSystem->getSize("ObjectData", block_num, "PSBlock"); + size = gMessageSystem->getSizeFast(_PREHASH_ObjectData, block_num, _PREHASH_PSBlock); if (!size) { @@ -344,7 +344,7 @@ bool LLPartSysData::isNullPS(const S32 block_num) return true; } - gMessageSystem->getBinaryData("ObjectData", "PSBlock", ps_data_block, size, block_num, PS_MAX_DATA_BLOCK_SIZE); + gMessageSystem->getBinaryDataFast(_PREHASH_ObjectData, _PREHASH_PSBlock, ps_data_block, size, block_num, PS_MAX_DATA_BLOCK_SIZE); LLDataPackerBinaryBuffer dp(ps_data_block, size); if (size > PS_LEGACY_DATA_BLOCK_SIZE) @@ -373,7 +373,7 @@ bool LLPartSysData::unpackBlock(const S32 block_num) U8 ps_data_block[PS_MAX_DATA_BLOCK_SIZE]; // Check size of block - S32 size = gMessageSystem->getSize("ObjectData", block_num, "PSBlock"); + S32 size = gMessageSystem->getSizeFast(_PREHASH_ObjectData, block_num, _PREHASH_PSBlock); if (size > PS_MAX_DATA_BLOCK_SIZE) { @@ -382,7 +382,7 @@ bool LLPartSysData::unpackBlock(const S32 block_num) } // Get from message - gMessageSystem->getBinaryData("ObjectData", "PSBlock", ps_data_block, size, block_num, PS_MAX_DATA_BLOCK_SIZE); + gMessageSystem->getBinaryDataFast(_PREHASH_ObjectData, _PREHASH_PSBlock, ps_data_block, size, block_num, PS_MAX_DATA_BLOCK_SIZE); LLDataPackerBinaryBuffer dp(ps_data_block, size); diff --git a/indra/newview/llappviewerlinux.h b/indra/newview/llappviewerlinux.h index 8154d38921..594bb64243 100644 --- a/indra/newview/llappviewerlinux.h +++ b/indra/newview/llappviewerlinux.h @@ -43,7 +43,7 @@ public: // Main application logic // bool init() override; // Override to do application initialization - std::string generateSerialNumber(); + std::string generateSerialNumber() override; bool setupSLURLHandler(); protected: diff --git a/indra/newview/llface.cpp b/indra/newview/llface.cpp index 6f825c6a81..37802fa175 100644 --- a/indra/newview/llface.cpp +++ b/indra/newview/llface.cpp @@ -58,12 +58,6 @@ #include "llmeshrepository.h" #include "llskinningutil.h" -#if LL_LINUX -// Work-around spurious used before init warning on Vector4a -// -#pragma GCC diagnostic ignored "-Wuninitialized" -#endif - #define LL_MAX_INDICES_COUNT 1000000 static LLStaticHashedString sTextureIndexIn("texture_index_in"); diff --git a/indra/newview/llviewermessage.cpp b/indra/newview/llviewermessage.cpp index e9f6d7175e..efd5a4b8ad 100644 --- a/indra/newview/llviewermessage.cpp +++ b/indra/newview/llviewermessage.cpp @@ -3730,9 +3730,7 @@ void process_sound_trigger(LLMessageSystem *msg, void **) { if (!gAudiop) { -#if !LL_LINUX LL_WARNS("AudioEngine") << "LLAudioEngine instance doesn't exist!" << LL_ENDL; -#endif return; } @@ -3804,9 +3802,7 @@ void process_preload_sound(LLMessageSystem *msg, void **user_data) { if (!gAudiop) { -#if !LL_LINUX LL_WARNS("AudioEngine") << "LLAudioEngine instance doesn't exist!" << LL_ENDL; -#endif return; } diff --git a/indra/newview/llviewerwindow.cpp b/indra/newview/llviewerwindow.cpp index 0d40aaea6a..d6ed7acd33 100644 --- a/indra/newview/llviewerwindow.cpp +++ b/indra/newview/llviewerwindow.cpp @@ -780,14 +780,14 @@ public: addText(xpos, ypos, "Projection Matrix"); ypos += y_inc; -#if LL_DARWIN +#if LL_CLANG // For sprintf deprecation #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" #endif // View last column is always <0,0,0,1> MATRIX_ROW_F32_TO_STR(gGLModelView, 12,camera_lines[3]); addText(xpos, ypos, std::string(camera_lines[3])); ypos += y_inc; -#if LL_DARWIN +#if LL_CLANG #pragma clang diagnostic pop #endif MATRIX_ROW_N32_TO_STR(gGLModelView, 8,camera_lines[2]); addText(xpos, ypos, std::string(camera_lines[2])); ypos += y_inc; @@ -1932,13 +1932,8 @@ LLViewerWindow::LLViewerWindow(const Params& p) ms_sleep(5000) ; //wait for 5 seconds. LLSplashScreen::update(LLTrans::getString("ShuttingDown")); -#if LL_LINUX - LL_WARNS() << "Unable to create window, be sure screen is set at 32-bit color and your graphics driver is configured correctly. See README-linux.txt for further information." - << LL_ENDL; -#else LL_WARNS("Window") << "Unable to create window, be sure screen is set at 32-bit color in Control Panels->Display->Settings" << LL_ENDL; -#endif LLAppViewer::instance()->fastQuit(1); } else if (!LLViewerShaderMgr::sInitialized) diff --git a/indra/newview/llvoicewebrtc.cpp b/indra/newview/llvoicewebrtc.cpp index 32f2139679..3a1aa5f995 100644 --- a/indra/newview/llvoicewebrtc.cpp +++ b/indra/newview/llvoicewebrtc.cpp @@ -2325,7 +2325,7 @@ LLVoiceWebRTCConnection::LLVoiceWebRTCConnection(const LLUUID ®ionID, const s // retries wait a short period...randomize it so // all clients don't try to reconnect at once. - mRetryWaitSecs = (F32)((F32) rand() / (RAND_MAX)) + 0.5f; + mRetryWaitSecs = (F32)((F32) rand() / F32(RAND_MAX)) + 0.5f; mWebRTCPeerConnectionInterface = llwebrtc::newPeerConnection(); mWebRTCPeerConnectionInterface->setSignalingObserver(this); @@ -2931,7 +2931,7 @@ bool LLVoiceWebRTCConnection::connectionStateMachine() case VOICE_STATE_SESSION_UP: { mRetryWaitPeriod = 0; - mRetryWaitSecs = (F32)((F32)rand() / (RAND_MAX)) + 0.5f; + mRetryWaitSecs = (F32)((F32)rand() / F32(RAND_MAX)) + 0.5f; // we'll stay here as long as the session remains up. if (mShutDown) @@ -2969,7 +2969,7 @@ bool LLVoiceWebRTCConnection::connectionStateMachine() { // back off the retry period, and do it by a small random // bit so all clients don't reconnect at once. - mRetryWaitSecs += (F32)((F32) rand() / (RAND_MAX)) + 0.5f; + mRetryWaitSecs += (F32)((F32) rand() / F32(RAND_MAX)) + 0.5f; mRetryWaitPeriod = 0; } } diff --git a/indra/newview/pipeline.cpp b/indra/newview/pipeline.cpp index be7c57015c..262da507be 100644 --- a/indra/newview/pipeline.cpp +++ b/indra/newview/pipeline.cpp @@ -122,16 +122,27 @@ #include "SMAAAreaTex.h" #include "SMAASearchTex.h" #include "llerror.h" -#ifndef LL_WINDOWS -#define A_GCC 1 + +#if LL_CLANG +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunused-function" +#pragma clang diagnostic ignored "-Wunused-variable" +#elif LL_GNUC +#pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-function" #pragma GCC diagnostic ignored "-Wunused-variable" -#if LL_LINUX #pragma GCC diagnostic ignored "-Wrestrict" #endif +#ifndef LL_WINDOWS +#define A_GCC 1 #endif #define A_CPU 1 #include "app_settings/shaders/class1/deferred/CASF.glsl" // This is also C++ +#if LL_CLANG +#pragma clang diagnostic pop +#elif LL_GNUC +#pragma GCC diagnostic pop +#endif extern bool gSnapshot; bool gShiftFrame = false; diff --git a/indra/test/lltut.h b/indra/test/lltut.h index 581a08654d..fdc1cd7dfe 100644 --- a/indra/test/lltut.h +++ b/indra/test/lltut.h @@ -75,12 +75,12 @@ namespace tut // overloads declared above. // turn off warnings about unused functions from clang for tut package -#if __clang__ +#if LL_CLANG #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-function" #endif #include -#if __clang__ +#if LL_CLANG #pragma clang diagnostic pop #endif -- cgit v1.3 From 3b88739957d8b0d5072646e571d27b743e68fe2e Mon Sep 17 00:00:00 2001 From: Rye Date: Tue, 9 Dec 2025 19:27:14 -0500 Subject: Rework legacy lltest executable into individual integration tests and restore some disabled tests Removes dead llprimlinkinfo and related test Remove dead llassetuploadqueue llhttpclient lltimestampcache lltranscode tests Remove dead mock_http_client Remove duplicate hex_dump.h Fix crash in LLDataPacker test --- indra/llcommon/CMakeLists.txt | 14 + indra/llcommon/llsdjson.cpp | 1 - indra/llcommon/tests/llapp_test.cpp | 162 +++ indra/llcommon/tests/lldoubledispatch_test.cpp | 240 ++++ indra/llcommon/tests/llevents_test.cpp | 506 +++++++++ indra/llcommon/tests/llhttpdate_test.cpp | 162 +++ indra/llcommon/tests/llsd_test.cpp | 830 ++++++++++++++ indra/llcommon/tests/llsdserialize_test.cpp | 6 +- indra/llcommon/tests/llsdutil_test.cpp | 434 +++++++ indra/llcommon/tests/llstreamtools_test.cpp | 883 +++++++++++++++ indra/llinventory/CMakeLists.txt | 3 + indra/llinventory/tests/llpermissions_test.cpp | 491 ++++++++ indra/llinventory/tests/llsaleinfo_test.cpp | 194 ++++ indra/llinventory/tests/lluserrelations_test.cpp | 156 +++ indra/llmessage/CMakeLists.txt | 15 +- indra/llmessage/tests/io_test.cpp | 1181 ++++++++++++++++++++ indra/llmessage/tests/llbuffer_test.cpp | 271 +++++ indra/llmessage/tests/llcurl_stub.cpp | 99 -- indra/llmessage/tests/lldatapacker_test.cpp | 572 ++++++++++ indra/llmessage/tests/llhttpclient_test.cpp | 311 ------ indra/llmessage/tests/llhttpnode_test.cpp | 428 +++++++ indra/llmessage/tests/lliohttpserver_test.cpp | 350 ++++++ indra/llmessage/tests/llmessageconfig_test.cpp | 236 ++++ .../tests/llmessagetemplateparser_test.cpp | 368 ++++++ indra/llmessage/tests/llpipeutil.cpp | 183 +++ indra/llmessage/tests/llpipeutil.h | 163 +++ indra/llmessage/tests/llsdmessagebuilder_test.cpp | 837 ++++++++++++++ indra/llmessage/tests/llsdmessagereader_test.cpp | 324 ++++++ indra/llmessage/tests/llservicebuilder_test.cpp | 173 +++ .../tests/lltemplatemessagebuilder_test.cpp | 971 ++++++++++++++++ indra/llmessage/tests/llxorcipher_test.cpp | 131 +++ indra/llmessage/tests/message_test.cpp | 147 +++ indra/llprimitive/llprimlinkinfo.h | 393 ------- indra/test/CMakeLists.txt | 120 +- indra/test/hexdump.h | 97 -- indra/test/io.cpp | 1181 -------------------- indra/test/llapp_tut.cpp | 162 --- indra/test/llassetuploadqueue_tut.cpp | 195 ---- indra/test/llbuffer_tut.cpp | 271 ----- indra/test/lldatapacker_tut.cpp | 570 ---------- indra/test/lldoubledispatch_tut.cpp | 240 ---- indra/test/llevents_tut.cpp | 506 --------- indra/test/llhttpdate_tut.cpp | 162 --- indra/test/llhttpnode_tut.cpp | 428 ------- indra/test/lliohttpserver_tut.cpp | 350 ------ indra/test/llmessageconfig_tut.cpp | 236 ---- indra/test/llmessagetemplateparser_tut.cpp | 368 ------ indra/test/llpermissions_tut.cpp | 491 -------- indra/test/llpipeutil.cpp | 183 --- indra/test/llpipeutil.h | 163 --- indra/test/llsaleinfo_tut.cpp | 194 ---- indra/test/llsd_new_tut.cpp | 830 -------------- indra/test/llsdmessagebuilder_tut.cpp | 837 -------------- indra/test/llsdmessagereader_tut.cpp | 324 ------ indra/test/llsdutil_tut.cpp | 434 ------- indra/test/llservicebuilder_tut.cpp | 173 --- indra/test/llstreamtools_tut.cpp | 883 --------------- indra/test/lltemplatemessagebuilder_tut.cpp | 971 ---------------- indra/test/lltimestampcache_tut.cpp | 124 -- indra/test/lltranscode_tut.cpp | 86 -- indra/test/lluserrelations_tut.cpp | 156 --- indra/test/llxorcipher_tut.cpp | 131 --- indra/test/message_tut.cpp | 147 --- indra/test/mock_http_client.cpp | 82 -- indra/test/mock_http_client.h | 190 ---- indra/test/prim_linkability_tut.cpp | 495 -------- 66 files changed, 10440 insertions(+), 12575 deletions(-) create mode 100644 indra/llcommon/tests/llapp_test.cpp create mode 100644 indra/llcommon/tests/lldoubledispatch_test.cpp create mode 100644 indra/llcommon/tests/llevents_test.cpp create mode 100644 indra/llcommon/tests/llhttpdate_test.cpp create mode 100644 indra/llcommon/tests/llsd_test.cpp create mode 100644 indra/llcommon/tests/llsdutil_test.cpp create mode 100644 indra/llcommon/tests/llstreamtools_test.cpp create mode 100644 indra/llinventory/tests/llpermissions_test.cpp create mode 100644 indra/llinventory/tests/llsaleinfo_test.cpp create mode 100644 indra/llinventory/tests/lluserrelations_test.cpp create mode 100644 indra/llmessage/tests/io_test.cpp create mode 100644 indra/llmessage/tests/llbuffer_test.cpp delete mode 100644 indra/llmessage/tests/llcurl_stub.cpp create mode 100644 indra/llmessage/tests/lldatapacker_test.cpp delete mode 100644 indra/llmessage/tests/llhttpclient_test.cpp create mode 100644 indra/llmessage/tests/llhttpnode_test.cpp create mode 100644 indra/llmessage/tests/lliohttpserver_test.cpp create mode 100644 indra/llmessage/tests/llmessageconfig_test.cpp create mode 100644 indra/llmessage/tests/llmessagetemplateparser_test.cpp create mode 100644 indra/llmessage/tests/llpipeutil.cpp create mode 100644 indra/llmessage/tests/llpipeutil.h create mode 100644 indra/llmessage/tests/llsdmessagebuilder_test.cpp create mode 100644 indra/llmessage/tests/llsdmessagereader_test.cpp create mode 100644 indra/llmessage/tests/llservicebuilder_test.cpp create mode 100644 indra/llmessage/tests/lltemplatemessagebuilder_test.cpp create mode 100644 indra/llmessage/tests/llxorcipher_test.cpp create mode 100644 indra/llmessage/tests/message_test.cpp delete mode 100644 indra/llprimitive/llprimlinkinfo.h delete mode 100644 indra/test/hexdump.h delete mode 100644 indra/test/io.cpp delete mode 100644 indra/test/llapp_tut.cpp delete mode 100644 indra/test/llassetuploadqueue_tut.cpp delete mode 100644 indra/test/llbuffer_tut.cpp delete mode 100644 indra/test/lldatapacker_tut.cpp delete mode 100644 indra/test/lldoubledispatch_tut.cpp delete mode 100644 indra/test/llevents_tut.cpp delete mode 100644 indra/test/llhttpdate_tut.cpp delete mode 100644 indra/test/llhttpnode_tut.cpp delete mode 100644 indra/test/lliohttpserver_tut.cpp delete mode 100644 indra/test/llmessageconfig_tut.cpp delete mode 100644 indra/test/llmessagetemplateparser_tut.cpp delete mode 100644 indra/test/llpermissions_tut.cpp delete mode 100644 indra/test/llpipeutil.cpp delete mode 100644 indra/test/llpipeutil.h delete mode 100644 indra/test/llsaleinfo_tut.cpp delete mode 100644 indra/test/llsd_new_tut.cpp delete mode 100644 indra/test/llsdmessagebuilder_tut.cpp delete mode 100644 indra/test/llsdmessagereader_tut.cpp delete mode 100644 indra/test/llsdutil_tut.cpp delete mode 100644 indra/test/llservicebuilder_tut.cpp delete mode 100644 indra/test/llstreamtools_tut.cpp delete mode 100644 indra/test/lltemplatemessagebuilder_tut.cpp delete mode 100644 indra/test/lltimestampcache_tut.cpp delete mode 100644 indra/test/lltranscode_tut.cpp delete mode 100644 indra/test/lluserrelations_tut.cpp delete mode 100644 indra/test/llxorcipher_tut.cpp delete mode 100644 indra/test/message_tut.cpp delete mode 100644 indra/test/mock_http_client.cpp delete mode 100644 indra/test/mock_http_client.h delete mode 100644 indra/test/prim_linkability_tut.cpp (limited to 'indra/llmessage') diff --git a/indra/llcommon/CMakeLists.txt b/indra/llcommon/CMakeLists.txt index c3b892b204..7311c6faf6 100644 --- a/indra/llcommon/CMakeLists.txt +++ b/indra/llcommon/CMakeLists.txt @@ -317,16 +317,20 @@ if (LL_TESTS) LL_ADD_INTEGRATION_TEST(classic_callback "" "${test_libs}") LL_ADD_INTEGRATION_TEST(commonmisc "" "${test_libs}") LL_ADD_INTEGRATION_TEST(lazyeventapi "" "${test_libs}") + LL_ADD_INTEGRATION_TEST(llapp "" "${test_libs}") LL_ADD_INTEGRATION_TEST(llbase64 "" "${test_libs}") LL_ADD_INTEGRATION_TEST(llcond "" "${test_libs}") LL_ADD_INTEGRATION_TEST(lldate "" "${test_libs}") LL_ADD_INTEGRATION_TEST(lldeadmantimer "" "${test_libs}") LL_ADD_INTEGRATION_TEST(lldependencies "" "${test_libs}") + LL_ADD_INTEGRATION_TEST(lldoubledispatch "" "${test_libs}") LL_ADD_INTEGRATION_TEST(llerror "" "${test_libs}") LL_ADD_INTEGRATION_TEST(lleventcoro "" "${test_libs}") LL_ADD_INTEGRATION_TEST(lleventdispatcher "" "${test_libs}") LL_ADD_INTEGRATION_TEST(lleventfilter "" "${test_libs}") + LL_ADD_INTEGRATION_TEST(llevents "" "${test_libs}") LL_ADD_INTEGRATION_TEST(llframetimer "" "${test_libs}") + LL_ADD_INTEGRATION_TEST(llhttpdate "" "${test_libs}") LL_ADD_INTEGRATION_TEST(llheteromap "" "${test_libs}") LL_ADD_INTEGRATION_TEST(llinstancetracker "" "${test_libs}") LL_ADD_INTEGRATION_TEST(llleap "" "${test_libs}") @@ -336,9 +340,12 @@ if (LL_TESTS) LL_ADD_INTEGRATION_TEST(llprocessor "" "${test_libs}") LL_ADD_INTEGRATION_TEST(llprocinfo "" "${test_libs}") LL_ADD_INTEGRATION_TEST(llrand "" "${test_libs}") + LL_ADD_INTEGRATION_TEST(llsd "" "${test_libs}") LL_ADD_INTEGRATION_TEST(llsdserialize "" "${test_libs}") + LL_ADD_INTEGRATION_TEST(llsdutil "" "llcommon;llmath") LL_ADD_INTEGRATION_TEST(llsingleton "" "${test_libs}") LL_ADD_INTEGRATION_TEST(llstreamqueue "" "${test_libs}") + LL_ADD_INTEGRATION_TEST(llstreamtools "" "${test_libs}") LL_ADD_INTEGRATION_TEST(llstring "" "${test_libs}") LL_ADD_INTEGRATION_TEST(lltrace "" "${test_libs}") LL_ADD_INTEGRATION_TEST(lltreeiterators "" "${test_libs}") @@ -354,4 +361,11 @@ if (LL_TESTS) ## throwing and catching exceptions. ##LL_ADD_INTEGRATION_TEST(llexception "" "${test_libs}") + # Skip precompiled header for tests that need special handling + set_source_files_properties( + tests/llsd_test.cpp + PROPERTIES + SKIP_PRECOMPILE_HEADERS TRUE + ) + endif (LL_TESTS) diff --git a/indra/llcommon/llsdjson.cpp b/indra/llcommon/llsdjson.cpp index 542a3c26e3..9abca48670 100644 --- a/indra/llcommon/llsdjson.cpp +++ b/indra/llcommon/llsdjson.cpp @@ -26,7 +26,6 @@ // Must turn on conditional declarations in header file so definitions end up // with proper linkage. -#define LLSD_DEBUG_INFO #include "linden_common.h" #include "llsdjson.h" diff --git a/indra/llcommon/tests/llapp_test.cpp b/indra/llcommon/tests/llapp_test.cpp new file mode 100644 index 0000000000..114af6edbf --- /dev/null +++ b/indra/llcommon/tests/llapp_test.cpp @@ -0,0 +1,162 @@ +/** + * @file llapp_tut.cpp + * @author Phoenix + * @date 2006-09-12 + * + * $LicenseInfo:firstyear=2006&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2006-2011, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +#include + +#include "linden_common.h" +#include "llapp.h" +#include "lltut.h" + + +namespace tut +{ + struct application + { + class LLTestApp : public LLApp + { + public: + virtual bool init() { return true; } + virtual bool cleanup() { return true; } + virtual bool frame() { return true; } + }; + LLTestApp* mApp; + application() + { + mApp = new LLTestApp; + } + ~application() + { + delete mApp; + } + }; + + typedef test_group application_t; + typedef application_t::object application_object_t; + tut::application_t tut_application("application"); + + template<> template<> + void application_object_t::test<1>() + { + LLSD defaults; + defaults["template"] = "../../../scripts/messages/message_template.msg"; + defaults["configdir"] = "."; + defaults["datadir"] = "data"; + mApp->setOptionData(LLApp::PRIORITY_DEFAULT, defaults); + + LLSD datadir_sd = mApp->getOption("datadir"); + ensure_equals("data type", datadir_sd.type(), LLSD::TypeString); + ensure_equals( + "data value", datadir_sd.asString(), std::string("data")); + } + + template<> template<> + void application_object_t::test<2>() + { + const int ARGC = 13; + const char* ARGV[ARGC] = + { + "", // argv[0] is usually the application name + "-crashcount", + "2", + "-space", + "spaceserver.grid.lindenlab.com", + "-db_host", + "localhost", + "--allowlslhttprequests", + "-asset-uri", + "http://test.lindenlab.com/assets", + "-data", + "127.0.0.1", + "--smtp" + }; + bool ok = mApp->parseCommandOptions(ARGC, const_cast(ARGV)); + ensure("command line parsed", ok); + ensure_equals( + "crashcount", mApp->getOption("crashcount").asInteger(), 2); + ensure_equals( + "space", + mApp->getOption("space").asString(), + std::string("spaceserver.grid.lindenlab.com")); + ensure_equals( + "db_host", + mApp->getOption("db_host").asString(), + std::string("localhost")); + ensure("allowlshlttprequests", mApp->getOption("smtp")); + ensure_equals( + "asset-uri", + mApp->getOption("asset-uri").asString(), + std::string("http://test.lindenlab.com/assets")); + ensure_equals( + "data", + mApp->getOption("data").asString(), + std::string("127.0.0.1")); + ensure("smtp", mApp->getOption("smtp")); + } + + template<> template<> + void application_object_t::test<3>() + { + const int ARGC = 4; + const char* ARGV[ARGC] = + { + "", // argv[0] is usually the application name + "crashcount", + "2", + "--space" + }; + bool ok = mApp->parseCommandOptions(ARGC, const_cast(ARGV)); + ensure("command line parse failure", !ok); + } + + template<> template<> + void application_object_t::test<4>() + { + const int ARGC = 4; + const char* ARGV[ARGC] = + { + "", // argv[0] is usually the application name + "--crashcount", + "2", + "space" + }; + bool ok = mApp->parseCommandOptions(ARGC, const_cast(ARGV)); + ensure("command line parse failure", !ok); + } + + + template<> template<> + void application_object_t::test<5>() + { + LLSD options; + options["boolean-test"] = true; + mApp->setOptionData(LLApp::PRIORITY_GENERAL_CONFIGURATION, options); + ensure("bool set", mApp->getOption("boolean-test").asBoolean()); + options["boolean-test"] = false; + mApp->setOptionData(LLApp::PRIORITY_RUNTIME_OVERRIDE, options); + ensure("bool unset", !mApp->getOption("boolean-test").asBoolean()); + } +} diff --git a/indra/llcommon/tests/lldoubledispatch_test.cpp b/indra/llcommon/tests/lldoubledispatch_test.cpp new file mode 100644 index 0000000000..79c4edc058 --- /dev/null +++ b/indra/llcommon/tests/lldoubledispatch_test.cpp @@ -0,0 +1,240 @@ +/** + * @file lldoubledispatch_tut.cpp + * @author Nat Goodspeed + * @date 2008-11-13 + * @brief Test for lldoubledispatch.h + * + * This program tests the DoubleDispatch class, using a variation on the example + * from Scott Meyers' "More Effective C++", Item 31. + * + * $LicenseInfo:firstyear=2008&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2010, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +// Precompiled header +#include "linden_common.h" +// associated header +#include "lldoubledispatch.h" +// STL headers +// std headers +#include +#include +#include +#include +// external library headers +// other Linden headers +#include "lltut.h" + + +/*---------------------------- Class hierarchy -----------------------------*/ +// All objects are GameObjects. +class GameObject +{ +public: + GameObject(const std::string& name): mName(name) {} + virtual ~GameObject() {} + virtual std::string stringize() { return std::string(typeid(*this).name()) + " " + mName; } + +protected: + std::string mName; +}; + +// SpaceStation, Asteroid and SpaceShip are peer GameObjects. +struct SpaceStation: public GameObject +{ + SpaceStation(const std::string& name): GameObject(name) {} + // Only a dummy SpaceStation is constructed without a name + SpaceStation(): GameObject("dummy") {} +}; + +struct Asteroid: public GameObject +{ + Asteroid(const std::string& name): GameObject(name) {} + Asteroid(): GameObject("dummy") {} +}; + +struct SpaceShip: public GameObject +{ + SpaceShip(const std::string& name): GameObject(name) {} + SpaceShip(): GameObject("dummy") {} +}; + +// SpaceShip is specialized further into CommercialShip and MilitaryShip. +struct CommercialShip: public SpaceShip +{ + CommercialShip(const std::string& name): SpaceShip(name) {} + CommercialShip(): SpaceShip("dummy") {} +}; + +struct MilitaryShip: public SpaceShip +{ + MilitaryShip(const std::string& name): SpaceShip(name) {} + MilitaryShip(): SpaceShip("dummy") {} +}; + +/*-------------------------- Collision functions ---------------------------*/ +// This mechanism permits us to overcome a limitation of Meyers' approach: we +// can declare the parameter types exactly as we want, rather than having to +// make them all GameObject& parameters. +std::string shipAsteroid(SpaceShip& ship, Asteroid& rock) +{ +// std::cout << rock.stringize() << " has pulverized " << ship.stringize() << std::endl; + return "shipAsteroid"; +} + +std::string militaryShipAsteroid(MilitaryShip& ship, Asteroid& rock) +{ +// std::cout << rock.stringize() << " has severely damaged " << ship.stringize() << std::endl; + return "militaryShipAsteroid"; +} + +std::string shipStation(SpaceShip& ship, SpaceStation& dock) +{ +// std::cout << ship.stringize() << " has docked at " << dock.stringize() << std::endl; + return "shipStation"; +} + +std::string asteroidStation(Asteroid& rock, SpaceStation& dock) +{ +// std::cout << rock.stringize() << " has damaged " << dock.stringize() << std::endl; + return "asteroidStation"; +} + +/*------------------------------- Test code --------------------------------*/ +namespace tut +{ + struct dispatch_data + { + dispatch_data(): + home(new SpaceStation("Terra Station")), + obstacle(new Asteroid("Ganymede")), + tug(new CommercialShip("Pilotfish")), + patrol(new MilitaryShip("Enterprise")) + {} + + // Instantiate and populate the DoubleDispatch object. + typedef LLDoubleDispatch DD; + DD dispatcher; + + // Instantiate a few GameObjects. Make sure we refer to them + // polymorphically, and don't let them leak. + std::unique_ptr home; + std::unique_ptr obstacle; + std::unique_ptr tug; + std::unique_ptr patrol; + + // prototype objects + Asteroid dummyAsteroid; + SpaceShip dummyShip; + MilitaryShip dummyMilitary; + CommercialShip dummyCommercial; + SpaceStation dummyStation; + }; + typedef test_group dispatch_group; + typedef dispatch_group::object dispatch_object; + tut::dispatch_group ddgr("double dispatch"); + + template<> template<> + void dispatch_object::test<1>() + { + // Describe param types using explicit DD::Type objects + // (order-sensitive add() variant) + dispatcher.add(DD::Type(), DD::Type(), shipAsteroid, true); + // naive adding, won't work + dispatcher.add(DD::Type(), DD::Type(), militaryShipAsteroid, true); + dispatcher.add(DD::Type(), DD::Type(), shipStation, true); + dispatcher.add(DD::Type(), DD::Type(), asteroidStation, true); + + // Try colliding them. + ensure_equals(dispatcher(*home, *tug), // reverse params, SpaceShip subclass + "shipStation"); + ensure_equals(dispatcher(*patrol, *home), // forward params, SpaceShip subclass + "shipStation"); + ensure_equals(dispatcher(*obstacle, *home), // forward params + "asteroidStation"); + ensure_equals(dispatcher(*home, *obstacle), // reverse params + "asteroidStation"); + ensure_equals(dispatcher(*tug, *obstacle), // forward params, SpaceShip subclass + "shipAsteroid"); + ensure_equals(dispatcher(*obstacle, *patrol), // reverse params, SpaceShip subclass + // won't use militaryShipAsteroid() because it was added + // in wrong order + "shipAsteroid"); + } + + template<> template<> + void dispatch_object::test<2>() + { + // Describe param types using explicit DD::Type objects + // (order-sensitive add() variant) + // adding in correct order + dispatcher.add(DD::Type(), DD::Type(), militaryShipAsteroid, true); + dispatcher.add(DD::Type(), DD::Type(), shipAsteroid, true); + dispatcher.add(DD::Type(), DD::Type(), shipStation, true); + dispatcher.add(DD::Type(), DD::Type(), asteroidStation, true); + + ensure_equals(dispatcher(*patrol, *obstacle), "militaryShipAsteroid"); + ensure_equals(dispatcher(*tug, *obstacle), "shipAsteroid"); + } + + template<> template<> + void dispatch_object::test<3>() + { + // Describe param types with actual prototype instances + // (order-insensitive add() variant) + dispatcher.add(dummyMilitary, dummyAsteroid, militaryShipAsteroid); + dispatcher.add(dummyShip, dummyAsteroid, shipAsteroid); + dispatcher.add(dummyShip, dummyStation, shipStation); + dispatcher.add(dummyAsteroid, dummyStation, asteroidStation); + + ensure_equals(dispatcher(*patrol, *obstacle), "militaryShipAsteroid"); + ensure_equals(dispatcher(*tug, *obstacle), "shipAsteroid"); + ensure_equals(dispatcher(*obstacle, *patrol), ""); + } + + template<> template<> + void dispatch_object::test<4>() + { + // Describe param types with actual prototype instances + // (order-insensitive add() variant) + dispatcher.add(dummyShip, dummyAsteroid, shipAsteroid); + // Even if we add the militaryShipAsteroid in the wrong order, it + // should still work. + dispatcher.add(dummyMilitary, dummyAsteroid, militaryShipAsteroid); + dispatcher.add(dummyShip, dummyStation, shipStation); + dispatcher.add(dummyAsteroid, dummyStation, asteroidStation); + + ensure_equals(dispatcher(*patrol, *obstacle), "militaryShipAsteroid"); + ensure_equals(dispatcher(*tug, *obstacle), "shipAsteroid"); + } + + template<> template<> + void dispatch_object::test<5>() + { + dispatcher.add(shipAsteroid); + dispatcher.add(militaryShipAsteroid); + dispatcher.add(shipStation); + dispatcher.add(asteroidStation); + + ensure_equals(dispatcher(*patrol, *obstacle), "militaryShipAsteroid"); + ensure_equals(dispatcher(*tug, *obstacle), "shipAsteroid"); + } +} // namespace tut diff --git a/indra/llcommon/tests/llevents_test.cpp b/indra/llcommon/tests/llevents_test.cpp new file mode 100644 index 0000000000..c5d5dcb9d4 --- /dev/null +++ b/indra/llcommon/tests/llevents_test.cpp @@ -0,0 +1,506 @@ +/** + * @file llevents_tut.cpp + * @author Nat Goodspeed + * @date 2008-09-12 + * @brief Test of llevents.h + * + * $LicenseInfo:firstyear=2008&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2010, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +#if LL_WINDOWS +#pragma warning (disable : 4675) // "resolved by ADL" -- just as I want! +#endif + +// Precompiled header +#include "linden_common.h" +// associated header +// UGLY HACK! We want to verify state internal to the classes without +// providing public accessors. +#define testable public +#include "llevents.h" +#undef testable +// STL headers +// std headers +#include +#include +// external library headers +#include +// other Linden headers +#include "tests/listener.h" // must PRECEDE lltut.h +#include "lltut.h" +#include "catch_and_store_what_in.h" +#include "stringize.h" + +template +T make(const T& value) +{ + return value; +} + +/***************************************************************************** + * tut test group + *****************************************************************************/ +namespace tut +{ +struct events_data +{ + events_data() : + pumps(LLEventPumps::instance()), + listener0("first"), + listener1("second") + { + } + LLEventPumps& pumps; + Listener listener0; + Listener listener1; + + void check_listener(const std::string& desc, const Listener& listener, LLSD::Integer got) + { + ensure_equals(STRINGIZE(listener << ' ' << desc), + listener.getLastEvent().asInteger(), got); + } +}; +typedef test_group events_group; +typedef events_group::object events_object; +tut::events_group evgr("events"); + +template<> template<> +void events_object::test<1>() +{ + set_test_name("basic operations"); + // Having to modify this to track the statically- + // constructed pumps in other TUT modules in this giant monolithic test + // executable isn't such a hot idea. + // ensure_equals("initial pump", pumps.mPumpMap.size(), 1); + size_t initial_pumps(pumps.mPumpMap.size()); + LLEventPump& per_frame(pumps.obtain("per-frame")); + ensure_equals("first explicit pump", pumps.mPumpMap.size(), initial_pumps + 1); + // Verify that per_frame was instantiated as an LLEventStream. + ensure("LLEventStream leaf class", dynamic_cast (&per_frame)); + ensure("enabled", per_frame.enabled()); + // Trivial test, but posting an event to an EventPump with no + // listeners should not blow up. The test is relevant because defining + // a boost::signal with a non-void return signature, using the default + // combiner, blows up if there are no listeners. This is because the + // default combiner is defined to return the value returned by the + // last listener, which is meaningless if there were no listeners. + per_frame.post(0); + LLBoundListener connection = listener0.listenTo(per_frame); + ensure("connected", connection.connected()); + ensure("not blocked", !connection.blocked()); + per_frame.post(1); + check_listener("received", listener0, 1); + { // block the connection + LLEventPump::Blocker block(connection); + ensure("blocked", connection.blocked()); + per_frame.post(2); + check_listener("not updated", listener0, 1); + } // unblock + ensure("unblocked", !connection.blocked()); + per_frame.post(3); + check_listener("unblocked", listener0, 3); + LLBoundListener sameConnection = per_frame.getListener(listener0.getName()); + ensure("still connected", sameConnection.connected()); + ensure("still not blocked", !sameConnection.blocked()); + { // block it again + LLEventPump::Blocker block(sameConnection); + ensure("re-blocked", sameConnection.blocked()); + per_frame.post(4); + check_listener("re-blocked", listener0, 3); + } // unblock + std::string threw = catch_what( + [&per_frame, this](){ + // NOTE: boost::bind() saves its arguments by VALUE! If you pass + // an object instance rather than a pointer, you'll end up binding + // to an internal copy of that instance! Use boost::ref() to + // capture a reference instead. + per_frame.listen(listener0.getName(), // note bug, dup name + boost::bind(&Listener::call, boost::ref(listener1), _1)); + }); + ensure_equals(threw, + std::string("DupListenerName: " + "Attempt to register duplicate listener name '") + + listener0.getName() + "' on " + typeid(per_frame).name() + + " '" + per_frame.getName() + "'"); + // do it right this time + listener1.listenTo(per_frame); + per_frame.post(5); + check_listener("got", listener0, 5); + check_listener("got", listener1, 5); + per_frame.enable(false); + per_frame.post(6); + check_listener("didn't get", listener0, 5); + check_listener("didn't get", listener1, 5); + per_frame.enable(); + per_frame.post(7); + check_listener("got", listener0, 7); + check_listener("got", listener1, 7); + per_frame.stopListening(listener0.getName()); + ensure("disconnected 0", ! connection.connected()); + ensure("disconnected 1", ! sameConnection.connected()); + per_frame.post(8); + check_listener("disconnected", listener0, 7); + check_listener("still connected", listener1, 8); + per_frame.stopListening(listener1.getName()); + per_frame.post(9); + check_listener("disconnected", listener1, 8); +} + +template<> template<> +void events_object::test<2>() +{ + set_test_name("callstop() returning true"); + LLEventPump& per_frame(pumps.obtain("per-frame")); + listener0.reset(0); + listener1.reset(0); + LLBoundListener bound0 = listener0.listenTo(per_frame, &Listener::callstop); + LLBoundListener bound1 = listener1.listenTo(per_frame, &Listener::call, + // after listener0 + make(LLEventPump::NameList{ listener0.getName() })); + ensure("enabled", per_frame.enabled()); + ensure("connected 0", bound0.connected()); + ensure("unblocked 0", !bound0.blocked()); + ensure("connected 1", bound1.connected()); + ensure("unblocked 1", !bound1.blocked()); + per_frame.post(1); + check_listener("got", listener0, 1); + // Because listener0.callstop() returns true, control never reaches listener1.call(). + check_listener("got", listener1, 0); +} + +bool chainEvents(Listener& someListener, const LLSD& event) +{ + // Make this call so we can watch for side effects for test purposes. + someListener.call(event); + // This function represents a recursive event chain -- or some other + // scenario in which an event handler raises additional events. + int value = event.asInteger(); + if (value) + { + LLEventPumps::instance().obtain("login").post(value - 1); + } + return false; +} + +template<> template<> +void events_object::test<3>() +{ + set_test_name("explicitly-instantiated LLEventStream"); + // Explicitly instantiate an LLEventStream, and verify that it + // self-registers with LLEventPumps + size_t registered = pumps.mPumpMap.size(); + size_t owned = pumps.mOurPumps.size(); + LLEventPump* localInstance; + { + LLEventStream myEventStream("stream"); + localInstance = &myEventStream; + LLEventPump& stream(pumps.obtain("stream")); + ensure("found named LLEventStream instance", &stream == localInstance); + ensure_equals("registered new instance", pumps.mPumpMap.size(), registered + 1); + ensure_equals("explicit instance not owned", pumps.mOurPumps.size(), owned); + } // destroy myEventStream -- should unregister + ensure_equals("destroyed instance unregistered", pumps.mPumpMap.size(), registered); + ensure_equals("destroyed instance not owned", pumps.mOurPumps.size(), owned); + LLEventPump& stream(pumps.obtain("stream")); + ensure("new LLEventStream instance", &stream != localInstance); + ensure_equals("obtain()ed instance registered", pumps.mPumpMap.size(), registered + 1); + ensure_equals("obtain()ed instance owned", pumps.mOurPumps.size(), owned + 1); +} + +template<> template<> +void events_object::test<4>() +{ + set_test_name("stopListening()"); + LLEventPump& login(pumps.obtain("login")); + listener0.listenTo(login); + login.stopListening(listener0.getName()); + // should not throw because stopListening() should have removed name + listener0.listenTo(login, &Listener::callstop); + LLBoundListener wrong = login.getListener("bogus"); + ensure("bogus connection disconnected", !wrong.connected()); + ensure("bogus connection blocked", wrong.blocked()); +} + +template<> template<> +void events_object::test<5>() +{ + set_test_name("chaining LLEventPump instances"); + LLEventPump& upstream(pumps.obtain("upstream")); + // One potentially-useful construct is to chain LLEventPumps together. + // Among other things, this allows you to turn subsets of listeners on + // and off in groups. + LLEventPump& filter0(pumps.obtain("filter0")); + LLEventPump& filter1(pumps.obtain("filter1")); + upstream.listen(filter0.getName(), boost::bind(&LLEventPump::post, boost::ref(filter0), _1)); + upstream.listen(filter1.getName(), boost::bind(&LLEventPump::post, boost::ref(filter1), _1)); + listener0.listenTo(filter0); + listener1.listenTo(filter1); + listener0.reset(0); + listener1.reset(0); + upstream.post(1); + check_listener("got unfiltered", listener0, 1); + check_listener("got unfiltered", listener1, 1); + filter0.enable(false); + upstream.post(2); + check_listener("didn't get filtered", listener0, 1); + check_listener("got filtered", listener1, 2); +} + +template<> template<> +void events_object::test<6>() +{ + set_test_name("listener dependency order"); + typedef LLEventPump::NameList NameList; + LLEventPump& button(pumps.obtain("button")); + Collect collector; + button.listen("Mary", + boost::bind(&Collect::add, boost::ref(collector), "Mary", _1), + // state that "Mary" must come after "checked" + make(NameList{ "checked" })); + button.listen("checked", + boost::bind(&Collect::add, boost::ref(collector), "checked", _1), + // "checked" must come after "spot" + make(NameList{ "spot" })); + button.listen("spot", + boost::bind(&Collect::add, boost::ref(collector), "spot", _1)); + button.post(1); + ensure_equals(collector.result, make(StringVec{ "spot", "checked", "Mary" })); + collector.clear(); + button.stopListening("Mary"); + button.listen("Mary", + boost::bind(&Collect::add, boost::ref(collector), "Mary", _1), + LLEventPump::empty, // no after dependencies + // now "Mary" must come before "spot" + make(NameList{ "spot" })); + button.post(2); + ensure_equals(collector.result, make(StringVec{ "Mary", "spot", "checked" })); + collector.clear(); + button.stopListening("spot"); + std::string threw = catch_what( + [&button, &collector](){ + button.listen("spot", + boost::bind(&Collect::add, boost::ref(collector), "spot", _1), + // after "Mary" and "checked" -- whoops! + make(NameList{ "Mary", "checked" })); + }); + // Obviously the specific wording of the exception text can + // change; go ahead and change the test to match. + // Establish that it contains: + // - the name and runtime type of the LLEventPump + ensure_contains("LLEventPump type", threw, typeid(button).name()); + ensure_contains("LLEventPump name", threw, "'button'"); + // - the name of the new listener that caused the problem + ensure_contains("new listener name", threw, "'spot'"); + // - a synopsis of the problematic dependencies. + ensure_contains("cyclic dependencies", threw, + "\"Mary\" -> before (\"spot\")"); + ensure_contains("cyclic dependencies", threw, + "after (\"spot\") -> \"checked\""); + ensure_contains("cyclic dependencies", threw, + "after (\"Mary\", \"checked\") -> \"spot\""); + button.listen("yellow", + boost::bind(&Collect::add, boost::ref(collector), "yellow", _1), make(NameList{ "checked" })); + button.listen("shoelaces", + boost::bind(&Collect::add, boost::ref(collector), "shoelaces", _1), make(NameList{ "checked" })); + button.post(3); + ensure_equals(collector.result, make(StringVec{ "Mary", "checked", "yellow", "shoelaces" })); + collector.clear(); + threw = catch_what( + [&button, &collector](){ + button.listen("of", + boost::bind(&Collect::add, boost::ref(collector), "of", _1), + make(NameList{ "shoelaces" }), + make(NameList{ "yellow" })); + }); + // Same remarks about the specific wording of the exception. Just + // ensure that it contains enough information to clarify the + // problem and what must be done to resolve it. + ensure_contains("LLEventPump type", threw, typeid(button).name()); + ensure_contains("LLEventPump name", threw, "'button'"); + ensure_contains("new listener name", threw, "'of'"); + ensure_contains("prev listener name", threw, "'yellow'"); + // std::cout << "Thrown Exception: " << threw << std::endl; + ensure_contains("old order", threw, "was: Mary, checked, yellow, shoelaces"); + ensure_contains("new order", threw, "now: Mary, checked, shoelaces, of, yellow"); + button.post(4); + ensure_equals(collector.result, make(StringVec{ "Mary", "checked", "yellow", "shoelaces" })); +} + +template<> template<> +void events_object::test<7>() +{ + set_test_name("tweaked and untweaked LLEventPump instance names"); + { // nested scope + // Hand-instantiate an LLEventStream... + LLEventStream bob("bob"); + std::string threw = catch_what( + [](){ + // then another with a duplicate name. + LLEventStream bob2("bob"); + }); + ensure("Caught DupPumpName", !threw.empty()); + } // delete first 'bob' + LLEventStream bob("bob"); // should work, previous one unregistered + LLEventStream bob1("bob", true);// allowed to tweak name + ensure_equals("tweaked LLEventStream name", bob1.getName(), "bob1"); + std::vector > streams; + for (int i = 2; i <= 10; ++i) + { + streams.push_back(std::shared_ptr(new LLEventStream("bob", true))); + } + ensure_equals("last tweaked LLEventStream name", streams.back()->getName(), "bob10"); +} + +// Define a function that accepts an LLListenerOrPumpName +void eventSource(const LLListenerOrPumpName& listener) +{ + // Pretend that some time has elapsed. Call listener immediately. + listener(17); +} + +template<> template<> +void events_object::test<8>() +{ + set_test_name("LLListenerOrPumpName"); + // Passing a boost::bind() expression to LLListenerOrPumpName + listener0.reset(0); + eventSource(boost::bind(&Listener::call, boost::ref(listener0), _1)); + check_listener("got by listener", listener0, 17); + // Passing a string LLEventPump name to LLListenerOrPumpName + listener0.reset(0); + LLEventStream random("random"); + listener0.listenTo(random); + eventSource("random"); + check_listener("got by pump name", listener0, 17); + std::string threw = catch_what( + [](){ + LLListenerOrPumpName empty; + empty(17); + }); + + ensure("threw Empty", !threw.empty()); +} + +class TempListener: public Listener +{ +public: + TempListener(const std::string& name, bool& liveFlag) : + Listener(name), mLiveFlag(liveFlag) + { + mLiveFlag = true; + } + + virtual ~TempListener() + { + mLiveFlag = false; + } + +private: + bool& mLiveFlag; +}; + +template<> template<> +void events_object::test<9>() +{ + set_test_name("listen(boost::bind(...TempListener...))"); + // listen() can't do anything about a plain TempListener instance: + // it's not managed with shared_ptr, nor is it an LLEventTrackable subclass + bool live = false; + LLEventPump& heaptest(pumps.obtain("heaptest")); + LLBoundListener connection; + { + TempListener tempListener("temp", live); + ensure("TempListener constructed", live); + connection = heaptest.listen(tempListener.getName(), + boost::bind(&Listener::call, + boost::ref(tempListener), + _1)); + heaptest.post(1); + check_listener("received", tempListener, 1); + } // presumably this will make newListener go away? + // verify that + ensure("TempListener destroyed", !live); + // This is the case against which we can't defend. Don't even try to + // post to heaptest -- that would engage Undefined Behavior. + // Cautiously inspect connection... + ensure("misleadingly connected", connection.connected()); + // then disconnect by hand. + heaptest.stopListening("temp"); +} + +class TempTrackableListener: public TempListener, public LLEventTrackable +{ +public: + TempTrackableListener(const std::string& name, bool& liveFlag): + TempListener(name, liveFlag) + {} +}; + +template<> template<> +void events_object::test<10>() +{ + set_test_name("listen(boost::bind(...TempTrackableListener ref...))"); + bool live = false; + LLEventPump& heaptest(pumps.obtain("heaptest")); + LLBoundListener connection; + { + TempTrackableListener tempListener("temp", live); + ensure("TempTrackableListener constructed", live); + connection = heaptest.listen(tempListener.getName(), + boost::bind(&TempTrackableListener::call, + boost::ref(tempListener), _1)); + heaptest.post(1); + check_listener("received", tempListener, 1); + } // presumably this will make tempListener go away? + // verify that + ensure("TempTrackableListener destroyed", ! live); + ensure("implicit disconnect", ! connection.connected()); + // now just make sure we don't blow up trying to access a freed object! + heaptest.post(2); +} + +template<> template<> +void events_object::test<11>() +{ + set_test_name("listen(boost::bind(...TempTrackableListener pointer...))"); + bool live = false; + LLEventPump& heaptest(pumps.obtain("heaptest")); + LLBoundListener connection; + { + TempTrackableListener* newListener(new TempTrackableListener("temp", live)); + ensure("TempTrackableListener constructed", live); + connection = heaptest.listen(newListener->getName(), + boost::bind(&TempTrackableListener::call, + newListener, _1)); + heaptest.post(1); + check_listener("received", *newListener, 1); + // explicitly destroy newListener + delete newListener; + } + // verify that + ensure("TempTrackableListener destroyed", ! live); + ensure("implicit disconnect", ! connection.connected()); + // now just make sure we don't blow up trying to access a freed object! + heaptest.post(2); +} + +} // namespace tut diff --git a/indra/llcommon/tests/llhttpdate_test.cpp b/indra/llcommon/tests/llhttpdate_test.cpp new file mode 100644 index 0000000000..b580b09a9f --- /dev/null +++ b/indra/llcommon/tests/llhttpdate_test.cpp @@ -0,0 +1,162 @@ +/** + * @file llhttpdate_tut.cpp + * @author Kartic Krishnamurthy + * @date Wednesday, 18 Jul 2007 17:00:00 GMT :) + * + * $LicenseInfo:firstyear=2007&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2010, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +#include "linden_common.h" +#include "lltut.h" + +#include "lldate.h" +#include "llcommon.h" +#include "llframetimer.h" + +#include +#include + +namespace tut +{ + struct httpdate_data + { + httpdate_data() + { + } + ~httpdate_data() + { + } + LLDate some_date; + }; + typedef test_group httpdate_test; + typedef httpdate_test::object httpdate_object; + tut::httpdate_test httpdate("httpdate"); + + template<> template<> + void httpdate_object::test<1>() + { + + static std::string epoch_expected = "Thursday, 01 Jan 1970 00:00:00 GMT" ; + ensure("Check Epoch in RFC 1123", ( epoch_expected == some_date.asRFC1123())); + } + + template<> template<> + void httpdate_object::test<2>() + { + + static std::string expected = "Wednesday, 18 Jul 2007 22:17:24 GMT" ; + some_date = LLDate(1184797044.037586); + ensure("Check some timestamp in RFC 1123", ( expected == some_date.asRFC1123())); + } + + // This test of course most generic.. runs off current time + template<> template<> + void httpdate_object::test<3>() + { + + //F64 sometime = LLFrameTimer::getTotalSeconds(); + time_t sometime; + time(&sometime); + some_date = LLDate((F64) sometime); + struct tm *result; + char expected[255]; + std::string actual; + + result = gmtime(&sometime); + /* + std::cout << " seconds: "<< result->tm_sec + << ", minutes: " << result->tm_min + << ", hours: " << result->tm_hour + << ", day of the month: " << result->tm_mday + << ", month: " << result->tm_mon + << ", year: " << result->tm_year + << ", day of the week: " << result->tm_wday + << ", day in the year: " << result->tm_yday + << ", DST: " << result->tm_isdst << std::endl; + */ + strftime(expected, 255, "%A, %d %b %Y %H:%M:%S GMT", result); + actual = some_date.asRFC1123(); + // probably not a good idea to use strcmp but this is just a unit test + ensure("Current time in RFC 1123", (strcmp(expected, actual.c_str()) == 0)); + } + + void test_date_string(const std::string &locale, struct tm *t, + const std::string &fmt, const std::string &expected) + { + std::string result = LLDate::toHTTPDateString(t, fmt); + LLStringUtil::toLower(result); + std::string label = std::string("toHTTPDateString - ") + locale; + ensure_equals(label.c_str(), result, expected); + } + + template<> template<> + void httpdate_object::test<4>() + { + // test localization of http dates + const char *en_locale = "en_US.UTF-8"; + const char *fr_locale = "fr_FR.UTF-8"; + + std::string prev_locale = LLStringUtil::getLocale(); + std::string prev_clocale = std::string(setlocale(LC_TIME, NULL)); + time_t test_time = 1252374030; // 8 Sep 2009 01:40:01 + struct tm *t = gmtime(&test_time); + + setlocale(LC_TIME, en_locale); + if (strcmp(setlocale(LC_TIME, NULL), en_locale) != 0) + { + setlocale(LC_TIME, prev_clocale.c_str()); + skip("Cannot set English locale"); + } + + LLStringUtil::setLocale(en_locale); + test_date_string(en_locale, t, "%d %B %Y - %H:%M", "08 september 2009 - 01:40"); + test_date_string(en_locale, t, "%H", "01"); + test_date_string(en_locale, t, "%M", "40"); + test_date_string(en_locale, t, "%I", "01"); + test_date_string(en_locale, t, "%d", "08"); + test_date_string(en_locale, t, "%Y", "2009"); + test_date_string(en_locale, t, "%p", "am"); + test_date_string(en_locale, t, "%A", "tuesday"); + test_date_string(en_locale, t, "%B", "september"); + + setlocale(LC_TIME, fr_locale); + if (strcmp(setlocale(LC_TIME, NULL), fr_locale) != 0) + { + LLStringUtil::setLocale(prev_locale); + setlocale(LC_TIME, prev_clocale.c_str()); + skip("Cannot set French locale"); + } + + LLStringUtil::setLocale(fr_locale); + test_date_string(fr_locale, t, "%d %B %Y - %H:%M", "08 septembre 2009 - 01:40"); + test_date_string(fr_locale, t, "%H", "01"); + test_date_string(fr_locale, t, "%M", "40"); + test_date_string(fr_locale, t, "%I", "01"); + test_date_string(fr_locale, t, "%d", "08"); + test_date_string(fr_locale, t, "%Y", "2009"); + test_date_string(fr_locale, t, "%A", "mardi"); + test_date_string(fr_locale, t, "%B", "septembre"); + + LLStringUtil::setLocale(prev_locale); + setlocale(LC_TIME, prev_clocale.c_str()); + } +} diff --git a/indra/llcommon/tests/llsd_test.cpp b/indra/llcommon/tests/llsd_test.cpp new file mode 100644 index 0000000000..9cc93bcd14 --- /dev/null +++ b/indra/llcommon/tests/llsd_test.cpp @@ -0,0 +1,830 @@ +/** + * @file llsd_new_tut.cpp + * @date February 2006 + * @brief LLSD unit tests + * + * $LicenseInfo:firstyear=2006&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2006-2011, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +#define LLSD_DEBUG_INFO +#include "linden_common.h" +#include "lltut.h" +#include "llsd.h" + +#include "llsdtraits.h" +#include "llstring.h" + +using std::fpclassify; + +namespace tut +{ + class SDCleanupCheck + { + private: + U32 mOutstandingAtStart; + public: + SDCleanupCheck() : mOutstandingAtStart(llsd::outstandingCount()) { } + ~SDCleanupCheck() + { + ensure_equals("SDCleanupCheck", + llsd::outstandingCount(), mOutstandingAtStart); + } + }; + + class SDAllocationCheck : public SDCleanupCheck + { + private: + std::string mMessage; + U32 mExpectedAllocations; + U32 mAllocationAtStart; + public: + SDAllocationCheck(const std::string& message, int expectedAllocations) + : mMessage(message), + mExpectedAllocations(expectedAllocations), + mAllocationAtStart(llsd::allocationCount()) + { } + ~SDAllocationCheck() + { + ensure_equals(mMessage + " SDAllocationCheck", + llsd::allocationCount() - mAllocationAtStart, + mExpectedAllocations); + } + }; + + struct SDTestData { + template + static void ensureTypeAndValue(const char* msg, const LLSD& actual, + T expectedValue) + { + LLSDTraits traits; + + std::string s(msg); + + ensure( s + " type", traits.checkType(actual)); + ensure_equals( s + " value", traits.get(actual), expectedValue); + } + + template + static void ensureTypeAndRefValue(const char* msg, const LLSD& actual, + const T& expectedValue) + { + LLSDTraits traits; + + std::string s(msg); + + ensure( s + " type", traits.checkType(actual)); + ensure_equals( s + " value", traits.get(actual), expectedValue); + } + }; + + typedef test_group SDTestGroup; + typedef SDTestGroup::object SDTestObject; + + SDTestGroup sdTestGroup("LLSD(new)"); + + // template<> template<> + // void SDTestObject::test<1>() + // // construction and test of undefined + // { + // SDCleanupCheck check; + + // LLSD u; + // ensure("is undefined", u.isUndefined()); + // } + + template<> template<> + void SDTestObject::test<2>() + // setting and fetching scalar types + { + SDCleanupCheck check; + + LLSD v; + + v = true; ensureTypeAndValue("set true", v, true); + v = false; ensureTypeAndValue("set false", v, false); + v = true; ensureTypeAndValue("set true again", v, true); + + v = 42; ensureTypeAndValue("set to 42", v, 42); + v = 0; ensureTypeAndValue("set to zero", v, 0); + v = -12345; ensureTypeAndValue("set to neg", v, -12345); + v = 2000000000; ensureTypeAndValue("set to big", v, 2000000000); + + v = 3.14159265359; + ensureTypeAndValue("set to pi", v, 3.14159265359); + ensure_not_equals("isn't float", v.asReal(), + (float)3.14159265359); + v = 6.7e256; ensureTypeAndValue("set to big", v, 6.7e256); + + LLUUID nullUUID; + LLUUID newUUID; + newUUID.generate(); + + v = nullUUID; ensureTypeAndValue("set to null UUID", v, nullUUID); + v = newUUID; ensureTypeAndValue("set to new UUID", v, newUUID); + v = nullUUID; ensureTypeAndValue("set to null again", v, nullUUID); + + // strings must be tested with two types of string objects + std::string s = "now is the time"; + const char* cs = "for all good zorks"; + + v = s; ensureTypeAndValue("set to std::string", v, s); + v = cs; ensureTypeAndValue("set to const char*", v, cs); + + LLDate epoch; + LLDate aDay("2001-10-22T10:11:12.00Z"); + + v = epoch; ensureTypeAndValue("set to epoch", v, epoch); + v = aDay; ensureTypeAndValue("set to a day", v, aDay); + + LLURI path("http://slurl.com/secondlife/Ambleside/57/104/26/"); + + v = path; ensureTypeAndValue("set to a uri", v, path); + + const char source[] = "once in a blue moon"; + std::vector data; + copy(&source[0], &source[sizeof(source)], back_inserter(data)); + + v = data; ensureTypeAndRefValue("set to data", v, data); + + v.clear(); + ensure("reset to undefined", v.type() == LLSD::TypeUndefined); + } + + template<> template<> + void SDTestObject::test<3>() + // construction via scalar values + // tests both constructor and initialize forms + { + SDCleanupCheck check; + + LLSD b1(true); ensureTypeAndValue("construct boolean", b1, true); + LLSD b2 = true; ensureTypeAndValue("initialize boolean", b2, true); + LLSD i1(42); ensureTypeAndValue("construct int", i1, 42); + LLSD i2 =42; ensureTypeAndValue("initialize int", i2, 42); + LLSD d1(1.2); ensureTypeAndValue("construct double", d1, 1.2); + LLSD d2 = 1.2; ensureTypeAndValue("initialize double", d2, 1.2); + + LLUUID newUUID; + newUUID.generate(); + LLSD u1(newUUID); + ensureTypeAndValue("construct UUID", u1, newUUID); + LLSD u2 = newUUID; + ensureTypeAndValue("initialize UUID", u2, newUUID); + + LLSD ss1(std::string("abc")); + ensureTypeAndValue("construct std::string", ss1, "abc"); + LLSD ss2 = std::string("abc"); + ensureTypeAndValue("initialize std::string",ss2, "abc"); + LLSD sl1(std::string("def")); + ensureTypeAndValue("construct std::string", sl1, "def"); + LLSD sl2 = std::string("def"); + ensureTypeAndValue("initialize std::string", sl2, "def"); + LLSD sc1("ghi"); + ensureTypeAndValue("construct const char*", sc1, "ghi"); + LLSD sc2 = "ghi"; + ensureTypeAndValue("initialize const char*",sc2, "ghi"); + + LLDate aDay("2001-10-22T10:11:12.00Z"); + LLSD t1(aDay); ensureTypeAndValue("construct LLDate", t1, aDay); + LLSD t2 = aDay; ensureTypeAndValue("initialize LLDate", t2, aDay); + + LLURI path("http://slurl.com/secondlife/Ambleside/57/104/26/"); + LLSD p1(path); ensureTypeAndValue("construct LLURI", p1, path); + LLSD p2 = path; ensureTypeAndValue("initialize LLURI", p2, path); + + const char source[] = "once in a blue moon"; + std::vector data; + copy(&source[0], &source[sizeof(source)], back_inserter(data)); + LLSD x1(data); ensureTypeAndRefValue("construct vector", x1, data); + LLSD x2 = data; ensureTypeAndRefValue("initialize vector", x2, data); + } + + void checkConversions(const char* msg, const LLSD& v, + LLSD::Boolean eBoolean, LLSD::Integer eInteger, + LLSD::Real eReal, const LLSD::String& eString) + { + std::string s(msg); + + ensure_equals(s+" to bool", v.asBoolean(), eBoolean); + ensure_equals(s+" to int", v.asInteger(), eInteger); + if (eReal == eReal) + { + ensure_equals(s+" to real", v.asReal(), eReal); + ensure_equals(s+" to string", v.asString(), eString); + } + else + { + int left = fpclassify(v.asReal()); + int right = fpclassify(eReal); + + ensure_equals(s+" to real", left, right); + // ensure_equals(s+" to string", v.asString(), eString); + // I've commented this check out, since there doesn't + // seem to be uniform string representation for NaN on + // all platforms. For example, on my Ubuntu 8.10 laptop + // with libc 2.11.1, sqrt(-1.0) will return '-nan', not + // 'nan'. + } + } + + template<> template<> + void SDTestObject::test<4>() + // conversion between undefined and basic scalar types: + // boolean, integer, real and string + { + SDCleanupCheck check; + + LLSD v; checkConversions("untitled", v, false, 0, 0.0, ""); + + v = false; checkConversions("false", v, false, 0, 0.0, ""); + v = true; checkConversions("true", v, true, 1, 1.0, "true"); + + v = 0; checkConversions("zero", v, false, 0, 0.0, "0"); + v = 1; checkConversions("one", v, true, 1, 1.0, "1"); + v = -33; checkConversions("neg33", v, true, -33, -33.0, "-33"); + + v = 0.0; checkConversions("0.0", v, false, 0, 0.0, "0"); + v = 0.5; checkConversions("point5", v, true, 0, 0.5, "0.5"); + v = 0.9; checkConversions("point9", v, true, 0, 0.9, "0.9"); + v = -3.9; checkConversions("neg3dot9", v, true, -3, -3.9, "-3.9"); + // Get rid of NaN test. First, some libraries don't reliably return + // NaN for sqrt(-1.0) -- meaning that I don't even know how to + // portably, reliably produce a NaN value. Second, we observe failures + // on different platforms in the asString() test. But LLSD's + // ImplReal::asString() does not itself recognize NaN! It merely + // passes the value through to llformat(), which passes it through to + // the library vsnprintf(). That is, even when we do produce NaN, + // we're not testing any LLSD code: we're testing the local library's + // vsnprintf() function, which (empirically) produces idiosyncratic + // results. This is just not a good test case. +// v = sqrt(-1.0); checkConversions("NaN", v, false, 0, sqrt(-1.0), "nan"); + + v = ""; checkConversions("empty", v, false, 0, 0.0, ""); + v = "0"; checkConversions("digit0", v, true, 0, 0.0, "0"); + v = "10"; checkConversions("digit10", v, true, 10, 10.0, "10"); + v = "-2.345"; checkConversions("decdigits", v, + true, -2, -2.345, "-2.345"); + v = "apple"; checkConversions("apple", v, true, 0, 0.0, "apple"); + v = "33bob"; checkConversions("digialpha", v, true, 0, 0.0, "33bob"); + v = " "; checkConversions("space", v, true, 0, 0.0, " "); + v = "\n"; checkConversions("newline", v, true, 0, 0.0, "\n"); + } + + template + void checkRoundTrip(const std::string& msg, const LLSD& actual, + const char* sExpected, T vExpected) + { + std::string str = actual.asString(); + + if (sExpected) { + ensure_equals(msg + " string", str, sExpected); + } + + LLSD u(str); + LLSDTraits traits; + + ensure_equals(msg + " value", traits.get(u), vExpected); + } + + + template<> template<> + void SDTestObject::test<5>() + // conversion of String to and from UUID, Date and URI. + { + SDCleanupCheck check; + + LLSD v; + + LLUUID nullUUID; + LLUUID someUUID; + someUUID.generate(); + + v = nullUUID; checkRoundTrip("null uuid", v, + "00000000-0000-0000-0000-000000000000", nullUUID); + v = someUUID; checkRoundTrip("random uuid", v, 0, someUUID); + + LLDate epoch; + LLDate beta("2003-04-30T04:00:00Z"); + LLDate oneOh("2003-06-23T04:00:00Z"); + + v = epoch; checkRoundTrip("epoch date", v, 0, epoch); + v = beta; checkRoundTrip("beta date", v, + "2003-04-30T04:00:00Z", beta); + v = oneOh; checkRoundTrip("1.0 date", v, + "2003-06-23T04:00:00Z", oneOh); + + LLURI empty; + LLURI path("http://slurl.com/secondlife/Ambleside/57/104/26/"); + LLURI mail("mailto:zero.linden@secondlife.com"); + + v = empty; checkRoundTrip("empty URI", v, 0, empty); + v = path; checkRoundTrip("path URI", v, + "http://slurl.com/secondlife/Ambleside/57/104/26/", + path); + v = mail; checkRoundTrip("mail URI", v, + "mailto:zero.linden@secondlife.com", mail); + } + + template<> template<> + void SDTestObject::test<6>() + // copy construction and assignment + // checking for shared values after constr. or assignment + // checking in both the same type and change of type case + { + SDCleanupCheck check; + + { + LLSD v = 42; + + LLSD w0(v); + ensureTypeAndValue("int constr.", w0, 42); + + LLSD w1(v); + w1 = 13; + ensureTypeAndValue("int constr. change case 1", w1, 13); + ensureTypeAndValue("int constr. change case 2", v, 42); + + LLSD w2(v); + v = 7; + ensureTypeAndValue("int constr. change case 3", w2, 42); + ensureTypeAndValue("int constr. change case 4", v, 7); + } + + { + LLSD v = 42; + + LLSD w1(v); + w1 = "bob"; + ensureTypeAndValue("string constr. change case 1", w1, "bob"); + ensureTypeAndValue("string constr. change case 2", v, 42); + + LLSD w2(v); + v = "amy"; + ensureTypeAndValue("string constr. change case 3", w2, 42); + ensureTypeAndValue("string constr. change case 4", v, "amy"); + } + + { + LLSD v = 42; + + LLSD w0; + w0 = v; + ensureTypeAndValue("int assign", w0, 42); + + LLSD w1; + w1 = v; + w1 = 13; + ensureTypeAndValue("int assign change case 1", w1, 13); + ensureTypeAndValue("int assign change case 2", v, 42); + + LLSD w2; + w2 = v; + v = 7; + ensureTypeAndValue("int assign change case 3", w2, 42); + ensureTypeAndValue("int assign change case 4", v, 7); + } + + { + LLSD v = 42; + + LLSD w1; + w1 = v; + w1 = "bob"; + ensureTypeAndValue("string assign change case 1", w1, "bob"); + ensureTypeAndValue("string assign change case 2", v, 42); + + LLSD w2; + w2 = v; + v = "amy"; + ensureTypeAndValue("string assign change case 3", w2, 42); + ensureTypeAndValue("string assign change case 4", v, "amy"); + } + } + + + template<> template<> + void SDTestObject::test<7>() + // Test assignment and casting to various scalar types. These + // assignments should invoke the right conversion without it being + // mentioned explicitly. The few exceptions are marked SAD. + { + SDCleanupCheck check; + + LLSD v(" 42.375"); + + bool b = false; + b = v; ensure_equals("assign to bool", b, true); + b = (bool)v; ensure_equals("cast to bool", b, true); + + int i = 99; + i = v; ensure_equals("assign to int", i, 42); + i = (int)v; ensure_equals("cast to int", i, 42); + + double d = 3.14159; + d = v; ensure_equals("assign to double", d, 42.375); + d = (double)v; ensure_equals("cast to double", d, 42.375); + + std::string s = "yo"; +// SAD s = v; ensure_equals("assign to string", s, " 42.375"); + s = (std::string)v; ensure_equals("cast to string", s, " 42.375"); + + std::string uuidStr = "b1e50c2b-b627-4d23-8a86-a65d97b6319b"; + v = uuidStr; + LLUUID u; + u = v; + ensure_equals("assign to LLUUID", u, LLUUID(uuidStr)); +// SAD u = (LLUUID)v; +// ensure_equals("cast to LLUUID", u, LLUUID(uuidStr)); + + std::string dateStr = "2005-10-24T15:00:00Z"; + v = dateStr; + LLDate date; + date = v; + ensure_equals("assign to LLDate", date.asString(), dateStr); +// SAD date = (LLDate)v; +// ensure_equals("cast to LLDate", date.asString(), dateStr); + + std::string uriStr = "http://secondlife.com"; + v = uriStr; + LLURI uri; + uri = v; + ensure_equals("assign to LLURI", uri.asString(), uriStr); +// SAD uri = (LLURI)v; +// ensure_equals("cast to LLURI", uri.asString(), uriStr); + } + + template<> template<> + void SDTestObject::test<8>() + // Test construction of various scalar types from LLSD. + // Test both construction and initialization forms. + // These should invoke the right conversion without it being + // mentioned explicitly. The few exceptions are marked SAD. + { + SDCleanupCheck check; + + LLSD v(" 42.375"); + + bool b1(v); ensure_equals("contruct bool", b1, true); + bool b2 = v; ensure_equals("initialize bool", b2, true); + + int i1(v); ensure_equals("contruct int", i1, 42); + int i2 = v; ensure_equals("initialize int", i2, 42); + + double d1(v); ensure_equals("contruct double", d1, 42.375); + double d2 = v; ensure_equals("initialize double", d2, 42.375); + + std::string s1(v); + std::string s2 = v; + ensure_equals("contruct string", s1, " 42.375"); + ensure_equals("initialize string", s2, " 42.375"); + + std::string t1(v); + std::string t2 = v.asString(); // SAD + ensure_equals("contruct std::string", t1, " 42.375"); + ensure_equals("initialize std::string", t2, " 42.375"); + + std::string uuidStr = "b1e50c2b-b627-4d23-8a86-a65d97b6319b"; + v = uuidStr; + LLUUID uuid1(v.asUUID()); // SAD + LLUUID uuid2 = v; + ensure_equals("contruct LLUUID", uuid1, LLUUID(uuidStr)); + ensure_equals("initialize LLUUID", uuid2, LLUUID(uuidStr)); + + std::string dateStr = "2005-10-24T15:00:00Z"; + v = dateStr; + LLDate date1(v.asDate()); // SAD + LLDate date2 = v; + ensure_equals("contruct LLDate", date1.asString(), dateStr); + ensure_equals("initialize LLDate", date2.asString(), dateStr); + + std::string uriStr = "http://secondlife.com"; + v = uriStr; + LLURI uri1(v.asURI()); // SAD + LLURI uri2 = v; + ensure_equals("contruct LLURI", uri1.asString(), uriStr); + ensure_equals("initialize LLURI", uri2.asString(), uriStr); + } + + + template<> template<> + void SDTestObject::test<9>() + // test to make sure v is interpreted as a bool in a various + // scenarios. + { + SDCleanupCheck check; + + LLSD v = "0"; + // magic value that is interpreted as boolean true, but integer false! + + ensure_equals("trinary operator bool", (v ? true : false), true); + ensure_equals("convert to int, then bool", + ((int)v ? true : false), false); + + if(v) + { + ensure("if converted to bool", true); + } + else + { + fail("bool did not convert to a bool in if statement."); + } + + if(!v) + { + fail("bool did not convert to a bool in negated if statement."); + } + } + + template<> template<> + void SDTestObject::test<10>() + // map operations + { + SDCleanupCheck check; + + LLSD v; + ensure("undefined has no members", !v.has("amy")); + ensure("undefined get() is undefined", v.get("bob").isUndefined()); + + v = LLSD::emptyMap(); + ensure("empty map is a map", v.isMap()); + ensure("empty map has no members", !v.has("cam")); + ensure("empty map get() is undefined", v.get("don").isUndefined()); + + v.clear(); + v.insert("eli", 43); + ensure("insert converts to map", v.isMap()); + ensure("inserted key is present", v.has("eli")); + ensureTypeAndValue("inserted value", v.get("eli"), 43); + + v.insert("fra", false); + ensure("first key still present", v.has("eli")); + ensure("second key is present", v.has("fra")); + ensureTypeAndValue("first value", v.get("eli"), 43); + ensureTypeAndValue("second value", v.get("fra"), false); + + v.erase("eli"); + ensure("first key now gone", !v.has("eli")); + ensure("second key still present", v.has("fra")); + ensure("first value gone", v.get("eli").isUndefined()); + ensureTypeAndValue("second value sill there", v.get("fra"), false); + + v.erase("fra"); + ensure("second key now gone", !v.has("fra")); + ensure("second value gone", v.get("fra").isUndefined()); + + v["gil"] = (std::string)"good morning"; + ensure("third key present", v.has("gil")); + ensureTypeAndValue("third key value", v.get("gil"), "good morning"); + + const LLSD& cv = v; // FIX ME IF POSSIBLE + ensure("missing key", cv["ham"].isUndefined()); + ensure("key not present", !v.has("ham")); + + LLSD w = 43; + const LLSD& cw = w; // FIX ME IF POSSIBLE + int i = cw["ian"]; + ensureTypeAndValue("other missing value", i, 0); + ensure("other missing key", !w.has("ian")); + ensure("no conversion", w.isInteger()); + + LLSD x; + x = v; + ensure("copy map type", x.isMap()); + ensureTypeAndValue("copy map value gil", x.get("gil"), "good morning"); + } + + + template<> template<> + void SDTestObject::test<11>() + // array operations + { + SDCleanupCheck check; + + LLSD v; + ensure_equals("undefined has no size", v.size(), 0); + ensure("undefined get() is undefined", v.get(0).isUndefined()); + + v = LLSD::emptyArray(); + ensure("empty array is an array", v.isArray()); + ensure_equals("empty array has no size", v.size(), 0); + ensure("empty map get() is undefined", v.get(0).isUndefined()); + + v.clear(); + v.append(88); + v.append("noodle"); + v.append(true); + ensure_equals("appened array size", v.size(), 3); + ensure("append array is an array", v.isArray()); + ensureTypeAndValue("append 0", v[0], 88); + ensureTypeAndValue("append 1", v[1], "noodle"); + ensureTypeAndValue("append 2", v[2], true); + + v.insert(0, 77); + v.insert(2, "soba"); + v.insert(4, false); + ensure_equals("inserted array size", v.size(), 6); + ensureTypeAndValue("post insert 0", v[0], 77); + ensureTypeAndValue("post insert 1", v[1], 88); + ensureTypeAndValue("post insert 2", v[2], "soba"); + ensureTypeAndValue("post insert 3", v[3], "noodle"); + ensureTypeAndValue("post insert 4", v[4], false); + ensureTypeAndValue("post insert 5", v[5], true); + + ensureTypeAndValue("get 1", v.get(1), 88); + v.set(1, "hot"); + ensureTypeAndValue("set 1", v.get(1), "hot"); + + v.erase(3); + ensure_equals("post erase array size", v.size(), 5); + ensureTypeAndValue("post erase 0", v[0], 77); + ensureTypeAndValue("post erase 1", v[1], "hot"); + ensureTypeAndValue("post erase 2", v[2], "soba"); + ensureTypeAndValue("post erase 3", v[3], false); + ensureTypeAndValue("post erase 4", v[4], true); + + v.append(34); + ensure_equals("size after append", v.size(), 6); + ensureTypeAndValue("post append 5", v[5], 34); + + LLSD w; + w = v; + ensure("copy array type", w.isArray()); + ensure_equals("copy array size", w.size(), 6); + ensureTypeAndValue("copy array 0", w[0], 77); + ensureTypeAndValue("copy array 1", w[1], "hot"); + ensureTypeAndValue("copy array 2", w[2], "soba"); + ensureTypeAndValue("copy array 3", w[3], false); + ensureTypeAndValue("copy array 4", w[4], true); + ensureTypeAndValue("copy array 5", w[5], 34); + } + + + template<> template<> + void SDTestObject::test<12>() + // no sharing + { + SDCleanupCheck check; + + LLSD a = 99; + LLSD b = a; + a = 34; + ensureTypeAndValue("top level original changed", a, 34); + ensureTypeAndValue("top level copy unaltered", b, 99); + b = a; + b = 66; + ensureTypeAndValue("top level original unaltered", a, 34); + ensureTypeAndValue("top level copy changed", b, 66); + + a[0] = "uno"; + a[1] = 99; + a[2] = 1.414; + b = a; + a[1] = 34; + ensureTypeAndValue("array member original changed", a[1], 34); + ensureTypeAndValue("array member copy unaltered", b[1], 99); + b = a; + b[1] = 66; + ensureTypeAndValue("array member original unaltered", a[1], 34); + ensureTypeAndValue("array member copy changed", b[1], 66); + + a["alpha"] = "uno"; + a["beta"] = 99; + a["gamma"] = 1.414; + b = a; + a["beta"] = 34; + ensureTypeAndValue("map member original changed", a["beta"], 34); + ensureTypeAndValue("map member copy unaltered", b["beta"], 99); + b = a; + b["beta"] = 66; + ensureTypeAndValue("map member original unaltered", a["beta"], 34); + ensureTypeAndValue("map member copy changed", b["beta"], 66); + } + + template<> template<> + void SDTestObject::test<13>() + // sharing implementation + { + SDCleanupCheck check; + + { + SDAllocationCheck check("copy construct undefinded", 0); + LLSD v; + LLSD w = v; + } + + { + SDAllocationCheck check("assign undefined", 0); + LLSD v; + LLSD w; + w = v; + } + + { + SDAllocationCheck check("assign integer value", 1); + LLSD v = 45; + v = 33; + v = 0; + } + + { + SDAllocationCheck check("copy construct integer", 1); + LLSD v = 45; + LLSD w = v; + } + + { + SDAllocationCheck check("assign integer", 1); + LLSD v = 45; + LLSD w; + w = v; + } + + { + SDAllocationCheck check("avoids extra clone", 2); + LLSD v = 45; + LLSD w = v; + w = "nice day"; + } + + { + SDAllocationCheck check("shared values test for threaded work", 9); + + //U32 start_llsd_count = LLSD::outstandingCount(); + + LLSD m = LLSD::emptyMap(); + + m["one"] = 1; + m["two"] = 2; + m["one_copy"] = m["one"]; // 3 (m, "one" and "two") + + m["undef_one"] = LLSD(); + m["undef_two"] = LLSD(); + m["undef_one_copy"] = m["undef_one"]; + + { // Ensure first_array gets freed to avoid counting it + LLSD first_array = LLSD::emptyArray(); + first_array.append(1.0f); + first_array.append(2.0f); + first_array.append(3.0f); // 7 + + m["array"] = first_array; + m["array_clone"] = first_array; + m["array_copy"] = m["array"]; // 7 + } + + m["string_one"] = "string one value"; + m["string_two"] = "string two value"; + m["string_one_copy"] = m["string_one"]; // 9 + + //U32 llsd_object_count = LLSD::outstandingCount(); + //std::cout << "Using " << (llsd_object_count - start_llsd_count) << " LLSD objects" << std::endl; + + //m.dumpStats(); + } + } + + template<> template<> + void SDTestObject::test<14>() + // make sure that assignment of char* NULL in a string does not crash. + { + LLSD v; + v = (const char*)NULL; + ensure("type is a string", v.isString()); + } + + /* TO DO: + conversion of undefined to UUID, Date, URI and Binary + conversion of undefined to map and array + test map operations + test array operations + test array extension + + test copying and assign maps and arrays (clone) + test iteration over map + test iteration over array + test iteration over scalar + + test empty map and empty array are indeed shared + test serializations + */ +} + diff --git a/indra/llcommon/tests/llsdserialize_test.cpp b/indra/llcommon/tests/llsdserialize_test.cpp index ee315051d8..272eb55521 100644 --- a/indra/llcommon/tests/llsdserialize_test.cpp +++ b/indra/llcommon/tests/llsdserialize_test.cpp @@ -52,7 +52,7 @@ typedef U32 uint32_t; #include "llformat.h" #include "llmemorystream.h" -#include "../test/hexdump.h" +#include "hexdump.h" #include "../test/lltut.h" #include "../test/namedtempfile.h" #include "stringize.h" @@ -1921,12 +1921,12 @@ namespace tut int bufflen{ static_cast(buffstr.length()) }; out.write(reinterpret_cast(&bufflen), sizeof(bufflen)); LL_DEBUGS() << "Wrote length: " - << hexdump(reinterpret_cast(&bufflen), + << LL::hexdump(reinterpret_cast(&bufflen), sizeof(bufflen)) << LL_ENDL; out.write(buffstr.c_str(), buffstr.length()); LL_DEBUGS() << "Wrote data: " - << hexmix(buffstr.c_str(), buffstr.length()) + << LL::hexmix(buffstr.c_str(), buffstr.length()) << LL_ENDL; } } diff --git a/indra/llcommon/tests/llsdutil_test.cpp b/indra/llcommon/tests/llsdutil_test.cpp new file mode 100644 index 0000000000..4b25a02f30 --- /dev/null +++ b/indra/llcommon/tests/llsdutil_test.cpp @@ -0,0 +1,434 @@ +/** + * @file llsdutil_tut.cpp + * @author Adroit + * @date 2007-02 + * @brief LLSD conversion routines test cases. + * + * $LicenseInfo:firstyear=2007&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2010, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +#include "linden_common.h" +#include "lltut.h" +#include "m4math.h" +#include "v2math.h" +#include "v2math.h" +#include "v3color.h" +#include "v3math.h" +#include "v3dmath.h" +#include "v4coloru.h" +#include "v4math.h" +#include "llquaternion.h" +#include "llsdutil.h" +#include "llsdutil_math.h" +#include "stringize.h" +#include +#include + +namespace tut +{ + struct llsdutil_data + { + void test_matches(const std::string& proto_key, const LLSD& possibles, + const char** begin, const char** end) + { + std::set succeed(begin, end); + LLSD prototype(possibles[proto_key]); + for (LLSD::map_const_iterator pi(possibles.beginMap()), pend(possibles.endMap()); + pi != pend; ++pi) + { + std::string match(llsd_matches(prototype, pi->second)); + std::set::const_iterator found = succeed.find(pi->first); + if (found != succeed.end()) + { + // This test is supposed to succeed. Comparing to the + // empty string ensures that if the test fails, it will + // display the string received so we can tell what failed. + ensure_equals("match", match, ""); + } + else + { + // This test is supposed to fail. If we get a false match, + // the string 'match' will be empty, which doesn't tell us + // much about which case went awry. So construct a more + // detailed description string. + ensure(proto_key + " shouldn't match " + pi->first, ! match.empty()); + } + } + } + }; + typedef test_group llsdutil_test;; + typedef llsdutil_test::object llsdutil_object; + tut::llsdutil_test tutil("llsdutil"); + + template<> template<> + void llsdutil_object::test<1>() + { + LLSD sd; + U64 valueIn , valueOut; + valueIn = U64L(0xFEDCBA9876543210); + sd = ll_sd_from_U64(valueIn); + valueOut = ll_U64_from_sd(sd); + ensure_equals("U64 valueIn->sd->valueOut", valueIn, valueOut); + } + + template<> template<> + void llsdutil_object::test<2>() + { + LLSD sd; + U32 valueIn, valueOut; + valueIn = 0x87654321; + sd = ll_sd_from_U32(valueIn); + valueOut = ll_U32_from_sd(sd); + ensure_equals("U32 valueIn->sd->valueOut", valueIn, valueOut); + } + + template<> template<> + void llsdutil_object::test<3>() + { + U32 valueIn, valueOut; + valueIn = 0x87654321; + LLSD sd; + sd = ll_sd_from_ipaddr(valueIn); + valueOut = ll_ipaddr_from_sd(sd); + ensure_equals("valueIn->sd->valueOut", valueIn, valueOut); + } + + template<> template<> + void llsdutil_object::test<4>() + { + LLSD sd; + LLVector3 vec1(-1.0, 2.0, -3.0); + sd = ll_sd_from_vector3(vec1); + LLVector3 vec2 = ll_vector3_from_sd(sd); + ensure_equals("vector3 -> sd -> vector3: 1", vec1, vec2); + + LLVector3 vec3(sd); + ensure_equals("vector3 -> sd -> vector3: 2", vec1, vec3); + + sd.clear(); + vec1.setVec(0., 0., 0.); + sd = ll_sd_from_vector3(vec1); + vec2 = ll_vector3_from_sd(sd); + ensure_equals("vector3 -> sd -> vector3: 3", vec1, vec2); + sd.clear(); + } + + template<> template<> + void llsdutil_object::test<5>() + { + LLSD sd; + LLVector3d vec1((F64)(U64L(0xFEDCBA9876543210) << 2), -1., 0); + sd = ll_sd_from_vector3d(vec1); + LLVector3d vec2 = ll_vector3d_from_sd(sd); + ensure_equals("vector3d -> sd -> vector3d: 1", vec1, vec2); + + LLVector3d vec3(sd); + ensure_equals("vector3d -> sd -> vector3d : 2", vec1, vec3); + } + + template<> template<> + void llsdutil_object::test<6>() + { + LLSD sd; + LLVector2 vec((F32) -3., (F32) 4.2); + sd = ll_sd_from_vector2(vec); + LLVector2 vec1 = ll_vector2_from_sd(sd); + ensure_equals("vector2 -> sd -> vector2", vec, vec1); + + LLSD sd2 = ll_sd_from_vector2(vec1); + ensure_equals("sd -> vector2 -> sd: 2", sd, sd2); + } + + template<> template<> + void llsdutil_object::test<7>() + { + LLSD sd; + LLQuaternion quat((F32) 1., (F32) -0.98, (F32) 2.3, (F32) 0xffff); + sd = ll_sd_from_quaternion(quat); + LLQuaternion quat1 = ll_quaternion_from_sd(sd); + ensure_equals("LLQuaternion -> sd -> LLQuaternion", quat, quat1); + + LLSD sd2 = ll_sd_from_quaternion(quat1); + ensure_equals("sd -> LLQuaternion -> sd ", sd, sd2); + } + + template<> template<> + void llsdutil_object::test<8>() + { + LLSD sd; + LLColor4 c(1.0f, 2.2f, 4.0f, 7.f); + sd = ll_sd_from_color4(c); + LLColor4 c1 =ll_color4_from_sd(sd); + ensure_equals("LLColor4 -> sd -> LLColor4", c, c1); + + LLSD sd1 = ll_sd_from_color4(c1); + ensure_equals("sd -> LLColor4 -> sd", sd, sd1); + } + + template<> template<> + void llsdutil_object::test<9>() + { + set_test_name("llsd_matches"); + + // for this test, construct a map of all possible LLSD types + LLSD map; + map.insert("empty", LLSD()); + map.insert("Boolean", LLSD::Boolean()); + map.insert("Integer", LLSD::Integer(0)); + map.insert("Real", LLSD::Real(0.0)); + map.insert("String", LLSD::String("bah")); + map.insert("NumString", LLSD::String("1")); + map.insert("UUID", LLSD::UUID()); + map.insert("Date", LLSD::Date()); + map.insert("URI", LLSD::URI()); + map.insert("Binary", LLSD::Binary()); + map.insert("Map", LLSD().with("foo", LLSD())); + // Only an empty array can be constructed on the fly + LLSD array; + array.append(LLSD()); + map.insert("Array", array); + + // These iterators are declared outside our various for loops to avoid + // fatal MSVC warning: "I used to be broken, but I'm all better now!" + LLSD::map_const_iterator mi, mend(map.endMap()); + + /*-------------------------- llsd_matches --------------------------*/ + + // empty prototype matches anything + for (mi = map.beginMap(); mi != mend; ++mi) + { + ensure_equals(std::string("empty matches ") + mi->first, llsd_matches(LLSD(), mi->second), ""); + } + + LLSD proto_array, data_array; + for (int i = 0; i < 3; ++i) + { + proto_array.append(LLSD()); + data_array.append(LLSD()); + } + + // prototype array matches only array + for (mi = map.beginMap(); mi != mend; ++mi) + { + ensure(std::string("array doesn't match ") + mi->first, + ! llsd_matches(proto_array, mi->second).empty()); + } + + // data array must be at least as long as prototype array + proto_array.append(LLSD()); + ensure_equals("data array too short", llsd_matches(proto_array, data_array), + "Array size 4 required instead of Array size 3"); + data_array.append(LLSD()); + ensure_equals("data array just right", llsd_matches(proto_array, data_array), ""); + data_array.append(LLSD()); + ensure_equals("data array longer", llsd_matches(proto_array, data_array), ""); + + // array element matching + data_array[0] = LLSD::String(); + ensure_equals("undefined prototype array entry", llsd_matches(proto_array, data_array), ""); + proto_array[0] = LLSD::Binary(); + ensure_equals("scalar prototype array entry", llsd_matches(proto_array, data_array), + "[0]: Binary required instead of String"); + data_array[0] = LLSD::Binary(); + ensure_equals("matching prototype array entry", llsd_matches(proto_array, data_array), ""); + + // build a coupla maps + LLSD proto_map, data_map; + data_map["got"] = LLSD(); + data_map["found"] = LLSD(); + for (LLSD::map_const_iterator dmi(data_map.beginMap()), dmend(data_map.endMap()); + dmi != dmend; ++dmi) + { + proto_map[dmi->first] = dmi->second; + } + proto_map["foo"] = LLSD(); + proto_map["bar"] = LLSD(); + + // prototype map matches only map + for (mi = map.beginMap(); mi != mend; ++mi) + { + ensure(std::string("map doesn't match ") + mi->first, + ! llsd_matches(proto_map, mi->second).empty()); + } + + // data map must contain all keys in prototype map + std::string error(llsd_matches(proto_map, data_map)); + ensure_contains("missing keys", error, "missing keys"); + ensure_contains("missing foo", error, "foo"); + ensure_contains("missing bar", error, "bar"); + ensure_does_not_contain("found found", error, "found"); + ensure_does_not_contain("got got", error, "got"); + data_map["bar"] = LLSD(); + error = llsd_matches(proto_map, data_map); + ensure_contains("missing foo", error, "foo"); + ensure_does_not_contain("got bar", error, "bar"); + data_map["foo"] = LLSD(); + ensure_equals("data map just right", llsd_matches(proto_map, data_map), ""); + data_map["extra"] = LLSD(); + ensure_equals("data map with extra", llsd_matches(proto_map, data_map), ""); + + // map element matching + data_map["foo"] = LLSD::String(); + ensure_equals("undefined prototype map entry", llsd_matches(proto_map, data_map), ""); + proto_map["foo"] = LLSD::Binary(); + ensure_equals("scalar prototype map entry", llsd_matches(proto_map, data_map), + "['foo']: Binary required instead of String"); + data_map["foo"] = LLSD::Binary(); + ensure_equals("matching prototype map entry", llsd_matches(proto_map, data_map), ""); + + // String + { + static const char* matches[] = { "String", "NumString", "Boolean", "Integer", + "Real", "UUID", "Date", "URI" }; + test_matches("String", map, boost::begin(matches), boost::end(matches)); + } + + // Boolean, Integer, Real + static const char* numerics[] = { "Boolean", "Integer", "Real" }; + for (const char **ni = boost::begin(numerics), **nend = boost::end(numerics); + ni != nend; ++ni) + { + static const char* matches[] = { "Boolean", "Integer", "Real", "String", "NumString" }; + test_matches(*ni, map, boost::begin(matches), boost::end(matches)); + } + + // UUID + { + static const char* matches[] = { "UUID", "String", "NumString" }; + test_matches("UUID", map, boost::begin(matches), boost::end(matches)); + } + + // Date + { + static const char* matches[] = { "Date", "String", "NumString" }; + test_matches("Date", map, boost::begin(matches), boost::end(matches)); + } + + // URI + { + static const char* matches[] = { "URI", "String", "NumString" }; + test_matches("URI", map, boost::begin(matches), boost::end(matches)); + } + + // Binary + { + static const char* matches[] = { "Binary" }; + test_matches("Binary", map, boost::begin(matches), boost::end(matches)); + } + + /*-------------------------- llsd_equals ---------------------------*/ + + // Cross-product of each LLSD type with every other + for (LLSD::map_const_iterator lmi(map.beginMap()), lmend(map.endMap()); + lmi != lmend; ++lmi) + { + for (LLSD::map_const_iterator rmi(map.beginMap()), rmend(map.endMap()); + rmi != rmend; ++rmi) + { + // Name this test based on the map keys naming the types of + // interest, e.g "String::Integer". + // We expect the values (xmi->second) to be equal if and only + // if the type names (xmi->first) are equal. + ensure(STRINGIZE(lmi->first << "::" << rmi->first), + bool(lmi->first == rmi->first) == + bool(llsd_equals(lmi->second, rmi->second))); + } + } + + // Array cases + LLSD rarray; + rarray.append(1.0); + rarray.append(2); + rarray.append("3"); + LLSD larray(rarray); + ensure("llsd_equals(equal arrays)", llsd_equals(larray, rarray)); + rarray[2] = "4"; + ensure("llsd_equals(different [2])", ! llsd_equals(larray, rarray)); + rarray = larray; + rarray.append(LLSD::Date()); + ensure("llsd_equals(longer right array)", ! llsd_equals(larray, rarray)); + rarray = larray; + rarray.erase(2); + ensure("llsd_equals(shorter right array)", ! llsd_equals(larray, rarray)); + + // Map cases + LLSD rmap; + rmap["San Francisco"] = 65; + rmap["Phoenix"] = 92; + rmap["Boston"] = 77; + LLSD lmap(rmap); + ensure("llsd_equals(equal maps)", llsd_equals(lmap, rmap)); + rmap["Boston"] = 80; + ensure("llsd_equals(different [\"Boston\"])", ! llsd_equals(lmap, rmap)); + rmap = lmap; + rmap["Atlanta"] = 95; + ensure("llsd_equals(superset right map)", ! llsd_equals(lmap, rmap)); + rmap = lmap; + lmap["Seattle"] = 72; + ensure("llsd_equals(superset left map)", ! llsd_equals(lmap, rmap)); + } + + template<> template<> + void llsdutil_object::test<10>() + { + set_test_name("llsd_hashing"); + + { + LLSD data_s1 = LLSD::String("The quick brown aardvark jumped over the lazy lemming."); + LLSD data_s2 = LLSD::String("The quick brown aardvark jumped over the lazy lemming."); + + ensure("hash: Identical string hashes match.", boost::hash{}(data_s1) == boost::hash{}(data_s2)); + } + { + LLSD data_r1 = LLSD::Real(3.0f); + LLSD data_i1 = LLSD::Integer(3); + ensure("hash: equivalent values but different types do not match.", boost::hash{}(data_r1) != boost::hash{}(data_i1)); + } + { + LLSD data_a1 = llsd::array("A", "B", "C"); + LLSD data_a2 = llsd::array("A", "B", "C"); + + ensure("hash: identical arrays produce identical results", boost::hash{}(data_a1) == boost::hash{}(data_a2)); + + data_a2.append(llsd::array(1, 2)); + + ensure("hash: changing the array changes the hash.", boost::hash{}(data_a1) != boost::hash{}(data_a2)); + + data_a1.append(llsd::array(1, 2)); + ensure("hash: identical arrays produce identical results with nested arrays", boost::hash{}(data_a1) == boost::hash{}(data_a2)); + } + { + LLSD data_m1 = LLSDMap("key1", LLSD::Real(3.0))("key2", "value2")("key3", llsd::array(1, 2, 3)); + LLSD data_m2 = LLSDMap("key1", LLSD::Real(3.0))("key2", "value2")("key3", llsd::array(1, 2, 3)); + + ensure("hash: identical maps produce identical results", boost::hash{}(data_m1) == boost::hash{}(data_m2)); + + LLSD data_m3 = LLSDMap("key1", LLSD::Real(5.0))("key2", "value2")("key3", llsd::array(1, 2, 3)); + ensure("hash: Different values in the map produce different hashes.", boost::hash{}(data_m1) != boost::hash{}(data_m3)); + + LLSD data_m4 = LLSDMap("keyA", LLSD::Real(3.0))("key2", "value2")("key3", llsd::array(1, 2, 3)); + ensure("hash: Different keys in the map produce different hashes.", boost::hash{}(data_m1) != boost::hash{}(data_m4)); + + } + } + +} diff --git a/indra/llcommon/tests/llstreamtools_test.cpp b/indra/llcommon/tests/llstreamtools_test.cpp new file mode 100644 index 0000000000..970afb3b02 --- /dev/null +++ b/indra/llcommon/tests/llstreamtools_test.cpp @@ -0,0 +1,883 @@ +/** + * @file llstreamtools_tut.cpp + * @author Adroit + * @date February 2007 + * @brief llstreamtools test cases. + * + * $LicenseInfo:firstyear=2007&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2010, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +#include + +#include "linden_common.h" +#include "llstreamtools.h" +#include "lltut.h" + + +namespace tut +{ + struct streamtools_data + { + }; + typedef test_group streamtools_test; + typedef streamtools_test::object streamtools_object; + tut::streamtools_test streamtools_testcase("streamtools"); + + //test cases for skip_whitespace() + template<> template<> + void streamtools_object::test<1>() + { + char arr[255]; + std::string str; + std::string expected_result; + std::string actual_result; + std::istringstream is; + + is.str(str = ""); + ensure("skip_whitespace: empty string", (false == skip_whitespace(is))); + + is.clear(); + is.str(str = " SecondLife is a 3D World"); + skip_whitespace(is); + is.get(arr, 255, '\0'); + expected_result = "SecondLife is a 3D World"; + ensure_equals("skip_whitespace: space", arr, expected_result); + + is.clear(); + is.str(str = "\t \tSecondLife is a 3D World"); + skip_whitespace(is); + is.get(arr, 255, '\0'); + expected_result = "SecondLife is a 3D World"; + ensure_equals("skip_whitespace: space and tabs", arr, expected_result); + + is.clear(); + is.str(str = "\t \tSecondLife is a 3D World "); + skip_whitespace(is); + is.get(arr, 255, '\0'); + expected_result = "SecondLife is a 3D World "; + ensure_equals("skip_whitespace: space at end", arr, expected_result); + + is.clear(); + is.str(str = "\t \r\nSecondLife is a 3D World"); + skip_whitespace(is); + is.get(arr, 255, '\0'); + expected_result = "\r\nSecondLife is a 3D World"; + ensure_equals("skip_whitespace: space at end", arr, expected_result); + } + + //testcases for skip_emptyspaces() + template<> template<> + void streamtools_object::test<2>() + { + char arr[255]; + std::string str; + std::string expected_result; + std::string actual_result; + std::istringstream is; + bool ret; + + is.clear(); + is.str(str = " \tSecondLife is a 3D World.\n"); + skip_emptyspace(is); + is.get(arr, 255, '\0'); + expected_result = "SecondLife is a 3D World.\n"; + ensure_equals("skip_emptyspace: space and tabs", arr, expected_result); + + is.clear(); + is.str(str = " \t\r\n \r SecondLife is a 3D World.\n"); + skip_emptyspace(is); + is.get(arr, 255, '\0'); + expected_result = "SecondLife is a 3D World.\n"; + ensure_equals("skip_emptyspace: space, tabs, carriage return, newline", arr, expected_result); + + is.clear(); + is.str(str = ""); + ret = skip_emptyspace(is); + is.get(arr, 255, '\0'); + ensure("skip_emptyspace: empty string", ret == false); + + is.clear(); + is.str(str = " \r\n \t "); + ret = skip_emptyspace(is); + is.get(arr, 255, '\0'); + ensure("skip_emptyspace: space newline empty", ret == false); + } + + //testcases for skip_comments_and_emptyspace() + template<> template<> + void streamtools_object::test<3>() + { + char arr[255]; + std::string str; + std::string expected_result; + std::string actual_result; + std::istringstream is; + bool ret; + + is.clear(); + is.str(str = " \t\r\n \r SecondLife is a 3D World.\n"); + skip_comments_and_emptyspace(is); + is.get(arr, 255, '\0'); + expected_result = "SecondLife is a 3D World.\n"; + ensure_equals("skip_comments_and_emptyspace: space, tabs, carriage return, newline", arr, expected_result); + + is.clear(); + is.str(str = "# \r\n SecondLife is a 3D World."); + skip_comments_and_emptyspace(is); + is.get(arr, 255, '\0'); + expected_result = "SecondLife is a 3D World."; + ensure_equals("skip_comments_and_emptyspace: skip comment - 1", arr, expected_result); + + is.clear(); + is.str(str = "# \r\n # SecondLife is a 3D World. ##"); + ensure("should not be good()", ! skip_comments_and_emptyspace(is)); + ensure("should be at eof()", is.eof()); + // don't get(): given bad state, we can't rely on results + + is.clear(); + is.str(str = " \r\n SecondLife is a 3D World. ##"); + skip_comments_and_emptyspace(is); + is.get(arr, 255, '\0'); + expected_result = "SecondLife is a 3D World. ##"; + ensure_equals("skip_comments_and_emptyspace: skip comment - 3", arr, expected_result); + + is.clear(); + is.str(str = ""); + ret = skip_comments_and_emptyspace(is); + ensure("skip_comments_and_emptyspace: empty string", ! ret); + + is.clear(); + is.str(str = " \r\n \t # SecondLife is a 3D World"); + ret = skip_comments_and_emptyspace(is); + ensure("skip_comments_and_emptyspace: space newline comment empty", ! ret); + } + + //testcases for skip_line() + template<> template<> + void streamtools_object::test<4>() + { + char arr[255]; + std::string str; + std::string expected_result; + std::string actual_result; + std::istringstream is; + bool ret; + + is.clear(); + is.str(str = "SecondLife is a 3D World.\n\n It provides an opportunity to the site \nuser to perform real life activities in virtual world."); + skip_line(is); + is.get(arr, 255, '\0'); + expected_result = "\n It provides an opportunity to the site \nuser to perform real life activities in virtual world."; + ensure_equals("skip_line: 1 newline", arr, expected_result); + + is.clear(); + is.str(expected_result); + skip_line(is); + is.get(arr, 255, '\0'); + expected_result = " It provides an opportunity to the site \nuser to perform real life activities in virtual world."; + ensure_equals("skip_line: 2 newline", arr, expected_result); + + is.clear(); + is.str(expected_result); + skip_line(is); + is.get(arr, 255, '\0'); + expected_result = "user to perform real life activities in virtual world."; + ensure_equals("skip_line: 3 newline", arr, expected_result); + + is.clear(); + is.str(str = ""); + ret = skip_line(is); + ensure("skip_line: empty string", ret == false); + } + + + // testcases for skip_to_next_word() + template<> template<> + void streamtools_object::test<5>() + { + char arr[255]; + std::string str; + std::string expected_result; + std::string actual_result; + std::istringstream is; + bool ret; + + is.clear(); + is.str(str = "SecondLife is a 3D_World.\n\n It-provides an opportunity to the site \nuser to perform real life activities in virtual world."); + skip_to_next_word(is); // get past SecondLife + is.get(arr, 255, '\0'); + expected_result = "is a 3D_World.\n\n It-provides an opportunity to the site \nuser to perform real life activities in virtual world."; + ensure_equals("skip_to_next_word: 1", arr, expected_result); + + is.clear(); + is.str(expected_result); + skip_to_next_word(is); // get past is + skip_to_next_word(is); // get past a + skip_to_next_word(is); // get past 3D_World.\n\n + is.get(arr, 255, '\0'); + expected_result = "It-provides an opportunity to the site \nuser to perform real life activities in virtual world."; + ensure_equals("skip_to_next_word: get past .\n\n 2", arr, expected_result); + + is.clear(); + is.str(expected_result); + skip_to_next_word(is); // get past It- + expected_result = "provides an opportunity to the site \nuser to perform real life activities in virtual world."; + is.get(arr, 255, '\0'); + ensure_equals("skip_to_next_word: get past -", arr, expected_result); + + is.clear(); + is.str(str = ""); + ret = skip_to_next_word(is); + ensure("skip_line: empty string", ret == false); + + is.clear(); + is.str(str = " \r\n\r\n"); + ret = skip_to_next_word(is); + ensure("skip_line: space new lines", ret == false); + } + + + //testcases for skip_to_end_of_next_keyword() + template<> template<> + void streamtools_object::test<6>() + { + char arr[255]; + std::string str; + std::string expected_result; + std::string actual_result; + std::istringstream is; + bool ret; + + is.clear(); + is.str(str = "FIRSTKEY followed by second delimiter\nSECONDKEY\t SecondValue followed by third delimiter \nSECONDKEY\nFOURTHKEY FOURTHVALUEis a 3DWorld."); + ret = skip_to_end_of_next_keyword("FIRSTKEY", is); + is.get(arr, 255, '\0'); + expected_result = " followed by second delimiter\nSECONDKEY\t SecondValue followed by third delimiter \nSECONDKEY\nFOURTHKEY FOURTHVALUEis a 3DWorld."; + ensure_equals("skip_to_end_of_next_keyword: 1", arr, expected_result); + + is.clear(); + is.str(expected_result); + ret = skip_to_end_of_next_keyword("SECONDKEY", is); + is.get(arr, 255, '\0'); + expected_result = "\t SecondValue followed by third delimiter \nSECONDKEY\nFOURTHKEY FOURTHVALUEis a 3DWorld."; + ensure_equals("skip_to_end_of_next_keyword: 2", arr, expected_result); + + is.clear(); + is.str(expected_result); + ret = skip_to_end_of_next_keyword("SECONDKEY", is); + is.get(arr, 255, '\0'); + expected_result = "\nFOURTHKEY FOURTHVALUEis a 3DWorld."; + ensure_equals("skip_to_end_of_next_keyword: 3", arr, expected_result); + + is.clear(); + is.str(expected_result); + ret = skip_to_end_of_next_keyword("FOURTHKEY", is); + is.get(arr, 255, '\0'); + expected_result = " FOURTHVALUEis a 3DWorld."; + ensure_equals("skip_to_end_of_next_keyword: 4", arr, expected_result); + + is.clear(); + is.str(str = "{should be skipped as newline/space/tab does not follow but this one should be picked\n { Does it?\n"); + ret = skip_to_end_of_next_keyword("{", is); + is.get(arr, 255, '\0'); + expected_result = " Does it?\n"; + ensure_equals("skip_to_end_of_next_keyword: multiple delim matches on same line", arr, expected_result); + + is.clear(); + is.str(str = "Delim { could not be found at start"); + ret = skip_to_end_of_next_keyword("{", is); + ensure("skip_to_end_of_next_keyword: delim should not be present", ret == false); + + is.clear(); + is.str(str = "Empty Delim"); + ret = skip_to_end_of_next_keyword("", is); + ensure("skip_to_end_of_next_keyword: empty delim should not be valid", ret == false); + + is.clear(); + is.str(str = ""); + ret = skip_to_end_of_next_keyword("}", is); + ensure("skip_to_end_of_next_keyword: empty string", ret == false); + } + + //testcases for get_word(std::string& output_string, std::istream& input_stream) + template<> template<> + void streamtools_object::test<7>() + { + std::string str; + std::string expected_result; + std::string actual_result; + std::istringstream is; + bool ret; + + is.clear(); + is.str(str = " First Second \t \r \n Third Fourth-ShouldThisBePartOfFourth Fifth\n"); + actual_result = ""; + ret = get_word(actual_result, is); + expected_result = "First"; + ensure_equals("get_word: 1", actual_result, expected_result); + + actual_result = ""; + ret = get_word(actual_result, is); + expected_result = "Second"; + ensure_equals("get_word: 2", actual_result, expected_result); + + actual_result = ""; + ret = get_word(actual_result, is); + expected_result = "Third"; + ensure_equals("get_word: 3", actual_result, expected_result); + + // the current implementation of get_word seems inconsistent with + // skip_to_next_word. skip_to_next_word treats any character other + // than alhpa-numeric and '_' as a delimter, while get_word() + // treats only isspace() (i.e. space, form-feed('\f'), newline ('\n'), + // carriage return ('\r'), horizontal tab ('\t'), and vertical tab ('\v') + // as delimiters + actual_result = ""; + ret = get_word(actual_result, is); // will copy Fourth-ShouldThisBePartOfFourth + expected_result = "Fourth-ShouldThisBePartOfFourth"; // as per current impl. + ensure_equals("get_word: 4", actual_result, expected_result); + + actual_result = ""; + ret = get_word(actual_result, is); // will copy Fifth + expected_result = "Fifth"; // as per current impl. + ensure_equals("get_word: 5", actual_result, expected_result); + + is.clear(); + is.str(str = " \t \r \n "); + actual_result = ""; + ret = get_word(actual_result, is); + ensure("get_word: empty all spaces, newline tabs", ret == false); + + is.clear(); + is.str(str = ""); + actual_result = ""; + ret = get_word(actual_result, is); + ensure("get_word: empty string", ret == false); + } + + // testcase for get_word and skip_to_next_word compatibility + template<> template<> + void streamtools_object::test<8>() + { + std::string str; + std::string expected_result; + std::string actual_result; + std::istringstream is; + + is.clear(); + is.str(str = " First Second \t \r \n Third Fourth-ShouldThisBePartOfFourth Fifth\n"); + actual_result = ""; + get_word(actual_result, is); // First + actual_result = ""; + get_word(actual_result, is); // Second + actual_result = ""; + get_word(actual_result, is); // Third + + // the current implementation of get_word seems inconsistent with + // skip_to_next_word. skip_to_next_word treats any character other + // than alhpa-numeric and '_' as a delimter, while get_word() + // treats only isspace() (i.e. space, form-feed('\f'), newline ('\n'), + // carriage return ('\r'), horizontal tab ('\t'), and vertical tab ('\v') + // as delimiters + actual_result = ""; + get_word(actual_result, is); // will copy Fourth-ShouldThisBePartOfFourth + + actual_result = ""; + get_word(actual_result, is); // will copy Fifth + + is.clear(); + is.str(str = " First Second \t \r \n Third Fourth_ShouldThisBePartOfFourth Fifth\n"); + skip_to_next_word(is); // should now point to First + skip_to_next_word(is); // should now point to Second + skip_to_next_word(is); // should now point to Third + skip_to_next_word(is); // should now point to Fourth + skip_to_next_word(is); // should now point to ShouldThisBePartOfFourth + expected_result = ""; + // will copy ShouldThisBePartOfFourth, the fifth word, + // while using get_word above five times result in getting "Fifth" + get_word(expected_result, is); + ensure_equals("get_word: skip_to_next_word compatibility", actual_result, expected_result); + } + + //testcases for get_word(std::string& output_string, std::istream& input_stream, int n) + template<> template<> + void streamtools_object::test<9>() + { + std::string str; + std::string expected_result; + std::string actual_result; + std::istringstream is; + bool ret; + + is.clear(); + is.str(str = " First Second \t \r \n Third Fourth-ShouldThisBePartOfFourth Fifth\n"); + actual_result = ""; + ret = get_word(actual_result, is, 255); + expected_result = "First"; + ensure_equals("get_word: 1", actual_result, expected_result); + + actual_result = ""; + ret = get_word(actual_result, is, 4); + expected_result = "Seco"; // should be cut short + ensure_equals("get_word: 2", actual_result, expected_result); + + actual_result = ""; + ret = get_word(actual_result, is, 255); + expected_result = "nd"; // get remainder of Second + ensure_equals("get_word: 3", actual_result, expected_result); + + actual_result = ""; + ret = get_word(actual_result, is, 0); // 0 size string + expected_result = ""; // get remainder of Second + ensure_equals("get_word: 0 sized output", actual_result, expected_result); + + actual_result = ""; + ret = get_word(actual_result, is, 255); + expected_result = "Third"; + ensure_equals("get_word: 4", actual_result, expected_result); + + is.clear(); + is.str(str = " \t \r \n "); + actual_result = ""; + ret = get_word(actual_result, is, 255); + ensure("get_word: empty all spaces, newline tabs", ret == false); + + is.clear(); + is.str(str = ""); + actual_result = ""; + ret = get_word(actual_result, is, 255); + ensure("get_word: empty string", ret == false); + } + + //test cases for get_line(std::string& output_string, std::istream& input_stream) + template<> template<> + void streamtools_object::test<10>() + { + std::string str; + std::string expected_result; + std::string actual_result; + std::istringstream is; + + is.clear(); + is.str(str = "First Second \t \r\n Third Fourth-ShouldThisBePartOfFourth IsThisFifth\n"); + actual_result = ""; + get_line(actual_result, is); + expected_result = "First Second \t \r\n"; + ensure_equals("get_line: 1", actual_result, expected_result); + + actual_result = ""; + get_line(actual_result, is); + expected_result = " Third Fourth-ShouldThisBePartOfFourth IsThisFifth\n"; + ensure_equals("get_line: 2", actual_result, expected_result); + + is.clear(); + is.str(str = "\nFirst Line.\n\nSecond Line.\n"); + actual_result = ""; + get_line(actual_result, is); + expected_result = "\n"; + ensure_equals("get_line: First char as newline", actual_result, expected_result); + + actual_result = ""; + get_line(actual_result, is); + expected_result = "First Line.\n"; + ensure_equals("get_line: 3", actual_result, expected_result); + + actual_result = ""; + get_line(actual_result, is); + expected_result = "\n"; + ensure_equals("get_line: 4", actual_result, expected_result); + + actual_result = ""; + get_line(actual_result, is); + expected_result = "Second Line.\n"; + ensure_equals("get_line: 5", actual_result, expected_result); + } + + //test cases for get_line(std::string& output_string, std::istream& input_stream) + template<> template<> + void streamtools_object::test<11>() + { + std::string str; + std::string expected_result; + std::string actual_result; + std::istringstream is; + bool ret; + + is.clear(); + is.str(str = "One Line only with no newline"); + actual_result = ""; + ret = get_line(actual_result, is); + expected_result = "One Line only with no newline"; + ensure_equals("get_line: No newline", actual_result, expected_result); + ensure_equals("return value is good state of stream", ret, is.good()); + } + + //test cases for get_line(std::string& output_string, std::istream& input_stream) + template<> template<> + void streamtools_object::test<12>() + { + std::string str; + std::string expected_result; + std::string actual_result; + std::istringstream is; + + // need to be check if this test case is wrong or the implementation is wrong. + is.clear(); + is.str(str = "Should not skip lone \r.\r\n"); + actual_result = ""; + get_line(actual_result, is); + expected_result = "Should not skip lone \r.\r\n"; + ensure_equals("get_line: carriage return skipped even though not followed by newline", actual_result, expected_result); + } + + //test cases for get_line(std::string& output_string, std::istream& input_stream) + template<> template<> + void streamtools_object::test<13>() + { + std::string str; + std::string expected_result; + std::string actual_result; + std::istringstream is; + + is.clear(); + is.str(str = "\n"); + actual_result = ""; + get_line(actual_result, is); + expected_result = "\n"; + ensure_equals("get_line: Just newline", actual_result, expected_result); + } + + + //testcases for get_line(std::string& output_string, std::istream& input_stream, int n) + template<> template<> + void streamtools_object::test<14>() + { + std::string str; + std::string expected_result; + std::string actual_result; + std::istringstream is; + + is.clear(); + is.str(str = "First Line.\nSecond Line.\n"); + actual_result = ""; + get_line(actual_result, is, 255); + expected_result = "First Line.\n"; + ensure_equals("get_line: Basic Operation", actual_result, expected_result); + + actual_result = ""; + get_line(actual_result, is, sizeof("Second")-1); + expected_result = "Second\n"; + ensure_equals("get_line: Insufficient length 1", actual_result, expected_result); + + actual_result = ""; + get_line(actual_result, is, 255); + expected_result = " Line.\n"; + ensure_equals("get_line: Remainder after earlier insufficient length", actual_result, expected_result); + + is.clear(); + is.str(str = "One Line only with no newline with limited length"); + actual_result = ""; + get_line(actual_result, is, sizeof("One Line only with no newline with limited length")-1); + expected_result = "One Line only with no newline with limited length\n"; + ensure_equals("get_line: No newline with limited length", actual_result, expected_result); + + is.clear(); + is.str(str = "One Line only with no newline"); + actual_result = ""; + get_line(actual_result, is, 255); + expected_result = "One Line only with no newline"; + ensure_equals("get_line: No newline", actual_result, expected_result); + } + + //testcases for get_line(std::string& output_string, std::istream& input_stream, int n) + template<> template<> + void streamtools_object::test<15>() + { + std::string str; + std::string expected_result; + std::string actual_result; + std::istringstream is; + bool ret; + + is.clear(); + is.str(str = "One Line only with no newline"); + actual_result = ""; + ret = get_line(actual_result, is, 255); + expected_result = "One Line only with no newline"; + ensure_equals("get_line: No newline", actual_result, expected_result); + ensure_equals("return value is good state of stream", ret, is.good()); + } + + //testcases for remove_last_char() + template<> template<> + void streamtools_object::test<16>() + { + std::string str; + std::string expected_result; + bool ret; + + str = "SecondLife is a 3D World"; + + ret = remove_last_char('d',str); + expected_result = "SecondLife is a 3D Worl"; + ensure_equals("remove_last_char: should remove last char", str, expected_result); + + str = "SecondLife is a 3D World"; + ret = remove_last_char('W',str); + expected_result = "SecondLife is a 3D World"; + ensure_equals("remove_last_char: should not remove as it is not last char", str, expected_result); + ensure("remove_last_char: should return false", ret == false); + + str = "SecondLife is a 3D World\n"; + ret = remove_last_char('\n',str); + expected_result = "SecondLife is a 3D World"; + ensure_equals("remove_last_char: should remove last newline", str, expected_result); + ensure("remove_last_char: should remove newline and return true", ret == true); + } + + + //testcases for unescaped_string() + template<> template<> + void streamtools_object::test<17>() + { + std::string str; + std::string expected_result; + + str = "SecondLife is a 3D world \\n"; + unescape_string(str); + expected_result = "SecondLife is a 3D world \n"; + ensure_equals("unescape_string: newline", str, expected_result); + + str = "SecondLife is a 3D world \\\\t \\n"; + unescape_string(str); + expected_result = "SecondLife is a 3D world \\t \n"; + ensure_equals("unescape_string: backslash and newline", str, expected_result); + + str = "SecondLife is a 3D world \\ "; + unescape_string(str); + expected_result = "SecondLife is a 3D world \\ "; + ensure_equals("unescape_string: insufficient to unescape", str, expected_result); + + str = "SecondLife is a 3D world \\n \\n \\n \\\\\\n"; + unescape_string(str); + expected_result = "SecondLife is a 3D world \n \n \n \\\n"; + ensure_equals("unescape_string: multipel newline and backslash", str, expected_result); + + str = "SecondLife is a 3D world \\t"; + unescape_string(str); + expected_result = "SecondLife is a 3D world \\t"; + ensure_equals("unescape_string: leaves tab as is", str, expected_result); + + str = "\\n"; + unescape_string(str); + expected_result = "\n"; + ensure_equals("unescape_string: only a newline", str, expected_result); + } + + //testcases for escape_string() + template<> template<> + void streamtools_object::test<18>() + { + std::string str; + std::string expected_result; + + str = "SecondLife is a 3D world \n"; + escape_string(str); + expected_result = "SecondLife is a 3D world \\n"; + ensure_equals("escape_string: newline", str, expected_result); + + str = "SecondLife is a 3D world \\t \n"; + escape_string(str); + expected_result = "SecondLife is a 3D world \\\\t \\n"; + ensure_equals("escape_string: backslash and newline", str, expected_result); + + str = "SecondLife is a 3D world \n \n \n \\\n"; + escape_string(str); + expected_result = "SecondLife is a 3D world \\n \\n \\n \\\\\\n"; + ensure_equals("escape_string: multipel newline and backslash", str, expected_result); + + str = "SecondLife is a 3D world \t"; + escape_string(str); + expected_result = "SecondLife is a 3D world \t"; + ensure_equals("unescape_string: leaves tab as is", str, expected_result); + + str = "\n"; + escape_string(str); + expected_result = "\\n"; + ensure_equals("unescape_string: only a newline", str, expected_result); + + // serialization/deserialization escape->unescape + str = "SecondLife is a 3D world \n \n \n \\\n"; + escape_string(str); + unescape_string(str); + expected_result = "SecondLife is a 3D world \n \n \n \\\n"; + ensure_equals("escape_string: should preserve with escape/unescape", str, expected_result); + + // serialization/deserialization unescape->escape + str = "SecondLife is a 3D world \\n \\n \\n \\\\"; + unescape_string(str); + escape_string(str); + expected_result = "SecondLife is a 3D world \\n \\n \\n \\\\"; + ensure_equals("escape_string: should preserve with unescape/escape", str, expected_result); + } + + // testcases for replace_newlines_with_whitespace() + template<> template<> + void streamtools_object::test<19>() + { + std::string str; + std::string expected_result; + + str = "SecondLife is a 3D \n\nworld\n"; + replace_newlines_with_whitespace(str); + expected_result = "SecondLife is a 3D world "; + ensure_equals("replace_newlines_with_whitespace: replace all newline", str, expected_result); + + str = "\nSecondLife is a 3D world\n"; + replace_newlines_with_whitespace(str); + expected_result = " SecondLife is a 3D world "; + ensure_equals("replace_newlines_with_whitespace: begin and newline", str, expected_result); + + str = "SecondLife is a 3D world\r\t"; + replace_newlines_with_whitespace(str); + expected_result = "SecondLife is a 3D world\r\t"; + ensure_equals("replace_newlines_with_whitespace: should only replace newline", str, expected_result); + + str = ""; + replace_newlines_with_whitespace(str); + expected_result = ""; + ensure_equals("replace_newlines_with_whitespace: empty string", str, expected_result); + } + + //testcases for remove_double_quotes() + template<> template<> + void streamtools_object::test<20>() + { + std::string str; + std::string expected_result; + + str = "SecondLife is a \"\"3D world"; + remove_double_quotes(str); + expected_result = "SecondLife is a 3D world"; + ensure_equals("remove_double_quotes: replace empty doube quotes", str, expected_result); + + str = "SecondLife is a \"3D world"; + remove_double_quotes(str); + expected_result = "SecondLife is a 3D world"; + ensure_equals("remove_double_quotes: keep as is it matching quote not found", str, expected_result); + } + + // testcases for get_brace_count() + template<> template<> + void streamtools_object::test<21>() + { + } + + //testcases for get_keyword_and_value() + template<> template<> + void streamtools_object::test<22>() + { + std::string s = "SecondLife is a 3D World"; + std::string keyword; + std::string value; + get_keyword_and_value(keyword, value, s); + ensure("get_keyword_and_value: Unable to get Keyword and Value", ((keyword == "SecondLife") && (value == "is a 3D World"))); + + s = "SecondLife"; + get_keyword_and_value(keyword, value, s); + ensure("get_keyword_and_value: value should be empty", ((keyword == "SecondLife") && (value == ""))); + + s = "SecondLife \t is cool! \n"; + get_keyword_and_value(keyword, value, s); + ensure("get_keyword_and_value: remove space before value but not after", ((keyword == "SecondLife") && (value == "is cool! "))); + } + + //testcases for get_keyword_and_value() + template<> template<> + void streamtools_object::test<23>() + { + std::string s; + std::string keyword = "SOME PRIOR KEYWORD"; + std::string value = "SOME PRIOR VALUE"; + + s = "SecondLife\n"; + get_keyword_and_value(keyword, value, s); + ensure("get_keyword_and_value: terminated with newline. value should be empty", ((keyword == "SecondLife") && (value == ""))); + } + + //testcases for get_keyword_and_value() + template<> template<> + void streamtools_object::test<24>() + { + std::string s; + std::string keyword = "SOME PRIOR KEYWORD"; + std::string value = "SOME PRIOR VALUE"; + + s = ""; + get_keyword_and_value(keyword, value, s); + ensure("get_keyword_and_value: empty string. keyword value should empty", ((keyword == "") && (value == ""))); + } + + //testcase for fullread() + template<> template<> + void streamtools_object::test<25>() + { + std::string str = "First Line.\nSecond Line\n"; + std::istringstream is(str); + char buf[255] = {0}; + + fullread(is, buf, 255); + ensure_memory_matches("fullread: read with newlines", (void*) buf, static_cast(str.size())-1, (void*) str.c_str(), static_cast(str.size())-1); + + is.clear(); + is.str(str = "First Line.\nSecond Line\n"); + memset(buf, 0, 255); + + char expected_string[] = "First Line.\nSecond"; + int len = sizeof(expected_string)-1; + fullread(is, buf, len); + ensure_memory_matches("fullread: read with newlines", (void*) buf, len, (void*) &expected_string, len); + } + + +// testcases for operator >> + + template<> template<> + void streamtools_object::test<26>() + { + char arr[255]; + std::string str; + std::string toCheck = "SecondLife" ; + std::string expected_result; + std::istringstream stream("SecondLife is a 3D World"); + stream >> toCheck.c_str(); + stream.get(arr, 255, '\0'); + expected_result = " is a 3D World"; + ensure_equals("istream << operator", arr, expected_result); + + stream.clear(); + stream.str(str = "SecondLife is a 3D World"); + toCheck = "is"; + stream >> toCheck.c_str(); + ensure("istream << operator should have failed", stream.good() == false); + } +} diff --git a/indra/llinventory/CMakeLists.txt b/indra/llinventory/CMakeLists.txt index 22966bc55b..e8f76eaa7d 100644 --- a/indra/llinventory/CMakeLists.txt +++ b/indra/llinventory/CMakeLists.txt @@ -75,4 +75,7 @@ if (LL_TESTS) set(test_libs llinventory llmath llcorehttp llfilesystem ) LL_ADD_INTEGRATION_TEST(inventorymisc "" "${test_libs}") LL_ADD_INTEGRATION_TEST(llparcel "" "${test_libs}") + LL_ADD_INTEGRATION_TEST(llpermissions "" "${test_libs}") + LL_ADD_INTEGRATION_TEST(llsaleinfo "" "${test_libs}") + LL_ADD_INTEGRATION_TEST(lluserrelations "" "${test_libs}") endif (LL_TESTS) diff --git a/indra/llinventory/tests/llpermissions_test.cpp b/indra/llinventory/tests/llpermissions_test.cpp new file mode 100644 index 0000000000..1328939004 --- /dev/null +++ b/indra/llinventory/tests/llpermissions_test.cpp @@ -0,0 +1,491 @@ +/** + * @file llpermissions_tut.cpp + * @author Adroit + * @date March 2007 + * @brief llpermissions test cases. + * + * $LicenseInfo:firstyear=2007&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2010, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +#include +#include "linden_common.h" + +#include "lltut.h" + +#include "message.h" +#include "llpermissions.h" + + +namespace tut +{ + struct permission + { + }; + typedef test_group permission_t; + typedef permission_t::object permission_object_t; + tut::permission_t tut_permission("permission"); + + template<> template<> + void permission_object_t::test<1>() + { + LLPermissions permissions; + LLUUID uuid = permissions.getCreator(); + LLUUID uuid1 = permissions.getOwner(); + LLUUID uuid2 = permissions.getGroup(); + LLUUID uuid3 = permissions.getLastOwner(); + + ensure("LLPermission Get Functions failed", (uuid == LLUUID::null && uuid1 == LLUUID::null && + uuid2 == LLUUID::null && uuid3 == LLUUID::null)); + ensure("LLPermission Get Functions failed", (permissions.getMaskBase() == PERM_ALL && permissions.getMaskOwner() == PERM_ALL && + permissions.getMaskGroup() == PERM_ALL && permissions.getMaskEveryone() == PERM_ALL && permissions.getMaskNextOwner() == PERM_ALL)); + ensure("Ownership functions failed", ((! permissions.isGroupOwned()) && (! permissions.isOwned()))); + } + + template<> template<> + void permission_object_t::test<2>() + { + LLPermissions permissions; + LLUUID creator("abf0d56b-82e5-47a2-a8ad-74741bb2c29e"); + LLUUID owner("68edcf47-ccd7-45b8-9f90-1649d7f12806"); + LLUUID lastOwner("5e47a0dc-97bf-44e0-8b40-de06718cee9d"); + LLUUID group("9c8eca51-53d5-42a7-bb58-cef070395db8"); + permissions.init(creator, owner, lastOwner, group); + + ensure_equals("init/getCreator():failed to return the creator ", creator, permissions.getCreator()); + ensure_equals("init/getOwner():failed to return the owner ", owner, permissions.getOwner()); + ensure_equals("init/getLastOwner():failed to return the group ", lastOwner, permissions.getLastOwner()); + ensure_equals("init/getGroup():failed to return the group ", group, permissions.getGroup()); + } + + template<> template<> + void permission_object_t::test<3>() + { + LLPermissions permissions; + U32 base = PERM_ALL; + U32 owner = PERM_ITEM_UNRESTRICTED; //PERM_ITEM_UNRESTRICTED = PERM_MODIFY | PERM_COPY | PERM_TRANSFER; + U32 group = PERM_TRANSFER | PERM_MOVE | PERM_COPY|PERM_MODIFY; + U32 everyone = PERM_TRANSFER | PERM_MOVE | PERM_MODIFY; + U32 next = PERM_NONE; + + U32 fixedbase = base; + U32 fixedowner = PERM_ITEM_UNRESTRICTED; //owner & fixedbase + U32 fixedgroup = PERM_ITEM_UNRESTRICTED; // no PERM_MOVE as owner does not have that perm either + U32 fixedeveryone = PERM_TRANSFER; // no PERM_MOVE. Everyone can never modify. + U32 fixednext = PERM_NONE; + + permissions.initMasks(base, owner, everyone, group, next); // will fix perms if not allowed. + ensure_equals("initMasks/getMaskBase():failed to return the MaskBase ", fixedbase, permissions.getMaskBase()); + ensure_equals("initMasks/getMaskOwner():failed to return the MaskOwner ", fixedowner, permissions.getMaskOwner()); + ensure_equals("initMasks/getMaskEveryone():failed to return the MaskGroup ", fixedgroup, permissions.getMaskGroup()); + ensure_equals("initMasks/getMaskEveryone():failed to return the MaskEveryone ", fixedeveryone, permissions.getMaskEveryone()); + ensure_equals("initMasks/getMaskNextOwner():failed to return the MaskNext ", fixednext, permissions.getMaskNextOwner()); + + // explictly set should maintain the values + permissions.setMaskBase(base); //no fixing + ensure_equals("setMaskBase/getMaskBase():failed to return the MaskBase ", base, permissions.getMaskBase()); + + permissions.setMaskOwner(owner); + ensure_equals("setMaskOwner/getMaskOwner():failed to return the MaskOwner ", owner, permissions.getMaskOwner()); + + permissions.setMaskEveryone(everyone); + ensure_equals("setMaskEveryone/getMaskEveryone():failed to return the MaskEveryone ", everyone, permissions.getMaskEveryone()); + + permissions.setMaskGroup(group); + ensure_equals("setMaskGroup/getMaskEveryone():failed to return the MaskGroup ", group, permissions.getMaskGroup()); + + permissions.setMaskNext(next); + ensure_equals("setMaskNext/getMaskNextOwner():failed to return the MaskNext ", next, permissions.getMaskNextOwner()); + + // further tests can be added to ensure perms for owner/group/everyone etc. get properly fixed. + // code however suggests that there is no explict check if the perms are correct and the user of this + // class is expected to know how to use them correctly. skipping further test cases for now for various + // perm combinations. + } + + template<> template<> + void permission_object_t::test<4>() + { + LLPermissions perm,perm1; + LLUUID creator("abf0d56b-82e5-47a2-a8ad-74741bb2c29e"); + LLUUID owner("68edcf47-ccd7-45b8-9f90-1649d7f12806"); + LLUUID lastOwner("5e47a0dc-97bf-44e0-8b40-de06718cee9d"); + LLUUID group("9c8eca51-53d5-42a7-bb58-cef070395db8"); + perm1.init(creator,owner,lastOwner,group); + perm.set(perm1); + ensure("set():failed to set ", (creator == perm.getCreator()) && (owner == perm.getOwner())&& + (lastOwner == perm.getLastOwner())&& (group == perm.getGroup())); + } + + template<> template<> + void permission_object_t::test<5>() + { + LLPermissions perm,perm1; + LLUUID creator("abf0d56b-82e5-47a2-a8ad-74741bb2c29e"); + LLUUID owner("68edcf47-ccd7-45b8-9f90-1649d7f12806"); + LLUUID lastOwner("5e47a0dc-97bf-44e0-8b40-de06718cee9d"); + LLUUID group("9c8eca51-53d5-42a7-bb58-cef070395db8"); + perm1.init(creator,owner,lastOwner,group); + + U32 base = PERM_TRANSFER; + U32 ownerp = PERM_TRANSFER; + U32 groupp = PERM_TRANSFER; + U32 everyone = PERM_TRANSFER; + U32 next = PERM_NONE; + + perm1.initMasks(base, ownerp, everyone, groupp, next); + + base = PERM_ALL; + ownerp = PERM_ITEM_UNRESTRICTED; //PERM_ITEM_UNRESTRICTED = PERM_MODIFY | PERM_COPY | PERM_TRANSFER; + groupp = PERM_TRANSFER | PERM_COPY|PERM_MODIFY; + everyone = PERM_TRANSFER; + next = PERM_NONE; + + perm.init(creator,owner,lastOwner,group); + perm.initMasks(base, ownerp, everyone, groupp, next); + + // restrict permissions by accumulation + perm.accumulate(perm1); + + U32 fixedbase = PERM_TRANSFER | PERM_MOVE; + U32 fixedowner = PERM_TRANSFER; + U32 fixedgroup = PERM_TRANSFER; + U32 fixedeveryone = PERM_TRANSFER; + U32 fixednext = PERM_NONE; + + ensure_equals("accumulate failed ", fixedbase, perm.getMaskBase()); + ensure_equals("accumulate failed ", fixedowner, perm.getMaskOwner()); + ensure_equals("accumulate failed ", fixedgroup, perm.getMaskGroup()); + ensure_equals("accumulate failed ", fixedeveryone, perm.getMaskEveryone()); + ensure_equals("accumulate failed ", fixednext, perm.getMaskNextOwner()); + } + + template<> template<> + void permission_object_t::test<6>() + { + LLPermissions perm; + LLUUID creator("abf0d56b-82e5-47a2-a8ad-74741bb2c29e"); + LLUUID owner("68edcf47-ccd7-45b8-9f90-1649d7f12806"); + LLUUID lastOwner("5e47a0dc-97bf-44e0-8b40-de06718cee9d"); + LLUUID group("9c8eca51-53d5-42a7-bb58-cef070395db8"); + perm.init(creator,owner,lastOwner,group); + ensure_equals("getSafeOwner:failed ", owner,perm.getSafeOwner()); + + ///NULL Owner + perm.init(creator,LLUUID::null,lastOwner,group); + ensure_equals("getSafeOwner:failed ", group, perm.getSafeOwner()); + } + + template<> template<> + void permission_object_t::test<7>() + { + LLPermissions perm1; + LLUUID uuid; + bool is_group_owned = false; + ensure("1:getOwnership:failed ", ! perm1.getOwnership(uuid,is_group_owned)); + + LLPermissions perm; + LLUUID creator("abf0d56b-82e5-47a2-a8ad-74741bb2c29e"); + LLUUID owner("68edcf47-ccd7-45b8-9f90-1649d7f12806"); + LLUUID lastOwner("5e47a0dc-97bf-44e0-8b40-de06718cee9d"); + LLUUID group("9c8eca51-53d5-42a7-bb58-cef070395db8"); + perm.init(creator,owner,lastOwner,group); + perm.getOwnership(uuid,is_group_owned); + ensure("2:getOwnership:failed ", ((uuid == owner) && (! is_group_owned))); + + perm.init(creator,LLUUID::null,lastOwner,group); + perm.getOwnership(uuid,is_group_owned); + ensure("3:getOwnership:failed ", ((uuid == group) && is_group_owned)); + } + + template<> template<> + void permission_object_t::test<8>() + { + LLPermissions perm,perm1; + LLUUID creator("abf0d56b-82e5-47a2-a8ad-74741bb2c29e"); + LLUUID owner("68edcf47-ccd7-45b8-9f90-1649d7f12806"); + LLUUID lastOwner("5e47a0dc-97bf-44e0-8b40-de06718cee9d"); + LLUUID group("9c8eca51-53d5-42a7-bb58-cef070395db8"); + perm.init(creator,owner,lastOwner,group); + perm1.init(creator,owner,lastOwner,group); + ensure_equals("getCRC32:failed ", perm.getCRC32(),perm1.getCRC32()); + } + + template<> template<> + void permission_object_t::test<9>() + { + LLPermissions perm; + LLUUID agent("abf0d56b-82e5-47a2-a8ad-74741bb2c29e"); + LLUUID owner("68edcf47-ccd7-45b8-9f90-1649d7f12806"); + LLUUID group("9c8eca51-53d5-42a7-bb58-cef070395db8"); + bool is_atomic = true; + ensure("setOwnerAndGroup():failed ", perm.setOwnerAndGroup(agent,owner,group,is_atomic)); + + LLUUID owner2("68edcf47-ccd7-45b8-9f90-1649d7f12807"); + LLUUID group2("9c8eca51-53d5-42a7-bb58-cef070395db9"); + + // cant change - agent need to be current owner + ensure("setOwnerAndGroup():failed ", ! perm.setOwnerAndGroup(agent,owner2,group2,is_atomic)); + + // should be able to change - agent and owner same as current owner + ensure("setOwnerAndGroup():failed ", perm.setOwnerAndGroup(owner,owner,group2,is_atomic)); + } + + template<> template<> + void permission_object_t::test<10>() + { + LLPermissions perm; + LLUUID agent; + LLUUID group("9c8eca51-53d5-42a7-bb58-cef070395db8"); + ensure("deedToGroup():failed ", perm.deedToGroup(agent,group)); + } + template<> template<> + void permission_object_t::test<11>() + { + LLPermissions perm; + LLUUID agent; + bool set = true; + U32 bits = PERM_TRANSFER | PERM_MODIFY; + ensure("setBaseBits():failed ", perm.setBaseBits(agent, set, bits)); + ensure("setOwnerBits():failed ", perm.setOwnerBits(agent, set, bits)); + + LLUUID agent1("9c8eca51-53d5-42a7-bb58-cef070395db8"); + ensure("setBaseBits():failed ", ! perm.setBaseBits(agent1, set, bits)); + ensure("setOwnerBits():failed ", ! perm.setOwnerBits(agent1, set, bits)); + } + + template<> template<> + void permission_object_t::test<12>() + { + LLPermissions perm; + LLUUID agent; + LLUUID group("9c8eca51-53d5-42a7-bb58-cef070395db8"); + bool set = true; + U32 bits = 10; + ensure("setGroupBits():failed ", perm.setGroupBits(agent,group, set, bits)); + ensure("setEveryoneBits():failed ", perm.setEveryoneBits(agent,group, set, bits)); + ensure("setNextOwnerBits():failed ", perm.setNextOwnerBits(agent,group, set, bits)); + + LLUUID agent1("abf0d56b-82e5-47a2-a8ad-74741bb2c29e"); + ensure("setGroupBits():failed ", ! perm.setGroupBits(agent1,group, set, bits)); + ensure("setEveryoneBits():failed ", ! perm.setEveryoneBits(agent1,group, set, bits)); + ensure("setNextOwnerBits():failed ", ! perm.setNextOwnerBits(agent1,group, set, bits)); + } + + template<> template<> + void permission_object_t::test<13>() + { + LLPermissions perm; + LLUUID agent; + LLUUID group("9c8eca51-53d5-42a7-bb58-cef070395db8"); + U32 bits = 10; + ensure("allowOperationBy():failed ", perm.allowOperationBy(bits,agent,group)); + + LLUUID agent1("abf0d56b-82e5-47a2-a8ad-74741bb2c29e"); + LLUUID creator("abf0d56b-82e5-47a2-a8ad-74741bb2c29e"); + LLUUID owner("68edcf47-ccd7-45b8-9f90-1649d7f12806"); + LLUUID lastOwner("5e47a0dc-97bf-44e0-8b40-de06718cee9d"); + perm.init(creator,owner,lastOwner,group); + ensure("allowOperationBy():failed ", perm.allowOperationBy(bits,agent1,group)); + } + + template<> template<> + void permission_object_t::test<14>() + { + LLPermissions perm; + LLUUID creator("abf0d56b-82e5-47a2-a8ad-74741bb2c29e"); + LLUUID owner; + LLUUID lastOwner("5e47a0dc-97bf-44e0-8b40-de06718cee9d"); + LLUUID group("9c8eca51-53d5-42a7-bb58-cef070395db8"); + perm.init(creator,owner,lastOwner,group); + LLUUID agent; + ensure("1:allowModifyBy():failed ", perm.allowModifyBy(agent)); + ensure("2:allowModifyBy():failed ", perm.allowModifyBy(agent,group)); + + LLUUID agent1("9c8eca51-53d5-42a7-bb58-cef070395db8"); + ensure("3:allowModifyBy():failed ", perm.allowModifyBy(agent1)); + ensure("4:allowModifyBy():failed ", perm.allowModifyBy(agent1,group)); + } + + template<> template<> + void permission_object_t::test<15>() + { + LLPermissions perm; + LLUUID creator("abf0d56b-82e5-47a2-a8ad-74741bb2c29e"); + LLUUID owner; + LLUUID lastOwner("5e47a0dc-97bf-44e0-8b40-de06718cee9d"); + LLUUID group("9c8eca51-53d5-42a7-bb58-cef070395db8"); + perm.init(creator,owner,lastOwner,group); + LLUUID agent; + ensure("1:allowCopyBy():failed ", perm.allowModifyBy(agent)); + ensure("2:allowCopyBy():failed ", perm.allowModifyBy(agent,group)); + + LLUUID agent1("9c8eca51-53d5-42a7-bb58-cef070395db8"); + ensure("3:allowCopyBy():failed ", perm.allowCopyBy(agent1)); + ensure("4:allowCopyBy():failed ", perm.allowCopyBy(agent1,group)); + } + + template<> template<> + void permission_object_t::test<16>() + { + LLPermissions perm; + LLUUID creator("abf0d56b-82e5-47a2-a8ad-74741bb2c29e"); + LLUUID owner; + LLUUID lastOwner("5e47a0dc-97bf-44e0-8b40-de06718cee9d"); + LLUUID group("9c8eca51-53d5-42a7-bb58-cef070395db8"); + perm.init(creator,owner,lastOwner,group); + LLUUID agent; + ensure("1:allowMoveBy():failed ", perm.allowMoveBy(agent)); + ensure("2:allowMoveBy():failed ", perm.allowMoveBy(agent,group)); + + LLUUID agent1("9c8eca51-53d5-42a7-bb58-cef070395db8"); + ensure("3:allowMoveBy():failed ", perm.allowMoveBy(agent1)); + ensure("4:allowMoveBy():failed ", perm.allowMoveBy(agent1,group)); + } + + template<> template<> + void permission_object_t::test<17>() + { + LLPermissions perm; + LLUUID creator("abf0d56b-82e5-47a2-a8ad-74741bb2c29e"); + LLUUID owner; + LLUUID lastOwner("5e47a0dc-97bf-44e0-8b40-de06718cee9d"); + LLUUID group("9c8eca51-53d5-42a7-bb58-cef070395db8"); + LLUUID agent; + ensure("1:allowMoveBy():failed ", perm.allowTransferTo(agent)); + + perm.init(creator,owner,lastOwner,group); + ensure("2:allowMoveBy():failed ", perm.allowTransferTo(agent)); + } + + template<> template<> + void permission_object_t::test<18>() + { + LLPermissions perm,perm1; + ensure_equals("1:Operator==:failed ", perm, perm1); + + LLUUID creator("abf0d56b-82e5-47a2-a8ad-74741bb2c29e"); + LLUUID owner("68edcf47-ccd7-45b8-9f90-1649d7f12806"); + LLUUID lastOwner("5e47a0dc-97bf-44e0-8b40-de06718cee9d"); + LLUUID group("9c8eca51-53d5-42a7-bb58-cef070395db8"); + perm.init(creator,owner,lastOwner,group); + perm = perm1; + ensure_equals("2:Operator==:failed ", perm, perm1); + } + + template<> template<> + void permission_object_t::test<19>() + { + LLPermissions perm,perm1; + LLUUID creator("abf0d56b-82e5-47a2-a8ad-74741bb2c29e"); + LLUUID owner("68edcf47-ccd7-45b8-9f90-1649d7f12806"); + LLUUID lastOwner("5e47a0dc-97bf-44e0-8b40-de06718cee9d"); + LLUUID group("9c8eca51-53d5-42a7-bb58-cef070395db8"); + perm.init(creator,owner,lastOwner,group); + ensure_not_equals("2:Operator==:failed ", perm, perm1); + } + + template<> template<> + void permission_object_t::test<20>() + { + LLPermissions perm,perm1; + LLUUID creator("abf0d56b-82e5-47a2-a8ad-74741bb2c29e"); + LLUUID owner("68edcf47-ccd7-45b8-9f90-1649d7f12806"); + LLUUID lastOwner("5e47a0dc-97bf-44e0-8b40-de06718cee9d"); + LLUUID group("9c8eca51-53d5-42a7-bb58-cef070395db8"); + perm.init(creator,owner,lastOwner,group); + + U32 base = PERM_TRANSFER | PERM_COPY; + U32 ownerp = PERM_TRANSFER; + U32 groupp = PERM_TRANSFER; + U32 everyone = PERM_TRANSFER; + U32 next = PERM_NONE; + + perm.initMasks(base, ownerp, everyone, groupp, next); + + std::ostringstream ostream; + perm.exportLegacyStream(ostream); + std::istringstream istream(ostream.str()); + perm1.importLegacyStream(istream); + + ensure_equals("exportStream()/importStream():failed to export and import the data ", perm1, perm); + } + + template<> template<> + void permission_object_t::test<21>() + { + LLPermissions perm,perm1; + LLUUID creator("abf0d56b-82e5-47a2-a8ad-74741bb2c29e"); + LLUUID owner("68edcf47-ccd7-45b8-9f90-1649d7f12806"); + LLUUID lastOwner("5e47a0dc-97bf-44e0-8b40-de06718cee9d"); + LLUUID group("9c8eca51-53d5-42a7-bb58-cef070395db8"); + perm.init(creator,owner,lastOwner,group); + std::ostringstream stream1, stream2; + stream1 << perm; + perm1.init(creator,owner,lastOwner,group); + stream2 << perm1; + ensure_equals("1:operator << failed", stream1.str(), stream2.str()); + } + + template<> template<> + void permission_object_t::test<22>() + { + LLPermissions perm,perm1; + LLUUID creator("abf0d56b-82e5-47a2-a8ad-74741bb2c29e"); + LLUUID owner("68edcf47-ccd7-45b8-9f90-1649d7f12806"); + LLUUID lastOwner("5e47a0dc-97bf-44e0-8b40-de06718cee9d"); + LLUUID group("9c8eca51-53d5-42a7-bb58-cef070395db8"); + perm.init(creator,owner,lastOwner,group); + + U32 base = PERM_TRANSFER | PERM_COPY; + U32 ownerp = PERM_TRANSFER; + U32 groupp = PERM_TRANSFER; + U32 everyone = PERM_TRANSFER; + U32 next = PERM_NONE; + + perm.initMasks(base, ownerp, everyone, groupp, next); + + LLSD sd = ll_create_sd_from_permissions(perm); + perm1 = ll_permissions_from_sd(sd); + ensure_equals("ll_permissions_from_sd() and ll_create_sd_from_permissions()functions failed", perm, perm1); + } + + template<> template<> + void permission_object_t::test<23>() + { + LLAggregatePermissions AggrPermission; + LLAggregatePermissions AggrPermission1; + ensure_equals("getU8() function failed", AggrPermission.getU8(), 0); + ensure("isEmpty() function failed", AggrPermission.isEmpty()); + AggrPermission.getValue(PERM_TRANSFER); + ensure_equals("getValue() function failed", AggrPermission.getValue(PERM_TRANSFER), 0x00); + + AggrPermission.aggregate(PERM_ITEM_UNRESTRICTED); + ensure("aggregate() function failed", ! AggrPermission.isEmpty()); + + AggrPermission1.aggregate(AggrPermission); + ensure("aggregate() function failed", ! AggrPermission1.isEmpty()); + + std::ostringstream stream1; + stream1 << AggrPermission; + ensure_equals("operator<< failed", stream1.str(), "{PI_COPY=All, PI_MODIFY=All, PI_TRANSFER=All}"); + } +} diff --git a/indra/llinventory/tests/llsaleinfo_test.cpp b/indra/llinventory/tests/llsaleinfo_test.cpp new file mode 100644 index 0000000000..1da7101aa3 --- /dev/null +++ b/indra/llinventory/tests/llsaleinfo_test.cpp @@ -0,0 +1,194 @@ +/** + * @file LLSaleInfo_tut.cpp + * @author Adroit + * @date 2007-03 + * @brief Test cases of llsaleinfo.h + * + * $LicenseInfo:firstyear=2007&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2010, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +#include +#include "linden_common.h" +#include "lltut.h" +#include "llsaleinfo.h" + +namespace tut +{ + struct llsaleinfo_tut + { + }; + typedef test_group llsaleinfo_tut_t; + typedef llsaleinfo_tut_t::object llsaleinfo_test_t; + tut::llsaleinfo_tut_t tut_llsaleinfo_test("llsaleinfo"); + + template<> template<> + void llsaleinfo_test_t::test<1>() + { + //test case for getSaleType(), getSalePrice(), getCRC32() fn. + //test case for setSaleType(), setSalePrice() fn. + + S32 sale_price = 10000; + LLSaleInfo llsaleinfo(LLSaleInfo::FS_COPY, sale_price); + const char* sale= "copy"; + + LLSD llsd_obj1 = ll_create_sd_from_sale_info(llsaleinfo); + LLSaleInfo saleinfo1 = ll_sale_info_from_sd(llsd_obj1); + + ensure("1. The getSaleType() fn failed", LLSaleInfo::FS_COPY == llsaleinfo.getSaleType()); + ensure("2. LLSaleInfo::isForSale() fn failed", true == llsaleinfo.isForSale()); + ensure("3. The getSalePrice() fn failed", sale_price == llsaleinfo.getSalePrice()); + ensure("4. The getCRC32() fn failed", 235833404 == llsaleinfo.getCRC32()); + ensure("5. LLSaleInfo::lookup(const char* name) fn failed", LLSaleInfo::FS_COPY == llsaleinfo.lookup(sale)); + ensure_equals("6. ll_create_sd_from_sale_info() fn failed", llsaleinfo.getSalePrice(), saleinfo1.getSalePrice()); + ensure_equals("7. ll_create_sd_from_sale_info() fn failed", llsaleinfo.getSaleType(), saleinfo1.getSaleType()); + + llsaleinfo.setSalePrice(10000000); + llsaleinfo.setSaleType(LLSaleInfo::FS_ORIGINAL); + sale = "cntn"; + llsd_obj1 = ll_create_sd_from_sale_info(llsaleinfo); + saleinfo1 = ll_sale_info_from_sd(llsd_obj1); + + ensure("8. The getSaleType() and setSaleType() fn failed", LLSaleInfo::FS_ORIGINAL == llsaleinfo.getSaleType()); + ensure("9. LLSaleInfo::isForSale() fn failed", true == llsaleinfo.isForSale()); + ensure("10. The getSalePrice() fn failed", 10000000 == llsaleinfo.getSalePrice()); + ensure("11. The getCRC32() fn failed", 127911702 == llsaleinfo.getCRC32()); + ensure("12. LLSaleInfo::lookup(const char* name) fn failed", LLSaleInfo::FS_CONTENTS == llsaleinfo.lookup(sale)); + ensure_equals("13. ll_create_sd_from_sale_info() fn failed", llsaleinfo.getSalePrice(), saleinfo1.getSalePrice()); + ensure_equals("14. ll_create_sd_from_sale_info() fn failed", llsaleinfo.getSaleType(), saleinfo1.getSaleType()); + + llsaleinfo.setSalePrice(55000550); + llsaleinfo.setSaleType(LLSaleInfo::FS_CONTENTS); + sale = "orig"; + llsd_obj1 = ll_create_sd_from_sale_info(llsaleinfo); + saleinfo1 = ll_sale_info_from_sd(llsd_obj1); + + ensure("15. The getSaleType() and setSaleType() fn failed", LLSaleInfo::FS_CONTENTS == llsaleinfo.getSaleType()); + ensure("16. LLSaleInfo::isForSale() fn failed", true == llsaleinfo.isForSale()); + ensure("17. The getSalePrice() fn failed", 55000550 == llsaleinfo.getSalePrice()); + ensure("18. The getCRC32() fn failed", 408735656 == llsaleinfo.getCRC32()); + ensure("19. LLSaleInfo::lookup(const char* name) fn failed", LLSaleInfo::FS_ORIGINAL == llsaleinfo.lookup(sale)); + ensure_equals("20. ll_create_sd_from_sale_info() fn failed", llsaleinfo.getSalePrice(), saleinfo1.getSalePrice()); + ensure_equals("21. ll_create_sd_from_sale_info() fn failed", llsaleinfo.getSaleType(), saleinfo1.getSaleType()); + + llsaleinfo.setSalePrice(-6432); + llsaleinfo.setSaleType(LLSaleInfo::FS_NOT); + sale = "not"; + llsd_obj1 = ll_create_sd_from_sale_info(llsaleinfo); + saleinfo1 = ll_sale_info_from_sd(llsd_obj1); + + ensure("22. The getSaleType() and setSaleType() fn failed", LLSaleInfo::FS_NOT == llsaleinfo.getSaleType()); + ensure("23. LLSaleInfo::isForSale() fn failed", false == llsaleinfo.isForSale()); + ensure("24. The getSalePrice() fn failed", 0 == llsaleinfo.getSalePrice()); + ensure("25. The getCRC32() fn failed", 0 == llsaleinfo.getCRC32()); + ensure("26. LLSaleInfo::lookup(const char* name) fn failed", LLSaleInfo::FS_NOT == llsaleinfo.lookup(sale)); + ensure_equals("27. ll_create_sd_from_sale_info() fn failed", llsaleinfo.getSalePrice(), saleinfo1.getSalePrice()); + ensure_equals("28. ll_create_sd_from_sale_info() fn failed", llsaleinfo.getSaleType(), saleinfo1.getSaleType()); + } + + template<> template<> + void llsaleinfo_test_t::test<2>() + { + S32 sale_price = 525452; + LLSaleInfo llsaleinfo(LLSaleInfo::FS_ORIGINAL, sale_price); + + std::ostringstream ostream; + llsaleinfo.exportLegacyStream(ostream); + + std::istringstream istream(ostream.str()); + LLSaleInfo llsaleinfo1; + U32 perm_mask = 0; + bool has_perm_mask = false; + llsaleinfo1.importLegacyStream(istream, has_perm_mask, perm_mask); + + ensure("importStream() fn failed ", + llsaleinfo.getSalePrice() == llsaleinfo1.getSalePrice() && + llsaleinfo.getSaleType() == llsaleinfo1.getSaleType()); + } + + template<> template<> + void llsaleinfo_test_t::test<3>() + { + S32 sale_price = 99000; + LLSaleInfo saleinfo(LLSaleInfo::FS_ORIGINAL, sale_price); + + LLSD sd_result = saleinfo.asLLSD(); + + U32 perm_mask = 0 ; + bool has_perm_mask = false; + + LLSaleInfo saleinfo1; + saleinfo1.fromLLSD( sd_result, has_perm_mask, perm_mask); + + ensure_equals("asLLSD and fromLLSD failed", saleinfo.getSalePrice(), saleinfo1.getSalePrice()); + ensure_equals("asLLSD and fromLLSD failed", saleinfo.getSaleType(), saleinfo1.getSaleType()); + } + + //static EForSale lookup(const char* name) fn test + template<> template<> + void llsaleinfo_test_t::test<4>() + { + S32 sale_price = 233223; + LLSaleInfo::EForSale ret_type = LLSaleInfo::lookup("orig"); + + ensure_equals("lookup(const char* name) fn failed", ret_type, LLSaleInfo::FS_ORIGINAL); + + LLSaleInfo saleinfo(LLSaleInfo::FS_COPY, sale_price); + const char* result = LLSaleInfo::lookup(LLSaleInfo::FS_COPY); + ensure("char* lookup(EForSale type) fn failed", 0 == strcmp("copy", result)); + } + + //void LLSaleInfo::accumulate(const LLSaleInfo& sale_info) fn test + template<> template<> + void llsaleinfo_test_t::test<5>() + { + S32 sale_price = 20; + LLSaleInfo saleinfo(LLSaleInfo::FS_COPY, sale_price); + LLSaleInfo saleinfo1(LLSaleInfo::FS_COPY, sale_price); + saleinfo1.accumulate(saleinfo); + ensure_equals("LLSaleInfo::accumulate(const LLSaleInfo& sale_info) fn failed", saleinfo1.getSalePrice(), 40); + + } + + // test cases of bool operator==(const LLSaleInfo &rhs) fn + // test case of bool operator!=(const LLSaleInfo &rhs) fn + template<> template<> + void llsaleinfo_test_t::test<6>() + { + S32 sale_price = 55000; + LLSaleInfo saleinfo(LLSaleInfo::FS_ORIGINAL, sale_price); + LLSaleInfo saleinfoequal(LLSaleInfo::FS_ORIGINAL, sale_price); + LLSaleInfo saleinfonotequal(LLSaleInfo::FS_ORIGINAL, sale_price*2); + + ensure("operator == fn. failed", true == (saleinfo == saleinfoequal)); + ensure("operator != fn. failed", true == (saleinfo != saleinfonotequal)); + } + + template<> template<> + void llsaleinfo_test_t::test<7>() + { + + //TBD: void LLSaleInfo::packMessage(LLMessageSystem* msg) const + //TBD: void LLSaleInfo::unpackMessage(LLMessageSystem* msg, const char* block) + //TBD: void LLSaleInfo::unpackMultiMessage(LLMessageSystem* msg, const char* block, S32 block_num) + } + +} diff --git a/indra/llinventory/tests/lluserrelations_test.cpp b/indra/llinventory/tests/lluserrelations_test.cpp new file mode 100644 index 0000000000..80a659da65 --- /dev/null +++ b/indra/llinventory/tests/lluserrelations_test.cpp @@ -0,0 +1,156 @@ +/** + * @file lluserrelations_tut.cpp + * @author Phoenix + * @date 2006-10-12 + * @brief Unit tests for the LLRelationship class. + * + * $LicenseInfo:firstyear=2006&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2010, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +#include + +#include "linden_common.h" +#include "lluserrelations.h" + +namespace tut +{ + struct user_relationship + { + LLRelationship mRelationship; + }; + typedef test_group user_relationship_t; + typedef user_relationship_t::object user_relationship_object_t; + tut::user_relationship_t tut_user_relationship("relationships"); + + template<> template<> + void user_relationship_object_t::test<1>() + { + // Test the default construction + ensure( + "No granted rights to", + !mRelationship.isRightGrantedTo( + LLRelationship::GRANT_ONLINE_STATUS)); + ensure( + "No granted rights from", + !mRelationship.isRightGrantedFrom( + LLRelationship::GRANT_ONLINE_STATUS)); + ensure("No online status",!mRelationship.isOnline()); + } + + template<> template<> + void user_relationship_object_t::test<2>() + { + // Test some granting + mRelationship.grantRights( + LLRelationship::GRANT_ONLINE_STATUS, + LLRelationship::GRANT_MODIFY_OBJECTS); + ensure( + "Granted rights to has online", + mRelationship.isRightGrantedTo( + LLRelationship::GRANT_ONLINE_STATUS)); + ensure( + "Granted rights from does not have online", + !mRelationship.isRightGrantedFrom( + LLRelationship::GRANT_ONLINE_STATUS)); + ensure( + "Granted rights to does not have modify", + !mRelationship.isRightGrantedTo( + LLRelationship::GRANT_MODIFY_OBJECTS)); + ensure( + "Granted rights from has modify", + mRelationship.isRightGrantedFrom( + LLRelationship::GRANT_MODIFY_OBJECTS)); + } + + template<> template<> + void user_relationship_object_t::test<3>() + { + // Test revoking + mRelationship.grantRights( + LLRelationship::GRANT_ONLINE_STATUS + | LLRelationship::GRANT_MAP_LOCATION, + LLRelationship::GRANT_ONLINE_STATUS); + ensure( + "Granted rights to has online and map", + mRelationship.isRightGrantedTo( + LLRelationship::GRANT_ONLINE_STATUS + | LLRelationship::GRANT_MAP_LOCATION)); + ensure( + "Granted rights from has online", + mRelationship.isRightGrantedFrom( + LLRelationship::GRANT_ONLINE_STATUS)); + + mRelationship.revokeRights( + LLRelationship::GRANT_MAP_LOCATION, + LLRelationship::GRANT_NONE); + ensure( + "Granted rights revoked map", + !mRelationship.isRightGrantedTo( + LLRelationship::GRANT_ONLINE_STATUS + | LLRelationship::GRANT_MAP_LOCATION)); + ensure( + "Granted rights revoked still has online", + mRelationship.isRightGrantedTo( + LLRelationship::GRANT_ONLINE_STATUS)); + + mRelationship.grantRights( + LLRelationship::GRANT_NONE, + LLRelationship::GRANT_MODIFY_OBJECTS); + ensure( + "Granted rights from still has online", + mRelationship.isRightGrantedFrom( + LLRelationship::GRANT_ONLINE_STATUS)); + ensure( + "Granted rights from has full grant", + mRelationship.isRightGrantedFrom( + LLRelationship::GRANT_ONLINE_STATUS + | LLRelationship::GRANT_MODIFY_OBJECTS)); + mRelationship.revokeRights( + LLRelationship::GRANT_NONE, + LLRelationship::GRANT_MODIFY_OBJECTS); + ensure( + "Granted rights from still has online", + mRelationship.isRightGrantedFrom( + LLRelationship::GRANT_ONLINE_STATUS)); + ensure( + "Granted rights from no longer modify", + !mRelationship.isRightGrantedFrom( + LLRelationship::GRANT_MODIFY_OBJECTS)); + } + + template<> template<> + void user_relationship_object_t::test<4>() + { + ensure("No online status", !mRelationship.isOnline()); + mRelationship.online(true); + ensure("Online status", mRelationship.isOnline()); + mRelationship.online(false); + ensure("No online status", !mRelationship.isOnline()); + } + +/* + template<> template<> + void user_relationship_object_t::test<>() + { + } +*/ +} diff --git a/indra/llmessage/CMakeLists.txt b/indra/llmessage/CMakeLists.txt index 86e262f56a..2e51e1b5d4 100644 --- a/indra/llmessage/CMakeLists.txt +++ b/indra/llmessage/CMakeLists.txt @@ -215,9 +215,22 @@ if (LL_TESTS) llcommon ) - #LL_ADD_INTEGRATION_TEST(llavatarnamecache "" "${test_libs}") + LL_ADD_INTEGRATION_TEST(io "tests/llpipeutil.cpp" "${test_libs}") + LL_ADD_INTEGRATION_TEST(llavatarnamecache "" "${test_libs}") + LL_ADD_INTEGRATION_TEST(llbuffer "" "${test_libs}") + LL_ADD_INTEGRATION_TEST(lldatapacker "" "${test_libs}") LL_ADD_INTEGRATION_TEST(llhost "" "${test_libs}") + LL_ADD_INTEGRATION_TEST(llhttpnode "" "${test_libs}") + LL_ADD_INTEGRATION_TEST(lliohttpserver "tests/llpipeutil.cpp" "${test_libs}") + LL_ADD_INTEGRATION_TEST(llsdmessagebuilder "" "${test_libs}") + LL_ADD_INTEGRATION_TEST(llsdmessagereader "" "${test_libs}") + LL_ADD_INTEGRATION_TEST(llmessageconfig "" "${test_libs}") + LL_ADD_INTEGRATION_TEST(llmessagetemplateparser "" "${test_libs}") LL_ADD_INTEGRATION_TEST(llpartdata "" "${test_libs}") + LL_ADD_INTEGRATION_TEST(llservicebuilder "" "${test_libs}") + LL_ADD_INTEGRATION_TEST(lltemplatemessagebuilder "" "${test_libs}") LL_ADD_INTEGRATION_TEST(llxfer_file "" "${test_libs}") + LL_ADD_INTEGRATION_TEST(llxorcipher "" "${test_libs}") + LL_ADD_INTEGRATION_TEST(message "" "${test_libs}") endif (LL_TESTS) diff --git a/indra/llmessage/tests/io_test.cpp b/indra/llmessage/tests/io_test.cpp new file mode 100644 index 0000000000..f77402065a --- /dev/null +++ b/indra/llmessage/tests/io_test.cpp @@ -0,0 +1,1181 @@ +/** + * @file io.cpp + * @author Phoenix + * @date 2005-10-02 + * @brief Tests for io classes and helpers + * + * $LicenseInfo:firstyear=2005&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2010, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +#include "linden_common.h" +#include "lltut.h" + +#include + +#include "apr_pools.h" + +#include "llbuffer.h" +#include "llbufferstream.h" +#include "lliosocket.h" +#include "llioutil.h" +#include "llmemorystream.h" +#include "llpipeutil.h" +#include "llpumpio.h" +#include "llsd.h" +#include "llsdserialize.h" +#include "llcommon.h" +#include "lluuid.h" +#include "llinstantmessage.h" + +namespace tut +{ + struct heap_buffer_data + { + heap_buffer_data() : mBuffer(NULL) {} + ~heap_buffer_data() { if(mBuffer) delete mBuffer; } + LLHeapBuffer* mBuffer; + }; + typedef test_group heap_buffer_test; + typedef heap_buffer_test::object heap_buffer_object; + tut::heap_buffer_test thb("heap_buffer"); + + template<> template<> + void heap_buffer_object::test<1>() + { + const S32 BUF_SIZE = 100; + mBuffer = new LLHeapBuffer(BUF_SIZE); + ensure_equals("empty buffer capacity", mBuffer->capacity(), BUF_SIZE); + const S32 SEGMENT_SIZE = 50; + LLSegment segment; + mBuffer->createSegment(0, SEGMENT_SIZE, segment); + ensure_equals("used buffer capacity", mBuffer->capacity(), BUF_SIZE); + } + + template<> template<> + void heap_buffer_object::test<2>() + { + const S32 BUF_SIZE = 10; + mBuffer = new LLHeapBuffer(BUF_SIZE); + LLSegment segment; + mBuffer->createSegment(0, BUF_SIZE, segment); + ensure("segment is in buffer", mBuffer->containsSegment(segment)); + ensure_equals("buffer consumed", mBuffer->bytesLeft(), 0); + bool created; + created = mBuffer->createSegment(0, 0, segment); + ensure("Create zero size segment fails", !created); + created = mBuffer->createSegment(0, BUF_SIZE, segment); + ensure("Create segment fails", !created); + } + + template<> template<> + void heap_buffer_object::test<3>() + { + const S32 BUF_SIZE = 10; + mBuffer = new LLHeapBuffer(BUF_SIZE); + LLSegment segment; + mBuffer->createSegment(0, BUF_SIZE, segment); + ensure("segment is in buffer", mBuffer->containsSegment(segment)); + ensure_equals("buffer consumed", mBuffer->bytesLeft(), 0); + bool reclaimed = mBuffer->reclaimSegment(segment); + ensure("buffer reclaimed.", reclaimed); + ensure_equals("buffer available", mBuffer->bytesLeft(), BUF_SIZE); + bool created; + created = mBuffer->createSegment(0, 0, segment); + ensure("Create zero size segment fails", !created); + created = mBuffer->createSegment(0, BUF_SIZE, segment); + ensure("Create another segment succeeds", created); + } + + template<> template<> + void heap_buffer_object::test<4>() + { + const S32 BUF_SIZE = 10; + const S32 SEGMENT_SIZE = 4; + mBuffer = new LLHeapBuffer(BUF_SIZE); + LLSegment seg1; + mBuffer->createSegment(0, SEGMENT_SIZE, seg1); + ensure("segment is in buffer", mBuffer->containsSegment(seg1)); + LLSegment seg2; + mBuffer->createSegment(0, SEGMENT_SIZE, seg2); + ensure("segment is in buffer", mBuffer->containsSegment(seg2)); + LLSegment seg3; + mBuffer->createSegment(0, SEGMENT_SIZE, seg3); + ensure("segment is in buffer", mBuffer->containsSegment(seg3)); + ensure_equals("segment is truncated", seg3.size(), 2); + LLSegment seg4; + bool created; + created = mBuffer->createSegment(0, SEGMENT_SIZE, seg4); + ensure("Create segment fails", !created); + bool reclaimed; + reclaimed = mBuffer->reclaimSegment(seg1); + ensure("buffer reclaim succeed.", reclaimed); + ensure_equals("no buffer available", mBuffer->bytesLeft(), 0); + reclaimed = mBuffer->reclaimSegment(seg2); + ensure("buffer reclaim succeed.", reclaimed); + ensure_equals("buffer reclaimed", mBuffer->bytesLeft(), 0); + reclaimed = mBuffer->reclaimSegment(seg3); + ensure("buffer reclaim succeed.", reclaimed); + ensure_equals("buffer reclaimed", mBuffer->bytesLeft(), BUF_SIZE); + created = mBuffer->createSegment(0, SEGMENT_SIZE, seg1); + ensure("segment is in buffer", mBuffer->containsSegment(seg1)); + ensure("Create segment succeds", created); + } +} + +namespace tut +{ + struct buffer_data + { + LLBufferArray mBuffer; + }; + typedef test_group buffer_test; + typedef buffer_test::object buffer_object; + tut::buffer_test tba("buffer_array"); + + template<> template<> + void buffer_object::test<1>() + { + const char HELLO_WORLD[] = "hello world"; + const S32 str_len = static_cast(strlen(HELLO_WORLD)); + LLChannelDescriptors ch = mBuffer.nextChannel(); + mBuffer.append(ch.in(), (U8*)HELLO_WORLD, str_len); + S32 count = mBuffer.countAfter(ch.in(), NULL); + ensure_equals("total append size", count, str_len); + LLBufferArray::segment_iterator_t it = mBuffer.beginSegment(); + U8* first = (*it).data(); + count = mBuffer.countAfter(ch.in(), first); + ensure_equals("offset append size", count, str_len - 1); + } + + template<> template<> + void buffer_object::test<2>() + { + const char HELLO_WORLD[] = "hello world"; + const S32 str_len = static_cast(strlen(HELLO_WORLD)); /* Flawfinder: ignore */ + LLChannelDescriptors ch = mBuffer.nextChannel(); + mBuffer.append(ch.in(), (U8*)HELLO_WORLD, str_len); + mBuffer.append(ch.in(), (U8*)HELLO_WORLD, str_len); + S32 count = mBuffer.countAfter(ch.in(), NULL); + ensure_equals("total append size", count, 2 * str_len); + LLBufferArray::segment_iterator_t it = mBuffer.beginSegment(); + U8* first = (*it).data(); + count = mBuffer.countAfter(ch.in(), first); + ensure_equals("offset append size", count, (2 * str_len) - 1); + } + + template<> template<> + void buffer_object::test<3>() + { + const char ONE[] = "one"; + const char TWO[] = "two"; + std::string expected(ONE); + expected.append(TWO); + LLChannelDescriptors ch = mBuffer.nextChannel(); + mBuffer.append(ch.in(), (U8*)ONE, 3); + mBuffer.append(ch.in(), (U8*)TWO, 3); + char buffer[255]; /* Flawfinder: ignore */ + S32 len = 6; + mBuffer.readAfter(ch.in(), NULL, (U8*)buffer, len); + ensure_equals(len, 6); + buffer[len] = '\0'; + std::string actual(buffer); + ensure_equals("read", actual, expected); + } + + template<> template<> + void buffer_object::test<4>() + { + const char ONE[] = "one"; + const char TWO[] = "two"; + std::string expected(ONE); + expected.append(TWO); + LLChannelDescriptors ch = mBuffer.nextChannel(); + mBuffer.append(ch.in(), (U8*)TWO, 3); + mBuffer.prepend(ch.in(), (U8*)ONE, 3); + char buffer[255]; /* Flawfinder: ignore */ + S32 len = 6; + mBuffer.readAfter(ch.in(), NULL, (U8*)buffer, len); + ensure_equals(len, 6); + buffer[len] = '\0'; + std::string actual(buffer); + ensure_equals("read", actual, expected); + } + + template<> template<> + void buffer_object::test<5>() + { + const char ONE[] = "one"; + const char TWO[] = "two"; + std::string expected("netwo"); + LLChannelDescriptors ch = mBuffer.nextChannel(); + mBuffer.append(ch.in(), (U8*)TWO, 3); + mBuffer.prepend(ch.in(), (U8*)ONE, 3); + char buffer[255]; /* Flawfinder: ignore */ + S32 len = 5; + LLBufferArray::segment_iterator_t it = mBuffer.beginSegment(); + U8* addr = (*it).data(); + mBuffer.readAfter(ch.in(), addr, (U8*)buffer, len); + ensure_equals(len, 5); + buffer[len] = '\0'; + std::string actual(buffer); + ensure_equals("read", actual, expected); + } + + template<> template<> + void buffer_object::test<6>() + { + std::string request("The early bird catches the worm."); + std::string response("If you're a worm, sleep late."); + std::ostringstream expected; + expected << "ContentLength: " << response.length() << "\r\n\r\n" + << response; + LLChannelDescriptors ch = mBuffer.nextChannel(); + mBuffer.append(ch.in(), (U8*)request.c_str(), static_cast(request.length())); + mBuffer.append(ch.out(), (U8*)response.c_str(), static_cast(response.length())); + S32 count = mBuffer.countAfter(ch.out(), NULL); + std::ostringstream header; + header << "ContentLength: " << count << "\r\n\r\n"; + std::string head(header.str()); + mBuffer.prepend(ch.out(), (U8*)head.c_str(), static_cast(head.length())); + char buffer[1024]; /* Flawfinder: ignore */ + S32 len = static_cast(response.size() + head.length()); + ensure_equals("same length", len, (S32)expected.str().length()); + mBuffer.readAfter(ch.out(), NULL, (U8*)buffer, len); + buffer[len] = '\0'; + std::string actual(buffer); + ensure_equals("threaded writes", actual, expected.str()); + } + + template<> template<> + void buffer_object::test<7>() + { + const S32 LINE_COUNT = 3; + std::string lines[LINE_COUNT] = + { + std::string("GET /index.htm HTTP/1.0\r\n"), + std::string("User-Agent: Wget/1.9.1\r\n"), + std::string("Host: localhost:8008\r\n") + }; + std::string text; + S32 i; + for(i = 0; i < LINE_COUNT; ++i) + { + text.append(lines[i]); + } + LLChannelDescriptors ch = mBuffer.nextChannel(); + mBuffer.append(ch.in(), (U8*)text.c_str(), static_cast(text.length())); + const S32 BUFFER_LEN = 1024; + char buf[BUFFER_LEN]; + S32 len; + U8* last = NULL; + std::string last_line; + for(i = 0; i < LINE_COUNT; ++i) + { + len = BUFFER_LEN; + last = mBuffer.readAfter(ch.in(), last, (U8*)buf, len); + char* newline = strchr((char*)buf, '\n'); + S32 offset = -((len - 1) - (S32)(newline - buf)); + ++newline; + *newline = '\0'; + last_line.assign(buf); + std::ostringstream message; + message << "line reads in line[" << i << "]"; + ensure_equals(message.str().c_str(), last_line, lines[i]); + last = mBuffer.seek(ch.in(), last, offset); + } + } + + template<> template<> + void buffer_object::test<8>() + { + LLChannelDescriptors ch = mBuffer.nextChannel(); + mBuffer.append(ch.in(), (U8*)"1", 1); + LLBufferArray buffer; + buffer.append(ch.in(), (U8*)"2", 1); + mBuffer.takeContents(buffer); + mBuffer.append(ch.in(), (U8*)"3", 1); + S32 count = mBuffer.countAfter(ch.in(), NULL); + ensure_equals("buffer size", count, 3); + U8* temp = new U8[count]; + mBuffer.readAfter(ch.in(), NULL, temp, count); + ensure("buffer content", (0 == memcmp(temp, (void*)"123", 3))); + delete[] temp; + } + + template<> template<> + void buffer_object::test<9>() + { + LLChannelDescriptors ch = mBuffer.nextChannel(); + mBuffer.append(ch.in(), (U8*)"1", 1); + S32 capacity = mBuffer.capacity(); + ensure("has capacity", capacity > 0); + U8* temp = new U8[capacity - 1]; + mBuffer.append(ch.in(), temp, capacity - 1); + capacity = mBuffer.capacity(); + ensure("has capacity when full", capacity > 0); + S32 used = mBuffer.countAfter(ch.in(), NULL); + ensure_equals("used equals capacity", used, capacity); + + LLBufferArray::segment_iterator_t iter = mBuffer.beginSegment(); + while(iter != mBuffer.endSegment()) + { + mBuffer.eraseSegment(iter++); + } + + used = mBuffer.countAfter(ch.in(), NULL); + ensure_equals("used is zero", used, 0); + S32 capacity2 = mBuffer.capacity(); + ensure_equals("capacity the same after erase", capacity2, capacity); + mBuffer.append(ch.in(), temp, capacity - 1); + capacity2 = mBuffer.capacity(); + ensure_equals("capacity the same after append", capacity2, capacity); + + delete[] temp; + } + +#if 0 + template<> template<> + void buffer_object::test<9>() + { + char buffer[1024]; /* Flawfinder: ignore */ + S32 size = sprintf(buffer, + "%d|%d|%s|%s|%s|%s|%s|%x|%x|%x|%x|%x|%s|%s|%d|%d|%x", + 7, + 7, + "Hang Glider INFO", + "18e84d1e-04a4-4c0d-8cb6-6c73477f0a9a", + "0e346d8b-4433-4d66-a6b0-fd37083abc4c", + "0e346d8b-4433-4d66-a6b0-fd37083abc4c", + "00000000-0000-0000-0000-000000000000", + 0x7fffffff, + 0x7fffffff, + 0, + 0, + 0x7fffffff, + "69e0d357-2e7c-8990-a2bc-7f61c868e5a3", + "2004-06-04 16:09:17 note card", + 0, + 10, + 0) + 1; + + //const char* expected = "7|7|Hang Glider INFO|18e84d1e-04a4-4c0d-8cb6-6c73477f0a9a|0e346d8b-4433-4d66-a6b0-fd37083abc4c|0e346d8b-4433-4d66-a6b0-fd37083abc4c|00000000-0000-0000-0000-000000000000|7fffffff|7fffffff|0|0|7fffffff|69e0d357-2e7c-8990-a2bc-7f61c868e5a3|2004-06-04 16:09:17 note card|0|10|0\0"; + + LLSD* bin_bucket = LLIMInfo::buildSDfrombuffer((U8*)buffer,size); + + char post_buffer[1024]; + U32 post_size; + LLIMInfo::getBinaryBucket(bin_bucket,(U8*)post_buffer,post_size); + ensure_equals("Buffer sizes",size,(S32)post_size); + ensure("Buffer content",!strcmp(buffer,post_buffer)); + } +#endif + + /* + template<> template<> + void buffer_object::test<>() + { + } + */ +} + +namespace tut +{ + struct buffer_and_stream_data + { + LLBufferArray mBuffer; + }; + typedef test_group bas_test; + typedef bas_test::object bas_object; + tut::bas_test tbs("buffer_stream"); + + template<> template<> + void bas_object::test<1>() + { + const char HELLO_WORLD[] = "hello world"; + const S32 str_len = static_cast(strlen(HELLO_WORLD)); /* Flawfinder: ignore */ + LLChannelDescriptors ch = mBuffer.nextChannel(); + LLBufferStream str(ch, &mBuffer); + mBuffer.append(ch.in(), (U8*)HELLO_WORLD, str_len); + std::string hello; + std::string world; + str >> hello >> world; + ensure_equals("first word", hello, std::string("hello")); + ensure_equals("second word", world, std::string("world")); + } + + template<> template<> + void bas_object::test<2>() + { + std::string part1("Eat my shor"); + std::string part2("ts ho"); + std::string part3("mer"); + std::string ignore("ignore me"); + LLChannelDescriptors ch = mBuffer.nextChannel(); + LLBufferStream str(ch, &mBuffer); + mBuffer.append(ch.in(), (U8*)part1.c_str(), static_cast(part1.length())); + mBuffer.append(ch.in(), (U8*)part2.c_str(), static_cast(part2.length())); + mBuffer.append(ch.out(), (U8*)ignore.c_str(), static_cast(ignore.length())); + mBuffer.append(ch.in(), (U8*)part3.c_str(), static_cast(part3.length())); + std::string eat; + std::string my; + std::string shorts; + std::string homer; + str >> eat >> my >> shorts >> homer; + ensure_equals("word1", eat, std::string("Eat")); + ensure_equals("word2", my, std::string("my")); + ensure_equals("word3", shorts, std::string("shorts")); + ensure_equals("word4", homer, std::string("homer")); + } + + template<> template<> + void bas_object::test<3>() + { + std::string part1("junk in "); + std::string part2("the trunk"); + const S32 CHANNEL = 0; + mBuffer.append(CHANNEL, (U8*)part1.c_str(), static_cast(part1.length())); + mBuffer.append(CHANNEL, (U8*)part2.c_str(), static_cast(part2.length())); + U8* last = 0; + const S32 BUF_LEN = 128; + char buf[BUF_LEN]; + S32 len = 11; + last = mBuffer.readAfter(CHANNEL, last, (U8*)buf, len); + buf[len] = '\0'; + std::string actual(buf); + ensure_equals("first read", actual, std::string("junk in the")); + last = mBuffer.seek(CHANNEL, last, -6); + len = 12; + last = mBuffer.readAfter(CHANNEL, last, (U8*)buf, len); + buf[len] = '\0'; + actual.assign(buf); + ensure_equals("seek and read", actual, std::string("in the trunk")); + } + + template<> template<> + void bas_object::test<4>() + { + std::string phrase("zippity do da!"); + const S32 CHANNEL = 0; + mBuffer.append(CHANNEL, (U8*)phrase.c_str(), static_cast(phrase.length())); + const S32 BUF_LEN = 128; + char buf[BUF_LEN]; + S32 len = 7; + U8* last = mBuffer.readAfter(CHANNEL, NULL, (U8*)buf, len); + mBuffer.splitAfter(last); + LLBufferArray::segment_iterator_t it = mBuffer.beginSegment(); + LLBufferArray::segment_iterator_t end = mBuffer.endSegment(); + std::string first((char*)((*it).data()), (*it).size()); + ensure_equals("first part", first, std::string("zippity")); + ++it; + std::string second((char*)((*it).data()), (*it).size()); + ensure_equals("second part", second, std::string(" do da!")); + ++it; + ensure("iterators equal", (it == end)); + } + + template<> template<> + void bas_object::test<5>() + { + LLChannelDescriptors ch = mBuffer.nextChannel(); + LLBufferStream str(ch, &mBuffer); + std::string h1("hello"); + std::string h2(", how are you doing?"); + std::string expected(h1); + expected.append(h2); + str << h1 << h2; + str.flush(); + const S32 BUF_LEN = 128; + char buf[BUF_LEN]; + S32 actual_len = BUF_LEN; + S32 expected_len = static_cast(h1.size() + h2.size()); + (void) mBuffer.readAfter(ch.out(), NULL, (U8*)buf, actual_len); + ensure_equals("streamed size", actual_len, expected_len); + buf[actual_len] = '\0'; + std::string actual(buf); + ensure_equals("streamed to buf", actual, expected); + } + + template<> template<> + void bas_object::test<6>() + { + LLChannelDescriptors ch = mBuffer.nextChannel(); + LLBufferStream bstr(ch, &mBuffer); + std::ostringstream ostr; + std::vector ids; + LLUUID id; + for(int i = 0; i < 5; ++i) + { + id.generate(); + ids.push_back(id); + } + bstr << "SELECT concat(u.username, ' ', l.name) " + << "FROM user u, user_last_name l " + << "WHERE u.last_name_id = l.last_name_id" + << " AND u.agent_id IN ('"; + ostr << "SELECT concat(u.username, ' ', l.name) " + << "FROM user u, user_last_name l " + << "WHERE u.last_name_id = l.last_name_id" + << " AND u.agent_id IN ('"; + std::copy( + ids.begin(), + ids.end(), + std::ostream_iterator(bstr, "','")); + std::copy( + ids.begin(), + ids.end(), + std::ostream_iterator(ostr, "','")); + bstr.seekp(-2, std::ios::cur); + ostr.seekp(-2, std::ios::cur); + bstr << ") "; + ostr << ") "; + bstr.flush(); + const S32 BUF_LEN = 512; + char buf[BUF_LEN]; /* Flawfinder: ignore */ + S32 actual_len = BUF_LEN; + (void) mBuffer.readAfter(ch.out(), NULL, (U8*)buf, actual_len); + buf[actual_len] = '\0'; + std::string actual(buf); + std::string expected(ostr.str()); + ensure_equals("size of string in seek",actual.size(),expected.size()); + ensure_equals("seek in ostream", actual, expected); + } + + template<> template<> + void bas_object::test<7>() + { + LLChannelDescriptors ch = mBuffer.nextChannel(); + LLBufferStream bstr(ch, &mBuffer); + bstr << "1"; + bstr.flush(); + S32 count = mBuffer.countAfter(ch.out(), NULL); + ensure_equals("buffer size 1", count, 1); + LLBufferArray buffer; + buffer.append(ch.out(), (U8*)"2", 1); + mBuffer.takeContents(buffer); + count = mBuffer.countAfter(ch.out(), NULL); + ensure_equals("buffer size 2", count, 2); + bstr << "3"; + bstr.flush(); + count = mBuffer.countAfter(ch.out(), NULL); + ensure_equals("buffer size 3", count, 3); + U8* temp = new U8[count]; + mBuffer.readAfter(ch.out(), NULL, temp, count); + ensure("buffer content", (0 == memcmp(temp, (void*)"123", 3))); + delete[] temp; + } + + template<> template<> + void bas_object::test<8>() + { + LLChannelDescriptors ch = mBuffer.nextChannel(); + LLBufferStream ostr(ch, &mBuffer); + typedef std::vector buf_t; + typedef std::vector actual_t; + actual_t actual; + buf_t source; + bool need_comma = false; + ostr << "["; + S32 total_size = 1; + for(S32 i = 2000; i < 2003; ++i) + { + if(need_comma) + { + ostr << ","; + ++total_size; + } + need_comma = true; + srand(69 + i); /* Flawfinder: ignore */ + S32 size = rand() % 1000 + 1000; + std::generate_n( + std::back_insert_iterator(source), + size, + rand); + actual.push_back(source); + ostr << "b(" << size << ")\""; + total_size += 8; + ostr.write((const char*)(&source[0]), size); + total_size += size; + source.clear(); + ostr << "\""; + ++total_size; + } + ostr << "]"; + ++total_size; + ostr.flush(); + + // now that we have a bunch of data on a stream, parse it all. + ch = mBuffer.nextChannel(); + S32 count = mBuffer.countAfter(ch.in(), NULL); + ensure_equals("size of buffer", count, total_size); + LLBufferStream istr(ch, &mBuffer); + LLSD data; + count = LLSDSerialize::fromNotation(data, istr, total_size); + ensure("sd parsed", data.isDefined()); + + for(S32 j = 0; j < 3; ++j) + { + std::ostringstream name; + LLSD child(data[j]); + name << "found buffer " << j; + ensure(name.str(), child.isDefined()); + source = child.asBinary(); + name.str(""); + name << "buffer " << j << " size"; + ensure_equals(name.str().c_str(), source.size(), actual[j].size()); + name.str(""); + name << "buffer " << j << " contents"; + ensure( + name.str(), + (0 == memcmp(&source[0], &actual[j][0], source.size()))); + } + } + + template<> template<> + void bas_object::test<9>() + { + LLChannelDescriptors ch = mBuffer.nextChannel(); + LLBufferStream ostr(ch, &mBuffer); + typedef std::vector buf_t; + buf_t source; + bool need_comma = false; + ostr << "{"; + S32 total_size = 1; + for(S32 i = 1000; i < 3000; ++i) + { + if(need_comma) + { + ostr << ","; + ++total_size; + } + need_comma = true; + ostr << "'" << i << "':"; + total_size += 7; + srand(69 + i); /* Flawfinder: ignore */ + S32 size = rand() % 1000 + 1000; + std::generate_n( + std::back_insert_iterator(source), + size, + rand); + ostr << "b(" << size << ")\""; + total_size += 8; + ostr.write((const char*)(&source[0]), size); + total_size += size; + source.clear(); + ostr << "\""; + ++total_size; + } + ostr << "}"; + ++total_size; + ostr.flush(); + + // now that we have a bunch of data on a stream, parse it all. + ch = mBuffer.nextChannel(); + S32 count = mBuffer.countAfter(ch.in(), NULL); + ensure_equals("size of buffer", count, total_size); + LLBufferStream istr(ch, &mBuffer); + LLSD data; + count = LLSDSerialize::fromNotation(data, istr, total_size); + ensure("sd parsed", data.isDefined()); + } + + template<> template<> + void bas_object::test<10>() + { +//#if LL_WINDOWS && _MSC_VER >= 1400 +// skip_fail("Fails on VS2005 due to broken LLSDSerialize::fromNotation() parser."); +//#endif + const char LOGIN_STREAM[] = "{'method':'login', 'parameter': [ {" + "'uri': 'sl-am:kellys.region.siva.lindenlab.com/location?start=url&px=128&py=128&pz=128&lx=0&ly=0&lz=0'}, " + "{'version': i1}, {'texture_data': [ '61d724fb-ad79-f637-2186-5cf457560daa', '6e38b9be-b7cc-e77a-8aec-029a42b0b416', " + "'a9073524-e89b-2924-ca6e-a81944109a1a', '658f18b5-5f1e-e593-f5d5-36c3abc7249a', '0cc799f4-8c99-6b91-bd75-b179b12429e2', " + "'59fd9b64-8300-a425-aad8-2ffcbe9a49d2', '59fd9b64-8300-a425-aad8-2ffcbe9a49d2', '5748decc-f629-461c-9a36-a35a221fe21f', " + "'b8fc9be2-26a6-6b47-690b-0e902e983484', 'a13ca0fe-3802-dc97-e79a-70d12171c724', 'dd9643cf-fd5d-0376-ed4a-b1cc646a97d5', " + "'4ad13ae9-a112-af09-210a-cf9353a7a9e7', 'c228d1cf-4b5d-4ba8-84f4-899a0796aa97', 'c228d1cf-4b5d-4ba8-84f4-899a0796aa97', " + "'c228d1cf-4b5d-4ba8-84f4-899a0796aa97', 'c228d1cf-4b5d-4ba8-84f4-899a0796aa97', 'c228d1cf-4b5d-4ba8-84f4-899a0796aa97', " + "'5748decc-f629-461c-9a36-a35a221fe21f', 'c228d1cf-4b5d-4ba8-84f4-899a0796aa97', 'c228d1cf-4b5d-4ba8-84f4-899a0796aa97']," + "'session_id': '324cfa9f-fe5d-4d1c-a317-35f20a86a4d1','position': [ i128, i128, i128],'last_name': 'Linden','group_title': '-> !BLING! <-','group_name': 'test!','agent_access': 'M'," + "'attachment_data': [ {'asset_id': 'aaede2b1-9955-09d4-5c93-2b557c778cf3','attachment_point': i6,'item_id': 'f3694abc-5122-db33-73d9-e0f4288dc2bf'}]," + "'buddy_ids': [ '101358d5-469d-4b24-9b85-4dc3c05e635d', '1b00fec7-6265-4875-acac-80d9cfe9295c', '203ad6df-b522-491d-ba48-4e24eb57aeff', " + "'22d4dcdb-aebb-47fa-b925-a871cc75ee48','27da3df5-1339-4463-80aa-40504ee3b3e5', '299d1720-b61f-4268-8c29-9614aa2d44c2', " + "'2b048a24-2737-4994-9fa5-becc8e466253', '2cd5dc14-a853-49a4-be3c-a5a7178e37bc', '3de548e1-57be-cfea-2b78-83ae3ad95998', " + "'3dee98e4-a6a3-4543-91c3-bbd528447ba7', '3e2d81a3-6263-6ffe-ad5c-8ce04bee07e9', '40e70b98-fed7-47f3-9700-1bce93f9350b', " + "'50a9b68e-b5aa-4d35-9137-3cfebda0a15c', '54295571-9357-43ff-ae74-a83b5138160f', '6191e2d7-5f96-4856-bdab-af0f79f47ae4', " + "'63e577d8-cd34-4235-a0a3-de0500133364', '79cfb666-4fd0-4af7-95df-fb7d96b4e24d', '8121c2f3-4a88-4c33-9899-8fc1273f47ee', " + "'909da964-ef23-4f2a-ba13-f2a8cfd454b6','a2e76fcd-9360-4f6d-a924-000000000001', 'aaa6d664-527e-4d83-9cbb-7ef79ccc7cc8', " + "'b79bfb6c-23be-49eb-b35b-30ff2f501b37', 'ba0d9c79-148c-4a79-8e3c-0665eebe2427', 'bc9bda98-57cd-498f-b993-4ff1ac9dec93', " + "'c62d16f6-81cb-419d-9cac-e46dc394084d', 'd48f8fa7-2512-4fe5-80c8-c0a923412e07', 'd77e3e24-7e6c-4c3f-96d0-a1746337f8fb', " + "'da615c63-a84b-4592-a3d6-a90dd3e92e6e', 'df47190a-7eb7-4aff-985f-2d1d3ad6c6e9', 'e3380196-72cd-499c-a2ba-caa180bd5fe4', " + "'e937863f-f134-4207-803b-d6e686651d6c', 'efcdf98b-5269-45ef-ac7a-0671f09ea9d9']," + "'circuit_code': i124,'group_id': '8615c885-9cf0-bf0a-6e40-0c11462aa652','limited_to_estate': i1,'look_at': [ i0, i0, i0]," + "'agent_id': '0e346d8b-4433-4d66-a6b0-fd37083abc4c','first_name': 'Kelly','start': 'url'}]}"; + LLChannelDescriptors ch = mBuffer.nextChannel(); + mBuffer.append(ch.out(), (U8*)LOGIN_STREAM, static_cast(strlen(LOGIN_STREAM))); /* Flawfinder: ignore */ + ch = mBuffer.nextChannel(); + LLBufferStream istr(ch, &mBuffer); + LLSD data; + S32 count = LLSDSerialize::fromNotation( + data, + istr, + mBuffer.count(ch.in())); + ensure("parsed something", (count > 0)); + ensure("sd parsed", data.isDefined()); + ensure_equals("sd type", data.type(), LLSD::TypeMap); + ensure("has method", data.has("method")); + ensure("has parameter", data.has("parameter")); + LLSD parameter = data["parameter"]; + ensure_equals("parameter is array", parameter.type(), LLSD::TypeArray); + LLSD agent_params = parameter[2]; + std::string s_value; + s_value = agent_params["last_name"].asString(); + ensure_equals("last name", s_value, std::string("Linden")); + s_value = agent_params["first_name"].asString(); + ensure_equals("first name", s_value, std::string("Kelly")); + s_value = agent_params["agent_access"].asString(); + ensure_equals("agent access", s_value, std::string("M")); + s_value = agent_params["group_name"].asString(); + ensure_equals("group name", s_value, std::string("test!")); + s_value = agent_params["group_title"].asString(); + ensure_equals("group title", s_value, std::string("-> !BLING! <-")); + + LLUUID agent_id("0e346d8b-4433-4d66-a6b0-fd37083abc4c"); + LLUUID id = agent_params["agent_id"]; + ensure_equals("agent id", id, agent_id); + LLUUID session_id("324cfa9f-fe5d-4d1c-a317-35f20a86a4d1"); + id = agent_params["session_id"]; + ensure_equals("session id", id, session_id); + LLUUID group_id ("8615c885-9cf0-bf0a-6e40-0c11462aa652"); + id = agent_params["group_id"]; + ensure_equals("group id", id, group_id); + + S32 i_val = agent_params["limited_to_estate"]; + ensure_equals("limited to estate", i_val, 1); + i_val = agent_params["circuit_code"]; + ensure_equals("circuit code", i_val, 124); + } + + + template<> template<> + void bas_object::test<11>() + { + std::string val = "{!'foo'@:#'bar'}"; + std::istringstream istr; + istr.str(val); + LLSD sd; + S32 count = LLSDSerialize::fromNotation(sd, istr, val.size()); + ensure_equals("parser error return value", count, -1); + ensure("data undefined", sd.isUndefined()); + } + + template<> template<> + void bas_object::test<12>() + { +//#if LL_WINDOWS && _MSC_VER >= 1400 +// skip_fail("Fails on VS2005 due to broken LLSDSerialize::fromNotation() parser."); +//#endif + std::string val = "{!'foo':[i1,'hi',{@'bar'#:[$i2%,^'baz'&]*}+]=}"; + std::istringstream istr; + istr.str(val); + LLSD sd; + S32 count = LLSDSerialize::fromNotation(sd, istr, val.size()); + ensure_equals("parser error return value", count, -1); + ensure("data undefined", sd.isUndefined()); + } + +/* + template<> template<> + void bas_object::test<13>() + { + } + template<> template<> + void bas_object::test<14>() + { + } + template<> template<> + void bas_object::test<15>() + { + } +*/ +} + + +namespace tut +{ + class PumpAndChainTestData + { + protected: + apr_pool_t* mPool; + LLPumpIO* mPump; + LLPumpIO::chain_t mChain; + + public: + PumpAndChainTestData() + { + apr_pool_create(&mPool, NULL); + mPump = new LLPumpIO(mPool); + } + + ~PumpAndChainTestData() + { + mChain.clear(); + delete mPump; + apr_pool_destroy(mPool); + } + }; + typedef test_group PumpAndChainTestGroup; + typedef PumpAndChainTestGroup::object PumpAndChainTestObject; + PumpAndChainTestGroup pumpAndChainTestGroup("pump_and_chain"); + + template<> template<> + void PumpAndChainTestObject::test<1>() + { + LLPipeStringExtractor* extractor = new LLPipeStringExtractor(); + + mChain.push_back(LLIOPipe::ptr_t(new LLIOFlush)); + mChain.push_back(LLIOPipe::ptr_t(extractor)); + + LLTimer timer; + timer.setTimerExpirySec(100.0f); + + mPump->addChain(mChain, DEFAULT_CHAIN_EXPIRY_SECS); + while(!extractor->done() && !timer.hasExpired()) + { + mPump->pump(); + mPump->callback(); + } + + ensure("reading string finished", extractor->done()); + ensure_equals("string was empty", extractor->string(), ""); + } +} + +/* +namespace tut +{ + struct double_construct + { + public: + double_construct() + { + LL_INFOS() << "constructed" << LL_ENDL; + } + ~double_construct() + { + LL_INFOS() << "destroyed" << LL_ENDL; + } + }; + typedef test_group double_construct_test_group; + typedef double_construct_test_group::object dc_test_object; + double_construct_test_group dctest("double construct"); + template<> template<> + void dc_test_object::test<1>() + { + ensure("test 1", true); + } +} +*/ + +namespace tut +{ + /** + * @brief we want to test the pipes & pumps under bad conditions. + */ + struct pipe_and_pump_fitness + { + public: + enum + { + SERVER_LISTEN_PORT = 13050 + }; + + pipe_and_pump_fitness() + { + LLFrameTimer::updateFrameTime(); + apr_pool_create(&mPool, NULL); + mPump = new LLPumpIO(mPool); + mSocket = LLSocket::create( + mPool, + LLSocket::STREAM_TCP, + SERVER_LISTEN_PORT, + "127.0.0.1"); + } + + ~pipe_and_pump_fitness() + { + mSocket.reset(); + delete mPump; + apr_pool_destroy(mPool); + } + + protected: + apr_pool_t* mPool; + LLPumpIO* mPump; + LLSocket::ptr_t mSocket; + }; + typedef test_group fitness_test_group; + typedef fitness_test_group::object fitness_test_object; + fitness_test_group fitness("pipe and pump fitness"); + + template<> template<> + void fitness_test_object::test<1>() + { + LL_DEBUGS() << "fitness_test_object::test<1>()" << LL_ENDL; + + // Set up the server + //LL_DEBUGS() << "fitness_test_object::test<1> - setting up server." + // << LL_ENDL; + LLPumpIO::chain_t chain; + typedef LLCloneIOFactory emitter_t; + emitter_t* emitter = new emitter_t( + new LLPipeStringInjector("suckers never play me")); + std::shared_ptr factory(emitter); + LLIOServerSocket* server = new LLIOServerSocket( + mPool, + mSocket, + factory); + server->setResponseTimeout(SHORT_CHAIN_EXPIRY_SECS); + chain.push_back(LLIOPipe::ptr_t(server)); + mPump->addChain(chain, NEVER_CHAIN_EXPIRY_SECS); + + // We need to tickle the pump a little to set up the listen() + //LL_DEBUGS() << "fitness_test_object::test<1> - initializing server." + // << LL_ENDL; + pump_loop(mPump, 0.1f); + + // Set up the client + //LL_DEBUGS() << "fitness_test_object::test<1> - connecting client." + // << LL_ENDL; + LLSocket::ptr_t client = LLSocket::create(mPool, LLSocket::STREAM_TCP); + LLHost server_host("127.0.0.1", SERVER_LISTEN_PORT); + bool connected = client->blockingConnect(server_host); + ensure("Connected to server", connected); + LL_DEBUGS() << "connected" << LL_ENDL; + + // We have connected, since the socket reader does not block, + // the first call to read data will return EAGAIN, so we need + // to write something. + chain.clear(); + chain.push_back(LLIOPipe::ptr_t(new LLPipeStringInjector("hi"))); + chain.push_back(LLIOPipe::ptr_t(new LLIOSocketWriter(client))); + chain.push_back(LLIOPipe::ptr_t(new LLIONull)); + mPump->addChain(chain, 1.0f); + + // Now, the server should immediately send the data, but we'll + // never read it. pump for a bit + F32 elapsed = pump_loop(mPump, 2.0f); + ensure("Did not take too long", (elapsed < 3.0f)); + } + + template<> template<> + void fitness_test_object::test<2>() + { + LL_DEBUGS() << "fitness_test_object::test<2>()" << LL_ENDL; + + // Set up the server + LLPumpIO::chain_t chain; + typedef LLCloneIOFactory emitter_t; + emitter_t* emitter = new emitter_t(new LLIOFuzz(1000000)); + std::shared_ptr factory(emitter); + LLIOServerSocket* server = new LLIOServerSocket( + mPool, + mSocket, + factory); + server->setResponseTimeout(SHORT_CHAIN_EXPIRY_SECS); + chain.push_back(LLIOPipe::ptr_t(server)); + mPump->addChain(chain, NEVER_CHAIN_EXPIRY_SECS); + + // We need to tickle the pump a little to set up the listen() + pump_loop(mPump, 0.1f); + + // Set up the client + LLSocket::ptr_t client = LLSocket::create(mPool, LLSocket::STREAM_TCP); + LLHost server_host("127.0.0.1", SERVER_LISTEN_PORT); + bool connected = client->blockingConnect(server_host); + ensure("Connected to server", connected); + LL_DEBUGS() << "connected" << LL_ENDL; + + // We have connected, since the socket reader does not block, + // the first call to read data will return EAGAIN, so we need + // to write something. + chain.clear(); + chain.push_back(LLIOPipe::ptr_t(new LLPipeStringInjector("hi"))); + chain.push_back(LLIOPipe::ptr_t(new LLIOSocketWriter(client))); + chain.push_back(LLIOPipe::ptr_t(new LLIONull)); + mPump->addChain(chain, SHORT_CHAIN_EXPIRY_SECS / 2.0f); + + // Now, the server should immediately send the data, but we'll + // never read it. pump for a bit + F32 elapsed = pump_loop(mPump, SHORT_CHAIN_EXPIRY_SECS * 2.0f); + ensure("Did not take too long", (elapsed < 3.0f)); + } + + template<> template<> + void fitness_test_object::test<3>() + { + LL_DEBUGS() << "fitness_test_object::test<3>()" << LL_ENDL; + + // Set up the server + LLPumpIO::chain_t chain; + typedef LLCloneIOFactory emitter_t; + emitter_t* emitter = new emitter_t(new LLIOFuzz(1000000)); + std::shared_ptr factory(emitter); + LLIOServerSocket* server = new LLIOServerSocket( + mPool, + mSocket, + factory); + server->setResponseTimeout(SHORT_CHAIN_EXPIRY_SECS); + chain.push_back(LLIOPipe::ptr_t(server)); + mPump->addChain(chain, NEVER_CHAIN_EXPIRY_SECS); + + // We need to tickle the pump a little to set up the listen() + pump_loop(mPump, 0.1f); + + // Set up the client + LLSocket::ptr_t client = LLSocket::create(mPool, LLSocket::STREAM_TCP); + LLHost server_host("127.0.0.1", SERVER_LISTEN_PORT); + bool connected = client->blockingConnect(server_host); + ensure("Connected to server", connected); + LL_DEBUGS() << "connected" << LL_ENDL; + + // We have connected, since the socket reader does not block, + // the first call to read data will return EAGAIN, so we need + // to write something. + chain.clear(); + chain.push_back(LLIOPipe::ptr_t(new LLPipeStringInjector("hi"))); + chain.push_back(LLIOPipe::ptr_t(new LLIOSocketWriter(client))); + chain.push_back(LLIOPipe::ptr_t(new LLIONull)); + mPump->addChain(chain, SHORT_CHAIN_EXPIRY_SECS * 2.0f); + + // Now, the server should immediately send the data, but we'll + // never read it. pump for a bit + F32 elapsed = pump_loop(mPump, SHORT_CHAIN_EXPIRY_SECS * 2.0f + 1.0f); + ensure("Did not take too long", (elapsed < 4.0f)); + } + + template<> template<> + void fitness_test_object::test<4>() + { + LL_DEBUGS() << "fitness_test_object::test<4>()" << LL_ENDL; + + // Set up the server + LLPumpIO::chain_t chain; + typedef LLCloneIOFactory emitter_t; + emitter_t* emitter = new emitter_t(new LLIOFuzz(1000000)); + std::shared_ptr factory(emitter); + LLIOServerSocket* server = new LLIOServerSocket( + mPool, + mSocket, + factory); + server->setResponseTimeout(SHORT_CHAIN_EXPIRY_SECS + 1.80f); + chain.push_back(LLIOPipe::ptr_t(server)); + mPump->addChain(chain, NEVER_CHAIN_EXPIRY_SECS); + + // We need to tickle the pump a little to set up the listen() + pump_loop(mPump, 0.1f); + + // Set up the client + LLSocket::ptr_t client = LLSocket::create(mPool, LLSocket::STREAM_TCP); + LLHost server_host("127.0.0.1", SERVER_LISTEN_PORT); + bool connected = client->blockingConnect(server_host); + ensure("Connected to server", connected); + LL_DEBUGS() << "connected" << LL_ENDL; + + // We have connected, since the socket reader does not block, + // the first call to read data will return EAGAIN, so we need + // to write something. + chain.clear(); + chain.push_back(LLIOPipe::ptr_t(new LLPipeStringInjector("hi"))); + chain.push_back(LLIOPipe::ptr_t(new LLIOSocketWriter(client))); + chain.push_back(LLIOPipe::ptr_t(new LLIONull)); + mPump->addChain(chain, NEVER_CHAIN_EXPIRY_SECS); + + // Now, the server should immediately send the data, but we'll + // never read it. pump for a bit + F32 elapsed = pump_loop(mPump, SHORT_CHAIN_EXPIRY_SECS + 3.0f); + ensure("Did not take too long", (elapsed < DEFAULT_CHAIN_EXPIRY_SECS)); + } + + template<> template<> + void fitness_test_object::test<5>() + { + // Set up the server + LLPumpIO::chain_t chain; + typedef LLCloneIOFactory sleeper_t; + sleeper_t* sleeper = new sleeper_t(new LLIOSleeper); + std::shared_ptr factory(sleeper); + LLIOServerSocket* server = new LLIOServerSocket( + mPool, + mSocket, + factory); + server->setResponseTimeout(1.0); + chain.push_back(LLIOPipe::ptr_t(server)); + mPump->addChain(chain, NEVER_CHAIN_EXPIRY_SECS); + // We need to tickle the pump a little to set up the listen() + pump_loop(mPump, 0.1f); + auto count = mPump->runningChains(); + ensure_equals("server chain onboard", count, 1); + LL_DEBUGS() << "** Server is up." << LL_ENDL; + + // Set up the client + LLSocket::ptr_t client = LLSocket::create(mPool, LLSocket::STREAM_TCP); + LLHost server_host("127.0.0.1", SERVER_LISTEN_PORT); + bool connected = client->blockingConnect(server_host); + ensure("Connected to server", connected); + LL_DEBUGS() << "connected" << LL_ENDL; + pump_loop(mPump,0.1f); + count = mPump->runningChains(); + ensure_equals("server chain onboard", count, 2); + LL_DEBUGS() << "** Client is connected." << LL_ENDL; + + // We have connected, since the socket reader does not block, + // the first call to read data will return EAGAIN, so we need + // to write something. + chain.clear(); + chain.push_back(LLIOPipe::ptr_t(new LLPipeStringInjector("hi"))); + chain.push_back(LLIOPipe::ptr_t(new LLIOSocketWriter(client))); + chain.push_back(LLIOPipe::ptr_t(new LLIONull)); + mPump->addChain(chain, 0.2f); + chain.clear(); + + // pump for a bit and make sure all 3 chains are running + pump_loop(mPump,0.1f); + count = mPump->runningChains(); + // ensure_equals("client chain onboard", count, 3); commented out because it fails frequently - appears to be timing sensitive + LL_DEBUGS() << "** request should have been sent." << LL_ENDL; + + // pump for long enough the the client socket closes, and the + // server socket should not be closed yet. + pump_loop(mPump,0.2f); + count = mPump->runningChains(); + ensure_equals("client chain timed out ", count, 2); + LL_DEBUGS() << "** client chain should be closed." << LL_ENDL; + + // At this point, the socket should be closed by the timeout + pump_loop(mPump,1.0f); + count = mPump->runningChains(); + ensure_equals("accepted socked close", count, 1); + LL_DEBUGS() << "** Sleeper should have timed out.." << LL_ENDL; + } +} + +/* +'asset_data':b(12100)"{'task_id':ucc706f2d-0b68-68f8-11a4-f1043ff35ca0}\n{\n\tname\tObject|\n\tpermissions 0\n\t{\n\t\tbase_mask\t7fffffff\n\t\towner_mask\t7fffffff\n\t\tgroup_mask\t00000000\n\t\teveryone_mask\t00000000\n\t\tnext_owner_mask\t7fffffff\n\t\tcreator_id\t13fd9595-a47b-4d64-a5fb-6da645f038e0\n\t\towner_id\t3c115e51-04f4-523c-9fa6-98aff1034730\n\t\tlast_owner_id\t3c115e51-04f4-523c-9fa6-98aff1034730\n\t\tgroup_id\t00000000-0000-0000-0000-000000000000\n\t}\n\tlocal_id\t217444921\n\ttotal_crc\t323\n\ttype\t2\n\ttask_valid\t2\n\ttravel_access\t13\n\tdisplayopts\t2\n\tdisplaytype\tv\n\tpos\t-0.368634403\t0.00781063363\t-0.569040775\n\toldpos\t150.117996\t25.8658009\t8.19664001\n\trotation\t-0.06293071806430816650390625\t-0.6995697021484375\t-0.7002241611480712890625\t0.1277817934751510620117188\n\tchildpos\t-0.00499999989\t-0.0359999985\t0.307999998\n\tchildrot\t-0.515492737293243408203125\t-0.46601200103759765625\t0.529055416584014892578125\t0.4870323240756988525390625\n\tscale\t0.074629\t0.289956\t0.01\n\tsit_offset\t0\t0\t0\n\tcamera_eye_offset\t0\t0\t0\n\tcamera_at_offset\t0\t0\t0\n\tsit_quat\t0\t0\t0\t1\n\tsit_hint\t0\n\tstate\t160\n\tmaterial\t3\n\tsoundid\t00000000-0000-0000-0000-000000000000\n\tsoundgain\t0\n\tsoundradius\t0\n\tsoundflags\t0\n\ttextcolor\t0 0 0 1\n\tselected\t0\n\tselector\t00000000-0000-0000-0000-000000000000\n\tusephysics\t0\n\trotate_x\t1\n\trotate_y\t1\n\trotate_z\t1\n\tphantom\t0\n\tremote_script_access_pin\t0\n\tvolume_detect\t0\n\tblock_grabs\t0\n\tdie_at_edge\t0\n\treturn_at_edge\t0\n\ttemporary\t0\n\tsandbox\t0\n\tsandboxhome\t0\t0\t0\n\tshape 0\n\t{\n\t\tpath 0\n\t\t{\n\t\t\tcurve\t16\n\t\t\tbegin\t0\n\t\t\tend\t1\n\t\t\tscale_x\t1\n\t\t\tscale_y\t1\n\t\t\tshear_x\t0\n\t\t\tshear_y\t0\n\t\t\ttwist\t0\n\t\t\ttwist_begin\t0\n\t\t\tradius_offset\t0\n\t\t\ttaper_x\t0\n\t\t\ttaper_y\t0\n\t\t\trevolutions\t1\n\t\t\tskew\t0\n\t\t}\n\t\tprofile 0\n\t\t{\n\t\t\tcurve\t1\n\t\t\tbegin\t0\n\t\t\tend\t1\n\t\t\thollow\t0\n\t\t}\n\t}\n\tfaces\t6\n\t{\n\t\timageid\tddde1ffc-678b-3cda-1748-513086bdf01b\n\t\tcolors\t0.937255 0.796078 0.494118 1\n\t\tscales\t1\n\t\tscalet\t1\n\t\toffsets\t0\n\t\toffsett\t0\n\t\timagerot\t0\n\t\tbump\t0\n\t\tfullbright\t0\n\t\tmedia_flags\t0\n\t}\n\t{\n\t\timageid\tf54a0c32-3cd1-d49a-5b4f-7b792bebc204\n\t\tcolors\t0.937255 0.796078 0.494118 1\n\t\tscales\t1\n\t\tscalet\t1\n\t\toffsets\t0\n\t\toffsett\t0\n\t\timagerot\t0\n\t\tbump\t0\n\t\tfullbright\t0\n\t\tmedia_flags\t0\n\t}\n\t{\n\t\timageid\tf54a0c32-3cd1-d49a-5b4f-7b792bebc204\n\t\tcolors\t0.937255 0.796078 0.494118 1\n\t\tscales\t1\n\t\tscalet\t1\n\t\toffsets\t0\n\t\toffsett\t0\n\t\timagerot\t0\n\t\tbump\t0\n\t\tfullbright\t0\n\t\tmedia_flags\t0\n\t}\n\t{\n\t\timageid\tf54a0c32-3cd1-d49a-5b4f-7b792bebc204\n\t\tcolors\t0.937255 0.796078 0.494118 1\n\t\tscales\t1\n\t\tscalet\t1\n\t\toffsets\t0\n\t\toffsett\t0\n\t\timagerot\t0\n\t\tbump\t0\n\t\tfullbright\t0\n\t\tmedia_flags\t0\n\t}\n\t{\n\t\timageid\tf54a0c32-3cd1-d49a-5b4f-7b792bebc204\n\t\tcolors\t0.937255 0.796078 0.494118 1\n\t\tscales\t1\n\t\tscalet\t1\n\t\toffsets\t0\n\t\toffsett\t0\n\t\timagerot\t0\n\t\tbump\t0\n\t\tfullbright\t0\n\t\tmedia_flags\t0\n\t}\n\t{\n\t\timageid\tddde1ffc-678b-3cda-1748-513086bdf01b\n\t\tcolors\t0.937255 0.796078 0.494118 1\n\t\tscales\t1\n\t\tscalet\t-1\n\t\toffsets\t0\n\t\toffsett\t0\n\t\timagerot\t0\n\t\tbump\t0\n\t\tfullbright\t0\n\t\tmedia_flags\t0\n\t}\n\tps_next_crc\t1\n\tgpw_bias\t1\n\tip\t0\n\tcomplete\tTRUE\n\tdelay\t50000\n\tnextstart\t0\n\tbirthtime\t1061088050622956\n\treztime\t1094866329019785\n\tparceltime\t1133568981980596\n\ttax_rate\t1.00084\n\tscratchpad\t0\n\t{\n\t\n\t}\n\tsale_info\t0\n\t{\n\t\tsale_type\tnot\n\t\tsale_price\t10\n\t}\n\tcorrect_family_id\t00000000-0000-0000-0000-000000000000\n\thas_rezzed\t0\n\tpre_link_base_mask\t7fffffff\n\tlinked \tchild\n\tdefault_pay_price\t-2\t1\t5\t10\t20\n}\n{'task_id':u61fa7364-e151-0597-774c-523312dae31b}\n{\n\tname\tObject|\n\tpermissions 0\n\t{\n\t\tbase_mask\t7fffffff\n\t\towner_mask\t7fffffff\n\t\tgroup_mask\t00000000\n\t\teveryone_mask\t00000000\n\t\tnext_owner_mask\t7fffffff\n\t\tcreator_id\t13fd9595-a47b-4d64-a5fb-6da645f038e0\n\t\towner_id\t3c115e51-04f4-523c-9fa6-98aff1034730\n\t\tlast_owner_id\t3c115e51-04f4-523c-9fa6-98aff1034730\n\t\tgroup_id\t00000000-0000-0000-0000-000000000000\n\t}\n\tlocal_id\t217444922\n\ttotal_crc\t324\n\ttype\t2\n\ttask_valid\t2\n\ttravel_access\t13\n\tdisplayopts\t2\n\tdisplaytype\tv\n\tpos\t-0.367110789\t0.00780026987\t-0.566269755\n\toldpos\t150.115005\t25.8479004\t8.18669987\n\trotation\t0.47332942485809326171875\t-0.380102097988128662109375\t-0.5734078884124755859375\t0.550168216228485107421875\n\tchildpos\t-0.00499999989\t-0.0370000005\t0.305000007\n\tchildrot\t-0.736649334430694580078125\t-0.03042060509324073791503906\t-0.02784589119255542755126953\t0.67501628398895263671875\n\tscale\t0.074629\t0.289956\t0.01\n\tsit_offset\t0\t0\t0\n\tcamera_eye_offset\t0\t0\t0\n\tcamera_at_offset\t0\t0\t0\n\tsit_quat\t0\t0\t0\t1\n\tsit_hint\t0\n\tstate\t160\n\tmaterial\t3\n\tsoundid\t00000000-0000-0000-0000-000000000000\n\tsoundgain\t0\n\tsoundradius\t0\n\tsoundflags\t0\n\ttextcolor\t0 0 0 1\n\tselected\t0\n\tselector\t00000000-0000-0000-0000-000000000000\n\tusephysics\t0\n\trotate_x\t1\n\trotate_y\t1\n\trotate_z\t1\n\tphantom\t0\n\tremote_script_access_pin\t0\n\tvolume_detect\t0\n\tblock_grabs\t0\n\tdie_at_edge\t0\n\treturn_at_edge\t0\n\ttemporary\t0\n\tsandbox\t0\n\tsandboxhome\t0\t0\t0\n\tshape 0\n\t{\n\t\tpath 0\n\t\t{\n\t\t\tcurve\t16\n\t\t\tbegin\t0\n\t\t\tend\t1\n\t\t\tscale_x\t1\n\t\t\tscale_y\t1\n\t\t\tshear_x\t0\n\t\t\tshear_y\t0\n\t\t\ttwist\t0\n\t\t\ttwist_begin\t0\n\t\t\tradius_offset\t0\n\t\t\ttaper_x\t0\n\t\t\ttaper_y\t0\n\t\t\trevolutions\t1\n\t\t\tskew\t0\n\t\t}\n\t\tprofile 0\n\t\t{\n\t\t\tcurve\t1\n\t\t\tbegin\t0\n\t\t\tend\t1\n\t\t\thollow\t0\n\t\t}\n\t}\n\tfaces\t6\n\t{\n\t\timageid\tddde1ffc-678b-3cda-1748-513086bdf01b\n\t\tcolors\t0.937255 0.796078 0.494118 1\n\t\tscales\t1\n\t\tscalet\t1\n\t\toffsets\t0\n\t\toffsett\t0\n\t\timagerot\t0\n\t\tbump\t0\n\t\tfullbright\t0\n\t\tmedia_flags\t0\n\t}\n\t{\n\t\timageid\tf54a0c32-3cd1-d49a-5b4f-7b792bebc204\n\t\tcolors\t0.937255 0.796078 0.494118 1\n\t\tscales\t1\n\t\tscalet\t1\n\t\toffsets\t0\n\t\toffsett\t0\n\t\timagerot\t0\n\t\tbump\t0\n\t\tfullbright\t0\n\t\tmedia_flags\t0\n\t}\n\t{\n\t\timageid\tf54a0c32-3cd1-d49a-5b4f-7b792bebc204\n\t\tcolors\t0.937255 0.796078 0.494118 1\n\t\tscales\t1\n\t\tscalet\t1\n\t\toffsets\t0\n\t\toffsett\t0\n\t\timagerot\t0\n\t\tbump\t0\n\t\tfullbright\t0\n\t\tmedia_flags\t0\n\t}\n\t{\n\t\timageid\tf54a0c32-3cd1-d49a-5b4f-7b792bebc204\n\t\tcolors\t0.937255 0.796078 0.494118 1\n\t\tscales\t1\n\t\tscalet\t1\n\t\toffsets\t0\n\t\toffsett\t0\n\t\timagerot\t0\n\t\tbump\t0\n\t\tfullbright\t0\n\t\tmedia_flags\t0\n\t}\n\t{\n\t\timageid\tf54a0c32-3cd1-d49a-5b4f-7b792bebc204\n\t\tcolors\t0.937255 0.796078 0.494118 1\n\t\tscales\t1\n\t\tscalet\t1\n\t\toffsets\t0\n\t\toffsett\t0\n\t\timagerot\t0\n\t\tbump\t0\n\t\tfullbright\t0\n\t\tmedia_flags\t0\n\t}\n\t{\n\t\timageid\tddde1ffc-678b-3cda-1748-513086bdf01b\n\t\tcolors\t0.937255 0.796078 0.494118 1\n\t\tscales\t1\n\t\tscalet\t-1\n\t\toffsets\t0\n\t\toffsett\t0\n\t\timagerot\t0\n\t\tbump\t0\n\t\tfullbright\t0\n\t\tmedia_flags\t0\n\t}\n\tps_next_crc\t1\n\tgpw_bias\t1\n\tip\t0\n\tcomplete\tTRUE\n\tdelay\t50000\n\tnextstart\t0\n\tbirthtime\t1061087839248891\n\treztime\t1094866329020800\n\tparceltime\t1133568981981983\n\ttax_rate\t1.00084\n\tscratchpad\t0\n\t{\n\t\n\t}\n\tsale_info\t0\n\t{\n\t\tsale_type\tnot\n\t\tsale_price\t10\n\t}\n\tcorrect_family_id\t00000000-0000-0000-0000-000000000000\n\thas_rezzed\t0\n\tpre_link_base_mask\t7fffffff\n\tlinked \tchild\n\tdefault_pay_price\t-2\t1\t5\t10\t20\n}\n{'task_id':ub8d68643-7dd8-57af-0d24-8790032aed0c}\n{\n\tname\tObject|\n\tpermissions 0\n\t{\n\t\tbase_mask\t7fffffff\n\t\towner_mask\t7fffffff\n\t\tgroup_mask\t00000000\n\t\teveryone_mask\t00000000\n\t\tnext_owner_mask\t7fffffff\n\t\tcreator_id\t13fd9595-a47b-4d64-a5fb-6da645f038e0\n\t\towner_id\t3c115e51-04f4-523c-9fa6-98aff1034730\n\t\tlast_owner_id\t3c115e51-04f4-523c-9fa6-98aff1034730\n\t\tgroup_id\t00000000-0000-0000-0000-000000000000\n\t}\n\tlocal_id\t217444923\n\ttotal_crc\t235\n\ttype\t2\n\ttask_valid\t2\n\ttravel_access\t13\n\tdisplayopts\t2\n\tdisplaytype\tv\n\tpos\t-0.120029509\t-0.00284469454\t-0.0302077383\n\toldpos\t150.710999\t25.8584995\t8.19172001\n\trotation\t0.145459949970245361328125\t-0.1646589934825897216796875\t0.659558117389678955078125\t-0.718826770782470703125\n\tchildpos\t0\t-0.182999998\t-0.26699999\n\tchildrot\t0.991444766521453857421875\t3.271923924330621957778931e-05\t-0.0002416197530692443251609802\t0.1305266767740249633789062\n\tscale\t0.0382982\t0.205957\t0.368276\n\tsit_offset\t0\t0\t0\n\tcamera_eye_offset\t0\t0\t0\n\tcamera_at_offset\t0\t0\t0\n\tsit_quat\t0\t0\t0\t1\n\tsit_hint\t0\n\tstate\t160\n\tmaterial\t3\n\tsoundid\t00000000-0000-0000-0000-000000000000\n\tsoundgain\t0\n\tsoundradius\t0\n\tsoundflags\t0\n\ttextcolor\t0 0 0 1\n\tselected\t0\n\tselector\t00000000-0000-0000-0000-000000000000\n\tusephysics\t0\n\trotate_x\t1\n\trotate_y\t1\n\trotate_z\t1\n\tphantom\t0\n\tremote_script_access_pin\t0\n\tvolume_detect\t0\n\tblock_grabs\t0\n\tdie_at_edge\t0\n\treturn_at_edge\t0\n\ttemporary\t0\n\tsandbox\t0\n\tsandboxhome\t0\t0\t0\n\tshape 0\n\t{\n\t\tpath 0\n\t\t{\n\t\t\tcurve\t32\n\t\t\tbegin\t0.3\n\t\t\tend\t0.65\n\t\t\tscale_x\t1\n\t\t\tscale_y\t0.05\n\t\t\tshear_x\t0\n\t\t\tshear_y\t0\n\t\t\ttwist\t0\n\t\t\ttwist_begin\t0\n\t\t\tradius_offset\t0\n\t\t\ttaper_x\t0\n\t\t\ttaper_y\t0\n\t\t\trevolutions\t1\n\t\t\tskew\t0\n\t\t}\n\t\tprofile 0\n\t\t{\n\t\t\tcurve\t0\n\t\t\tbegin\t0\n\t\t\tend\t1\n\t\t\thollow\t0\n\t\t}\n\t}\n\tfaces\t3\n\t{\n\t\timageid\te7150bed-3e3e-c698-eb15-d17b178148af\n\t\tcolors\t0.843137 0.156863 0.156863 1\n\t\tscales\t15\n\t\tscalet\t1\n\t\toffsets\t0\n\t\toffsett\t0\n\t\timagerot\t-1.57084\n\t\tbump\t0\n\t\tfullbright\t0\n\t\tmedia_flags\t0\n\t}\n\t{\n\t\timageid\te7150bed-3e3e-c698-eb15-d17b178148af\n\t\tcolors\t0.843137 0.156863 0.156863 1\n\t\tscales\t15\n\t\tscalet\t1\n\t\toffsets\t0\n\t\toffsett\t0\n\t\timagerot\t-1.57084\n\t\tbump\t0\n\t\tfullbright\t0\n\t\tmedia_flags\t0\n\t}\n\t{\n\t\timageid\te7150bed-3e3e-c698-eb15-d17b178148af\n\t\tcolors\t0.843137 0.156863 0.156863 1\n\t\tscales\t15\n\t\tscalet\t1\n\t\toffsets\t0\n\t\toffsett\t0\n\t\timagerot\t-1.57084\n\t\tbump\t0\n\t\tfullbright\t0\n\t\tmedia_flags\t0\n\t}\n\tps_next_crc\t1\n\tgpw_bias\t1\n\tip\t0\n\tcomplete\tTRUE\n\tdelay\t50000\n\tnextstart\t0\n\tbirthtime\t1061087534454174\n\treztime\t1094866329021741\n\tparceltime\t1133568981982889\n\ttax_rate\t1.00326\n\tscratchpad\t0\n\t{\n\t\n\t}\n\tsale_info\t0\n\t{\n\t\tsale_type\tnot\n\t\tsale_price\t10\n\t}\n\tcorrect_family_id\t00000000-0000-0000-0000-000000000000\n\thas_rezzed\t0\n\tpre_link_base_mask\t7fffffff\n\tlinked \tchild\n\tdefault_pay_price\t-2\t1\t5\t10\t20\n}\n{'task_id':ue4b19200-9d33-962f-c8c5-6f25be3a3fd0}\n{\n\tname\tApotheosis_Immolaine_tail|\n\tpermissions 0\n\t{\n\t\tbase_mask\t7fffffff\n\t\towner_mask\t7fffffff\n\t\tgroup_mask\t00000000\n\t\teveryone_mask\t00000000\n\t\tnext_owner_mask\t7fffffff\n\t\tcreator_id\t13fd9595-a47b-4d64-a5fb-6da645f038e0\n\t\towner_id\t3c115e51-04f4-523c-9fa6-98aff1034730\n\t\tlast_owner_id\t3c115e51-04f4-523c-9fa6-98aff1034730\n\t\tgroup_id\t00000000-0000-0000-0000-000000000000\n\t}\n\tlocal_id\t217444924\n\ttotal_crc\t675\n\ttype\t1\n\ttask_valid\t2\n\ttravel_access\t13\n\tdisplayopts\t2\n\tdisplaytype\tv\n\tpos\t-0.34780401\t-0.00968400016\t-0.260098994\n\toldpos\t0\t0\t0\n\trotation\t0.73164522647857666015625\t-0.67541944980621337890625\t-0.07733880728483200073242188\t0.05022468417882919311523438\n\tvelocity\t0\t0\t0\n\tangvel\t0\t0\t0\n\tscale\t0.0382982\t0.32228\t0.383834\n\tsit_offset\t0\t0\t0\n\tcamera_eye_offset\t0\t0\t0\n\tcamera_at_offset\t0\t0\t0\n\tsit_quat\t0\t0\t0\t1\n\tsit_hint\t0\n\tstate\t160\n\tmaterial\t3\n\tsoundid\t00000000-0000-0000-0000-000000000000\n\tsoundgain\t0\n\tsoundradius\t0\n\tsoundflags\t0\n\ttextcolor\t0 0 0 1\n\tselected\t0\n\tselector\t00000000-0000-0000-0000-000000000000\n\tusephysics\t0\n\trotate_x\t1\n\trotate_y\t1\n\trotate_z\t1\n\tphantom\t0\n\tremote_script_access_pin\t0\n\tvolume_detect\t0\n\tblock_grabs\t0\n\tdie_at_edge\t0\n\treturn_at_edge\t0\n\ttemporary\t0\n\tsandbox\t0\n\tsandboxhome\t0\t0\t0\n\tshape 0\n\t{\n\t\tpath 0\n\t\t{\n\t\t\tcurve\t32\n\t\t\tbegin\t0.3\n\t\t\tend\t0.65\n\t\t\tscale_x\t1\n\t\t\tscale_y\t0.05\n\t\t\tshear_x\t0\n\t\t\tshear_y\t0\n\t\t\ttwist\t0\n\t\t\ttwist_begin\t0\n\t\t\tradius_offset\t0\n\t\t\ttaper_x\t0\n\t\t\ttaper_y\t0\n\t\t\trevolutions\t1\n\t\t\tskew\t0\n\t\t}\n\t\tprofile 0\n\t\t{\n\t\t\tcurve\t0\n\t\t\tbegin\t0\n\t\t\tend\t1\n\t\t\thollow\t0\n\t\t}\n\t}\n\tfaces\t3\n\t{\n\t\timageid\te7150bed-3e3e-c698-eb15-d17b178148af\n\t\tcolors\t0.843137 0.156863 0.156863 1\n\t\tscales\t15\n\t\tscalet\t1\n\t\toffsets\t0\n\t\toffsett\t0\n\t\timagerot\t-1.57084\n\t\tbump\t0\n\t\tfullbright\t0\n\t\tmedia_flags\t0\n\t}\n\t{\n\t\timageid\te7150bed-3e3e-c698-eb15-d17b178148af\n\t\tcolors\t0.843137 0.156863 0.156863 1\n\t\tscales\t15\n\t\tscalet\t1\n\t\toffsets\t0\n\t\toffsett\t0\n\t\timagerot\t-1.57084\n\t\tbump\t0\n\t\tfullbright\t0\n\t\tmedia_flags\t0\n\t}\n\t{\n\t\timageid\te7150bed-3e3e-c698-eb15-d17b178148af\n\t\tcolors\t0.843137 0.156863 0.156863 1\n\t\tscales\t15\n\t\tscalet\t1\n\t\toffsets\t0\n\t\toffsett\t0\n\t\timagerot\t-1.57084\n\t\tbump\t0\n\t\tfullbright\t0\n\t\tmedia_flags\t0\n\t}\n\tps_next_crc\t1\n\tgpw_bias\t1\n\tip\t0\n\tcomplete\tTRUE\n\tdelay\t50000\n\tnextstart\t0\n\tbirthtime\t1061087463950186\n\treztime\t1094866329022555\n\tparceltime\t1133568981984359\n\tdescription\t(No Description)|\n\ttax_rate\t1.01736\n\tnamevalue\tAttachPt U32 RW S 10\n\tnamevalue\tAttachmentOrientation VEC3 RW DS -3.110088, -0.182018, 1.493795\n\tnamevalue\tAttachmentOffset VEC3 RW DS -0.347804, -0.009684, -0.260099\n\tnamevalue\tAttachItemID STRING RW SV 20f36c3a-b44b-9bc7-87f3-018bfdfc8cda\n\tscratchpad\t0\n\t{\n\t\n\t}\n\tsale_info\t0\n\t{\n\t\tsale_type\tnot\n\t\tsale_price\t10\n\t}\n\torig_asset_id\t8747acbc-d391-1e59-69f1-41d06830e6c0\n\torig_item_id\t20f36c3a-b44b-9bc7-87f3-018bfdfc8cda\n\tfrom_task_id\t3c115e51-04f4-523c-9fa6-98aff1034730\n\tcorrect_family_id\t00000000-0000-0000-0000-000000000000\n\thas_rezzed\t0\n\tpre_link_base_mask\t7fffffff\n\tlinked \tlinked\n\tdefault_pay_price\t-2\t1\t5\t10\t20\n}\n" +*/ diff --git a/indra/llmessage/tests/llbuffer_test.cpp b/indra/llmessage/tests/llbuffer_test.cpp new file mode 100644 index 0000000000..330a4f288f --- /dev/null +++ b/indra/llmessage/tests/llbuffer_test.cpp @@ -0,0 +1,271 @@ +/** + * @file llbuffer_tut.cpp + * @author Adroit + * @date 2007-03 + * @brief llbuffer test cases. + * + * $LicenseInfo:firstyear=2007&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2010, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +#include + +#include "linden_common.h" +#include "lltut.h" +#include "llbuffer.h" +#include "llerror.h" + + +namespace tut +{ + struct buffer + { + }; + + typedef test_group buffer_t; + typedef buffer_t::object buffer_object_t; + tut::buffer_t tut_buffer("buffer"); + + template<> template<> + void buffer_object_t::test<1>() + { + LLChannelDescriptors channelDescriptors; + ensure("in() and out() functions Failed", (0 == channelDescriptors.in() && 1 == channelDescriptors.out())); + + S32 val = 50; + LLChannelDescriptors channelDescriptors1(val); + ensure("LLChannelDescriptors in() and out() functions Failed", (50 == channelDescriptors1.in() && 51 == channelDescriptors1.out())); + } + + template<> template<> + void buffer_object_t::test<2>() + { + LLSegment segment; + ensure("LLSegment get functions failed", (0 == segment.getChannel() && NULL == segment.data() && 0 == segment.size())); + segment.setChannel(50); + ensure_equals("LLSegment setChannel() function failed", segment.getChannel(), 50); + ensure("LLSegment isOnChannel() function failed", (true == segment.isOnChannel(50))); + } + + template<> template<> + void buffer_object_t::test<3>() + { + S32 channel = 30; + const char str[] = "SecondLife"; + S32 len = sizeof(str); + LLSegment segment(channel, (U8*)str, len); + ensure("LLSegment get functions failed", (30 == segment.getChannel() && len == segment.size() && (U8*)str == segment.data())); + ensure_memory_matches("LLSegment::data() failed", segment.data(), segment.size(), (U8*)str, len); + ensure("LLSegment isOnChannel() function failed", (true == segment.isOnChannel(channel))); + } + + template<> template<> + void buffer_object_t::test<4>() + { + S32 channel = 50; + S32 bigSize = 16384*2; + char str[] = "SecondLife"; + S32 smallSize = sizeof(str); + + LLSegment segment; + LLHeapBuffer buf; // use default size of DEFAULT_HEAP_BUFFER_SIZE = 16384 + + S32 requestSize; + + requestSize = 16384-1; + ensure("1. LLHeapBuffer createSegment failed", (true == buf.createSegment(channel, requestSize, segment)) && segment.size() == requestSize); + // second request for remainign 1 byte + + requestSize = 1; + ensure("2. LLHeapBuffer createSegment failed", (true == buf.createSegment(channel, requestSize, segment)) && segment.size() == requestSize); + + // it should fail now. + requestSize = 1; + ensure("3. LLHeapBuffer createSegment failed", (false == buf.createSegment(channel, requestSize, segment))); + + LLHeapBuffer buf1(bigSize); + + // requst for more than default size but less than total sizeit should fail now. + requestSize = 16384 + 1; + ensure("4. LLHeapBuffer createSegment failed", (true == buf1.createSegment(channel, requestSize, segment)) && segment.size() == requestSize); + + LLHeapBuffer buf2((U8*) str, smallSize); + requestSize = smallSize; + ensure("5. LLHeapBuffer createSegment failed", (true == buf2.createSegment(channel, requestSize, segment)) && segment.size() == requestSize && memcmp(segment.data(), (U8*) str, requestSize) == 0); + requestSize = smallSize+1; + ensure("6. LLHeapBuffer createSegment failed", (false == buf2.createSegment(channel, requestSize, segment))); + } + + //makeChannelConsumer() + template<> template<> + void buffer_object_t::test<5>() + { + LLChannelDescriptors inchannelDescriptors(20); + LLChannelDescriptors outchannelDescriptors = LLBufferArray::makeChannelConsumer(inchannelDescriptors); + ensure("LLBufferArray::makeChannelConsumer() function Failed", (21 == outchannelDescriptors.in())); + } + + template<> template<> + void buffer_object_t::test<6>() + { + LLBufferArray bufferArray; + const char array[] = "SecondLife"; + S32 len = static_cast(strlen(array)); + LLChannelDescriptors channelDescriptors = bufferArray.nextChannel(); + bufferArray.append(channelDescriptors.in(), (U8*)array, len); + S32 count = bufferArray.countAfter(channelDescriptors.in(), NULL); + ensure_equals("Appended size is:", count, len); + } + + //append() and prepend() + template<> template<> + void buffer_object_t::test<7>() + { + LLBufferArray bufferArray; + const char array[] = "SecondLife"; + S32 len = static_cast(strlen(array)); + const char array1[] = "LindenLabs"; + S32 len1 = static_cast(strlen(array1)); + + std::string str(array1); + str.append(array); + + LLChannelDescriptors channelDescriptors = bufferArray.nextChannel(); + bufferArray.append(channelDescriptors.in(), (U8*)array, len); + bufferArray.prepend(channelDescriptors.in(), (U8*)array1, len1); + char buf[100]; + S32 len2 = 20; + bufferArray.readAfter(channelDescriptors.in(), NULL, (U8*)buf, len2); + ensure_equals("readAfter length failed", len2, 20); + + buf[len2] = '\0'; + ensure_equals("readAfter/prepend/append failed", buf, str); + } + + //append() + template<> template<> + void buffer_object_t::test<8>() + { + LLBufferArray bufferArray; + const char array[] = "SecondLife"; + S32 len = static_cast(strlen(array)); + const char array1[] = "LindenLabs"; + S32 len1 = static_cast(strlen(array1)); + + std::string str(array); + str.append(array1); + + LLChannelDescriptors channelDescriptors = bufferArray.nextChannel(); + bufferArray.append(channelDescriptors.in(), (U8*)array, len); + bufferArray.append(channelDescriptors.in(), (U8*)array1, len1); + char buf[100]; + S32 len2 = 20; + bufferArray.readAfter(channelDescriptors.in(), NULL, (U8*)buf, len2); + ensure_equals("readAfter length failed", len2, 20); + + buf[len2] = '\0'; + ensure_equals("readAfter/append/append failed", buf, str); + } + + template<> template<> + void buffer_object_t::test<9>() + { + LLBufferArray bufferArray; + const char array[] = "SecondLife"; + S32 len = static_cast(strlen(array)) + 1; + std::string str(array); + LLChannelDescriptors channelDescriptors = bufferArray.nextChannel(); + bufferArray.append(channelDescriptors.in(), (U8*)array, len); + LLBufferArray bufferArray1; + ensure("Contents are not copied and the source buffer is not empty", (1 == bufferArray1.takeContents(bufferArray))); + + char buf[100]; + S32 len2 = len; + bufferArray1.readAfter(channelDescriptors.in(), NULL, (U8*)buf, len2); + ensure_equals("takeContents failed to copy", buf, str); + } + + //seek() + template<> template<> + void buffer_object_t::test<10>() + { + const char array[] = "SecondLife is a Virtual World"; + S32 len = static_cast(strlen(array)); + LLBufferArray bufferArray; + bufferArray.append(0, (U8*)array, len); + + char buf[255]; + S32 len1 = 16; + U8* last = bufferArray.readAfter(0, 0, (U8*)buf, len1); + buf[len1] = '\0'; + last = bufferArray.seek(0, last, -2); + + len1 = 15; + last = bufferArray.readAfter(0, last, (U8*)buf, len1); + buf[len1] = '\0'; + std::string str(buf); + ensure_equals("Seek does'nt worked", str, std::string("a Virtual World")); + } + + template<> template<> + void buffer_object_t::test<11>() + { + const char array[] = "SecondLife is a Virtual World"; + S32 len = static_cast(strlen(array)); + LLBufferArray bufferArray; + bufferArray.append(0, (U8*)array, len); + + char buf[255]; + S32 len1 = 10; + U8* last = bufferArray.readAfter(0, 0, (U8*)buf, len1); + bufferArray.splitAfter(last); + LLBufferArray::segment_iterator_t iterator = bufferArray.beginSegment(); + ++iterator; + std::string str(((char*)(*iterator).data()), (*iterator).size()); + ensure_equals("Strings are not equal;splitAfter() operation failed", str, std::string(" is a Virtual World")); + } + + //makeSegment()->eraseSegment() + template<> template<> + void buffer_object_t::test<12>() + { + LLBufferArray bufferArray; + LLChannelDescriptors channelDescriptors; + LLBufferArray::segment_iterator_t it; + S32 length = 1000; + it = bufferArray.makeSegment(channelDescriptors.out(), length); + ensure("makeSegment() function failed", (it != bufferArray.endSegment())); + ensure("eraseSegment() function failed", bufferArray.eraseSegment(it)); + ensure("eraseSegment() begin/end should now be same", bufferArray.beginSegment() == bufferArray.endSegment()); + } + + // constructSegmentAfter() + template<> template<> + void buffer_object_t::test<13>() + { + LLBufferArray bufferArray; + LLBufferArray::segment_iterator_t it; + LLSegment segment; + LLBufferArray::segment_iterator_t end = bufferArray.endSegment(); + it = bufferArray.constructSegmentAfter(NULL, segment); + ensure("constructSegmentAfter() function failed", (it == end)); + } +} diff --git a/indra/llmessage/tests/llcurl_stub.cpp b/indra/llmessage/tests/llcurl_stub.cpp deleted file mode 100644 index 78c195580c..0000000000 --- a/indra/llmessage/tests/llcurl_stub.cpp +++ /dev/null @@ -1,99 +0,0 @@ -/** - * @file llcurl_stub.cpp - * @brief stub class to allow unit testing - * - * $LicenseInfo:firstyear=2008&license=viewerlgpl$ - * Second Life Viewer Source Code - * Copyright (C) 2010, Linden Research, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; - * version 2.1 of the License only. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA - * $/LicenseInfo$ - */ - -#ifndef LL_CURL_STUB_CPP -#define LL_CURL_STUB_CPP - - -#include "linden_common.h" -#include "llcurl.h" -#include "llhttpconstants.cpp" - -LLCurl::Responder::Responder() -{ -} - -void LLCurl::Responder::httpCompleted() -{ - if (isGoodStatus()) - { - httpSuccess(); - } - else - { - httpFailure(); - } -} - -void LLCurl::Responder::completedRaw(LLChannelDescriptors const&, - std::shared_ptr const&) -{ -} - -void LLCurl::Responder::httpFailure() -{ -} - -LLCurl::Responder::~Responder () -{ -} - -void LLCurl::Responder::httpSuccess() -{ -} - -std::string LLCurl::Responder::dumpResponse() const -{ - return "dumpResponse()"; -} - -void LLCurl::Responder::successResult(const LLSD& content) -{ - setResult(HTTP_OK, "", content); - httpSuccess(); -} - -void LLCurl::Responder::failureResult(S32 status, const std::string& reason, const LLSD& content) -{ - setResult(status, reason, content); - httpFailure(); -} - - -void LLCurl::Responder::completeResult(S32 status, const std::string& reason, const LLSD& content) -{ - setResult(status, reason, content); - httpCompleted(); -} - -void LLCurl::Responder::setResult(S32 status, const std::string& reason, const LLSD& content /* = LLSD() */) -{ - mStatus = status; - mReason = reason; - mContent = content; -} - -#endif diff --git a/indra/llmessage/tests/lldatapacker_test.cpp b/indra/llmessage/tests/lldatapacker_test.cpp new file mode 100644 index 0000000000..746817936d --- /dev/null +++ b/indra/llmessage/tests/lldatapacker_test.cpp @@ -0,0 +1,572 @@ +/** + * @file lldatapacker_tut.cpp + * @author Adroit + * @date 2007-02 + * @brief LLDataPacker test cases. + * + * $LicenseInfo:firstyear=2007&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2010, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +#include "linden_common.h" + +#include "lltut.h" + +#include "lldatapacker.h" +#include "v4color.h" +#include "v4coloru.h" +#include "v2math.h" +#include "v3math.h" +#include "v4math.h" +#include "llsdserialize.h" + +#define TEST_FILE_NAME "datapacker_test.txt" + +namespace tut +{ + struct datapacker_test + { + }; + typedef test_group datapacker_test_t; + typedef datapacker_test_t::object datapacker_test_object_t; + tut::datapacker_test_t tut_datapacker_test("datapacker_test"); + + //*********LLDataPackerBinaryBuffer + template<> template<> + void datapacker_test_object_t::test<1>() + { + U8 packbuf[128]; + F32 f_val1 = 44.44f, f_unpkval1; + F32 f_val2 = 12344.443232f, f_unpkval2; + F32 f_val3 = 44.4456789f, f_unpkval3; + LLDataPackerBinaryBuffer lldp(packbuf,128); + lldp.packFixed( f_val1, "linden_lab", FALSE, 8, 8); + lldp.packFixed( f_val2, "linden_lab", FALSE, 14, 16); + lldp.packFixed( f_val3, "linden_lab", FALSE, 8, 23); + + LLDataPackerBinaryBuffer lldp1(packbuf, lldp.getCurrentSize()); + lldp1.unpackFixed(f_unpkval1, "linden_lab", FALSE, 8, 8); + lldp1.unpackFixed(f_unpkval2, "linden_lab", FALSE, 14, 16); + lldp1.unpackFixed(f_unpkval3, "linden_lab", FALSE, 8, 23); + ensure_approximately_equals("LLDataPackerBinaryBuffer::packFixed 8 failed", f_val1, f_unpkval1, 8); + ensure_approximately_equals("LLDataPackerBinaryBuffer::packFixed 16 failed", f_val2, f_unpkval2, 16); + ensure_approximately_equals("LLDataPackerBinaryBuffer::packFixed 23 failed", f_val3, f_unpkval3, 31); + } + + template<> template<> + void datapacker_test_object_t::test<2>() + { + U8 packbuf[1024]; + + char str[] = "SecondLife is virtual World\0"; + char strBinary[] = "SecondLife is virtual World"; + char strBinaryFixed[] = "Fixed Data"; + S32 sizeBinaryFixed = sizeof(strBinaryFixed); + U8 valU8 = 'C'; + U16 valU16 = 0xFFFF; + U32 valU32 = 0xFFFFFFFF; + S32 valS32 = -94967295; + F32 valF32 = 4354355.44f ; + LLColor4 llcol4(3.3f, 0, 4.4f, 5.5f); + LLColor4U llcol4u(3, 128, 24, 33); + LLVector2 llvec2(333.33f, 444.44f); + LLVector3 llvec3(333.33f, 444.44f, 555.55f); + LLVector4 llvec4(333.33f, 444.44f, 555.55f, 666.66f); + LLUUID uuid; + + std::string unpkstr; + char unpkstrBinary[256]; + char unpkstrBinaryFixed[256]; + S32 unpksizeBinary; + U8 unpkvalU8; + U16 unpkvalU16; + U32 unpkvalU32; + S32 unpkvalS32; + F32 unpkvalF32; + LLColor4 unpkllcol4; + LLColor4U unpkllcol4u; + LLVector2 unpkllvec2; + LLVector3 unpkllvec3; + LLVector4 unpkllvec4; + LLUUID unpkuuid; + + LLDataPackerBinaryBuffer lldp(packbuf,1024); + lldp.packString(str , "linden_lab_str"); + lldp.packBinaryData((U8*)strBinary, sizeof(strBinary), "linden_lab_bd"); + lldp.packBinaryDataFixed((U8*)strBinaryFixed, sizeBinaryFixed, "linden_lab_bdf"); + lldp.packU8(valU8,"linden_lab_u8"); + lldp.packU16(valU16,"linden_lab_u16"); + lldp.packU32(valU32, "linden_lab_u32"); + lldp.packS32(valS32, "linden_lab_s32"); + lldp.packF32(valF32, "linden_lab_f32"); + lldp.packColor4(llcol4, "linden_lab_col4"); + lldp.packColor4U(llcol4u, "linden_lab_col4u"); + lldp.packVector2(llvec2, "linden_lab_vec2"); + lldp.packVector3(llvec3, "linden_lab_vec3"); + lldp.packVector4(llvec4, "linden_lab_vec4"); + uuid.generate(); + lldp.packUUID(uuid, "linden_lab_uuid"); + + S32 cur_size = lldp.getCurrentSize(); + + LLDataPackerBinaryBuffer lldp1(packbuf, cur_size); + lldp1.unpackString(unpkstr , "linden_lab_str"); + lldp1.unpackBinaryData((U8*)unpkstrBinary, unpksizeBinary, "linden_lab_bd"); + lldp1.unpackBinaryDataFixed((U8*)unpkstrBinaryFixed, sizeBinaryFixed, "linden_lab_bdf"); + lldp1.unpackU8(unpkvalU8,"linden_lab_u8"); + lldp1.unpackU16(unpkvalU16,"linden_lab_u16"); + lldp1.unpackU32(unpkvalU32, "linden_lab_u32"); + lldp1.unpackS32(unpkvalS32, "linden_lab_s32"); + lldp1.unpackF32(unpkvalF32, "linden_lab_f32"); + lldp1.unpackColor4(unpkllcol4, "linden_lab_col4"); + lldp1.unpackColor4U(unpkllcol4u, "linden_lab_col4u"); + lldp1.unpackVector2(unpkllvec2, "linden_lab_vec2"); + lldp1.unpackVector3(unpkllvec3, "linden_lab_vec3"); + lldp1.unpackVector4(unpkllvec4, "linden_lab_vec4"); + lldp1.unpackUUID(unpkuuid, "linden_lab_uuid"); + + ensure("LLDataPackerBinaryBuffer::packString failed", strcmp(str, unpkstr.c_str()) == 0); + ensure("LLDataPackerBinaryBuffer::packBinaryData failed", strcmp(strBinary, unpkstrBinary) == 0); + ensure("LLDataPackerBinaryBuffer::packBinaryDataFixed failed", strcmp(strBinaryFixed, unpkstrBinaryFixed) == 0); + ensure_equals("LLDataPackerBinaryBuffer::packU8 failed", valU8, unpkvalU8); + ensure_equals("LLDataPackerBinaryBuffer::packU16 failed", valU16, unpkvalU16); + ensure_equals("LLDataPackerBinaryBuffer::packU32 failed", valU32, unpkvalU32); + ensure_equals("LLDataPackerBinaryBuffer::packS32 failed", valS32, unpkvalS32); + ensure("LLDataPackerBinaryBuffer::packF32 failed", is_approx_equal(valF32, unpkvalF32)); + ensure_equals("LLDataPackerBinaryBuffer::packColor4 failed", llcol4, unpkllcol4); + ensure_equals("LLDataPackerBinaryBuffer::packColor4U failed", llcol4u, unpkllcol4u); + ensure_equals("LLDataPackerBinaryBuffer::packVector2 failed", llvec2, unpkllvec2); + ensure_equals("LLDataPackerBinaryBuffer::packVector3 failed", llvec3, unpkllvec3); + ensure_equals("LLDataPackerBinaryBuffer::packVector4 failed", llvec4, unpkllvec4); + ensure_equals("LLDataPackerBinaryBuffer::packUUID failed", uuid, unpkuuid); + } + + template<> template<> + void datapacker_test_object_t::test<3>() + { + U8 packbuf[128]; + char str[] = "SecondLife is virtual World"; + S32 strSize = sizeof(str); // include '\0' + LLDataPackerBinaryBuffer lldp(packbuf, 128); + lldp.packString(str , "linden_lab"); + + ensure("LLDataPackerBinaryBuffer: current size is wrong", strSize == lldp.getCurrentSize()); + ensure("LLDataPackerBinaryBuffer: buffer size is wrong", 128 == lldp.getBufferSize()); + + lldp.reset(); + ensure("LLDataPackerBinaryBuffer::reset failed",0 == lldp.getCurrentSize()); + } + + template<> template<> + void datapacker_test_object_t::test<4>() + { + U8* packbuf = new U8[128]; + char str[] = "SecondLife is virtual World"; + LLDataPackerBinaryBuffer lldp(packbuf, 128); + lldp.packString(str , "linden_lab"); + lldp.freeBuffer(); + ensure("LLDataPackerBinaryBuffer.freeBuffer failed" , 0 == lldp.getBufferSize()); + + } + + template<> template<> + void datapacker_test_object_t::test<5>() + { + U8* buf = new U8[]("SecondLife is virtual World"); + S32 size = sizeof(buf); + LLDataPackerBinaryBuffer lldp(buf, size); + U8* new_buf = new U8[]("Its Amazing"); + size = sizeof(new_buf)-1; + lldp.assignBuffer(new_buf, size); + ensure("LLDataPackerBinaryBuffer::assignBuffer failed" , ((lldp.getBufferSize() == size) && (0 == lldp.getCurrentSize()))) ; + } + + template<> template<> + void datapacker_test_object_t::test<6>() + { + U8 packbuf[128]; + char str[] = "SecondLife is virtual World"; + LLDataPackerBinaryBuffer lldp(packbuf, 128); + lldp.packString(str , "linden_lab"); + U8 new_buffer[128]; + std::string unpkbuf; + LLDataPackerBinaryBuffer lldp1(new_buffer,128); + lldp1 = lldp; + lldp1.unpackString(unpkbuf, "linden_lab"); + ensure("1. LLDataPackerBinaryBuffer::operator= failed" , lldp1.getBufferSize() == lldp.getBufferSize()); + ensure_equals("2.LLDataPackerBinaryBuffer::operator= failed", str,unpkbuf); + } + + //*********LLDataPackerAsciiBuffer + + template<> template<> + void datapacker_test_object_t::test<7>() + { + char packbuf[128]; + F32 f_val = 44.44f, f_unpkval; + LLDataPackerAsciiBuffer lldp(packbuf,128); + lldp.packFixed( f_val, "linden_lab", FALSE, 8, 8); + + LLDataPackerAsciiBuffer lldp1(packbuf, lldp.getCurrentSize()); + lldp1.unpackFixed(f_unpkval, "linden_lab", FALSE, 8, 8); + ensure_approximately_equals("LLDataPackerAsciiBuffer::packFixed failed", f_val, f_unpkval, 8); + } + + template<> template<> + void datapacker_test_object_t::test<8>() + { + char packbuf[1024]; + + char str[] = "SecondLife is virtual World\0"; + char strBinary[] = "SecondLife is virtual World"; + char strBinaryFixed[] = "Fixed Data"; + S32 sizeBinaryFixed = sizeof(strBinaryFixed); + U8 valU8 = 'C'; + U16 valU16 = 0xFFFF; + U32 valU32 = 0xFFFFFFFF; + S32 valS32 = -94967295; + F32 valF32 = 4354355.44f ; + LLColor4 llcol4(3.3f, 0, 4.4f, 5.5f); + LLColor4U llcol4u(3, 128, 24, 33); + LLVector2 llvec2(333.33f, 444.44f); + LLVector3 llvec3(333.33f, 444.44f, 555.55f); + LLVector4 llvec4(4354355.44f, 444.44f, 555.55f, 666.66f); + LLUUID uuid; + + std::string unpkstr; + char unpkstrBinary[256]; + char unpkstrBinaryFixed[256]; + S32 unpksizeBinary; + U8 unpkvalU8; + U16 unpkvalU16; + U32 unpkvalU32; + S32 unpkvalS32; + F32 unpkvalF32; + LLColor4 unpkllcol4; + LLColor4U unpkllcol4u; + LLVector2 unpkllvec2; + LLVector3 unpkllvec3; + LLVector4 unpkllvec4; + LLUUID unpkuuid; + + LLDataPackerAsciiBuffer lldp(packbuf,1024); + lldp.packString(str , "linden_lab_str"); + lldp.packBinaryData((U8*)strBinary, sizeof(strBinary), "linden_lab_bd"); + lldp.packBinaryDataFixed((U8*)strBinaryFixed, sizeBinaryFixed, "linden_lab_bdf"); + lldp.packU8(valU8,"linden_lab_u8"); + lldp.packU16(valU16,"linden_lab_u16"); + lldp.packU32(valU32, "linden_lab_u32"); + lldp.packS32(valS32, "linden_lab_s32"); + lldp.packF32(valF32, "linden_lab_f32"); + lldp.packColor4(llcol4, "linden_lab_col4"); + lldp.packColor4U(llcol4u, "linden_lab_col4u"); + lldp.packVector2(llvec2, "linden_lab_vec2"); + lldp.packVector3(llvec3, "linden_lab_vec3"); + lldp.packVector4(llvec4, "linden_lab_vec4"); + uuid.generate(); + lldp.packUUID(uuid, "linden_lab_uuid"); + + S32 cur_size = lldp.getCurrentSize(); + + LLDataPackerAsciiBuffer lldp1(packbuf, cur_size); + lldp1.unpackString(unpkstr , "linden_lab_str"); + lldp1.unpackBinaryData((U8*)unpkstrBinary, unpksizeBinary, "linden_lab_bd"); + lldp1.unpackBinaryDataFixed((U8*)unpkstrBinaryFixed, sizeBinaryFixed, "linden_lab_bdf"); + lldp1.unpackU8(unpkvalU8,"linden_lab_u8"); + lldp1.unpackU16(unpkvalU16,"linden_lab_u16"); + lldp1.unpackU32(unpkvalU32, "linden_lab_u32"); + lldp1.unpackS32(unpkvalS32, "linden_lab_s32"); + lldp1.unpackF32(unpkvalF32, "linden_lab_f32"); + lldp1.unpackColor4(unpkllcol4, "linden_lab_col4"); + lldp1.unpackColor4U(unpkllcol4u, "linden_lab_col4u"); + lldp1.unpackVector2(unpkllvec2, "linden_lab_vec2"); + lldp1.unpackVector3(unpkllvec3, "linden_lab_vec3"); + lldp1.unpackVector4(unpkllvec4, "linden_lab_vec4"); + lldp1.unpackUUID(unpkuuid, "linden_lab_uuid"); + + ensure("LLDataPackerAsciiBuffer::packString failed", strcmp(str, unpkstr.c_str()) == 0); + ensure("LLDataPackerAsciiBuffer::packBinaryData failed", strcmp(strBinary, unpkstrBinary) == 0); + ensure("LLDataPackerAsciiBuffer::packBinaryDataFixed failed", strcmp(strBinaryFixed, unpkstrBinaryFixed) == 0); + ensure_equals("LLDataPackerAsciiBuffer::packU8 failed", valU8, unpkvalU8); + ensure_equals("LLDataPackerAsciiBuffer::packU16 failed", valU16, unpkvalU16); + ensure_equals("LLDataPackerAsciiBuffer::packU32 failed", valU32, unpkvalU32); + ensure_equals("LLDataPackerAsciiBuffer::packS32 failed", valS32, unpkvalS32); + ensure("LLDataPackerAsciiBuffer::packF32 failed", is_approx_equal(valF32, unpkvalF32)); + ensure_equals("LLDataPackerAsciiBuffer::packColor4 failed", llcol4, unpkllcol4); + ensure_equals("LLDataPackerAsciiBuffer::packColor4U failed", llcol4u, unpkllcol4u); + ensure_equals("LLDataPackerAsciiBuffer::packVector2 failed", llvec2, unpkllvec2); + ensure_equals("LLDataPackerAsciiBuffer::packVector3 failed", llvec3, unpkllvec3); + ensure_equals("LLDataPackerAsciiBuffer::packVector4 failed", llvec4, unpkllvec4); + ensure_equals("LLDataPackerAsciiBuffer::packUUID failed", uuid, unpkuuid); + } + + template<> template<> + void datapacker_test_object_t::test<9>() + { + char* packbuf = new char[128]; + char str[] = "SecondLife is virtual World"; + LLDataPackerAsciiBuffer lldp(packbuf, 128); + lldp.packString(str , "linden_lab"); + lldp.freeBuffer(); + ensure("LLDataPackerAsciiBuffer::freeBuffer failed" , 0 == lldp.getBufferSize()); + } + + template<> template<> + void datapacker_test_object_t::test<10>() + { + char buf[] = "SecondLife is virtual World"; + S32 size = sizeof(buf); + LLDataPackerAsciiBuffer lldp(buf, size); + char new_buf[] = "Its Amazing"; + size = sizeof(new_buf); + lldp.assignBuffer(new_buf, size); + ensure("LLDataPackerAsciiBuffer::assignBuffer failed" , ((lldp.getBufferSize() == size) && (1 == lldp.getCurrentSize()))) ; + } + + //*********LLDataPackerAsciiFile + + template<> template<> + void datapacker_test_object_t::test<11>() + { + F32 f_val = 44.44f, f_unpkval; + + LLFILE* fp = LLFile::fopen(TEST_FILE_NAME, "w+"); + if(!fp) + { + LL_ERRS() << "File couldnt be open" << LL_ENDL; + return; + } + + LLDataPackerAsciiFile lldp(fp,2); + lldp.packFixed( f_val, "linden_lab", FALSE, 8, 8); + + fflush(fp); + fseek(fp,0,SEEK_SET); + LLDataPackerAsciiFile lldp1(fp,2); + + lldp1.unpackFixed(f_unpkval, "linden_lab", FALSE, 8, 8); + fclose(fp); + + ensure_approximately_equals("LLDataPackerAsciiFile::packFixed failed", f_val, f_unpkval, 8); + } + + template<> template<> + void datapacker_test_object_t::test<12>() + { + char str[] = "SecondLife is virtual World\0"; + char strBinary[] = "SecondLife is virtual World"; + char strBinaryFixed[] = "Fixed Data"; + S32 sizeBinaryFixed = sizeof(strBinaryFixed); + U8 valU8 = 'C'; + U16 valU16 = 0xFFFF; + U32 valU32 = 0xFFFFFFFF; + S32 valS32 = -94967295; + F32 valF32 = 4354355.44f ; + LLColor4 llcol4(3.3f, 0, 4.4f, 5.5f); + LLColor4U llcol4u(3, 128, 24, 33); + LLVector2 llvec2(333.33f, 444.44f); + LLVector3 llvec3(333.33f, 444.44f, 555.55f); + LLVector4 llvec4(333.33f, 444.44f, 555.55f, 666.66f); + LLUUID uuid; + + std::string unpkstr; + char unpkstrBinary[256]; + char unpkstrBinaryFixed[256]; + S32 unpksizeBinary; + U8 unpkvalU8; + U16 unpkvalU16; + U32 unpkvalU32; + S32 unpkvalS32; + F32 unpkvalF32; + LLColor4 unpkllcol4; + LLColor4U unpkllcol4u; + LLVector2 unpkllvec2; + LLVector3 unpkllvec3; + LLVector4 unpkllvec4; + LLUUID unpkuuid; + + LLFILE* fp = LLFile::fopen(TEST_FILE_NAME,"w+"); + if(!fp) + { + LL_ERRS() << "File couldnt be open" << LL_ENDL; + return; + } + + LLDataPackerAsciiFile lldp(fp,2); + + lldp.packString(str , "linden_lab_str"); + lldp.packBinaryData((U8*)strBinary, sizeof(strBinary), "linden_lab_bd"); + lldp.packBinaryDataFixed((U8*)strBinaryFixed, sizeBinaryFixed, "linden_lab_bdf"); + lldp.packU8(valU8,"linden_lab_u8"); + lldp.packU16(valU16,"linden_lab_u16"); + lldp.packU32(valU32, "linden_lab_u32"); + lldp.packS32(valS32, "linden_lab_s32"); + lldp.packF32(valF32, "linden_lab_f32"); + lldp.packColor4(llcol4, "linden_lab_col4"); + lldp.packColor4U(llcol4u, "linden_lab_col4u"); + lldp.packVector2(llvec2, "linden_lab_vec2"); + lldp.packVector3(llvec3, "linden_lab_vec3"); + lldp.packVector4(llvec4, "linden_lab_vec4"); + uuid.generate(); + lldp.packUUID(uuid, "linden_lab_uuid"); + + fflush(fp); + fseek(fp,0,SEEK_SET); + LLDataPackerAsciiFile lldp1(fp,2); + + lldp1.unpackString(unpkstr , "linden_lab_str"); + lldp1.unpackBinaryData((U8*)unpkstrBinary, unpksizeBinary, "linden_lab_bd"); + lldp1.unpackBinaryDataFixed((U8*)unpkstrBinaryFixed, sizeBinaryFixed, "linden_lab_bdf"); + lldp1.unpackU8(unpkvalU8,"linden_lab_u8"); + lldp1.unpackU16(unpkvalU16,"linden_lab_u16"); + lldp1.unpackU32(unpkvalU32, "linden_lab_u32"); + lldp1.unpackS32(unpkvalS32, "linden_lab_s32"); + lldp1.unpackF32(unpkvalF32, "linden_lab_f32"); + lldp1.unpackColor4(unpkllcol4, "linden_lab_col4"); + lldp1.unpackColor4U(unpkllcol4u, "linden_lab_col4u"); + lldp1.unpackVector2(unpkllvec2, "linden_lab_vec2"); + lldp1.unpackVector3(unpkllvec3, "linden_lab_vec3"); + lldp1.unpackVector4(unpkllvec4, "linden_lab_vec4"); + lldp1.unpackUUID(unpkuuid, "linden_lab_uuid"); + + fclose(fp); + + ensure("LLDataPackerAsciiFile::packString failed", strcmp(str, unpkstr.c_str()) == 0); + ensure("LLDataPackerAsciiFile::packBinaryData failed", strcmp(strBinary, unpkstrBinary) == 0); + ensure("LLDataPackerAsciiFile::packBinaryDataFixed failed", strcmp(strBinaryFixed, unpkstrBinaryFixed) == 0); + ensure_equals("LLDataPackerAsciiFile::packU8 failed", valU8, unpkvalU8); + ensure_equals("LLDataPackerAsciiFile::packU16 failed", valU16, unpkvalU16); + ensure_equals("LLDataPackerAsciiFile::packU32 failed", valU32, unpkvalU32); + ensure_equals("LLDataPackerAsciiFile::packS32 failed", valS32, unpkvalS32); + ensure("LLDataPackerAsciiFile::packF32 failed", is_approx_equal(valF32, unpkvalF32)); + ensure_equals("LLDataPackerAsciiFile::packColor4 failed", llcol4, unpkllcol4); + ensure_equals("LLDataPackerAsciiFile::packColor4U failed", llcol4u, unpkllcol4u); + ensure_equals("LLDataPackerAsciiFile::packVector2 failed", llvec2, unpkllvec2); + ensure_equals("LLDataPackerAsciiFile::packVector3 failed", llvec3, unpkllvec3); + ensure_equals("LLDataPackerAsciiFile::packVector4 failed", llvec4, unpkllvec4); + ensure_equals("LLDataPackerAsciiFile::packUUID failed", uuid, unpkuuid); + } + + template<> template<> + void datapacker_test_object_t::test<13>() + { + F32 f_val = 44.44f, f_unpkval; + + std::ostringstream ostr; + LLDataPackerAsciiFile lldp(ostr,2); + lldp.packFixed( f_val, "linden_lab", FALSE, 8, 8); + + std::istringstream istr(ostr.str()); + LLDataPackerAsciiFile lldp1(istr,2); + + lldp1.unpackFixed(f_unpkval, "linden_lab", FALSE, 8, 8); + + ensure_approximately_equals("LLDataPackerAsciiFile::packFixed (iostring) failed", f_val, f_unpkval, 8); + } + + template<> template<> + void datapacker_test_object_t::test<14>() + { + char str[] = "SecondLife is virtual World\0"; + char strBinary[] = "SecondLife is virtual World"; + char strBinaryFixed[] = "Fixed Data"; + S32 sizeBinaryFixed = sizeof(strBinaryFixed); + U8 valU8 = 'C'; + U16 valU16 = 0xFFFF; + U32 valU32 = 0xFFFFFFFF; + S32 valS32 = -94967295; + F32 valF32 = 4354355.44f ; + LLColor4 llcol4(3.3f, 0, 4.4f, 5.5f); + LLColor4U llcol4u(3, 128, 24, 33); + LLVector2 llvec2(3333333.33f, 444.333344f); + LLVector3 llvec3(3323233.33f, 444.4324f, 555.553232f); + LLVector4 llvec4(333.33233f, 444.4323234f, 55323225.55f, 6323236.66f); + LLUUID uuid; + + std::string unpkstr; + char unpkstrBinary[256]; + char unpkstrBinaryFixed[256]; + S32 unpksizeBinary; + U8 unpkvalU8; + U16 unpkvalU16; + U32 unpkvalU32; + S32 unpkvalS32; + F32 unpkvalF32; + LLColor4 unpkllcol4; + LLColor4U unpkllcol4u; + LLVector2 unpkllvec2; + LLVector3 unpkllvec3; + LLVector4 unpkllvec4; + LLUUID unpkuuid; + + std::ostringstream ostr; + LLDataPackerAsciiFile lldp(ostr,2); + + lldp.packString(str , "linden_lab_str"); + lldp.packBinaryData((U8*)strBinary, sizeof(strBinary), "linden_lab_bd"); + lldp.packBinaryDataFixed((U8*)strBinaryFixed, sizeBinaryFixed, "linden_lab_bdf"); + lldp.packU8(valU8,"linden_lab_u8"); + lldp.packU16(valU16,"linden_lab_u16"); + lldp.packU32(valU32, "linden_lab_u32"); + lldp.packS32(valS32, "linden_lab_s32"); + lldp.packF32(valF32, "linden_lab_f32"); + lldp.packColor4(llcol4, "linden_lab_col4"); + lldp.packColor4U(llcol4u, "linden_lab_col4u"); + lldp.packVector2(llvec2, "linden_lab_vec2"); + lldp.packVector3(llvec3, "linden_lab_vec3"); + lldp.packVector4(llvec4, "linden_lab_vec4"); + uuid.generate(); + lldp.packUUID(uuid, "linden_lab_uuid"); + + std::istringstream istr(ostr.str()); + LLDataPackerAsciiFile lldp1(istr,2); + + lldp1.unpackString(unpkstr , "linden_lab_str"); + lldp1.unpackBinaryData((U8*)unpkstrBinary, unpksizeBinary, "linden_lab_bd"); + lldp1.unpackBinaryDataFixed((U8*)unpkstrBinaryFixed, sizeBinaryFixed, "linden_lab_bdf"); + lldp1.unpackU8(unpkvalU8,"linden_lab_u8"); + lldp1.unpackU16(unpkvalU16,"linden_lab_u16"); + lldp1.unpackU32(unpkvalU32, "linden_lab_u32"); + lldp1.unpackS32(unpkvalS32, "linden_lab_s32"); + lldp1.unpackF32(unpkvalF32, "linden_lab_f32"); + lldp1.unpackColor4(unpkllcol4, "linden_lab_col4"); + lldp1.unpackColor4U(unpkllcol4u, "linden_lab_col4u"); + lldp1.unpackVector2(unpkllvec2, "linden_lab_vec2"); + lldp1.unpackVector3(unpkllvec3, "linden_lab_vec3"); + lldp1.unpackVector4(unpkllvec4, "linden_lab_vec4"); + lldp1.unpackUUID(unpkuuid, "linden_lab_uuid"); + + ensure("LLDataPackerAsciiFile::packString (iostring) failed", strcmp(str, unpkstr.c_str()) == 0); + ensure("LLDataPackerAsciiFile::packBinaryData (iostring) failed", strcmp(strBinary, unpkstrBinary) == 0); + ensure("LLDataPackerAsciiFile::packBinaryDataFixed (iostring) failed", strcmp(strBinaryFixed, unpkstrBinaryFixed) == 0); + ensure_equals("LLDataPackerAsciiFile::packU8 (iostring) failed", valU8, unpkvalU8); + ensure_equals("LLDataPackerAsciiFile::packU16 (iostring) failed", valU16, unpkvalU16); + ensure_equals("LLDataPackerAsciiFile::packU32 (iostring) failed", valU32, unpkvalU32); + ensure_equals("LLDataPackerAsciiFile::packS32 (iostring) failed", valS32, unpkvalS32); + ensure("LLDataPackerAsciiFile::packF32 (iostring) failed", is_approx_equal(valF32, unpkvalF32)); + ensure_equals("LLDataPackerAsciiFile::packColor4 (iostring) failed", llcol4, unpkllcol4); + ensure_equals("LLDataPackerAsciiFile::packColor4U (iostring) failed", llcol4u, unpkllcol4u); + ensure_equals("LLDataPackerAsciiFile::packVector2 (iostring) failed", llvec2, unpkllvec2); + ensure_equals("LLDataPackerAsciiFile::packVector3 (iostring) failed", llvec3, unpkllvec3); + ensure_equals("LLDataPackerAsciiFile::packVector4 (iostring) failed", llvec4, unpkllvec4); + ensure_equals("LLDataPackerAsciiFile::packUUID (iostring) failed", uuid, unpkuuid); + } +} diff --git a/indra/llmessage/tests/llhttpclient_test.cpp b/indra/llmessage/tests/llhttpclient_test.cpp deleted file mode 100644 index 1881144d3e..0000000000 --- a/indra/llmessage/tests/llhttpclient_test.cpp +++ /dev/null @@ -1,311 +0,0 @@ -/** - * @file llhttpclient_test.cpp - * @brief Testing the HTTP client classes. - * - * $LicenseInfo:firstyear=2006&license=viewerlgpl$ - * Second Life Viewer Source Code - * Copyright (C) 2010, Linden Research, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; - * version 2.1 of the License only. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA - * $/LicenseInfo$ - */ - -/** - * - * These classes test the HTTP client framework. - * - */ - -#include -#include "linden_common.h" - -#include "lltut.h" -#include "llhttpclient.h" -#include "llformat.h" -#include "llpipeutil.h" -#include "llproxy.h" -#include "llpumpio.h" - -#include "lliosocket.h" -#include "llstring.h" -#include "stringize.h" -#include "llcleanup.h" - -namespace tut -{ - struct HTTPClientTestData - { - public: - HTTPClientTestData(): - PORT(LLStringUtil::getenv("PORT")), - // Turning NULL PORT into empty string doesn't make things work; - // that's just to keep this initializer from blowing up. We test - // PORT separately in the constructor body. - local_server(STRINGIZE("http://127.0.0.1:" << PORT << "/")) - { - ensure("Set environment variable PORT to local test server port", !PORT.empty()); - apr_pool_create(&mPool, NULL); - LLCurl::initClass(false); - mClientPump = new LLPumpIO(mPool); - - LLHTTPClient::setPump(*mClientPump); - } - - ~HTTPClientTestData() - { - delete mClientPump; - SUBSYSTEM_CLEANUP(LLProxy); - apr_pool_destroy(mPool); - } - - void runThePump(float timeout = 100.0f) - { - LLTimer timer; - timer.setTimerExpirySec(timeout); - - while(!mSawCompleted && !mSawCompletedHeader && !timer.hasExpired()) - { - LLFrameTimer::updateFrameTime(); - if (mClientPump) - { - mClientPump->pump(); - mClientPump->callback(); - } - } - } - - const std::string PORT; - const std::string local_server; - - private: - apr_pool_t* mPool; - LLPumpIO* mClientPump; - - protected: - void ensureStatusOK() - { - if (mSawError) - { - std::string msg = - llformat("httpFailure() called when not expected, status %d", - mStatus); - fail(msg); - } - } - - void ensureStatusError() - { - if (!mSawError) - { - fail("httpFailure() wasn't called"); - } - } - - LLSD getResult() - { - return mResult; - } - LLSD getHeader() - { - return mHeader; - } - - protected: - bool mSawError; - U32 mStatus; - std::string mReason; - bool mSawCompleted; - bool mSawCompletedHeader; - LLSD mResult; - LLSD mHeader; - bool mResultDeleted; - - class Result : public LLHTTPClient::Responder - { - protected: - Result(HTTPClientTestData& client) - : mClient(client) - { - } - - public: - static Result* build(HTTPClientTestData& client) - { - return new Result(client); - } - - ~Result() - { - mClient.mResultDeleted = true; - } - - protected: - virtual void httpFailure() - { - mClient.mSawError = true; - mClient.mStatus = getStatus(); - mClient.mReason = getReason(); - } - - virtual void httpSuccess() - { - mClient.mResult = getContent(); - } - - virtual void httpCompleted() - { - LLHTTPClient::Responder::httpCompleted(); - - mClient.mSawCompleted = true; - mClient.mSawCompletedHeader = true; - mClient.mHeader = getResponseHeaders(); - } - - private: - HTTPClientTestData& mClient; - }; - - friend class Result; - - protected: - LLHTTPClient::ResponderPtr newResult() - { - mSawError = false; - mStatus = 0; - mSawCompleted = false; - mSawCompletedHeader = false; - mResult.clear(); - mHeader.clear(); - mResultDeleted = false; - - return Result::build(*this); - } - }; - - - typedef test_group HTTPClientTestGroup; - typedef HTTPClientTestGroup::object HTTPClientTestObject; - HTTPClientTestGroup httpClientTestGroup("http_client"); - - template<> template<> - void HTTPClientTestObject::test<1>() - { - LLHTTPClient::get(local_server, newResult()); - runThePump(); - ensureStatusOK(); - ensure("result object wasn't destroyed", mResultDeleted); - } - - template<> template<> - void HTTPClientTestObject::test<2>() - { - // Please nobody listen on this particular port... - LLHTTPClient::get("http://127.0.0.1:7950", newResult()); - runThePump(); - ensureStatusError(); - } - - template<> template<> - void HTTPClientTestObject::test<3>() - { - LLSD sd; - - sd["list"][0]["one"] = 1; - sd["list"][0]["two"] = 2; - sd["list"][1]["three"] = 3; - sd["list"][1]["four"] = 4; - - LLHTTPClient::post(local_server + "web/echo", sd, newResult()); - runThePump(); - ensureStatusOK(); - ensure_equals("echoed result matches", getResult(), sd); - } - - template<> template<> - void HTTPClientTestObject::test<4>() - { - LLSD sd; - - sd["message"] = "This is my test message."; - - LLHTTPClient::put(local_server + "test/storage", sd, newResult()); - runThePump(); - ensureStatusOK(); - - LLHTTPClient::get(local_server + "test/storage", newResult()); - runThePump(); - ensureStatusOK(); - ensure_equals("echoed result matches", getResult(), sd); - - } - - template<> template<> - void HTTPClientTestObject::test<5>() - { - LLSD sd; - sd["status"] = 543; - sd["reason"] = "error for testing"; - - LLHTTPClient::post(local_server + "test/error", sd, newResult()); - runThePump(); - ensureStatusError(); - ensure_contains("reason", mReason, sd["reason"]); - } - - template<> template<> - void HTTPClientTestObject::test<6>() - { - const F32 timeout = 1.0f; - LLHTTPClient::get(local_server + "test/timeout", newResult(), LLSD(), timeout); - runThePump(timeout * 5.0f); - ensureStatusError(); - ensure_equals("reason", mReason, "STATUS_EXPIRED"); - } - - template<> template<> - void HTTPClientTestObject::test<7>() - { - LLHTTPClient::get(local_server, newResult()); - runThePump(); - ensureStatusOK(); - LLSD expected = getResult(); - - LLSD result; - result = LLHTTPClient::blockingGet(local_server); - LLSD body = result["body"]; - ensure_equals("echoed result matches", body.size(), expected.size()); - } - template<> template<> - void HTTPClientTestObject::test<8>() - { - // This is testing for the presence of the Header in the returned results - // from an HTTP::get call. - LLHTTPClient::get(local_server, newResult()); - runThePump(); - ensureStatusOK(); - LLSD header = getHeader(); - ensure("got a header", ! header.emptyMap().asBoolean()); - } - template<> template<> - void HTTPClientTestObject::test<9>() - { - LLHTTPClient::head(local_server, newResult()); - runThePump(); - ensureStatusOK(); - ensure("result object wasn't destroyed", mResultDeleted); - } -} diff --git a/indra/llmessage/tests/llhttpnode_test.cpp b/indra/llmessage/tests/llhttpnode_test.cpp new file mode 100644 index 0000000000..c38dee120b --- /dev/null +++ b/indra/llmessage/tests/llhttpnode_test.cpp @@ -0,0 +1,428 @@ +/** + * @file lliohttpnode_tut.cpp + * @date May 2006 + * @brief HTTP server unit tests + * + * $LicenseInfo:firstyear=2006&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2010, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +#include "linden_common.h" +#include "lltut.h" +#include "llhttpnode.h" +#include "llsdhttpserver.h" + +namespace tut +{ + struct HTTPNodeTestData + { + LLHTTPNode mRoot; + LLSD mContext; + + const LLSD& context() { return mContext; } + + std::string remainderPath() + { + std::ostringstream pathOutput; + bool addSlash = false; + + LLSD& remainder = mContext[CONTEXT_REQUEST]["remainder"]; + for (LLSD::array_const_iterator i = remainder.beginArray(); + i != remainder.endArray(); + ++i) + { + if (addSlash) { pathOutput << '/'; } + pathOutput << i->asString(); + addSlash = true; + } + + return pathOutput.str(); + } + + void ensureRootTraversal(const std::string& path, + const LLHTTPNode* expectedNode, + const char* expectedRemainder) + { + mContext.clear(); + + const LLHTTPNode* actualNode = mRoot.traverse(path, mContext); + + ensure_equals("traverse " + path + " node", + actualNode, expectedNode); + ensure_equals("traverse " + path + " remainder", + remainderPath(), expectedRemainder); + } + + class Response : public LLHTTPNode::Response + { + public: + static LLPointer create() {return new Response();} + + LLSD mResult; + + void result(const LLSD& result) { mResult = result; } + void status(S32 code, const std::string& message) { } + void extendedResult(S32 code, const std::string& message, const LLSD& headers) { } + void extendedResult(S32 code, const LLSD& result, const LLSD& headers) { } + + private: + Response() {;} // Must be accessed through LLPointer. + }; + + typedef LLPointer ResponsePtr; + + LLSD get(const std::string& path) + { + mContext.clear(); + const LLHTTPNode* node = mRoot.traverse(path, mContext); + ensure(path + " found", node != NULL); + + ResponsePtr response = Response::create(); + node->get(LLHTTPNode::ResponsePtr(response), mContext); + return response->mResult; + } + + LLSD post(const std::string& path, const LLSD& input) + { + mContext.clear(); + const LLHTTPNode* node = mRoot.traverse(path, mContext); + ensure(path + " found", node != NULL); + + ResponsePtr response = Response::create(); + node->post(LLHTTPNode::ResponsePtr(response), mContext, input); + return response->mResult; + } + + void ensureMemberString(const std::string& name, + const LLSD& actualMap, const std::string& member, + const std::string& expectedValue) + { + ensure_equals(name + " " + member, + actualMap[member].asString(), expectedValue); + } + + + void ensureInArray(const LLSD& actualArray, + const std::string& expectedValue) + { + LLSD::array_const_iterator i = actualArray.beginArray(); + LLSD::array_const_iterator end = actualArray.endArray(); + + for (; i != end; ++i) + { + std::string path = i->asString(); + + if (path == expectedValue) + { + return; + } + } + + fail("didn't find " + expectedValue); + } + + }; + + typedef test_group HTTPNodeTestGroup; + typedef HTTPNodeTestGroup::object HTTPNodeTestObject; + HTTPNodeTestGroup httpNodeTestGroup("http node"); + + template<> template<> + void HTTPNodeTestObject::test<1>() + { + // traversal of the lone node + + ensureRootTraversal("", &mRoot, ""); + ensureRootTraversal("/", &mRoot, ""); + ensureRootTraversal("foo", NULL, "foo"); + ensureRootTraversal("foo/bar", NULL, "foo/bar"); + + ensure_equals("root of root", mRoot.rootNode(), &mRoot); + } + + template<> template<> + void HTTPNodeTestObject::test<2>() + { + // simple traversal of a single node + + LLHTTPNode* helloNode = new LLHTTPNode; + mRoot.addNode("hello", helloNode); + + ensureRootTraversal("hello", helloNode, ""); + ensureRootTraversal("/hello", helloNode, ""); + ensureRootTraversal("hello/", helloNode, ""); + ensureRootTraversal("/hello/", helloNode, ""); + + ensureRootTraversal("hello/there", NULL, "there"); + + ensure_equals("root of hello", helloNode->rootNode(), &mRoot); + } + + template<> template<> + void HTTPNodeTestObject::test<3>() + { + // traversal of mutli-branched tree + + LLHTTPNode* greekNode = new LLHTTPNode; + LLHTTPNode* alphaNode = new LLHTTPNode; + LLHTTPNode* betaNode = new LLHTTPNode; + LLHTTPNode* gammaNode = new LLHTTPNode; + + greekNode->addNode("alpha", alphaNode); + greekNode->addNode("beta", betaNode); + greekNode->addNode("gamma", gammaNode); + mRoot.addNode("greek", greekNode); + + LLHTTPNode* hebrewNode = new LLHTTPNode; + LLHTTPNode* alephNode = new LLHTTPNode; + + hebrewNode->addNode("aleph", alephNode); + mRoot.addNode("hebrew", hebrewNode); + + ensureRootTraversal("greek/alpha", alphaNode, ""); + ensureRootTraversal("greek/beta", betaNode, ""); + ensureRootTraversal("greek/delta", NULL, "delta"); + ensureRootTraversal("greek/gamma", gammaNode, ""); + ensureRootTraversal("hebrew/aleph", alephNode, ""); + + ensure_equals("root of greek", greekNode->rootNode(), &mRoot); + ensure_equals("root of alpha", alphaNode->rootNode(), &mRoot); + ensure_equals("root of beta", betaNode->rootNode(), &mRoot); + ensure_equals("root of gamma", gammaNode->rootNode(), &mRoot); + ensure_equals("root of hebrew", hebrewNode->rootNode(), &mRoot); + ensure_equals("root of aleph", alephNode->rootNode(), &mRoot); + } + + template<> template<> + void HTTPNodeTestObject::test<4>() + { + // automatic creation of parent nodes and not overriding existing nodes + + LLHTTPNode* alphaNode = new LLHTTPNode; + LLHTTPNode* betaNode = new LLHTTPNode; + LLHTTPNode* gammaNode = new LLHTTPNode; + LLHTTPNode* gamma2Node = new LLHTTPNode; + + mRoot.addNode("greek/alpha", alphaNode); + mRoot.addNode("greek/beta", betaNode); + + mRoot.addNode("greek/gamma", gammaNode); + mRoot.addNode("greek/gamma", gamma2Node); + + LLHTTPNode* alephNode = new LLHTTPNode; + + mRoot.addNode("hebrew/aleph", alephNode); + + ensureRootTraversal("greek/alpha", alphaNode, ""); + ensureRootTraversal("greek/beta", betaNode, ""); + ensureRootTraversal("greek/delta", NULL, "delta"); + ensureRootTraversal("greek/gamma", gammaNode, ""); + ensureRootTraversal("hebrew/aleph", alephNode, ""); + + ensure_equals("root of alpha", alphaNode->rootNode(), &mRoot); + ensure_equals("root of beta", betaNode->rootNode(), &mRoot); + ensure_equals("root of gamma", gammaNode->rootNode(), &mRoot); + ensure_equals("root of aleph", alephNode->rootNode(), &mRoot); + } + + class IntegerNode : public LLHTTPNode + { + public: + virtual void get(ResponsePtr response, const LLSD& context) const + { + int n = context["extra"]["value"]; + + LLSD info; + info["value"] = n; + info["positive"] = n > 0; + info["zero"] = n == 0; + info["negative"] = n < 0; + + response->result(info); + } + + virtual bool validate(const std::string& name, LLSD& context) const + { + int n; + std::istringstream i_stream(name); + i_stream >> n; + + if (i_stream.fail() || i_stream.get() != EOF) + { + return false; + } + + context["extra"]["value"] = n; + return true; + } + }; + + class SquareNode : public LLHTTPNode + { + public: + virtual void get(ResponsePtr response, const LLSD& context) const + { + int n = context["extra"]["value"]; + response->result(n*n); + } + }; + + template<> template<> + void HTTPNodeTestObject::test<5>() + { + // wildcard nodes + + LLHTTPNode* miscNode = new LLHTTPNode; + LLHTTPNode* iNode = new IntegerNode; + LLHTTPNode* sqNode = new SquareNode; + + mRoot.addNode("test/misc", miscNode); + mRoot.addNode("test/", iNode); + mRoot.addNode("test//square", sqNode); + + ensureRootTraversal("test/42", iNode, ""); + ensure_equals("stored integer", + context()["extra"]["value"].asInteger(), 42); + + ensureRootTraversal("test/bob", NULL, "bob"); + ensure("nothing stored", + context()["extra"]["value"].isUndefined()); + + ensureRootTraversal("test/3/square", sqNode, ""); + ResponsePtr response = Response::create(); + sqNode->get(LLHTTPNode::ResponsePtr(response), context()); + ensure_equals("square result", response->mResult.asInteger(), 9); + } + + class AlphaNode : public LLHTTPNode + { + public: + virtual bool handles(const LLSD& remainder, LLSD& context) const + { + LLSD::array_const_iterator i = remainder.beginArray(); + LLSD::array_const_iterator end = remainder.endArray(); + + for (; i != end; ++i) + { + std::string s = i->asString(); + if (s.empty() || s[0] != 'a') + { + return false; + } + } + + return true; + } + }; + + template<> template<> + void HTTPNodeTestObject::test<6>() + { + // nodes that handle remainders + + LLHTTPNode* miscNode = new LLHTTPNode; + LLHTTPNode* aNode = new AlphaNode; + LLHTTPNode* zNode = new LLHTTPNode; + + mRoot.addNode("test/misc", miscNode); + mRoot.addNode("test/alpha", aNode); + mRoot.addNode("test/alpha/zebra", zNode); + + ensureRootTraversal("test/alpha", aNode, ""); + ensureRootTraversal("test/alpha/abe", aNode, "abe"); + ensureRootTraversal("test/alpha/abe/amy", aNode, "abe/amy"); + ensureRootTraversal("test/alpha/abe/bea", NULL, "abe/bea"); + ensureRootTraversal("test/alpha/bob", NULL, "bob"); + ensureRootTraversal("test/alpha/zebra", zNode, ""); + } + + template<> template<> + void HTTPNodeTestObject::test<7>() + { + // test auto registration + + LLHTTPStandardServices::useServices(); + LLHTTPRegistrar::buildAllServices(mRoot); + + { + LLSD result = get("web/hello"); + ensure_equals("hello result", result.asString(), "hello"); + } + { + LLSD stuff = 3.14159; + LLSD result = post("web/echo", stuff); + ensure_equals("echo result", result, stuff); + } + } + + template<> template<> + void HTTPNodeTestObject::test<8>() + { + // test introspection + + LLHTTPRegistrar::buildAllServices(mRoot); + + mRoot.addNode("test/misc", new LLHTTPNode); + mRoot.addNode("test/", new IntegerNode); + mRoot.addNode("test//square", new SquareNode); + + const LLSD result = get("web/server/api"); + + ensure("result is array", result.isArray()); + ensure("result size", result.size() >= 2); + + ensureInArray(result, "web/echo"); + ensureInArray(result, "web/hello"); + ensureInArray(result, "test/misc"); + ensureInArray(result, "test/"); + ensureInArray(result, "test//square"); + } + + template<> template<> + void HTTPNodeTestObject::test<9>() + { + // test introspection details + + LLHTTPRegistrar::buildAllServices(mRoot); + + const LLSD helloDetails = get("web/server/api/web/hello"); + + ensure_contains("hello description", + helloDetails["description"].asString(), "hello"); + ensure_equals("method name", helloDetails["api"][0].asString(), std::string("GET")); + ensureMemberString("hello", helloDetails, "output", "\"hello\""); + ensure_contains("hello __file__", + helloDetails["__file__"].asString(), "llsdhttpserver.cpp"); + ensure("hello line", helloDetails["__line__"].isInteger()); + + + const LLSD echoDetails = get("web/server/api/web/echo"); + + ensure_contains("echo description", + echoDetails["description"].asString(), "echo"); + ensure_equals("method name", echoDetails["api"][0].asString(), std::string("POST")); + ensureMemberString("echo", echoDetails, "input", ""); + ensureMemberString("echo", echoDetails, "output", ""); + ensure_contains("echo __file__", + echoDetails["__file__"].asString(), "llsdhttpserver.cpp"); + ensure("echo", echoDetails["__line__"].isInteger()); + } +} diff --git a/indra/llmessage/tests/lliohttpserver_test.cpp b/indra/llmessage/tests/lliohttpserver_test.cpp new file mode 100644 index 0000000000..7034f4a063 --- /dev/null +++ b/indra/llmessage/tests/lliohttpserver_test.cpp @@ -0,0 +1,350 @@ +/** + * @file lliohttpserver_tut.cpp + * @date May 2006 + * @brief HTTP server unit tests + * + * $LicenseInfo:firstyear=2006&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2010, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +#include "linden_common.h" +#include "lltut.h" +#include "llbufferstream.h" +#include "lliohttpserver.h" +#include "llsdhttpserver.h" +#include "llsdserialize.h" +#include "llcommon.h" + +#include "llpipeutil.h" + + +namespace tut +{ + class HTTPServiceTestData + { + public: + class DelayedEcho : public LLHTTPNode + { + HTTPServiceTestData* mTester; + + public: + DelayedEcho(HTTPServiceTestData* tester) : mTester(tester) { } + + void post(ResponsePtr response, const LLSD& context, const LLSD& input) const + { + ensure("response already set", mTester->mResponse == ResponsePtr(NULL)); + mTester->mResponse = response; + mTester->mResult = input; + } + }; + + class WireHello : public LLIOPipe + { + protected: + virtual EStatus process_impl( + const LLChannelDescriptors& channels, + buffer_ptr_t& buffer, + bool& eos, + LLSD& context, + LLPumpIO* pump) + { + if(!eos) return STATUS_BREAK; + LLSD sd = "yo!"; + LLBufferStream ostr(channels, buffer.get()); + ostr << LLSDXMLStreamer(sd); + return STATUS_DONE; + } + }; + + HTTPServiceTestData() + : mResponse(NULL) + { + LLHTTPStandardServices::useServices(); + LLHTTPRegistrar::buildAllServices(mRoot); + mRoot.addNode("/delayed/echo", new DelayedEcho(this)); + mRoot.addNode("/wire/hello", new LLHTTPNodeForPipe); + } + + ~HTTPServiceTestData() + { + } + + LLHTTPNode mRoot; + LLHTTPNode::ResponsePtr mResponse; + LLSD mResult; + + void pumpPipe(LLPumpIO* pump, S32 iterations) + { + while(iterations > 0) + { + pump->pump(); + pump->callback(); + --iterations; + } + } + + std::string makeRequest( + const std::string& name, + const std::string& httpRequest, + bool timeout = false) + { + LLPipeStringInjector* injector = new LLPipeStringInjector(httpRequest); + LLPipeStringExtractor* extractor = new LLPipeStringExtractor(); + + apr_pool_t* pool; + apr_pool_create(&pool, NULL); + + LLPumpIO* pump; + pump = new LLPumpIO(pool); + + LLPumpIO::chain_t chain; + LLSD context; + + chain.push_back(LLIOPipe::ptr_t(injector)); + LLIOHTTPServer::createPipe(chain, mRoot, LLSD()); + chain.push_back(LLIOPipe::ptr_t(extractor)); + + pump->addChain(chain, DEFAULT_CHAIN_EXPIRY_SECS); + + pumpPipe(pump, 10); + if(mResponse.notNull() && (! timeout)) + { + mResponse->result(mResult); + mResponse = NULL; + } + pumpPipe(pump, 10); + + std::string httpResult = extractor->string(); + + chain.clear(); + delete pump; + apr_pool_destroy(pool); + + if(mResponse.notNull() && timeout) + { + mResponse->result(mResult); + mResponse = NULL; + } + + return httpResult; + } + + std::string httpGET(const std::string& uri, + bool timeout = false) + { + std::string httpRequest = "GET " + uri + " HTTP/1.0\r\n\r\n"; + return makeRequest(uri, httpRequest, timeout); + } + + std::string httpPOST(const std::string& uri, + const std::string& body, + bool timeout, + const std::string& evilExtra = "") + { + std::ostringstream httpRequest; + httpRequest << "POST " + uri + " HTTP/1.0\r\n"; + httpRequest << "Content-Length: " << body.size() << "\r\n"; + httpRequest << "\r\n"; + httpRequest << body; + httpRequest << evilExtra; + + return makeRequest(uri, httpRequest.str(), timeout); + } + + std::string httpPOST(const std::string& uri, + const std::string& body, + const std::string& evilExtra = "") + { + bool timeout = false; + return httpPOST(uri, body, timeout, evilExtra); + } + }; + + typedef test_group HTTPServiceTestGroup; + typedef HTTPServiceTestGroup::object HTTPServiceTestObject; + HTTPServiceTestGroup httpServiceTestGroup("http service"); + + template<> template<> + void HTTPServiceTestObject::test<1>() + { + std::string result = httpGET("web/hello"); + + ensure_starts_with("web/hello status", result, + "HTTP/1.0 200 OK\r\n"); + + ensure_contains("web/hello content type", result, + "Content-Type: application/llsd+xml\r\n"); + + ensure_contains("web/hello content length", result, + "Content-Length: 36\r\n"); + + ensure_contains("web/hello content", result, + "\r\n" + "hello" + ); + } + + template<> template<> + void HTTPServiceTestObject::test<2>() + { + // test various HTTP errors + + std::string actual; + + actual = httpGET("web/missing"); + ensure_starts_with("web/missing 404", actual, + "HTTP/1.0 404 Not Found\r\n"); + + actual = httpGET("web/echo"); + ensure_starts_with("web/echo 405", actual, + "HTTP/1.0 405 Method Not Allowed\r\n"); + } + + template<> template<> + void HTTPServiceTestObject::test<3>() + { + // test POST & content-length handling + + std::string result; + + result = httpPOST("web/echo", + "42"); + + ensure_starts_with("web/echo status", result, + "HTTP/1.0 200 OK\r\n"); + + ensure_contains("web/echo content type", result, + "Content-Type: application/llsd+xml\r\n"); + + ensure_contains("web/echo content length", result, + "Content-Length: 35\r\n"); + + ensure_contains("web/hello content", result, + "\r\n" + "42" + ); + +/* TO DO: this test doesn't pass!! + + result = httpPOST("web/echo", + "evil", + "really! evil!!!"); + + ensure_equals("web/echo evil result", result, + "HTTP/1.0 200 OK\r\n" + "Content-Length: 34\r\n" + "\r\n" + "evil" + ); +*/ + } + + template<> template<> + void HTTPServiceTestObject::test<4>() + { + // test calling things based on pipes + + std::string result; + + result = httpGET("wire/hello"); + + ensure_contains("wire/hello", result, "yo!"); + } + + template<> template<> + void HTTPServiceTestObject::test<5>() + { + // test timeout before async response + std::string result; + + bool timeout = true; + result = httpPOST("delayed/echo", + "agent99", timeout); + + ensure_equals("timeout delayed/echo status", result, std::string("")); + } + + template<> template<> + void HTTPServiceTestObject::test<6>() + { + // test delayed service + std::string result; + + result = httpPOST("delayed/echo", + "agent99"); + + ensure_starts_with("delayed/echo status", result, + "HTTP/1.0 200 OK\r\n"); + + ensure_contains("delayed/echo content", result, + "\r\n" + "agent99" + ); + } + + template<> template<> + void HTTPServiceTestObject::test<7>() + { + // test large request + std::stringstream stream; + + //U32 size = 36 * 1024 * 1024; + //U32 size = 36 * 1024; + //std::vector data(size); + //memset(&(data[0]), '1', size); + //data[size - 1] = '\0'; + + + //std::string result = httpPOST("web/echo", &(data[0])); + + stream << ""; + for(U32 i = 0; i < 1000000; ++i) + { + stream << "42"; + } + stream << ""; + LL_INFOS() << "HTTPServiceTestObject::test<7>" + << stream.str().length() << LL_ENDL; + std::string result = httpPOST("web/echo", stream.str()); + ensure_starts_with("large echo status", result, "HTTP/1.0 200 OK\r\n"); + } + + template<> template<> + void HTTPServiceTestObject::test<8>() + { + // test the OPTIONS http method -- the default implementation + // should return the X-Documentation-URL + std::ostringstream http_request; + http_request << "OPTIONS / HTTP/1.0\r\nHost: localhost\r\n\r\n"; + bool timeout = false; + std::string result = makeRequest("/", http_request.str(), timeout); + ensure_starts_with("OPTIONS verb ok", result, "HTTP/1.0 200 OK\r\n"); + ensure_contains( + "Doc url header exists", + result, + "X-Documentation-URL: http://localhost"); + } + + + /* TO DO: + test generation of not found and method not allowed errors + */ +} diff --git a/indra/llmessage/tests/llmessageconfig_test.cpp b/indra/llmessage/tests/llmessageconfig_test.cpp new file mode 100644 index 0000000000..93443467a2 --- /dev/null +++ b/indra/llmessage/tests/llmessageconfig_test.cpp @@ -0,0 +1,236 @@ +/** + * @file llmessageconfig_tut.cpp + * @date March 2007 + * @brief LLMessageConfig unit tests + * + * $LicenseInfo:firstyear=2006&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2010, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +#include "linden_common.h" +#include "llmessageconfig.h" +#include "lltut.h" +#include "llsdserialize.h" +#include "llfile.h" +#include "lltimer.h" +#include "llframetimer.h" +#include "llsdutil.h" + +namespace tut +{ + struct LLMessageConfigTestData { + std::string mTestConfigDir; + + LLMessageConfigTestData() + { + LLUUID random; + random.generate(); + // generate temp dir + std::ostringstream oStr; +#if LL_WINDOWS + oStr << "llmessage-config-test-" << random; +#else + oStr << "/tmp/llmessage-config-test-" << random; +#endif + mTestConfigDir = oStr.str(); + LLFile::mkdir(mTestConfigDir); + writeConfigFile(LLSD()); + LLMessageConfig::initClass("simulator", mTestConfigDir); + } + + ~LLMessageConfigTestData() + { + // rm contents of temp dir + int rmfile = LLFile::remove((mTestConfigDir + "/message.xml")); + ensure_equals("rmfile value", rmfile, 0); + // rm temp dir + int rmdir = LLFile::rmdir(mTestConfigDir); + ensure_equals("rmdir value", rmdir, 0); + } + + void writeConfigFile(const LLSD& config) + { + llofstream file((mTestConfigDir + "/message.xml").c_str()); + if (file.is_open()) + { + LLSDSerialize::toPrettyXML(config, file); + } + file.close(); + } + }; + + typedef test_group LLMessageConfigTestGroup; + typedef LLMessageConfigTestGroup::object LLMessageConfigTestObject; + LLMessageConfigTestGroup llMessageConfigTestGroup("LLMessageConfig"); + + template<> template<> + void LLMessageConfigTestObject::test<1>() + // tests server defaults + { + LLSD config; + config["serverDefaults"]["simulator"] = "template"; + LLMessageConfig::useConfig(config); + ensure_equals("Ensure server default is not template", + LLMessageConfig::getServerDefaultFlavor(), + LLMessageConfig::TEMPLATE_FLAVOR); + } + + template<> template<> + void LLMessageConfigTestObject::test<2>() + // tests message flavors + { + LLSD config; + config["serverDefaults"]["simulator"] = "template"; + config["messages"]["msg1"]["flavor"] = "template"; + config["messages"]["msg2"]["flavor"] = "llsd"; + LLMessageConfig::useConfig(config); + ensure_equals("Ensure msg template flavor", + LLMessageConfig::getMessageFlavor("msg1"), + LLMessageConfig::TEMPLATE_FLAVOR); + ensure_equals("Ensure msg llsd flavor", + LLMessageConfig::getMessageFlavor("msg2"), + LLMessageConfig::LLSD_FLAVOR); + } + + template<> template<> + void LLMessageConfigTestObject::test<4>() + // tests message flavor defaults + { + LLSD config; + config["serverDefaults"]["simulator"] = "llsd"; + config["messages"]["msg1"]["trusted-sender"] = true; + LLMessageConfig::useConfig(config); + ensure_equals("Ensure missing message gives no flavor", + LLMessageConfig::getMessageFlavor("Test"), + LLMessageConfig::NO_FLAVOR); + ensure_equals("Ensure missing flavor is NO_FLAVOR even with sender trustedness set", + LLMessageConfig::getMessageFlavor("msg1"), + LLMessageConfig::NO_FLAVOR); + ensure_equals("Ensure server default is llsd", + LLMessageConfig::getServerDefaultFlavor(), + LLMessageConfig::LLSD_FLAVOR); + } + + template<> template<> + void LLMessageConfigTestObject::test<3>() + // tests trusted/untrusted senders + { + LLSD config; + config["serverDefaults"]["simulator"] = "template"; + config["messages"]["msg1"]["flavor"] = "llsd"; + config["messages"]["msg1"]["trusted-sender"] = false; + config["messages"]["msg2"]["flavor"] = "llsd"; + config["messages"]["msg2"]["trusted-sender"] = true; + LLMessageConfig::useConfig(config); + ensure_equals("Ensure untrusted is untrusted", + LLMessageConfig::getSenderTrustedness("msg1"), + LLMessageConfig::UNTRUSTED); + ensure_equals("Ensure trusted is trusted", + LLMessageConfig::getSenderTrustedness("msg2"), + LLMessageConfig::TRUSTED); + ensure_equals("Ensure missing trustedness is NOT_SET", + LLMessageConfig::getSenderTrustedness("msg3"), + LLMessageConfig::NOT_SET); + } + + template<> template<> + void LLMessageConfigTestObject::test<5>() + // tests trusted/untrusted without flag, only flavor + { + LLSD config; + config["serverDefaults"]["simulator"] = "template"; + config["messages"]["msg1"]["flavor"] = "llsd"; + LLMessageConfig::useConfig(config); + ensure_equals("Ensure msg1 exists, has llsd flavor", + LLMessageConfig::getMessageFlavor("msg1"), + LLMessageConfig::LLSD_FLAVOR); + ensure_equals("Ensure missing trusted is not set", + LLMessageConfig::getSenderTrustedness("msg1"), + LLMessageConfig::NOT_SET); + } + + template<> template<> + void LLMessageConfigTestObject::test<6>() + { + LLSD config; + config["capBans"]["MapLayer"] = true; + config["capBans"]["MapLayerGod"] = false; + LLMessageConfig::useConfig(config); + ensure_equals("Ensure cap ban true MapLayer", + LLMessageConfig::isCapBanned("MapLayer"), + true); + ensure_equals("Ensure cap ban false", + LLMessageConfig::isCapBanned("MapLayerGod"), + false); + } + + template<> template<> + void LLMessageConfigTestObject::test<7>() + // tests that config changes are picked up/refreshed periodically + { + LLSD config; + config["serverDefaults"]["simulator"] = "llsd"; + writeConfigFile(config); + + // wait for it to reload after N seconds + ms_sleep(6*1000); + LLFrameTimer::updateFrameTime(); + ensure_equals("Ensure reload after 6 seconds", + LLMessageConfig::getServerDefaultFlavor(), + LLMessageConfig::LLSD_FLAVOR); + } + + template<> template<> + void LLMessageConfigTestObject::test<8>() + // tests that config changes are picked up/refreshed periodically + { + LLSD config; + config["serverDefaults"]["simulator"] = "template"; + config["messages"]["msg1"]["flavor"] = "llsd"; + config["messages"]["msg1"]["only-send-latest"] = true; + config["messages"]["msg2"]["flavor"] = "llsd"; + config["messages"]["msg2"]["only-send-latest"] = false; + LLMessageConfig::useConfig(config); + ensure_equals("Ensure msg1 exists, sent latest-only", + LLMessageConfig::onlySendLatest("msg1"), + true); + ensure_equals("Ensure msg2 exists, sent latest-only", + LLMessageConfig::onlySendLatest("msg2"), + false); + } + + template<> template<> + void LLMessageConfigTestObject::test<9>() + // tests that event queue max is reloaded + { + LLSD config; + config["maxQueuedEvents"] = 200; + LLMessageConfig::useConfig(config); + ensure_equals("Ensure setting maxQueuedEvents", + LLMessageConfig::getMaxQueuedEvents(), + 200); + + LLMessageConfig::useConfig(LLSD()); + ensure_equals("Ensure default of event queue max 100", + LLMessageConfig::getMaxQueuedEvents(), + 100); + } +} diff --git a/indra/llmessage/tests/llmessagetemplateparser_test.cpp b/indra/llmessage/tests/llmessagetemplateparser_test.cpp new file mode 100644 index 0000000000..f665fdde4d --- /dev/null +++ b/indra/llmessage/tests/llmessagetemplateparser_test.cpp @@ -0,0 +1,368 @@ +/** + * @file llmessagetemplateparser_tut.cpp + * @date April 2007 + * @brief LLMessageTemplateParser unit tests + * + * $LicenseInfo:firstyear=2006&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2010, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +#include "linden_common.h" +#include "llmessagetemplateparser.h" +#include "lltut.h" + +namespace tut +{ + struct LLMessageTemplateParserTestData { + LLMessageTemplateParserTestData() : mMessage("unset message") + { + } + + ~LLMessageTemplateParserTestData() + { + } + + void ensure_next(LLTemplateTokenizer & tokens, + std::string value, + U32 line) + { + std::string next = tokens.next(); + ensure_equals(mMessage + " token matches", next, value); + ensure_equals(mMessage + " line matches", tokens.line(), line); + } + + char * prehash(const char * name) + { + return LLMessageStringTable::getInstance()->getString(name); + } + + void ensure_block_attributes(std::string identifier, + const LLMessageTemplate * message, + const char * name, + EMsgBlockType type, + S32 number, + S32 total_size) + { + const LLMessageBlock * block = message->getBlock(prehash(name)); + identifier = identifier + ":" + message->mName + ":" + name + " block"; + ensure(identifier + " exists", block != NULL); + ensure_equals(identifier + " name", block->mName, prehash(name)); + ensure_equals(identifier + " type", block->mType, type); + ensure_equals(identifier + " number", block->mNumber, number); + ensure_equals(identifier + " total size", block->mTotalSize, total_size); + } + + void ensure_variable_attributes(std::string identifier, + const LLMessageBlock * block, + const char * name, + EMsgVariableType type, + S32 size) + { + const LLMessageVariable * var = block->getVariable(prehash(name)); + identifier = identifier + ":" + block->mName + ":" + name + " variable"; + ensure(identifier + " exists", var != NULL); + ensure_equals( + identifier + " name", var->getName(), prehash(name)); + ensure_equals( + identifier + " type", var->getType(), type); + ensure_equals(identifier + " size", var->getSize(), size); + } + + std::string mMessage; + + }; + + typedef test_group LLMessageTemplateParserTestGroup; + typedef LLMessageTemplateParserTestGroup::object LLMessageTemplateParserTestObject; + LLMessageTemplateParserTestGroup llMessageTemplateParserTestGroup("LLMessageTemplateParser"); + + template<> template<> + void LLMessageTemplateParserTestObject::test<1>() + // tests tokenizer constructor and next methods + { + mMessage = "test method 1 walkthrough"; + LLTemplateTokenizer tokens("first line\nnext\t line\n\nfourth"); + ensure_next(tokens, "first", 1); + ensure_next(tokens, "line", 1); + ensure_next(tokens, "next", 2); + ensure_next(tokens, "line", 2); + ensure_next(tokens, "fourth", 4); + + tokens = LLTemplateTokenizer("\n\t{ \t Test1 Fixed \n 523 }\n\n"); + ensure(tokens.want("{")); + ensure_next(tokens, "Test1", 2); + ensure_next(tokens, "Fixed", 2); + ensure_next(tokens, "523", 3); + ensure(tokens.want("}")); + + tokens = LLTemplateTokenizer("first line\nnext\t line\n\nfourth"); + ensure(tokens.want("first")); + ensure_next(tokens, "line", 1); + ensure_next(tokens, "next", 2); + ensure_next(tokens, "line", 2); + ensure(tokens.want("fourth")); + } + + template<> template<> + void LLMessageTemplateParserTestObject::test<2>() + // tests tokenizer want method + { + // *NOTE: order matters + LLTemplateTokenizer tokens("first line\nnext\t line\n\nfourth"); + ensure_equals("wants first token", tokens.want("first"), true); + ensure_equals("doesn't want blar token", tokens.want("blar"), false); + ensure_equals("wants line token", tokens.want("line"), true); + } + + template<> template<> + void LLMessageTemplateParserTestObject::test<3>() + // tests tokenizer eof methods + { + LLTemplateTokenizer tokens("single\n\n"); + ensure_equals("is not at eof at beginning", tokens.atEOF(), false); + ensure_equals("doesn't want eof", tokens.wantEOF(), false); + ensure_equals("wants the first token just to consume it", + tokens.want("single"), true); + ensure_equals("is not at eof in middle", tokens.atEOF(), false); + ensure_equals("wants eof", tokens.wantEOF(), true); + ensure_equals("is at eof at end", tokens.atEOF(), true); + } + + template<> template<> + void LLMessageTemplateParserTestObject::test<4>() + // tests variable parsing method + { + LLTemplateTokenizer tokens(std::string("{ Test0 \n\t\n U32 \n\n }")); + LLMessageVariable * var = LLTemplateParser::parseVariable(tokens); + + ensure("test0 var parsed", var != 0); + ensure_equals("name of variable", std::string(var->getName()), std::string("Test0")); + ensure_equals("type of variable is U32", var->getType(), MVT_U32); + ensure_equals("size of variable", var->getSize(), 4); + + delete var; + + std::string message_string("\n\t{ \t Test1 Fixed \n 523 }\n\n"); + tokens = LLTemplateTokenizer(message_string); + var = LLTemplateParser::parseVariable(tokens); + + ensure("test1 var parsed", var != 0); + ensure_equals("name of variable", std::string(var->getName()), std::string("Test1")); + ensure_equals("type of variable is Fixed", var->getType(), MVT_FIXED); + ensure_equals("size of variable", var->getSize(), 523); + + delete var; + + // *NOTE: the parsers call LL_ERRS() on invalid input, so we can't really + // test that :-( + } + + template<> template<> + void LLMessageTemplateParserTestObject::test<5>() + // tests block parsing method + { + LLTemplateTokenizer tokens("{ BlockA Single { VarX F32 } }"); + LLMessageBlock * block = LLTemplateParser::parseBlock(tokens); + + ensure("blockA block parsed", block != 0); + ensure_equals("name of block", std::string(block->mName), std::string("BlockA")); + ensure_equals("type of block is Single", block->mType, MBT_SINGLE); + ensure_equals("total size of block", block->mTotalSize, 4); + ensure_equals("number of block defaults to 1", block->mNumber, 1); + ensure_equals("variable type of VarX is F32", + block->getVariableType(prehash("VarX")), MVT_F32); + ensure_equals("variable size of VarX", + block->getVariableSize(prehash("VarX")), 4); + + delete block; + + tokens = LLTemplateTokenizer("{ Stuff Variable { Id LLUUID } }"); + block = LLTemplateParser::parseBlock(tokens); + + ensure("stuff block parsed", block != 0); + ensure_equals("name of block", std::string(block->mName), std::string("Stuff")); + ensure_equals("type of block is Multiple", block->mType, MBT_VARIABLE); + ensure_equals("total size of block", block->mTotalSize, 16); + ensure_equals("number of block defaults to 1", block->mNumber, 1); + ensure_equals("variable type of Id is LLUUID", + block->getVariableType(prehash("Id")), MVT_LLUUID); + ensure_equals("variable size of Id", + block->getVariableSize(prehash("Id")), 16); + + delete block; + + tokens = LLTemplateTokenizer("{ Stuff2 Multiple 45 { Shid LLVector3d } }"); + block = LLTemplateParser::parseBlock(tokens); + + ensure("stuff2 block parsed", block != 0); + ensure_equals("name of block", std::string(block->mName), std::string("Stuff2")); + ensure_equals("type of block is Multiple", block->mType, MBT_MULTIPLE); + ensure_equals("total size of block", block->mTotalSize, 24); + ensure_equals("number of blocks", block->mNumber, 45); + ensure_equals("variable type of Shid is Vector3d", + block->getVariableType(prehash("Shid")), MVT_LLVector3d); + ensure_equals("variable size of Shid", + block->getVariableSize(prehash("Shid")), 24); + + delete block; + } + + template<> template<> + void LLMessageTemplateParserTestObject::test<6>() + // tests message parsing method on a simple message + { + std::string message_skel( + "{\n" + "TestMessage Low 1 NotTrusted Zerocoded\n" + "// comment \n" + " {\n" + "TestBlock1 Single\n" + " { Test1 U32 }\n" + " }\n" + " {\n" + " NeighborBlock Multiple 4\n" + " { Test0 U32 }\n" + " { Test1 U32 }\n" + " { Test2 U32 }\n" + " }\n" + "}"); + LLTemplateTokenizer tokens(message_skel); + LLMessageTemplate * message = LLTemplateParser::parseMessage(tokens); + + ensure("simple message parsed", message != 0); + ensure_equals("name of message", std::string(message->mName), std::string("TestMessage")); + ensure_equals("frequency is Low", message->mFrequency, MFT_LOW); + ensure_equals("trust is untrusted", message->mTrust, MT_NOTRUST); + ensure_equals("message number", message->mMessageNumber, (U32)((255 << 24) | (255 << 16) | 1)); + ensure_equals("message encoding is zerocoded", message->mEncoding, ME_ZEROCODED); + ensure_equals("message deprecation is notdeprecated", message->mDeprecation, MD_NOTDEPRECATED); + + LLMessageBlock * block = message->getBlock(prehash("NonexistantBlock")); + ensure("Nonexistant block does not exist", block == 0); + + delete message; + } + + template<> template<> + void LLMessageTemplateParserTestObject::test<7>() + // tests message parsing method on a deprecated message + { + std::string message_skel( + "{\n" + "TestMessageDeprecated High 34 Trusted Unencoded Deprecated\n" + " {\n" + "TestBlock2 Single\n" + " { Test2 S32 }\n" + " }\n" + "}"); + LLTemplateTokenizer tokens(message_skel); + LLMessageTemplate * message = LLTemplateParser::parseMessage(tokens); + + ensure("deprecated message parsed", message != 0); + ensure_equals("name of message", std::string(message->mName), std::string("TestMessageDeprecated")); + ensure_equals("frequency is High", message->mFrequency, MFT_HIGH); + ensure_equals("trust is trusted", message->mTrust, MT_TRUST); + ensure_equals("message number", message->mMessageNumber, (U32)34); + ensure_equals("message encoding is unencoded", message->mEncoding, ME_UNENCODED); + ensure_equals("message deprecation is deprecated", message->mDeprecation, MD_DEPRECATED); + + delete message; + } + + template<> template<> void LLMessageTemplateParserTestObject::test<8>() + // tests message parsing on RezMultipleAttachmentsFromInv, a possibly-faulty message + { + std::string message_skel( + "{\n\ + RezMultipleAttachmentsFromInv Low 452 NotTrusted Zerocoded\n\ + {\n\ + AgentData Single\n\ + { AgentID LLUUID }\n\ + { SessionID LLUUID }\n\ + } \n\ + {\n\ + HeaderData Single\n\ + { CompoundMsgID LLUUID } // All messages a single \"compound msg\" must have the same id\n\ + { TotalObjects U8 }\n\ + { FirstDetachAll BOOL }\n\ + }\n\ + {\n\ + ObjectData Variable // 1 to 4 of these per packet\n\ + { ItemID LLUUID }\n\ + { OwnerID LLUUID }\n\ + { AttachmentPt U8 } // 0 for default\n\ + { ItemFlags U32 }\n\ + { GroupMask U32 }\n\ + { EveryoneMask U32 }\n\ + { NextOwnerMask U32 }\n\ + { Name Variable 1 }\n\ + { Description Variable 1 }\n\ + }\n\ + }\n\ + "); + LLTemplateTokenizer tokens(message_skel); + LLMessageTemplate * message = LLTemplateParser::parseMessage(tokens); + + ensure("RezMultipleAttachmentsFromInv message parsed", message != 0); + ensure_equals("name of message", message->mName, prehash("RezMultipleAttachmentsFromInv")); + ensure_equals("frequency is low", message->mFrequency, MFT_LOW); + ensure_equals("trust is not trusted", message->mTrust, MT_NOTRUST); + ensure_equals("message number", message->mMessageNumber, (U32)((255 << 24) | (255 << 16) | 452)); + ensure_equals("message encoding is zerocoded", message->mEncoding, ME_ZEROCODED); + + ensure_block_attributes( + "RMAFI", message, "AgentData", MBT_SINGLE, 1, 16+16); + LLMessageBlock * block = message->getBlock(prehash("AgentData")); + ensure_variable_attributes("RMAFI", + block, "AgentID", MVT_LLUUID, 16); + ensure_variable_attributes("RMAFI", + block, "SessionID", MVT_LLUUID, 16); + + ensure_block_attributes( + "RMAFI", message, "HeaderData", MBT_SINGLE, 1, 16+1+1); + block = message->getBlock(prehash("HeaderData")); + ensure_variable_attributes( + "RMAFI", block, "CompoundMsgID", MVT_LLUUID, 16); + ensure_variable_attributes( + "RMAFI", block, "TotalObjects", MVT_U8, 1); + ensure_variable_attributes( + "RMAFI", block, "FirstDetachAll", MVT_BOOL, 1); + + + ensure_block_attributes( + "RMAFI", message, "ObjectData", MBT_VARIABLE, 1, -1); + block = message->getBlock(prehash("ObjectData")); + ensure_variable_attributes("RMAFI", block, "ItemID", MVT_LLUUID, 16); + ensure_variable_attributes("RMAFI", block, "OwnerID", MVT_LLUUID, 16); + ensure_variable_attributes("RMAFI", block, "AttachmentPt", MVT_U8, 1); + ensure_variable_attributes("RMAFI", block, "ItemFlags", MVT_U32, 4); + ensure_variable_attributes("RMAFI", block, "GroupMask", MVT_U32, 4); + ensure_variable_attributes("RMAFI", block, "EveryoneMask", MVT_U32, 4); + ensure_variable_attributes("RMAFI", block, "NextOwnerMask", MVT_U32, 4); + ensure_variable_attributes("RMAFI", block, "Name", MVT_VARIABLE, 1); + ensure_variable_attributes("RMAFI", block, "Description", MVT_VARIABLE, 1); + + delete message; + } + + + +} diff --git a/indra/llmessage/tests/llpipeutil.cpp b/indra/llmessage/tests/llpipeutil.cpp new file mode 100644 index 0000000000..1dd4bdfa3c --- /dev/null +++ b/indra/llmessage/tests/llpipeutil.cpp @@ -0,0 +1,183 @@ +/** + * @file llpipeutil.cpp + * @date 2006-05-18 + * @brief Utility pipe fittings for injecting and extracting strings + * + * $LicenseInfo:firstyear=2006&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2010, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + + +#include "linden_common.h" +#include "llpipeutil.h" + +#include +#include + +#include "llbufferstream.h" +#include "lldefs.h" +#include "llframetimer.h" +#include "llpumpio.h" +#include "llrand.h" +#include "lltimer.h" + +F32 pump_loop(LLPumpIO* pump, F32 seconds) +{ + LLTimer timer; + timer.setTimerExpirySec(seconds); + while(!timer.hasExpired()) + { + LLFrameTimer::updateFrameTime(); + pump->pump(); + pump->callback(); + } + return timer.getElapsedTimeF32(); +} + +//virtual +LLIOPipe::EStatus LLPipeStringInjector::process_impl( + const LLChannelDescriptors& channels, + buffer_ptr_t& buffer, + bool& eos, + LLSD& context, + LLPumpIO* pump) +{ + buffer->append(channels.out(), (U8*) mString.data(), static_cast(mString.size())); + eos = true; + return STATUS_DONE; +} + + +LLIOPipe::EStatus LLPipeStringExtractor::process_impl( + const LLChannelDescriptors& channels, + buffer_ptr_t& buffer, + bool& eos, + LLSD& context, + LLPumpIO* pump) +{ + if(!eos) return STATUS_BREAK; + if(!pump || !buffer) return STATUS_PRECONDITION_NOT_MET; + + LLBufferStream istr(channels, buffer.get()); + std::ostringstream ostr; + while (istr.good()) + { + char buf[1024]; /* Flawfinder: ignore */ + istr.read(buf, sizeof(buf)); /* Flawfinder: ignore */ + ostr.write(buf, istr.gcount()); + } + mString = ostr.str(); + mDone = true; + + return STATUS_DONE; +} + + +// virtual +LLIOPipe::EStatus LLIOFuzz::process_impl( + const LLChannelDescriptors& channels, + buffer_ptr_t& buffer, + bool& eos, + LLSD& context, + LLPumpIO* pump) +{ + while(mByteCount) + { + std::vector data; + data.reserve(10000); + int size = llmin(10000, mByteCount); + std::generate_n( + std::back_insert_iterator< std::vector >(data), + size, + rand); + buffer->append(channels.out(), &data[0], size); + mByteCount -= size; + } + return STATUS_OK; +} + +struct random_ascii_generator +{ + random_ascii_generator() {} + U8 operator()() + { + int rv = rand(); + rv %= (127 - 32); + rv += 32; + return rv; + } +}; + +// virtual +LLIOPipe::EStatus LLIOASCIIFuzz::process_impl( + const LLChannelDescriptors& channels, + buffer_ptr_t& buffer, + bool& eos, + LLSD& context, + LLPumpIO* pump) +{ + while(mByteCount) + { + std::vector data; + data.reserve(10000); + int size = llmin(10000, mByteCount); + std::generate_n( + std::back_insert_iterator< std::vector >(data), + size, + random_ascii_generator()); + buffer->append(channels.out(), &data[0], size); + mByteCount -= size; + } + return STATUS_OK; +} + +// virtual +LLIOPipe::EStatus LLIONull::process_impl( + const LLChannelDescriptors& channels, + buffer_ptr_t& buffer, + bool& eos, + LLSD& context, + LLPumpIO* pump) +{ + return STATUS_OK; +} + +// virtual +LLIOPipe::EStatus LLIOSleeper::process_impl( + const LLChannelDescriptors& channels, + buffer_ptr_t& buffer, + bool& eos, + LLSD& context, + LLPumpIO* pump) +{ + if(!mRespond) + { + LL_DEBUGS() << "LLIOSleeper::process_impl() sleeping." << LL_ENDL; + mRespond = true; + static const F64 SLEEP_TIME = 2.0; + pump->sleepChain(SLEEP_TIME); + return STATUS_BREAK; + } + LL_DEBUGS() << "LLIOSleeper::process_impl() responding." << LL_ENDL; + LLBufferStream ostr(channels, buffer.get()); + ostr << "huh? sorry, I was sleeping." << std::endl; + return STATUS_DONE; +} diff --git a/indra/llmessage/tests/llpipeutil.h b/indra/llmessage/tests/llpipeutil.h new file mode 100644 index 0000000000..97d9e1c85c --- /dev/null +++ b/indra/llmessage/tests/llpipeutil.h @@ -0,0 +1,163 @@ +/** + * @file llpipeutil.h + * @date 2006-05-18 + * @brief Utility pipe fittings for injecting and extracting strings + * + * $LicenseInfo:firstyear=2006&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2010, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +#ifndef LL_LLPIPEUTIL_H +#define LL_LLPIPEUTIL_H + +#include "lliopipe.h" + + +/** + * @brief Simple function which pumps for the specified time. + */ +F32 pump_loop(LLPumpIO* pump, F32 seconds); + +/** + * @brief Simple class which writes a string and then marks the stream + * as done. + */ +class LLPipeStringInjector : public LLIOPipe +{ +public: + LLPipeStringInjector(const std::string& string) + : mString(string) + { } + +protected: + virtual EStatus process_impl( + const LLChannelDescriptors& channels, + buffer_ptr_t& buffer, + bool& eos, + LLSD& context, + LLPumpIO* pump); + +private: + std::string mString; +}; + + +class LLPipeStringExtractor : public LLIOPipe +{ +public: + LLPipeStringExtractor() : mDone(false) { } + + bool done() { return mDone; } + std::string string() { return mString; } + +protected: + // LLIOPipe API implementation. + virtual EStatus process_impl( + const LLChannelDescriptors& channels, + LLIOPipe::buffer_ptr_t& buffer, + bool& eos, + LLSD& context, + LLPumpIO* pump); + +private: + bool mDone; + std::string mString; +}; + +/** + * @brief Generate a specified number of bytes of random data + */ +class LLIOFuzz : public LLIOPipe +{ +public: + LLIOFuzz(int byte_count) : mByteCount(byte_count) {} + +protected: + virtual EStatus process_impl( + const LLChannelDescriptors& channels, + buffer_ptr_t& buffer, + bool& eos, + LLSD& context, + LLPumpIO* pump); + +private: + int mByteCount; +}; + +/** + * @brief Generate some ascii fuz + */ +class LLIOASCIIFuzz : public LLIOPipe +{ +public: + LLIOASCIIFuzz(int byte_count) : mByteCount(byte_count) {} + +protected: + virtual EStatus process_impl( + const LLChannelDescriptors& channels, + buffer_ptr_t& buffer, + bool& eos, + LLSD& context, + LLPumpIO* pump); + +private: + int mByteCount; +}; + + +/** + * @brief Pipe that does nothing except return STATUS_OK + */ +class LLIONull : public LLIOPipe +{ +public: + LLIONull() {} + +protected: + virtual EStatus process_impl( + const LLChannelDescriptors& channels, + buffer_ptr_t& buffer, + bool& eos, + LLSD& context, + LLPumpIO* pump); +}; + +/** + * @brief Pipe that sleeps, and then responds later. + */ +class LLIOSleeper : public LLIOPipe +{ +public: + LLIOSleeper() : mRespond(false) {} + +protected: + virtual EStatus process_impl( + const LLChannelDescriptors& channels, + buffer_ptr_t& buffer, + bool& eos, + LLSD& context, + LLPumpIO* pump); +private: + bool mRespond; + +}; + +#endif // LL_LLPIPEUTIL_H diff --git a/indra/llmessage/tests/llsdmessagebuilder_test.cpp b/indra/llmessage/tests/llsdmessagebuilder_test.cpp new file mode 100644 index 0000000000..6804c3e29e --- /dev/null +++ b/indra/llmessage/tests/llsdmessagebuilder_test.cpp @@ -0,0 +1,837 @@ +/** + * @file llsdmessagebuilder_tut.cpp + * @date February 2006 + * @brief LLSDMessageBuilder unit tests + * + * $LicenseInfo:firstyear=2006&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2010, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +#include + +#include "linden_common.h" +#include "lltut.h" +#include "llmessagetemplate.h" +#include "llsdmessagebuilder.h" +#include "llsdmessagereader.h" +#include "llsdtraits.h" +#include "llmath.h" +#include "llquaternion.h" +#include "u64.h" +#include "v3dmath.h" +#include "v3math.h" +#include "v4math.h" +#include "llsdutil.h" +//#include "llsdutil.cpp" +#include "llsdutil_math.cpp" +#include "lltemplatemessagebuilder.h" + +namespace tut +{ + static LLTemplateMessageBuilder::message_template_name_map_t templateNameMap; + + LLMsgData* messageData = NULL; + LLMsgBlkData* messageBlockData = NULL; + + struct LLSDMessageBuilderTestData { + + LLSDMessageBuilderTestData() + { + messageData = new LLMsgData("testMessage"); + messageBlockData = new LLMsgBlkData("testBlock", 0); + } + + static LLSDMessageBuilder defaultBuilder() + { + LLSDMessageBuilder builder; + builder.newMessage("name"); + builder.nextBlock("block"); + return builder; + } + + static LLSDMessageReader setReader(const LLSDMessageBuilder& builder) + { + LLSDMessageReader reader; + reader.setMessage("name", builder.getMessage()); + return reader; + } + + static void addValue(LLMsgBlkData* mbd, char* name, void* v, EMsgVariableType type, int size, int data_size = -1) + { + LLMsgVarData tmp(name, type); + tmp.addData(v, size, type, data_size); + mbd->mMemberVarData[name] = tmp; + } + + + static LLMessageBlock* defaultTemplateBlock(const EMsgVariableType type = MVT_NULL, const S32 size = 0, EMsgBlockType block = MBT_VARIABLE) + { + return createTemplateBlock(_PREHASH_Test0, type, size, block); + } + + static LLMessageBlock* createTemplateBlock(const char* name, const EMsgVariableType type = MVT_NULL, const S32 size = 0, EMsgBlockType block = MBT_VARIABLE) + { + LLMessageBlock* result = new LLMessageBlock(name, block); + if(type != MVT_NULL) + { + result->addVariable(const_cast(_PREHASH_Test0), type, size); + } + return result; + } + + static LLTemplateMessageBuilder* defaultTemplateBuilder(LLMessageTemplate& messageTemplate, char* name = const_cast(_PREHASH_Test0)) + { + templateNameMap[_PREHASH_TestMessage] = &messageTemplate; + LLTemplateMessageBuilder* builder = new LLTemplateMessageBuilder(templateNameMap); + builder->newMessage(_PREHASH_TestMessage); + builder->nextBlock(name); + return builder; + } + + static LLMessageTemplate defaultTemplate() + { + return LLMessageTemplate(_PREHASH_TestMessage, 1, MFT_HIGH); + } + }; + + typedef test_group LLSDMessageBuilderTestGroup; + typedef LLSDMessageBuilderTestGroup::object LLSDMessageBuilderTestObject; + LLSDMessageBuilderTestGroup llsdMessageBuilderTestGroup("LLSDMessageBuilder"); + + template<> template<> + void LLSDMessageBuilderTestObject::test<1>() + // construction and test of undefined + { + LLSDMessageBuilder builder = defaultBuilder(); + LLSDMessageReader reader = setReader(builder); + } + + template<> template<> + void LLSDMessageBuilderTestObject::test<2>() + // bool + { + bool outValue, inValue = true; + LLSDMessageBuilder builder = defaultBuilder(); + builder.addBOOL("var", inValue); + LLSDMessageReader reader = setReader(builder); + reader.getBOOL("block", "var", outValue); + ensure_equals("Ensure bool", inValue, outValue); + } + + template<> template<> + void LLSDMessageBuilderTestObject::test<3>() + // U8 + { + U8 outValue, inValue = 2; + LLSDMessageBuilder builder = defaultBuilder(); + builder.addU8("var", inValue); + LLSDMessageReader reader = setReader(builder); + reader.getU8("block", "var", outValue); + ensure_equals("Ensure U8", inValue, outValue); + } + + template<> template<> + void LLSDMessageBuilderTestObject::test<4>() + // S16 + { + S16 outValue, inValue = 90; + LLSDMessageBuilder builder = defaultBuilder(); + builder.addS16("var", inValue); + LLSDMessageReader reader = setReader(builder); + reader.getS16("block", "var", outValue); + ensure_equals("Ensure S16", inValue, outValue); + } + + template<> template<> + void LLSDMessageBuilderTestObject::test<5>() + // U16 + { + U16 outValue, inValue = 3; + LLSDMessageBuilder builder = defaultBuilder(); + builder.addU16("var", inValue); + LLSDMessageReader reader = setReader(builder); + reader.getU16("block", "var", outValue); + ensure_equals("Ensure U16", inValue, outValue); + } + + template<> template<> + void LLSDMessageBuilderTestObject::test<6>() + // S32 + { + S32 outValue, inValue = 44; + LLSDMessageBuilder builder = defaultBuilder(); + builder.addS32("var", inValue); + LLSDMessageReader reader = setReader(builder); + reader.getS32("block", "var", outValue); + ensure_equals("Ensure S32", inValue, outValue); + } + + template<> template<> + void LLSDMessageBuilderTestObject::test<7>() + // F32 + { + F32 outValue, inValue = 121.44f; + LLSDMessageBuilder builder = defaultBuilder(); + builder.addF32("var", inValue); + LLSDMessageReader reader = setReader(builder); + reader.getF32("block", "var", outValue); + ensure_equals("Ensure F32", inValue, outValue); + } + + template<> template<> + void LLSDMessageBuilderTestObject::test<8>() + // U32 + { + U32 outValue, inValue = 88; + LLSDMessageBuilder builder = defaultBuilder(); + builder.addU32("var", inValue); + LLSDMessageReader reader = setReader(builder); + reader.getU32("block", "var", outValue); + ensure_equals("Ensure U32", inValue, outValue); + } + + template<> template<> + void LLSDMessageBuilderTestObject::test<9>() + // U64 + { + U64 outValue, inValue = 121; + LLSDMessageBuilder builder = defaultBuilder(); + builder.addU64("var", inValue); + LLSDMessageReader reader = setReader(builder); + reader.getU64("block", "var", outValue); + ensure_equals("Ensure U64", inValue, outValue); + } + + template<> template<> + void LLSDMessageBuilderTestObject::test<10>() + // F64 + { + F64 outValue, inValue = 3232143.33; + LLSDMessageBuilder builder = defaultBuilder(); + builder.addF64("var", inValue); + LLSDMessageReader reader = setReader(builder); + reader.getF64("block", "var", outValue); + ensure_equals("Ensure F64", inValue, outValue); + } + + template<> template<> + void LLSDMessageBuilderTestObject::test<11>() + // Vector3 + { + LLVector3 outValue, inValue = LLVector3(1,2,3); + LLSDMessageBuilder builder = defaultBuilder(); + builder.addVector3("var", inValue); + LLSDMessageReader reader = setReader(builder); + reader.getVector3("block", "var", outValue); + ensure_equals("Ensure Vector3", inValue, outValue); + } + + template<> template<> + void LLSDMessageBuilderTestObject::test<12>() + // Vector4 + { + LLVector4 outValue, inValue = LLVector4(1,2,3,4); + LLSDMessageBuilder builder = defaultBuilder(); + builder.addVector4("var", inValue); + LLSDMessageReader reader = setReader(builder); + reader.getVector4("block", "var", outValue); + ensure_equals("Ensure Vector4", inValue, outValue); + } + + template<> template<> + void LLSDMessageBuilderTestObject::test<13>() + // Vector3d + { + LLVector3d outValue, inValue = LLVector3d(1,2,3); + LLSDMessageBuilder builder = defaultBuilder(); + builder.addVector3d("var", inValue); + LLSDMessageReader reader = setReader(builder); + reader.getVector3d("block", "var", outValue); + ensure_equals("Ensure Vector3d", inValue, outValue); + } + + template<> template<> + void LLSDMessageBuilderTestObject::test<14>() + // Quaternion + { + LLQuaternion outValue, inValue = LLQuaternion(1,LLVector3(2,3,4)); + LLSDMessageBuilder builder = defaultBuilder(); + builder.addQuat("var", inValue); + LLSDMessageReader reader = setReader(builder); + reader.getQuat("block", "var", outValue); + ensure_equals("Ensure Quaternion", inValue, outValue); + } + + template<> template<> + void LLSDMessageBuilderTestObject::test<15>() + // UUID + { + LLUUID outValue, inValue; + inValue.generate(); + LLSDMessageBuilder builder = defaultBuilder(); + builder.addUUID("var", inValue); + LLSDMessageReader reader = setReader(builder); + reader.getUUID("block", "var", outValue); + ensure_equals("Ensure UUID", inValue, outValue); + } + + template<> template<> + void LLSDMessageBuilderTestObject::test<16>() + // IPAddr + { + U32 outValue, inValue = 12344556; + LLSDMessageBuilder builder = defaultBuilder(); + builder.addIPAddr("var", inValue); + LLSDMessageReader reader = setReader(builder); + reader.getIPAddr("block", "var", outValue); + ensure_equals("Ensure IPAddr", inValue, outValue); + } + + template<> template<> + void LLSDMessageBuilderTestObject::test<17>() + // IPPort + { + U16 outValue, inValue = 80; + LLSDMessageBuilder builder = defaultBuilder(); + builder.addIPPort("var", inValue); + LLSDMessageReader reader = setReader(builder); + reader.getIPPort("block", "var", outValue); + ensure_equals("Ensure IPPort", inValue, outValue); + } + + template<> template<> + void LLSDMessageBuilderTestObject::test<18>() + { + std::string outValue, inValue = "testing"; + LLSDMessageBuilder builder = defaultBuilder(); + builder.addString("var", inValue.c_str()); + LLSDMessageReader reader = setReader(builder); + char buffer[MAX_STRING]; + reader.getString("block", "var", MAX_STRING, buffer); + outValue = buffer; + ensure_equals("Ensure String", inValue, outValue); + } + + template<> template<> + void LLSDMessageBuilderTestObject::test<19>() + { + LLMsgBlkData* mbd = new LLMsgBlkData("testBlock", 0); + LLMsgData* md = new LLMsgData("testMessage"); + md->addBlock(mbd); + LLSDMessageBuilder builder = defaultBuilder(); + + builder.copyFromMessageData(*md); + LLSD output = builder.getMessage(); + + ensure("Ensure message block created when copied from legacy message to llsd", output["testBlock"].isDefined()); + } + + // MVT_FIXED + template<> template<> + void LLSDMessageBuilderTestObject::test<20>() + { + char binData[] = "abcdefghijklmnop"; + + addValue(messageBlockData, (char *)"testBinData", &binData, MVT_FIXED, sizeof(binData)); + messageData->addBlock(messageBlockData); + LLSDMessageBuilder builder = defaultBuilder(); + + builder.copyFromMessageData(*messageData); + LLSD output = builder.getMessage(); + + std::vector v = output["testBlock"][0]["testBinData"].asBinary(); + ensure("Ensure MVT_S16Array data copied from legacy to llsd give a valid vector", v.size() > 0); + + ensure_memory_matches("Ensure fixed binary data works in a message copied from legacy to llsd", + &v[0], sizeof(binData), binData, sizeof(binData)); + } + + // MVT_VARIABLE data_size 1 (U8's) + template<> template<> + void LLSDMessageBuilderTestObject::test<21>() + { + /* U8 binData[] = "abcdefghijklmnop"; + + addValue(messageBlockData, "testBinData", &binData, MVT_VARIABLE, sizeof(binData), 1); + messageData->addBlock(messageBlockData); + LLSDMessageBuilder builder = defaultBuilder(); + + builder.copyFromMessageData(*messageData); + LLSD output = builder.getMessage(); + + std::vector v = output["testBlock"][0]["testBinData"].asBinary(); + ensure("Ensure MVT_S16Array data copied from legacy to llsd give a valid vector", v.size() > 0); + + ensure_memory_matches("Ensure MVT_VARIABLE U8 binary data works in a message copied from legacy to llsd", + &v[0], sizeof(binData), binData, sizeof(binData));*/ + } + + // MVT_VARIABLE data_size 2 (U16's) + template<> template<> + void LLSDMessageBuilderTestObject::test<22>() + { + U16 binData[] = {1,2,3,4,5,6,7,8,9}; //9 shorts + + addValue(messageBlockData, (char *)"testBinData", &binData, MVT_VARIABLE, sizeof(binData) >> 1, 2); + messageData->addBlock(messageBlockData); + LLSDMessageBuilder builder = defaultBuilder(); + + builder.copyFromMessageData(*messageData); + LLSD output = builder.getMessage(); + + std::vector v = output["testBlock"][0]["testBinData"].asBinary(); + ensure("Ensure MVT_S16Array data copied from legacy to llsd give a valid vector", v.size() > 0); + + ensure_memory_matches("Ensure MVT_VARIABLE U16 binary data works in a message copied from legacy to llsd", + &v[0], sizeof(binData) >> 1, binData, sizeof(binData) >> 1); + } + + // MVT_VARIABLE data_size 4 (S32's) + template<> template<> + void LLSDMessageBuilderTestObject::test<23>() + { + U32 binData[] = {9,8,7,6,5,4,3,2,1}; + + addValue(messageBlockData, (char *)"testBinData", &binData, MVT_VARIABLE, sizeof(binData) >> 2, 4); + messageData->addBlock(messageBlockData); + LLSDMessageBuilder builder = defaultBuilder(); + + builder.copyFromMessageData(*messageData); + LLSD output = builder.getMessage(); + + std::vector v = output["testBlock"][0]["testBinData"].asBinary(); + ensure("Ensure MVT_S16Array data copied from legacy to llsd give a valid vector", v.size() > 0); + + ensure_memory_matches("Ensure MVT_VARIABLE S32 binary data works in a message copied from legacy to llsd", + &v[0], sizeof(binData) >> 2, binData, sizeof(binData) >> 2); + } + + // MVT_U8 + template<> template<> + void LLSDMessageBuilderTestObject::test<24>() + { + U8 data = 0xa5; + + addValue(messageBlockData, (char *)"testBinData", &data, MVT_U8, sizeof(data)); + messageData->addBlock(messageBlockData); + LLSDMessageBuilder builder = defaultBuilder(); + + builder.copyFromMessageData(*messageData); + LLSD output = builder.getMessage(); + + ensure_equals("Ensure MVT_U8 data works in a message copied from legacy to llsd", + output["testBlock"][0]["testBinData"].asInteger(), data); + } + + // MVT_U16 + template<> template<> + void LLSDMessageBuilderTestObject::test<25>() + { + U16 data = 0xa55a; + + addValue(messageBlockData, (char *)"testBinData", &data, MVT_U16, sizeof(data)); + messageData->addBlock(messageBlockData); + LLSDMessageBuilder builder = defaultBuilder(); + + builder.copyFromMessageData(*messageData); + LLSD output = builder.getMessage(); + + ensure_equals("Ensure MVT_U16 data works in a message copied from legacy to llsd", + output["testBlock"][0]["testBinData"].asInteger(), data); + } + + // MVT_U32 + template<> template<> + void LLSDMessageBuilderTestObject::test<26>() + { + U32 data = 0xa55a7117; + + addValue(messageBlockData, (char *)"testBinData", &data, MVT_U32, sizeof(data)); + messageData->addBlock(messageBlockData); + LLSDMessageBuilder builder = defaultBuilder(); + + builder.copyFromMessageData(*messageData); + LLSD output = builder.getMessage(); + + ensure_equals("Ensure MVT_U32 data works in a message copied from legacy to llsd", + ll_U32_from_sd(output["testBlock"][0]["testBinData"]), data); + } + + // MVT_U64 - crush into an s32: LLSD does not support 64 bit values + template<> template<> + void LLSDMessageBuilderTestObject::test<27>() + { + U64 data = U64L(0xa55a711711223344); + addValue(messageBlockData, (char *)"testBinData", &data, MVT_U64, sizeof(data)); + messageData->addBlock(messageBlockData); + LLSDMessageBuilder builder = defaultBuilder(); + + builder.copyFromMessageData(*messageData); + LLSD output = builder.getMessage(); + + ensure_equals("Ensure MVT_U64 data works in a message copied from legacy to llsd", + ll_U64_from_sd(output["testBlock"][0]["testBinData"]), data); + } + + // MVT_S8 + template<> template<> + void LLSDMessageBuilderTestObject::test<28>() + { + S8 data = -31; + + addValue(messageBlockData, (char *)"testBinData", &data, MVT_S8, sizeof(data)); + messageData->addBlock(messageBlockData); + LLSDMessageBuilder builder = defaultBuilder(); + + builder.copyFromMessageData(*messageData); + LLSD output = builder.getMessage(); + + ensure_equals("Ensure MVT_S8 data works in a message copied from legacy to llsd", + output["testBlock"][0]["testBinData"].asInteger(), data); + } + + // MVT_S16 + template<> template<> + void LLSDMessageBuilderTestObject::test<29>() + { + S16 data = -31; + + addValue(messageBlockData, (char *)"testBinData", &data, MVT_S16, sizeof(data)); + messageData->addBlock(messageBlockData); + LLSDMessageBuilder builder = defaultBuilder(); + + builder.copyFromMessageData(*messageData); + LLSD output = builder.getMessage(); + + ensure_equals("Ensure MVT_S16 data works in a message copied from legacy to llsd", + output["testBlock"][0]["testBinData"].asInteger(), data); + } + + // MVT_S32 + template<> template<> + void LLSDMessageBuilderTestObject::test<30>() + { + S32 data = -3100; + + addValue(messageBlockData, (char *)"testBinData", &data, MVT_S32, sizeof(data)); + messageData->addBlock(messageBlockData); + LLSDMessageBuilder builder = defaultBuilder(); + + builder.copyFromMessageData(*messageData); + LLSD output = builder.getMessage(); + + ensure_equals("Ensure MVT_S32 data works in a message copied from legacy to llsd", + output["testBlock"][0]["testBinData"].asInteger(), data); + } + + // MVT_S64 - crush into an s32: LLSD does not support 64 bit values + template<> template<> + void LLSDMessageBuilderTestObject::test<31>() + { + S64 data = -31003100; + + addValue(messageBlockData, (char *)"testBinData", &data, MVT_S64, sizeof(data)); + messageData->addBlock(messageBlockData); + LLSDMessageBuilder builder = defaultBuilder(); + + builder.copyFromMessageData(*messageData); + LLSD output = builder.getMessage(); + + ensure_equals("Ensure MVT_S64 data works in a message copied from legacy to llsd", + output["testBlock"][0]["testBinData"].asInteger(), (S32)data); + } + + // MVT_F32 + template<> template<> + void LLSDMessageBuilderTestObject::test<32>() + { + F32 data = 1234.1234f; + + addValue(messageBlockData, (char *)"testBinData", &data, MVT_F32, sizeof(data)); + messageData->addBlock(messageBlockData); + LLSDMessageBuilder builder = defaultBuilder(); + + builder.copyFromMessageData(*messageData); + LLSD output = builder.getMessage(); + + ensure_equals("Ensure MVT_F32 data works in a message copied from legacy to llsd", + output["testBlock"][0]["testBinData"].asReal(), data); + } + + // MVT_F64 + template<> template<> + void LLSDMessageBuilderTestObject::test<33>() + { + F64 data = 1234.1234; + + addValue(messageBlockData, (char *)"testBinData", &data, MVT_F64, sizeof(data)); + messageData->addBlock(messageBlockData); + LLSDMessageBuilder builder = defaultBuilder(); + + builder.copyFromMessageData(*messageData); + LLSD output = builder.getMessage(); + + ensure_equals("Ensure MVT_F64 data works in a message copied from legacy to llsd", + output["testBlock"][0]["testBinData"].asReal(), data); + } + + // MVT_LLVector3 + template<> template<> + void LLSDMessageBuilderTestObject::test<34>() + { + LLVector3 data(1,2,3); + + addValue(messageBlockData, (char *)"testBinData", &data, MVT_LLVector3, sizeof(data)); + messageData->addBlock(messageBlockData); + LLSDMessageBuilder builder = defaultBuilder(); + + builder.copyFromMessageData(*messageData); + LLSD output = builder.getMessage(); + + ensure_equals("Ensure MVT_LLVector3 data works in a message copied from legacy to llsd", + ll_vector3_from_sd(output["testBlock"][0]["testBinData"]), data); + } + + // MVT_LLVector3d + template<> template<> + void LLSDMessageBuilderTestObject::test<35>() + { + LLVector3d data(1,2,3); + + addValue(messageBlockData, (char *)"testBinData", &data, MVT_LLVector3d, sizeof(data)); + messageData->addBlock(messageBlockData); + LLSDMessageBuilder builder = defaultBuilder(); + + builder.copyFromMessageData(*messageData); + LLSD output = builder.getMessage(); + + ensure_equals("Ensure MVT_LLVector3 data works in a message copied from legacy to llsd", + ll_vector3d_from_sd(output["testBlock"][0]["testBinData"]), data); + } + + // MVT_LLVector4 + template<> template<> + void LLSDMessageBuilderTestObject::test<36>() + { + LLVector4 data(1,2,3,4); + LLSD v = ll_sd_from_vector4(data); + + addValue(messageBlockData, (char *)"testBinData", &data, MVT_LLVector4, sizeof(data)); + messageData->addBlock(messageBlockData); + LLSDMessageBuilder builder = defaultBuilder(); + + builder.copyFromMessageData(*messageData); + LLSD output = builder.getMessage(); + + ensure_equals("Ensure MVT_LLVector4 data works in a message copied from legacy to llsd", + output["testBlock"][0]["testBinData"], v); + } + + // MVT_LLQuaternion + template<> template<> + void LLSDMessageBuilderTestObject::test<37>() + { + LLQuaternion data(0.3713907f, 0.5570861f, 0.7427813f,0.0f); + + //we send a quaternion packed into a vec3 (w is infered) - so sizeof(vec) == 12 bytes not 16. + LLVector3 vec = data.packToVector3(); + + addValue(messageBlockData, (char *)"testBinData", &vec, MVT_LLQuaternion, sizeof(vec)); + messageData->addBlock(messageBlockData); + LLSDMessageBuilder builder = defaultBuilder(); + + builder.copyFromMessageData(*messageData); + LLSD output = builder.getMessage(); + + ensure_equals("Ensure MVT_LLQuaternion data works in a message copied from legacy to llsd", + ll_quaternion_from_sd(output["testBlock"][0]["testBinData"]), data); + } + + // MVT_LLUUID + template<> template<> + void LLSDMessageBuilderTestObject::test<38>() + { + LLUUID data("01234567-0123-0123-0123-234567abcdef"); + + addValue(messageBlockData, (char *)"testBinData", &data, MVT_LLUUID, sizeof(data)); + messageData->addBlock(messageBlockData); + LLSDMessageBuilder builder = defaultBuilder(); + + builder.copyFromMessageData(*messageData); + LLSD output = builder.getMessage(); + + std::string v = output["testBlock"][0]["testBinData"].asUUID().asString(); + + ensure_equals("Ensure MVT_LLUUID data works in a message copied from legacy to llsd", + output["testBlock"][0]["testBinData"].asUUID(), data); + } + + // MVT_BOOL + template<> template<> + void LLSDMessageBuilderTestObject::test<39>() + { + bool valueTrue = true; + bool valueFalse = false; + + LLMsgData* md = new LLMsgData("testMessage"); + LLMsgBlkData* mbd = new LLMsgBlkData("testBlock", 0); + addValue(mbd, (char *)"testBoolFalse", &valueFalse, MVT_BOOL, sizeof(bool)); + addValue(mbd, (char *)"testBoolTrue", &valueTrue, MVT_BOOL, sizeof(bool)); + md->addBlock(mbd); + LLSDMessageBuilder builder = defaultBuilder(); + + builder.copyFromMessageData(*md); + LLSD output = builder.getMessage(); + + ensure("Ensure bools work in a message copied from legacy to llsd", + output["testBlock"][0]["testBoolTrue"].asBoolean() && !output["testBlock"][0]["testBoolFalse"].asBoolean()); + } + + // MVT_IP_ADDR + template<> template<> + void LLSDMessageBuilderTestObject::test<40>() + { + U32 data(0xff887766); + LLSD v = ll_sd_from_ipaddr(data); + + addValue(messageBlockData, (char *)"testBinData", &data, MVT_IP_ADDR, sizeof(data)); + messageData->addBlock(messageBlockData); + LLSDMessageBuilder builder = defaultBuilder(); + + builder.copyFromMessageData(*messageData); + LLSD output = builder.getMessage(); + + ensure_equals("Ensure MVT_IP_ADDR data works in a message copied from legacy to llsd", + output["testBlock"][0]["testBinData"], v); + } + + // MVT_IP_PORT + template<> template<> + void LLSDMessageBuilderTestObject::test<41>() + { + U16 data = 0xff88; + + addValue(messageBlockData, (char *)"testBinData", &data, MVT_IP_PORT, sizeof(data)); + messageData->addBlock(messageBlockData); + LLSDMessageBuilder builder = defaultBuilder(); + + builder.copyFromMessageData(*messageData); + LLSD output = builder.getMessage(); + + ensure_equals("Ensure MVT_IP_PORT data works in a message copied from legacy to llsd", + output["testBlock"][0]["testBinData"].asInteger(), data); + } + + // MVT_U16Vec3 + template<> template<> + void LLSDMessageBuilderTestObject::test<42>() + { + U16 data[3] = {0,1,2}; + + addValue(messageBlockData, (char *)"testBinData", &data, MVT_U16Vec3, sizeof(data)); + messageData->addBlock(messageBlockData); + LLSDMessageBuilder builder = defaultBuilder(); + + builder.copyFromMessageData(*messageData); + LLSD output = builder.getMessage(); + + std::vector v = output["testBlock"][0]["testBinData"].asBinary(); + ensure("Ensure MVT_U16Vec3 data copied from legacy to llsd give a valid vector", v.size() > 0); + + ensure_memory_matches("Ensure MVT_U16Vec3 data works in a message copied from legacy to llsd", + (U16*)&v[0], 6, data, 6); + } + + // MVT_U16Quat + template<> template<> + void LLSDMessageBuilderTestObject::test<43>() + { + U16 data[4] = {0,1,2,4}; + + addValue(messageBlockData, (char *)"testBinData", &data, MVT_U16Quat, sizeof(data)); + messageData->addBlock(messageBlockData); + LLSDMessageBuilder builder = defaultBuilder(); + + builder.copyFromMessageData(*messageData); + LLSD output = builder.getMessage(); + + std::vector v = output["testBlock"][0]["testBinData"].asBinary(); + ensure("Ensure MVT_U16Quat data copied from legacy to llsd give a valid vector", v.size() > 0); + + ensure_memory_matches("Ensure MVT_U16Quat data works in a message copied from legacy to llsd", + (U16*)&v[0], 8, data, 8); + } + + // MVT_S16Array + template<> template<> + void LLSDMessageBuilderTestObject::test<44>() + { + S16 data[19] = {0,-1,2,-4,5,-6,7,-8,9,-10,11,-12,13,-14,15,16,17,18}; + + addValue(messageBlockData, (char *)"testBinData", &data, MVT_S16Array, sizeof(data)); + messageData->addBlock(messageBlockData); + LLSDMessageBuilder builder = defaultBuilder(); + + builder.copyFromMessageData(*messageData); + LLSD output = builder.getMessage(); + + std::vector v = output["testBlock"][0]["testBinData"].asBinary(); + ensure("Ensure MVT_S16Array data copied from legacy to llsd give a valid vector", v.size() > 0); + + ensure_memory_matches("Ensure MVT_S16Array data works in a message copied from legacy to llsd", + (U16*)&v[0], 19, data, 19); + } + + template<> template<> + void LLSDMessageBuilderTestObject::test<45>() + { + LLMessageTemplate messageTemplate = defaultTemplate(); + messageTemplate.addBlock(defaultTemplateBlock(MVT_U8, 1)); + U8 inValue = 2; + LLTemplateMessageBuilder* template_builder = defaultTemplateBuilder(messageTemplate); + template_builder->addU8(_PREHASH_Test0, inValue); + + LLSDMessageBuilder builder; + builder.copyFromMessageData(*template_builder->getCurrentMessage()); + LLSD output = builder.getMessage(); + + ensure_equals(output["Test0"][0]["Test0"].asInteger(), 2); + + } + + template<> template<> + void LLSDMessageBuilderTestObject::test<46>() + { + LLMessageTemplate messageTemplate = defaultTemplate(); + messageTemplate.addBlock(defaultTemplateBlock(MVT_VARIABLE, 1)); + std::string inValue = "testing"; + LLTemplateMessageBuilder* builder = defaultTemplateBuilder(messageTemplate); + builder->addString(_PREHASH_Test0, inValue.c_str()); + + LLSDMessageBuilder sd_builder; + sd_builder.copyFromMessageData(*builder->getCurrentMessage()); + LLSD output = sd_builder.getMessage(); + + ensure_equals(output["Test0"][0]["Test0"].asString(), std::string("testing")); + } + +} + diff --git a/indra/llmessage/tests/llsdmessagereader_test.cpp b/indra/llmessage/tests/llsdmessagereader_test.cpp new file mode 100644 index 0000000000..dd6520ea33 --- /dev/null +++ b/indra/llmessage/tests/llsdmessagereader_test.cpp @@ -0,0 +1,324 @@ +/** + * @file llsdmessagereader_tut.cpp + * @date February 2006 + * @brief LLSDMessageReader unit tests + * + * $LicenseInfo:firstyear=2006&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2010, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +#include +#include "linden_common.h" +#include "lltut.h" +#include "v3dmath.h" +#include "v3math.h" +#include "v4math.h" +#include "llquaternion.h" + +#include "message.h" +#include "llsdmessagereader.h" +#include "llsdutil.h" +#include "llsdutil_math.h" + +namespace tut +{ + struct LLSDMessageReaderTestData { + static void ensureMessageName(const std::string& msg_name, + const LLSD& msg_data, + const std::string& expected_name) + { + LLSDMessageReader msg; + msg.setMessage(LLMessageStringTable::getInstance()->getString(msg_name.c_str()), msg_data); + ensure_equals("Ensure name", std::string(msg.getMessageName()), + expected_name); + } + + static void ensureNumberOfBlocks(const LLSD& msg_data, + const std::string& block, + S32 expected_number) + { + LLSDMessageReader msg; + msg.setMessage("fakename", msg_data); + ensure_equals("Ensure number of blocks", msg.getNumberOfBlocks(block.c_str()), + expected_number); + } + + static void ensureMessageSize(const LLSD& msg_data, + S32 expected_size) + { + LLSDMessageReader msg; + msg.setMessage("fakename", msg_data); + ensure_equals( "Ensure size", msg.getMessageSize(), expected_size); + } + + static void ensureBool(const LLSD& msg_data, + const std::string& block, + const std::string& var, + S32 blocknum, + bool expected) + { + LLSDMessageReader msg; + msg.setMessage("fakename", msg_data); + bool test_data; + msg.getBOOL(block.c_str(), var.c_str(), test_data, blocknum); + ensure_equals( "Ensure bool field", test_data, expected); + } + }; + + typedef test_group LLSDMessageReaderTestGroup; + typedef LLSDMessageReaderTestGroup::object LLSDMessageReaderTestObject; + LLSDMessageReaderTestGroup llsdMessageReaderTestGroup("LLSDMessageReader"); + + template<> template<> + void LLSDMessageReaderTestObject::test<1>() + // construction and test of empty LLSD + { + LLSD message = LLSD::emptyMap(); + + ensureMessageName("", message, ""); + ensureNumberOfBlocks(message, "Fakeblock", 0); + ensureMessageSize(message, 0); + } + + template<> template<> + void LLSDMessageReaderTestObject::test<2>() + // construction and test of simple message with one block + { + LLSD message = LLSD::emptyMap(); + message["block1"] = LLSD::emptyArray(); + message["block1"][0] = LLSD::emptyMap(); + message["block1"][0]["Field1"] = 0; + + ensureMessageName("name2", message, "name2"); + ensureNumberOfBlocks(message, "block1", 1); + ensureMessageSize(message, 0); + } + + template<> template<> + void LLSDMessageReaderTestObject::test<3>() + // multiple blocks + { + LLSD message = LLSD::emptyMap(); + message["block1"] = LLSD::emptyArray(); + bool bool_true = true; + bool bool_false = false; + message["block1"][0] = LLSD::emptyMap(); + message["block1"][0]["BoolField1"] = bool_true; + message["block1"][1] = LLSD::emptyMap(); + message["block1"][1]["BoolField1"] = bool_false; + message["block1"][1]["BoolField2"] = bool_true; + + ensureMessageName("name3", message, "name3"); + ensureBool(message, "block1", "BoolField1", 0, true); + ensureBool(message, "block1", "BoolField1", 1, false); + ensureBool(message, "block1", "BoolField2", 1, true); + ensureNumberOfBlocks(message, "block1", 2); + ensureMessageSize(message, 0); + } + + template + LLSDMessageReader testType(const T& value) + { + LLSD message = LLSD::emptyMap(); + message["block"][0]["var"] = value; + LLSDMessageReader msg; + msg.setMessage("fakename", message); + return msg; + } + + template<> template<> + void LLSDMessageReaderTestObject::test<4>() + // S8 + { + S8 outValue, inValue = -3; + LLSDMessageReader msg = testType(inValue); + msg.getS8("block", "var", outValue); + ensure_equals("Ensure S8", outValue, inValue); + } + template<> template<> + void + LLSDMessageReaderTestObject::test<5>() + // U8 + { + U8 outValue, inValue = 2; + LLSDMessageReader msg = testType(inValue); + msg.getU8("block", "var", outValue); + ensure_equals("Ensure U8", outValue, inValue); + } + template<> template<> + void LLSDMessageReaderTestObject::test<6>() + // S16 + { + S16 outValue, inValue = 90; + LLSDMessageReader msg = testType(inValue); + msg.getS16("block", "var", outValue); + ensure_equals("Ensure S16", outValue, inValue); + } + template<> template<> + void LLSDMessageReaderTestObject::test<7>() + // U16 + { + U16 outValue, inValue = 3; + LLSDMessageReader msg = testType(inValue); + msg.getU16("block", "var", outValue); + ensure_equals("Ensure S16", outValue, inValue); + } + template<> template<> + void LLSDMessageReaderTestObject::test<8>() + // S32 + { + S32 outValue, inValue = 44; + LLSDMessageReader msg = testType(inValue); + msg.getS32("block", "var", outValue); + ensure_equals("Ensure S32", outValue, inValue); + } + template<> template<> + void LLSDMessageReaderTestObject::test<9>() + // F32 + { + F32 outValue, inValue = 121.44f; + LLSDMessageReader msg = testType(inValue); + msg.getF32("block", "var", outValue); + ensure_equals("Ensure F32", outValue, inValue); + } + template<> template<> + void LLSDMessageReaderTestObject::test<10>() + // U32 + { + U32 outValue, inValue = 88; + LLSD sdValue = ll_sd_from_U32(inValue); + LLSDMessageReader msg = testType(sdValue); + msg.getU32("block", "var", outValue); + ensure_equals("Ensure U32", outValue, inValue); + } + template<> template<> + void LLSDMessageReaderTestObject::test<11>() + // U64 + { + U64 outValue, inValue = 121; + LLSD sdValue = ll_sd_from_U64(inValue); + LLSDMessageReader msg = testType(sdValue); + msg.getU64("block", "var", outValue); + ensure_equals("Ensure U64", outValue, inValue); + } + template<> template<> + void LLSDMessageReaderTestObject::test<12>() + // F64 + { + F64 outValue, inValue = 3232143.33; + LLSDMessageReader msg = testType(inValue); + msg.getF64("block", "var", outValue); + ensure_equals("Ensure F64", outValue, inValue); + } + template<> template<> + void LLSDMessageReaderTestObject::test<13>() + // String + { + std::string outValue, inValue = "testing"; + LLSDMessageReader msg = testType(inValue.c_str()); + + char buffer[MAX_STRING]; + msg.getString("block", "var", MAX_STRING, buffer); + outValue = buffer; + ensure_equals("Ensure String", outValue, inValue); + } + template<> template<> + void LLSDMessageReaderTestObject::test<14>() + // Vector3 + { + LLVector3 outValue, inValue = LLVector3(1,2,3); + LLSD sdValue = ll_sd_from_vector3(inValue); + LLSDMessageReader msg = testType(sdValue); + msg.getVector3("block", "var", outValue); + ensure_equals("Ensure Vector3", outValue, inValue); + } + template<> template<> + void LLSDMessageReaderTestObject::test<15>() + // Vector4 + { + LLVector4 outValue, inValue = LLVector4(1,2,3,4); + LLSD sdValue = ll_sd_from_vector4(inValue); + LLSDMessageReader msg = testType(sdValue); + msg.getVector4("block", "var", outValue); + ensure_equals("Ensure Vector4", outValue, inValue); + } + template<> template<> + void LLSDMessageReaderTestObject::test<16>() + // Vector3d + { + LLVector3d outValue, inValue = LLVector3d(1,2,3); + LLSD sdValue = ll_sd_from_vector3d(inValue); + LLSDMessageReader msg = testType(sdValue); + msg.getVector3d("block", "var", outValue); + ensure_equals("Ensure Vector3d", outValue, inValue); + } + template<> template<> + void LLSDMessageReaderTestObject::test<17>() + // Quaternion + { + LLQuaternion outValue, inValue = LLQuaternion(1,LLVector3(2,3,4)); + LLSD sdValue = ll_sd_from_quaternion(inValue); + LLSDMessageReader msg = testType(sdValue); + msg.getQuat("block", "var", outValue); + ensure_equals("Ensure Quaternion", outValue, inValue); + } + template<> template<> + void LLSDMessageReaderTestObject::test<18>() + // UUID + { + LLUUID outValue, inValue; + inValue.generate(); + LLSDMessageReader msg = testType(inValue); + msg.getUUID("block", "var", outValue); + ensure_equals("Ensure UUID", outValue, inValue); + } + template<> template<> + void LLSDMessageReaderTestObject::test<19>() + // IPAddr + { + U32 outValue, inValue = 12344556; + LLSD sdValue = ll_sd_from_ipaddr(inValue); + LLSDMessageReader msg = testType(sdValue); + msg.getIPAddr("block", "var", outValue); + ensure_equals("Ensure IPAddr", outValue, inValue); + } + template<> template<> + void LLSDMessageReaderTestObject::test<20>() + // IPPort + { + U16 outValue, inValue = 80; + LLSDMessageReader msg = testType(inValue); + msg.getIPPort("block", "var", outValue); + ensure_equals("Ensure IPPort", outValue, inValue); + } + template<> template<> + void LLSDMessageReaderTestObject::test<21>() + // Binary + { + std::vector outValue(2), inValue(2); + inValue[0] = 0; + inValue[1] = 1; + + LLSDMessageReader msg = testType(inValue); + msg.getBinaryData("block", "var", &(outValue[0]), static_cast(inValue.size())); + ensure_equals("Ensure Binary", outValue, inValue); + } +} diff --git a/indra/llmessage/tests/llservicebuilder_test.cpp b/indra/llmessage/tests/llservicebuilder_test.cpp new file mode 100644 index 0000000000..0bc17865d6 --- /dev/null +++ b/indra/llmessage/tests/llservicebuilder_test.cpp @@ -0,0 +1,173 @@ +/** +* @file llservicebuilder_tut.cpp +* @brief LLServiceBuilder unit tests +* @date March 2007 +* +* $LicenseInfo:firstyear=2006&license=viewerlgpl$ +* Second Life Viewer Source Code +* Copyright (C) 2010, Linden Research, Inc. +* +* This library is free software; you can redistribute it and/or +* modify it under the terms of the GNU Lesser General Public +* License as published by the Free Software Foundation; +* version 2.1 of the License only. +* +* This library is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* Lesser General Public License for more details. +* +* You should have received a copy of the GNU Lesser General Public +* License along with this library; if not, write to the Free Software +* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +* +* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA +* $/LicenseInfo$ +*/ + +#include + +#include "linden_common.h" +#include "lltut.h" +#include "llsd.h" +#include "llservicebuilder.h" + +namespace tut +{ + + struct ServiceBuilderTestData { + LLServiceBuilder mServiceBuilder; + }; + + typedef test_group ServiceBuilderTestGroup; + typedef ServiceBuilderTestGroup::object ServiceBuilderTestObject; + + ServiceBuilderTestGroup serviceBuilderTestGroup("ServiceBuilder"); + + template<> template<> + void ServiceBuilderTestObject::test<1>() + { + //Simple service build and reply with no mapping + LLSD test_block; + test_block["service-builder"] = "/agent/name"; + mServiceBuilder.createServiceDefinition("ServiceBuilderTest", test_block["service-builder"]); + std::string test_url = mServiceBuilder.buildServiceURI("ServiceBuilderTest"); + ensure_equals("Basic URL Creation", test_url , "/agent/name"); + } + + template<> template<> + void ServiceBuilderTestObject::test<2>() + { + //Simple replace test + LLSD test_block; + test_block["service-builder"] = "/agent/{$agent-id}/name"; + mServiceBuilder.createServiceDefinition("ServiceBuilderTest", test_block["service-builder"]); + LLSD data_map; + data_map["agent-id"] = "257c631f-a0c5-4f29-8a9f-9031feaae6c6"; + std::string test_url = mServiceBuilder.buildServiceURI("ServiceBuilderTest", data_map); + ensure_equals("Replacement URL Creation", test_url , "/agent/257c631f-a0c5-4f29-8a9f-9031feaae6c6/name"); + } + + template<> template<> + void ServiceBuilderTestObject::test<3>() + { + //Incorrect service test + LLSD test_block; + test_block["service-builder"] = "/agent/{$agent-id}/name"; + mServiceBuilder.createServiceDefinition("ServiceBuilderTest", test_block["service-builder"]); + std::string test_url = mServiceBuilder.buildServiceURI("ServiceBuilder"); + ensure_equals("Replacement URL Creation for Non-existant Service", test_url , ""); + } + + template<> template<> + void ServiceBuilderTestObject::test<4>() + { + //Incorrect service test + LLSD test_block; + test_block["service-builder"] = "/agent/{$agent-id}/name"; + mServiceBuilder.createServiceDefinition("ServiceBuilderTest", test_block["service-builder"]); + LLSD data_map; + data_map["agent_id"] = "257c631f-a0c5-4f29-8a9f-9031feaae6c6"; + std::string test_url = mServiceBuilder.buildServiceURI("ServiceBuilderTest", data_map); + ensure_equals("Replacement URL Creation for Non-existant Service", test_url , "/agent/{$agent-id}/name"); + } + + template<> template<> + void ServiceBuilderTestObject::test<5>() + { + LLSD test_block; + test_block["service-builder"] = "/proc/{$proc}{%params}"; + mServiceBuilder.createServiceDefinition("ServiceBuilderTest", test_block["service-builder"]); + LLSD data_map; + data_map["proc"] = "do/something/useful"; + data_map["params"]["estate_id"] = 1; + data_map["params"]["query"] = "public"; + std::string test_url = mServiceBuilder.buildServiceURI("ServiceBuilderTest", data_map); + ensure_equals( + "two part URL Creation", + test_url , + "/proc/do/something/useful?estate_id=1&query=public"); + } + + template<> template<> + void ServiceBuilderTestObject::test<6>() + { + LLSD test_block; + test_block["service-builder"] = "Which way to the {${$baz}}?"; + mServiceBuilder.createServiceDefinition( + "ServiceBuilderTest", + test_block["service-builder"]); + + LLSD data_map; + data_map["foo"] = "bar"; + data_map["baz"] = "foo"; + std::string test_url = mServiceBuilder.buildServiceURI( + "ServiceBuilderTest", + data_map); + ensure_equals( + "recursive url creation", + test_url , + "Which way to the bar?"); + } + + template<> template<> + void ServiceBuilderTestObject::test<7>() + { + LLSD test_block; + test_block["service-builder"] = "Which way to the {$foo}?"; + mServiceBuilder.createServiceDefinition( + "ServiceBuilderTest", + test_block["service-builder"]); + + LLSD data_map; + data_map["baz"] = "foo"; + std::string test_url = mServiceBuilder.buildServiceURI( + "ServiceBuilderTest", + data_map); + ensure_equals( + "fails to do replacement", + test_url , + "Which way to the {$foo}?"); + } + + template<> template<> + void ServiceBuilderTestObject::test<8>() + { + LLSD test_block; + test_block["service-builder"] = "/proc/{$proc}{%params}"; + mServiceBuilder.createServiceDefinition( + "ServiceBuilderTest", + test_block["service-builder"]); + LLSD data_map; + data_map["proc"] = "do/something/useful"; + data_map["params"] = LLSD(); + std::string test_url = mServiceBuilder.buildServiceURI( + "ServiceBuilderTest", + data_map); + ensure_equals( + "strip params", + test_url , + "/proc/do/something/useful"); + } +} + diff --git a/indra/llmessage/tests/lltemplatemessagebuilder_test.cpp b/indra/llmessage/tests/lltemplatemessagebuilder_test.cpp new file mode 100644 index 0000000000..ddf1c3dbcc --- /dev/null +++ b/indra/llmessage/tests/lltemplatemessagebuilder_test.cpp @@ -0,0 +1,971 @@ +/** + * @file lltemplatemessagebuilder_tut.cpp + * @date 2007-04 + * @brief Tests for building messages. + * + * $LicenseInfo:firstyear=2007&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2010, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +#include +#include "linden_common.h" +#include "lltut.h" + +#include "llapr.h" +#include "llmessagetemplate.h" +#include "llmath.h" +#include "llquaternion.h" +#include "lltemplatemessagebuilder.h" +#include "lltemplatemessagereader.h" +#include "message_prehash.h" +#include "u64.h" +#include "v3dmath.h" +#include "v3math.h" +#include "v4math.h" + +namespace tut +{ + static LLTemplateMessageBuilder::message_template_name_map_t nameMap; + static LLTemplateMessageReader::message_template_number_map_t numberMap; + + struct LLTemplateMessageBuilderTestData + { + static LLMessageTemplate defaultTemplate() + { + static bool init = false; + if(! init) + { + ll_init_apr(); + const F32 circuit_heartbeat_interval=5; + const F32 circuit_timeout=100; + + start_messaging_system("notafile", 13035, + 1, + 0, + 0, + false, + "notasharedsecret", + NULL, + false, + circuit_heartbeat_interval, + circuit_timeout); + //init_prehash_data(); + init = true; + } + return LLMessageTemplate(_PREHASH_TestMessage, 1, MFT_HIGH); + } + + static LLMessageBlock* defaultBlock(const EMsgVariableType type = MVT_NULL, const S32 size = 0, EMsgBlockType block = MBT_VARIABLE) + { + return createBlock(const_cast(_PREHASH_Test0), type, size, block); + } + + static LLMessageBlock* createBlock(char* name, const EMsgVariableType type = MVT_NULL, const S32 size = 0, EMsgBlockType block = MBT_VARIABLE) + { + LLMessageBlock* result = new LLMessageBlock(name, block); + if(type != MVT_NULL) + { + result->addVariable(const_cast(_PREHASH_Test0), type, size); + } + return result; + } + + static LLTemplateMessageBuilder* defaultBuilder(LLMessageTemplate& messageTemplate, char* name = const_cast(_PREHASH_Test0)) + { + nameMap[_PREHASH_TestMessage] = &messageTemplate; + LLTemplateMessageBuilder* builder = new LLTemplateMessageBuilder(nameMap); + builder->newMessage(_PREHASH_TestMessage); + builder->nextBlock(name); + return builder; + } + + /** Takes ownership of builder */ + static LLTemplateMessageReader* setReader( + LLMessageTemplate& messageTemplate, + LLTemplateMessageBuilder* builder, + U8 offset = 0) + { + numberMap[1] = &messageTemplate; + const U32 bufferSize = 1024; + U8 buffer[bufferSize]; + // zero out the packet ID field + memset(buffer, 0, LL_PACKET_ID_SIZE); + U32 builtSize = builder->buildMessage(buffer, bufferSize, offset); + delete builder; + LLTemplateMessageReader* reader = new LLTemplateMessageReader(numberMap); + reader->validateMessage(buffer, builtSize, LLHost()); + reader->readMessage(buffer, LLHost()); + return reader; + } + + }; + + typedef test_group LLTemplateMessageBuilderTestGroup; + typedef LLTemplateMessageBuilderTestGroup::object LLTemplateMessageBuilderTestObject; + LLTemplateMessageBuilderTestGroup templateMessageBuilderTestGroup("LLTemplateMessageBuilder"); + + template<> template<> + void LLTemplateMessageBuilderTestObject::test<1>() + // construction and test of undefined + { + LLMessageTemplate messageTemplate = defaultTemplate(); + messageTemplate.addBlock(defaultBlock()); + LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); + LLTemplateMessageReader* reader = setReader(messageTemplate, builder); + delete reader; + } + + template<> template<> + void LLTemplateMessageBuilderTestObject::test<2>() + // bool + { + LLMessageTemplate messageTemplate = defaultTemplate(); + messageTemplate.addBlock(defaultBlock(MVT_BOOL, 1)); + bool outValue, inValue = true; + LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); + builder->addBOOL(_PREHASH_Test0, inValue); + LLTemplateMessageReader* reader = setReader(messageTemplate, builder); + reader->getBOOL(_PREHASH_Test0, _PREHASH_Test0, outValue); + ensure_equals("Ensure bool", inValue, outValue); + delete reader; + } + + template<> template<> + void LLTemplateMessageBuilderTestObject::test<3>() + // U8 + { + LLMessageTemplate messageTemplate = defaultTemplate(); + messageTemplate.addBlock(defaultBlock(MVT_U8, 1)); + U8 outValue, inValue = 2; + LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); + builder->addU8(_PREHASH_Test0, inValue); + LLTemplateMessageReader* reader = setReader(messageTemplate, builder); + reader->getU8(_PREHASH_Test0, _PREHASH_Test0, outValue); + ensure_equals("Ensure U8", inValue, outValue); + delete reader; + } + + template<> template<> + void LLTemplateMessageBuilderTestObject::test<4>() + // S16 + { + LLMessageTemplate messageTemplate = defaultTemplate(); + messageTemplate.addBlock(defaultBlock(MVT_S16, 2)); + S16 outValue, inValue = 90; + LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); + builder->addS16(_PREHASH_Test0, inValue); + LLTemplateMessageReader* reader = setReader(messageTemplate, builder); + reader->getS16(_PREHASH_Test0, _PREHASH_Test0, outValue); + ensure_equals("Ensure S16", inValue, outValue); + delete reader; + } + + template<> template<> + void LLTemplateMessageBuilderTestObject::test<5>() + // U16 + { + LLMessageTemplate messageTemplate = defaultTemplate(); + messageTemplate.addBlock(defaultBlock(MVT_U16, 2)); + U16 outValue, inValue = 3; + LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); + builder->addU16(_PREHASH_Test0, inValue); + LLTemplateMessageReader* reader = setReader(messageTemplate, builder); + reader->getU16(_PREHASH_Test0, _PREHASH_Test0, outValue); + ensure_equals("Ensure U16", inValue, outValue); + delete reader; + } + + template<> template<> + void LLTemplateMessageBuilderTestObject::test<6>() + // S32 + { + LLMessageTemplate messageTemplate = defaultTemplate(); + messageTemplate.addBlock(defaultBlock(MVT_S32, 4)); + S32 outValue, inValue = 44; + LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); + builder->addS32(_PREHASH_Test0, inValue); + LLTemplateMessageReader* reader = setReader(messageTemplate, builder); + reader->getS32(_PREHASH_Test0, _PREHASH_Test0, outValue); + ensure_equals("Ensure S32", inValue, outValue); + delete reader; + } + + template<> template<> + void LLTemplateMessageBuilderTestObject::test<7>() + // F32 + { + LLMessageTemplate messageTemplate = defaultTemplate(); + messageTemplate.addBlock(defaultBlock(MVT_F32, 4)); + F32 outValue, inValue = 121.44f; + LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); + builder->addF32(_PREHASH_Test0, inValue); + LLTemplateMessageReader* reader = setReader(messageTemplate, builder); + reader->getF32(_PREHASH_Test0, _PREHASH_Test0, outValue); + ensure_equals("Ensure F32", inValue, outValue); + delete reader; + } + + template<> template<> + void LLTemplateMessageBuilderTestObject::test<8>() + // U32 + { + LLMessageTemplate messageTemplate = defaultTemplate(); + messageTemplate.addBlock(defaultBlock(MVT_U32, 4)); + U32 outValue, inValue = 88; + LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); + builder->addU32(_PREHASH_Test0, inValue); + LLTemplateMessageReader* reader = setReader(messageTemplate, builder); + reader->getU32(_PREHASH_Test0, _PREHASH_Test0, outValue); + ensure_equals("Ensure U32", inValue, outValue); + delete reader; + } + + template<> template<> + void LLTemplateMessageBuilderTestObject::test<9>() + // U64 + { + LLMessageTemplate messageTemplate = defaultTemplate(); + messageTemplate.addBlock(defaultBlock(MVT_U64, 8)); + U64 outValue, inValue = 121; + LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); + builder->addU64(_PREHASH_Test0, inValue); + LLTemplateMessageReader* reader = setReader(messageTemplate, builder); + reader->getU64(_PREHASH_Test0, _PREHASH_Test0, outValue); + ensure_equals("Ensure U64", inValue, outValue); + delete reader; + } + + template<> template<> + void LLTemplateMessageBuilderTestObject::test<10>() + // F64 + { + LLMessageTemplate messageTemplate = defaultTemplate(); + messageTemplate.addBlock(defaultBlock(MVT_F64, 8)); + F64 outValue, inValue = 3232143.33; + LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); + builder->addF64(_PREHASH_Test0, inValue); + LLTemplateMessageReader* reader = setReader(messageTemplate, builder); + reader->getF64(_PREHASH_Test0, _PREHASH_Test0, outValue); + ensure_equals("Ensure F64", inValue, outValue); + delete reader; + } + + template<> template<> + void LLTemplateMessageBuilderTestObject::test<11>() + // Vector3 + { + LLMessageTemplate messageTemplate = defaultTemplate(); + messageTemplate.addBlock(defaultBlock(MVT_LLVector3, 12)); + LLVector3 outValue, inValue = LLVector3(1,2,3); + LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); + builder->addVector3(_PREHASH_Test0, inValue); + LLTemplateMessageReader* reader = setReader(messageTemplate, builder); + reader->getVector3(_PREHASH_Test0, _PREHASH_Test0, outValue); + ensure_equals("Ensure LLVector3", inValue, outValue); + delete reader; + } + + template<> template<> + void LLTemplateMessageBuilderTestObject::test<12>() + // Vector4 + { + LLMessageTemplate messageTemplate = defaultTemplate(); + messageTemplate.addBlock(defaultBlock(MVT_LLVector4, 16)); + LLVector4 outValue, inValue = LLVector4(1,2,3,4); + LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); + builder->addVector4(_PREHASH_Test0, inValue); + LLTemplateMessageReader* reader = setReader(messageTemplate, builder); + reader->getVector4(_PREHASH_Test0, _PREHASH_Test0, outValue); + ensure_equals("Ensure LLVector4", inValue, outValue); + delete reader; + } + + template<> template<> + void LLTemplateMessageBuilderTestObject::test<13>() + // Vector3d + { + LLMessageTemplate messageTemplate = defaultTemplate(); + messageTemplate.addBlock(defaultBlock(MVT_LLVector3d, 24)); + LLVector3d outValue, inValue = LLVector3d(1,2,3); + LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); + builder->addVector3d(_PREHASH_Test0, inValue); + LLTemplateMessageReader* reader = setReader(messageTemplate, builder); + reader->getVector3d(_PREHASH_Test0, _PREHASH_Test0, outValue); + ensure_equals("Ensure LLVector3d", inValue, outValue); + delete reader; + } + + template<> template<> + void LLTemplateMessageBuilderTestObject::test<14>() + // Quaternion + { + LLMessageTemplate messageTemplate = defaultTemplate(); + messageTemplate.addBlock(defaultBlock(MVT_LLQuaternion, 12)); + LLQuaternion outValue, inValue = LLQuaternion(0.0f, LLVector3(0.3713907f, 0.5570861f, 0.7427813f)); + + LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); + builder->addQuat(_PREHASH_Test0, inValue); + LLTemplateMessageReader* reader = setReader(messageTemplate, builder); + reader->getQuat(_PREHASH_Test0, _PREHASH_Test0, outValue); + ensure_equals("Ensure LLQuaternion", inValue, outValue); + delete reader; + } + + template<> template<> + void LLTemplateMessageBuilderTestObject::test<15>() + // UUID + { + LLMessageTemplate messageTemplate = defaultTemplate(); + messageTemplate.addBlock(defaultBlock(MVT_LLUUID, 16)); + LLUUID outValue, inValue; + inValue.generate(); + LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); + builder->addUUID(_PREHASH_Test0, inValue); + LLTemplateMessageReader* reader = setReader(messageTemplate, builder); + reader->getUUID(_PREHASH_Test0, _PREHASH_Test0, outValue); + ensure_equals("Ensure UUID", inValue, outValue); + delete reader; + } + + template<> template<> + void LLTemplateMessageBuilderTestObject::test<16>() + // IPAddr + { + LLMessageTemplate messageTemplate = defaultTemplate(); + messageTemplate.addBlock(defaultBlock(MVT_IP_ADDR, 4)); + U32 outValue, inValue = 12344556; + LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); + builder->addIPAddr(_PREHASH_Test0, inValue); + LLTemplateMessageReader* reader = setReader(messageTemplate, builder); + reader->getIPAddr(_PREHASH_Test0, _PREHASH_Test0, outValue); + ensure_equals("Ensure IPAddr", inValue, outValue); + delete reader; + } + + template<> template<> + void LLTemplateMessageBuilderTestObject::test<17>() + // IPPort + { + LLMessageTemplate messageTemplate = defaultTemplate(); + messageTemplate.addBlock(defaultBlock(MVT_IP_PORT, 2)); + U16 outValue, inValue = 80; + LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); + builder->addIPPort(_PREHASH_Test0, inValue); + LLTemplateMessageReader* reader = setReader(messageTemplate, builder); + reader->getIPPort(_PREHASH_Test0, _PREHASH_Test0, outValue); + ensure_equals("Ensure IPPort", inValue, outValue); + delete reader; + } + + template<> template<> + void LLTemplateMessageBuilderTestObject::test<18>() + // String + { + LLMessageTemplate messageTemplate = defaultTemplate(); + messageTemplate.addBlock(defaultBlock(MVT_VARIABLE, 1)); + std::string outValue, inValue = "testing"; + LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); + builder->addString(_PREHASH_Test0, inValue.c_str()); + LLTemplateMessageReader* reader = setReader(messageTemplate, builder); + char buffer[MAX_STRING]; + reader->getString(_PREHASH_Test0, _PREHASH_Test0, MAX_STRING, buffer); + outValue = buffer; + ensure_equals("Ensure String", inValue, outValue); + delete reader; + } + + template<> template<> + void LLTemplateMessageBuilderTestObject::test<19>() + // block name !-> binary order + { + U8 buffer1[MAX_BUFFER_SIZE]; + memset(buffer1, 0, MAX_BUFFER_SIZE); + U8 buffer2[MAX_BUFFER_SIZE]; + memset(buffer2, 0, MAX_BUFFER_SIZE); + U32 bufferSize1, bufferSize2; + + // build template: Test0 before Test1 + LLMessageTemplate messageTemplate = defaultTemplate(); + messageTemplate.addBlock(createBlock(const_cast(_PREHASH_Test0), MVT_U32, 4, MBT_SINGLE)); + messageTemplate.addBlock(createBlock(const_cast(_PREHASH_Test1), MVT_U32, 4, MBT_SINGLE)); + + // build message: 1st declared block var == 0xaaaa, 2nd declared block var == 0xbbbb + LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate, const_cast(_PREHASH_Test0)); + builder->addU32(_PREHASH_Test0, 0xaaaa); + builder->nextBlock(_PREHASH_Test1); + builder->addU32(_PREHASH_Test0, 0xbbbb); + bufferSize1 = builder->buildMessage(buffer1, MAX_BUFFER_SIZE, 0); + delete builder; + + // build template: Test1 before Test0 + messageTemplate = defaultTemplate(); + messageTemplate.addBlock(createBlock(const_cast(_PREHASH_Test1), MVT_U32, 4, MBT_SINGLE)); + messageTemplate.addBlock(createBlock(const_cast(_PREHASH_Test0), MVT_U32, 4, MBT_SINGLE)); + + // build message: 1st declared block var == 0xaaaa, 2nd declared block var == 0xbbbb + builder = defaultBuilder(messageTemplate, const_cast(_PREHASH_Test1)); + builder->addU32(_PREHASH_Test0, 0xaaaa); + builder->nextBlock(_PREHASH_Test0); + builder->addU32(_PREHASH_Test0, 0xbbbb); + bufferSize2 = builder->buildMessage(buffer2, MAX_BUFFER_SIZE, 0); + delete builder; + + ensure_equals("Ensure Buffer Sizes Equal", bufferSize1, bufferSize2); + ensure_equals("Ensure Buffer Contents Equal", memcmp(buffer1, buffer2, bufferSize1), 0); + } + + template<> template<> + void LLTemplateMessageBuilderTestObject::test<20>() + // block build order !-> binary order + { + U8 buffer1[MAX_BUFFER_SIZE]; + memset(buffer1, 0, MAX_BUFFER_SIZE); + U8 buffer2[MAX_BUFFER_SIZE]; + memset(buffer2, 0, MAX_BUFFER_SIZE); + U32 bufferSize1, bufferSize2; + + // build template: Test0 before Test1 + LLMessageTemplate messageTemplate = defaultTemplate(); + messageTemplate.addBlock(createBlock(const_cast(_PREHASH_Test0), MVT_U32, 4, MBT_SINGLE)); + messageTemplate.addBlock(createBlock(const_cast(_PREHASH_Test1), MVT_U32, 4, MBT_SINGLE)); + + // build message: 1st declared block var == 0xaaaa, 2nd declared block var == 0xbbbb + LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate, const_cast(_PREHASH_Test0)); + builder->addU32(_PREHASH_Test0, 0xaaaa); + builder->nextBlock(_PREHASH_Test1); + builder->addU32(_PREHASH_Test0, 0xbbbb); + bufferSize1 = builder->buildMessage(buffer1, MAX_BUFFER_SIZE, 0); + delete builder; + + // build message: 1st declared block var == 0xaaaa, 2nd declared block var == 0xbbbb + builder = defaultBuilder(messageTemplate, const_cast(_PREHASH_Test1)); + builder->addU32(_PREHASH_Test0, 0xbbbb); + builder->nextBlock(_PREHASH_Test0); + builder->addU32(_PREHASH_Test0, 0xaaaa); + bufferSize2 = builder->buildMessage(buffer2, MAX_BUFFER_SIZE, 0); + delete builder; + + ensure_equals("Ensure Buffer Sizes Equal", bufferSize1, bufferSize2); + ensure_equals("Ensure Buffer Contents Equal", memcmp(buffer1, buffer2, bufferSize1), 0); + } + + template<> template<> + void LLTemplateMessageBuilderTestObject::test<21>() + // block appended in declaration -> data appended in binary + { + U8 buffer1[MAX_BUFFER_SIZE]; + memset(buffer1, 0, MAX_BUFFER_SIZE); + U8 buffer2[MAX_BUFFER_SIZE]; + memset(buffer2, 0, MAX_BUFFER_SIZE); + U32 bufferSize1, bufferSize2; + + // Build template: Test0 only + LLMessageTemplate messageTemplate = defaultTemplate(); + messageTemplate.addBlock(createBlock(const_cast(_PREHASH_Test0), MVT_U32, 4, MBT_SINGLE)); + + // Build message + LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate, const_cast(_PREHASH_Test0)); + builder->addU32(_PREHASH_Test0, 0xaaaa); + bufferSize1 = builder->buildMessage(buffer1, MAX_BUFFER_SIZE, 0); + delete builder; + + // Build template: Test0 before Test1 + messageTemplate = defaultTemplate(); + messageTemplate.addBlock(createBlock(const_cast(_PREHASH_Test0), MVT_U32, 4, MBT_SINGLE)); + messageTemplate.addBlock(createBlock(const_cast(_PREHASH_Test1), MVT_U32, 4, MBT_SINGLE)); + + // Build message + builder = defaultBuilder(messageTemplate, const_cast(_PREHASH_Test0)); + builder->addU32(_PREHASH_Test0, 0xaaaa); + builder->nextBlock(_PREHASH_Test1); + builder->addU32(_PREHASH_Test0, 0xbbbb); + bufferSize2 = builder->buildMessage(buffer2, MAX_BUFFER_SIZE, 0); + delete builder; + + ensure_not_equals("Ensure Buffer Sizes Not Equal", bufferSize1, bufferSize2); + ensure_equals("Ensure Buffer Prefix Equal", memcmp(buffer1, buffer2, bufferSize1), 0); + ensure_not_equals("Ensure Buffer Contents Not Equal", memcmp(buffer1, buffer2, bufferSize2), 0); + } + + template<> template<> + void LLTemplateMessageBuilderTestObject::test<22>() + // repeated penultimate block (crashes when data in LLDynamicArrayIndexed) + { + U32 inTest00 = 0, inTest01 = 1, inTest1 = 2; + U32 outTest00, outTest01, outTest1; + LLMessageTemplate messageTemplate = defaultTemplate(); + messageTemplate.addBlock(createBlock(const_cast(_PREHASH_Test0), MVT_U32, 4)); + messageTemplate.addBlock(createBlock(const_cast(_PREHASH_Test1), MVT_U32, 4)); + LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); + builder->addU32(_PREHASH_Test0, inTest00); + builder->nextBlock(_PREHASH_Test0); + builder->addU32(_PREHASH_Test0, inTest01); + builder->nextBlock(_PREHASH_Test1); + builder->addU32(_PREHASH_Test0, inTest1); + LLTemplateMessageReader* reader = setReader(messageTemplate, builder); + reader->getU32(_PREHASH_Test0, _PREHASH_Test0, outTest00, 0); + reader->getU32(_PREHASH_Test0, _PREHASH_Test0, outTest01, 1); + reader->getU32(_PREHASH_Test1, _PREHASH_Test0, outTest1); + ensure_equals("Ensure Test0[0]", inTest00, outTest00); + ensure_equals("Ensure Test0[1]", inTest01, outTest01); + ensure_equals("Ensure Test1", inTest1, outTest1); + delete reader; + } + + template<> template<> + void LLTemplateMessageBuilderTestObject::test<23>() + // variable repeated block name never accessed + { + U32 inTest = 1, outTest; + LLMessageTemplate messageTemplate = defaultTemplate(); + messageTemplate.addBlock( + createBlock(const_cast(_PREHASH_Test0), MVT_U32, 4, MBT_SINGLE)); + messageTemplate.addBlock(createBlock(const_cast(_PREHASH_Test1), MVT_U32, 4)); + + LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); + builder->addU32(_PREHASH_Test0, inTest); + + LLTemplateMessageReader* reader = setReader(messageTemplate, builder); + reader->getU32(_PREHASH_Test0, _PREHASH_Test0, outTest); + S32 blockCount = reader->getNumberOfBlocks(const_cast(_PREHASH_Test1)); + ensure_equals("Ensure block count", blockCount, 0); + ensure_equals("Ensure Test0", inTest, outTest); + delete reader; + } + + template<> template<> + void LLTemplateMessageBuilderTestObject::test<24>() + // forwarding message + { + // build template + LLMessageTemplate messageTemplate = defaultTemplate(); + messageTemplate.addBlock(createBlock(const_cast(_PREHASH_Test0), MVT_U32, 4)); + + // build message + LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); + builder->addU32(_PREHASH_Test0, 42); + + // read message + LLTemplateMessageReader* reader = setReader(messageTemplate, builder); + + // forward message + builder = defaultBuilder(messageTemplate); + builder->newMessage(_PREHASH_TestMessage); + reader->copyToBuilder(*builder); + U8 buffer[MAX_BUFFER_SIZE]; + builder->buildMessage(buffer, MAX_BUFFER_SIZE, 0); + + delete builder; + delete reader; + } + + template<> template<> + void LLTemplateMessageBuilderTestObject::test<25>() + // non-zero offset with undefined + { + LLMessageTemplate messageTemplate = defaultTemplate(); + messageTemplate.addBlock(defaultBlock()); + LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); + LLTemplateMessageReader* reader = setReader( + messageTemplate, builder, 10); + delete reader; + } + + template<> template<> + void LLTemplateMessageBuilderTestObject::test<26>() + // non-zero offset with bool + { + LLMessageTemplate messageTemplate = defaultTemplate(); + messageTemplate.addBlock(defaultBlock(MVT_BOOL, 1)); + bool outValue, inValue = true; + LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); + builder->addBOOL(_PREHASH_Test0, inValue); + LLTemplateMessageReader* reader = setReader( + messageTemplate, builder, 1); + reader->getBOOL(_PREHASH_Test0, _PREHASH_Test0, outValue); + ensure_equals("Ensure bool", inValue, outValue); + delete reader; + } + + template<> template<> + void LLTemplateMessageBuilderTestObject::test<27>() + // non-zero offset with U8 + { + LLMessageTemplate messageTemplate = defaultTemplate(); + messageTemplate.addBlock(defaultBlock(MVT_U8, 1)); + U8 outValue, inValue = 2; + LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); + builder->addU8(_PREHASH_Test0, inValue); + LLTemplateMessageReader* reader = setReader( + messageTemplate, builder, 255); + reader->getU8(_PREHASH_Test0, _PREHASH_Test0, outValue); + ensure_equals("Ensure U8", inValue, outValue); + delete reader; + } + + template<> template<> + void LLTemplateMessageBuilderTestObject::test<28>() + // non-zero offset with S16 + { + LLMessageTemplate messageTemplate = defaultTemplate(); + messageTemplate.addBlock(defaultBlock(MVT_S16, 2)); + S16 outValue, inValue = 90; + LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); + builder->addS16(_PREHASH_Test0, inValue); + LLTemplateMessageReader* reader = setReader( + messageTemplate, builder, 2); + reader->getS16(_PREHASH_Test0, _PREHASH_Test0, outValue); + ensure_equals("Ensure S16", inValue, outValue); + delete reader; + } + + template<> template<> + void LLTemplateMessageBuilderTestObject::test<29>() + // non-zero offset with U16 + { + LLMessageTemplate messageTemplate = defaultTemplate(); + messageTemplate.addBlock(defaultBlock(MVT_U16, 2)); + U16 outValue, inValue = 3; + LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); + builder->addU16(_PREHASH_Test0, inValue); + LLTemplateMessageReader* reader = setReader( + messageTemplate, builder, 4); + reader->getU16(_PREHASH_Test0, _PREHASH_Test0, outValue); + ensure_equals("Ensure U16", inValue, outValue); + delete reader; + } + + template<> template<> + void LLTemplateMessageBuilderTestObject::test<30>() + // non-zero offset with S32 + { + LLMessageTemplate messageTemplate = defaultTemplate(); + messageTemplate.addBlock(defaultBlock(MVT_S32, 4)); + S32 outValue, inValue = 44; + LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); + builder->addS32(_PREHASH_Test0, inValue); + LLTemplateMessageReader* reader = setReader( + messageTemplate, builder, 4); + reader->getS32(_PREHASH_Test0, _PREHASH_Test0, outValue); + ensure_equals("Ensure S32", inValue, outValue); + delete reader; + } + + template<> template<> + void LLTemplateMessageBuilderTestObject::test<31>() + // non-zero offset with F32 + { + LLMessageTemplate messageTemplate = defaultTemplate(); + messageTemplate.addBlock(defaultBlock(MVT_F32, 4)); + F32 outValue, inValue = 121.44f; + LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); + builder->addF32(_PREHASH_Test0, inValue); + LLTemplateMessageReader* reader = setReader( + messageTemplate, builder, 16); + reader->getF32(_PREHASH_Test0, _PREHASH_Test0, outValue); + ensure_equals("Ensure F32", inValue, outValue); + delete reader; + } + + template<> template<> + void LLTemplateMessageBuilderTestObject::test<32>() + // non-zero offset with U32 + { + LLMessageTemplate messageTemplate = defaultTemplate(); + messageTemplate.addBlock(defaultBlock(MVT_U32, 4)); + U32 outValue, inValue = 88; + LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); + builder->addU32(_PREHASH_Test0, inValue); + LLTemplateMessageReader* reader = setReader( + messageTemplate, builder, 127); + reader->getU32(_PREHASH_Test0, _PREHASH_Test0, outValue); + ensure_equals("Ensure U32", inValue, outValue); + delete reader; + } + + template<> template<> + void LLTemplateMessageBuilderTestObject::test<33>() + // non-zero offset with U64 + { + LLMessageTemplate messageTemplate = defaultTemplate(); + messageTemplate.addBlock(defaultBlock(MVT_U64, 8)); + U64 outValue, inValue = 121; + LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); + builder->addU64(_PREHASH_Test0, inValue); + LLTemplateMessageReader* reader = setReader( + messageTemplate, builder, 32); + reader->getU64(_PREHASH_Test0, _PREHASH_Test0, outValue); + ensure_equals("Ensure U64", inValue, outValue); + delete reader; + } + + template<> template<> + void LLTemplateMessageBuilderTestObject::test<34>() + // non-zero offset with F64 + { + LLMessageTemplate messageTemplate = defaultTemplate(); + messageTemplate.addBlock(defaultBlock(MVT_F64, 8)); + F64 outValue, inValue = 3232143.33; + LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); + builder->addF64(_PREHASH_Test0, inValue); + LLTemplateMessageReader* reader = setReader( + messageTemplate, builder, 128); + reader->getF64(_PREHASH_Test0, _PREHASH_Test0, outValue); + ensure_equals("Ensure F64", inValue, outValue); + delete reader; + } + + template<> template<> + void LLTemplateMessageBuilderTestObject::test<35>() + // non-zero offset with Vector3 + { + LLMessageTemplate messageTemplate = defaultTemplate(); + messageTemplate.addBlock(defaultBlock(MVT_LLVector3, 12)); + LLVector3 outValue, inValue = LLVector3(1,2,3); + LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); + builder->addVector3(_PREHASH_Test0, inValue); + LLTemplateMessageReader* reader = setReader( + messageTemplate, builder, 63); + reader->getVector3(_PREHASH_Test0, _PREHASH_Test0, outValue); + ensure_equals("Ensure LLVector3", inValue, outValue); + delete reader; + } + + template<> template<> + void LLTemplateMessageBuilderTestObject::test<36>() + // non-zero offset with Vector4 + { + LLMessageTemplate messageTemplate = defaultTemplate(); + messageTemplate.addBlock(defaultBlock(MVT_LLVector4, 16)); + LLVector4 outValue, inValue = LLVector4(1,2,3,4); + LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); + builder->addVector4(_PREHASH_Test0, inValue); + LLTemplateMessageReader* reader = setReader( + messageTemplate, builder, 64); + reader->getVector4(_PREHASH_Test0, _PREHASH_Test0, outValue); + ensure_equals("Ensure LLVector4", inValue, outValue); + delete reader; + } + + template<> template<> + void LLTemplateMessageBuilderTestObject::test<37>() + // non-zero offset with Vector3d + { + LLMessageTemplate messageTemplate = defaultTemplate(); + messageTemplate.addBlock(defaultBlock(MVT_LLVector3d, 24)); + LLVector3d outValue, inValue = LLVector3d(1,2,3); + LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); + builder->addVector3d(_PREHASH_Test0, inValue); + LLTemplateMessageReader* reader = setReader( + messageTemplate, builder, 64); + reader->getVector3d(_PREHASH_Test0, _PREHASH_Test0, outValue); + ensure_equals("Ensure LLVector3d", inValue, outValue); + delete reader; + } + + template<> template<> + void LLTemplateMessageBuilderTestObject::test<38>() + // non-zero offset with Quaternion + { + LLMessageTemplate messageTemplate = defaultTemplate(); + messageTemplate.addBlock(defaultBlock(MVT_LLQuaternion, 12)); + LLQuaternion outValue, inValue = LLQuaternion(0.0f, LLVector3(0.3713907f, 0.5570861f, 0.7427813f)); + LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); + builder->addQuat(_PREHASH_Test0, inValue); + LLTemplateMessageReader* reader = setReader( + messageTemplate, builder, 12); + reader->getQuat(_PREHASH_Test0, _PREHASH_Test0, outValue); + ensure_equals("Ensure LLQuaternion", inValue, outValue); + delete reader; + } + + template<> template<> + void LLTemplateMessageBuilderTestObject::test<39>() + // non-zero offset with UUID + { + LLMessageTemplate messageTemplate = defaultTemplate(); + messageTemplate.addBlock(defaultBlock(MVT_LLUUID, 16)); + LLUUID outValue, inValue; + inValue.generate(); + LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); + builder->addUUID(_PREHASH_Test0, inValue); + LLTemplateMessageReader* reader = setReader( + messageTemplate, builder, 31); + reader->getUUID(_PREHASH_Test0, _PREHASH_Test0, outValue); + ensure_equals("Ensure UUID", inValue, outValue); + delete reader; + } + + template<> template<> + void LLTemplateMessageBuilderTestObject::test<40>() + // non-zero offset with IPAddr + { + LLMessageTemplate messageTemplate = defaultTemplate(); + messageTemplate.addBlock(defaultBlock(MVT_IP_ADDR, 4)); + U32 outValue, inValue = 12344556; + LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); + builder->addIPAddr(_PREHASH_Test0, inValue); + LLTemplateMessageReader* reader = setReader( + messageTemplate, builder, 32); + reader->getIPAddr(_PREHASH_Test0, _PREHASH_Test0, outValue); + ensure_equals("Ensure IPAddr", inValue, outValue); + delete reader; + } + + template<> template<> + void LLTemplateMessageBuilderTestObject::test<41>() + // non-zero offset with IPPort + { + LLMessageTemplate messageTemplate = defaultTemplate(); + messageTemplate.addBlock(defaultBlock(MVT_IP_PORT, 2)); + U16 outValue, inValue = 80; + LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); + builder->addIPPort(_PREHASH_Test0, inValue); + LLTemplateMessageReader* reader = setReader( + messageTemplate, builder, 6); + reader->getIPPort(_PREHASH_Test0, _PREHASH_Test0, outValue); + ensure_equals("Ensure IPPort", inValue, outValue); + delete reader; + } + + template<> template<> + void LLTemplateMessageBuilderTestObject::test<42>() + // non-zero offset with String + { + LLMessageTemplate messageTemplate = defaultTemplate(); + messageTemplate.addBlock(defaultBlock(MVT_VARIABLE, 1)); + std::string outValue, inValue = "testing"; + LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); + builder->addString(_PREHASH_Test0, inValue.c_str()); + LLTemplateMessageReader* reader = setReader( + messageTemplate, builder, 255); + char buffer[MAX_STRING]; + reader->getString(_PREHASH_Test0, _PREHASH_Test0, MAX_STRING, buffer); + outValue = buffer; + ensure_equals("Ensure String", inValue, outValue); + delete reader; + } + + template<> template<> + void LLTemplateMessageBuilderTestObject::test<43>() + // read past end of message -> default values (forward compatibility) + { + // build message with single block + LLMessageTemplate messageTemplate = defaultTemplate(); + messageTemplate.addBlock(defaultBlock(MVT_U32, 4, MBT_SINGLE)); + U32 outValue, outValue2, inValue = 0xbbbbbbbb; + LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); + builder->addU32(_PREHASH_Test0, inValue); + const U32 bufferSize = 1024; + U8 buffer[bufferSize]; + memset(buffer, 0xaa, bufferSize); + memset(buffer, 0, LL_PACKET_ID_SIZE); + U32 builtSize = builder->buildMessage(buffer, bufferSize, 0); + delete builder; + + // add block to reader template + messageTemplate.addBlock(createBlock(const_cast(_PREHASH_Test1), MVT_U32, 4, MBT_SINGLE)); + + // read message value and default value + numberMap[1] = &messageTemplate; + LLTemplateMessageReader* reader = + new LLTemplateMessageReader(numberMap); + reader->validateMessage(buffer, builtSize, LLHost()); + reader->readMessage(buffer, LLHost()); + reader->getU32(_PREHASH_Test0, _PREHASH_Test0, outValue); + reader->getU32(_PREHASH_Test1, _PREHASH_Test0, outValue2); + ensure_equals("Ensure present value ", outValue, inValue); + ensure_equals("Ensure default value ", outValue2, 0); + delete reader; + } + + template<> template<> + void LLTemplateMessageBuilderTestObject::test<44>() + // read variable block past end of message -> 0 repeats + { + // build message with single block + LLMessageTemplate messageTemplate = defaultTemplate(); + messageTemplate.addBlock(defaultBlock(MVT_U32, 4, MBT_SINGLE)); + U32 outValue, outValue2, inValue = 0xbbbbbbbb; + LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); + builder->addU32(_PREHASH_Test0, inValue); + const U32 bufferSize = 1024; + U8 buffer[bufferSize]; + memset(buffer, 0xaa, bufferSize); + memset(buffer, 0, LL_PACKET_ID_SIZE); + U32 builtSize = builder->buildMessage(buffer, bufferSize, 0); + delete builder; + + // add variable block to reader template + messageTemplate.addBlock(createBlock(const_cast(_PREHASH_Test1), MVT_U32, 4)); + + // read message value and check block repeat count + numberMap[1] = &messageTemplate; + LLTemplateMessageReader* reader = + new LLTemplateMessageReader(numberMap); + reader->validateMessage(buffer, builtSize, LLHost()); + reader->readMessage(buffer, LLHost()); + reader->getU32(_PREHASH_Test0, _PREHASH_Test0, outValue); + outValue2 = reader->getNumberOfBlocks(_PREHASH_Test1); + ensure_equals("Ensure present value ", outValue, inValue); + ensure_equals("Ensure 0 repeats ", outValue2, 0); + delete reader; + } + + template<> template<> + void LLTemplateMessageBuilderTestObject::test<45>() + // read variable length data past end of message -> 0 length + { + // build message with single block + LLMessageTemplate messageTemplate = defaultTemplate(); + messageTemplate.addBlock(defaultBlock(MVT_U32, 4, MBT_SINGLE)); + U32 outValue, inValue = 0xbbbbbbbb; + LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); + builder->addU32(_PREHASH_Test0, inValue); + const U32 bufferSize = 1024; + U8 buffer[bufferSize]; + memset(buffer, 0xaa, bufferSize); + memset(buffer, 0, LL_PACKET_ID_SIZE); + U32 builtSize = builder->buildMessage(buffer, bufferSize, 0); + delete builder; + + // add variable block to reader template + messageTemplate.addBlock(createBlock(const_cast(_PREHASH_Test1), MVT_VARIABLE, 4, + MBT_SINGLE)); + + // read message value and default string + numberMap[1] = &messageTemplate; + LLTemplateMessageReader* reader = + new LLTemplateMessageReader(numberMap); + reader->validateMessage(buffer, builtSize, LLHost()); + reader->readMessage(buffer, LLHost()); + reader->getU32(_PREHASH_Test0, _PREHASH_Test0, outValue); + (void)outValue; + char outBuffer[bufferSize]; + memset(buffer, 0xcc, bufferSize); + reader->getString(_PREHASH_Test1, _PREHASH_Test0, bufferSize, + outBuffer); + ensure_equals("Ensure present value ", outValue, inValue); + ensure_equals("Ensure unchanged buffer ", strlen(outBuffer), 0); + delete reader; + } +} + diff --git a/indra/llmessage/tests/llxorcipher_test.cpp b/indra/llmessage/tests/llxorcipher_test.cpp new file mode 100644 index 0000000000..9acac53604 --- /dev/null +++ b/indra/llmessage/tests/llxorcipher_test.cpp @@ -0,0 +1,131 @@ +/** + * @file llxorcipher_tut.cpp + * @author Adroit + * @date 2007-03 + * @brief llxorcipher, llnullcipher test cases. + * + * $LicenseInfo:firstyear=2007&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2010, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +#include "linden_common.h" +#include "lltut.h" +#include "llxorcipher.h" +#include "llnullcipher.h" + +namespace tut +{ + struct cipher + { + }; + typedef test_group cipher_t; + typedef cipher_t::object cipher_object_t; + tut::cipher_t tut_cipher("cipher"); + + //encrypt->decrypt + template<> template<> + void cipher_object_t::test<1>() + { + const U32 len = 3; + const U8 pad[] = "abc"; + const char str[] = "SecondLife"; + const S32 str_len = sizeof(str); + U8 encrypted[str_len]; + U8 decrypted[str_len]; + LLXORCipher xorCipher(pad, len); + LLXORCipher xorCipher1(pad, len); + + U32 length = xorCipher.requiredEncryptionSpace(50); + ensure("requiredEncryptionSpace() function failed", (length == 50)); + + U32 lenEncrypted = xorCipher.encrypt((U8 *) str, str_len, encrypted, str_len); + ensure("Encryption failed", (lenEncrypted == str_len)); + U32 lenDecrypted = xorCipher1.decrypt(encrypted, str_len, decrypted, str_len); + ensure("Decryption failed", (lenDecrypted == str_len)); + ensure_memory_matches("LLXORCipher Encrypt/Decrypt failed", str, str_len, decrypted, lenDecrypted); + } + + // operator= + template<> template<> + void cipher_object_t::test<2>() + { + const U8 pad[] = "ABCDEFGHIJKLMNOPQ"; // pad len longer than data to be ciphered + const U32 pad_len = sizeof(pad); + const U8 pad1[] = "SecondLife"; + const U32 pad_len1 = sizeof(pad1); + const char str[] = "To Be Ciphered"; + const S32 str_len = sizeof(str); + U8 encrypted[str_len]; + U8 decrypted[str_len]; + + LLXORCipher xorCipher(pad, pad_len); + LLXORCipher xorCipher1(pad1, pad_len1); + + xorCipher.encrypt((U8 *) str, str_len, encrypted, str_len); + // make xorCipher1 same as xorCipher..so that xorCipher1 can decrypt what was + // encrypted using xorCipher + xorCipher1 = xorCipher; + U32 lenDecrypted = xorCipher1.decrypt(encrypted, str_len, decrypted, str_len); + ensure_memory_matches("LLXORCipher operator= failed", str, str_len, decrypted, lenDecrypted); + } + + //in place encrypt->decrypt + template<> template<> + void cipher_object_t::test<3>() + { + U32 padNum = 0x12349087; + const U8* pad = (U8*) &padNum; + const U32 pad_len = sizeof(U32); + char str[] = "To Be Ciphered a long string.........!!!."; + char str1[] = "To Be Ciphered a long string.........!!!."; // same as str + const S32 str_len = sizeof(str); + + LLXORCipher xorCipher(pad, pad_len); + LLXORCipher xorCipher1(pad, pad_len); + xorCipher.encrypt((U8 *) str, str_len); + // it should not be the same as original data! + ensure("LLXORCipher: In Place encrypt failed", memcmp(str, str1, str_len) != 0); + xorCipher1.decrypt((U8 *) str, str_len); + // it should not be the same as original data! + ensure_memory_matches("LLXORCipher: In Place decrypt failed", str, str_len, str1, str_len); + } + + //LLNullCipher encrypt->decrypt + template<> template<> + void cipher_object_t::test<4>() + { + const char str[] = "SecondLife"; + const S32 str_len = sizeof(str); + U8 encrypted[str_len]; + U8 decrypted[str_len]; + LLNullCipher nullCipher; + LLNullCipher nullCipher1; + + U32 length = nullCipher.requiredEncryptionSpace(50); + ensure("LLNullCipher::requiredEncryptionSpace() function failed", (length == 50)); + + U32 len1 = nullCipher.encrypt((U8 *) str, str_len, encrypted, str_len); + ensure_memory_matches("LLNullCipher - Source transformed during encryption.", encrypted, len1, str, str_len); + + U32 len2 = nullCipher1.decrypt(encrypted, str_len, decrypted, str_len); + ensure_memory_matches("LLNullCipher - Decryption failed", decrypted, len2, str, str_len); + } +} diff --git a/indra/llmessage/tests/message_test.cpp b/indra/llmessage/tests/message_test.cpp new file mode 100644 index 0000000000..11cd710ef6 --- /dev/null +++ b/indra/llmessage/tests/message_test.cpp @@ -0,0 +1,147 @@ +/** + * @file lldatapacker_tut.cpp + * @date 2007-04 + * @brief LLDataPacker test cases. + * + * $LicenseInfo:firstyear=2007&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2010, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +#include +#include "linden_common.h" +#include "lltut.h" +#include "llhttpconstants.h" +#include "llapr.h" +#include "llmessageconfig.h" +#include "llsdserialize.h" +#include "message.h" +#include "message_prehash.h" + +namespace +{ + struct Response : public LLHTTPNode::Response + { + virtual void result(const LLSD&) {} + virtual void status(S32 code, const std::string& message) + { + mStatus = code; + } + virtual void extendedResult(S32 code, const std::string& message, const LLSD& headers) { } + virtual void extendedResult(S32 code, const LLSD& result, const LLSD& headers) { } + S32 mStatus; + }; +} + +namespace tut +{ + struct LLMessageSystemTestData + { + std::string mTestConfigDir; + std::string mSep; + + LLMessageSystemTestData() + { + static bool init = false; + if(!init) + { + ll_init_apr(); + //init_prehash_data(); + init = true; + } + const F32 circuit_heartbeat_interval=5; + const F32 circuit_timeout=100; + + + // currently test disconnected message system + start_messaging_system("notafile", 13035, + 1, + 0, + 0, + false, + "notasharedsecret", + NULL, + false, + circuit_heartbeat_interval, + circuit_timeout + ); + // generate temp dir + std::ostringstream ostr; +#if LL_WINDOWS + mSep = "\\"; + ostr << "C:" << mSep; +#else + mSep = "/"; + ostr << mSep << "tmp" << mSep; +#endif + LLUUID random; + random.generate(); + ostr << "message-test-" << random; + mTestConfigDir = ostr.str(); + LLFile::mkdir(mTestConfigDir); + writeConfigFile(LLSD()); + LLMessageConfig::initClass("simulator", ostr.str()); + } + + ~LLMessageSystemTestData() + { + // not end_messaging_system() + delete static_cast(gMessageSystem); + gMessageSystem = NULL; + + // rm contents of temp dir + std::ostringstream ostr; + ostr << mTestConfigDir << mSep << "message.xml"; + int rmfile = LLFile::remove(ostr.str()); + ensure_equals("rmfile value", rmfile, 0); + + // rm temp dir + int rmdir = LLFile::rmdir(mTestConfigDir); + ensure_equals("rmdir value", rmdir, 0); + } + + void writeConfigFile(const LLSD& config) + { + std::string ostr(mTestConfigDir + mSep + "message.xml"); + llofstream file(ostr.c_str()); + if (file.is_open()) + { + LLSDSerialize::toPrettyXML(config, file); + } + file.close(); + } + }; + + typedef test_group LLMessageSystemTestGroup; + typedef LLMessageSystemTestGroup::object LLMessageSystemTestObject; + LLMessageSystemTestGroup messageTestGroup("LLMessageSystem"); + + template<> template<> + void LLMessageSystemTestObject::test<1>() + // dispatch unknown message + { + const char* name = "notamessasge"; + const LLSD message; + const LLPointer response = new Response(); + gMessageSystem->dispatch(name, message, response); + ensure_equals(response->mStatus, HTTP_NOT_FOUND); + } +} + diff --git a/indra/llprimitive/llprimlinkinfo.h b/indra/llprimitive/llprimlinkinfo.h deleted file mode 100644 index 67e40fd5be..0000000000 --- a/indra/llprimitive/llprimlinkinfo.h +++ /dev/null @@ -1,393 +0,0 @@ -/** - * @file llprimlinkinfo.h - * @author andrew@lindenlab.com - * @brief A template for determining which prims in a set are linkable - * - * $LicenseInfo:firstyear=2007&license=viewerlgpl$ - * Second Life Viewer Source Code - * Copyright (C) 2010, Linden Research, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; - * version 2.1 of the License only. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA - * $/LicenseInfo$ - */ - - -#ifndef LL_PRIM_LINK_INFO_H -#define LL_PRIM_LINK_INFO_H - -// system includes -#include -#include -#include -#include - -// common includes -#include "stdtypes.h" -#include "v3math.h" -#include "llquaternion.h" -#include "llsphere.h" - - -const F32 MAX_OBJECT_SPAN = 54.f; // max distance from outside edge of an object to the farthest edge -const F32 OBJECT_SPAN_BONUS = 2.f; // infinitesimally small prims can always link up to this distance -const S32 MAX_PRIMS_PER_OBJECT = 256; - - -template < typename DATA_TYPE > -class LLPrimLinkInfo -{ -public: - LLPrimLinkInfo(); - LLPrimLinkInfo( DATA_TYPE data, const LLSphere& sphere ); - ~LLPrimLinkInfo(); - - void set( DATA_TYPE data, const LLSphere& sphere ); - void append( DATA_TYPE data, const LLSphere& sphere ); - void getData( std::list< DATA_TYPE >& data_list ) const; - F32 getDiameter() const; - LLVector3 getCenter() const; - - // returns 'true' if this info can link with other_info - bool canLink( const LLPrimLinkInfo< DATA_TYPE >& other_info ); - - S32 getPrimCount() const { return mDataMap.size(); } - - void mergeLinkableSet( typename std::list< LLPrimLinkInfo < DATA_TYPE > >& unlinked ); - - void transform(const LLVector3& position, const LLQuaternion& rotation); - -private: - // returns number of merges made - S32 merge(LLPrimLinkInfo< DATA_TYPE >& other_info); - - // returns number of collapses made - static S32 collapse(typename std::list< LLPrimLinkInfo < DATA_TYPE > >& unlinked ); - - void computeBoundingSphere(); - - // Internal utility to encapsulate the link rules - F32 get_max_linkable_span(const LLSphere& first, const LLSphere& second); - F32 get_span(const LLSphere& first, const LLSphere& second); - -private: - std::map< DATA_TYPE, LLSphere > mDataMap; - LLSphere mBoundingSphere; -}; - - - -template < typename DATA_TYPE > -LLPrimLinkInfo< DATA_TYPE >::LLPrimLinkInfo() -: mBoundingSphere( LLVector3(0.f, 0.f, 0.f), 0.f ) -{ -} - -template < typename DATA_TYPE > -LLPrimLinkInfo< DATA_TYPE >::LLPrimLinkInfo( DATA_TYPE data, const LLSphere& sphere) -: mBoundingSphere(sphere) -{ - mDataMap[data] = sphere; -} - -template < typename DATA_TYPE > -LLPrimLinkInfo< DATA_TYPE >::~LLPrimLinkInfo() -{ - mDataMap.clear(); -} - -template < typename DATA_TYPE > -void LLPrimLinkInfo< DATA_TYPE>::set( DATA_TYPE data, const LLSphere& sphere ) -{ - if (!mDataMap.empty()) - { - mDataMap.clear(); - } - mDataMap[data] = sphere; - mBoundingSphere = sphere; -} - -template < typename DATA_TYPE > -void LLPrimLinkInfo< DATA_TYPE>::append( DATA_TYPE data, const LLSphere& sphere ) -{ - mDataMap[data] = sphere; - if (!mBoundingSphere.contains(sphere)) - { - computeBoundingSphere(); - } -} - -template < typename DATA_TYPE > -void LLPrimLinkInfo< DATA_TYPE >::getData( std::list< DATA_TYPE >& data_list) const -{ - typename std::map< DATA_TYPE, LLSphere >::const_iterator map_itr; - for (map_itr = mDataMap.begin(); map_itr != mDataMap.end(); ++map_itr) - { - data_list.push_back(map_itr->first); - } -} - -template < typename DATA_TYPE > -F32 LLPrimLinkInfo< DATA_TYPE >::getDiameter() const -{ - return 2.f * mBoundingSphere.getRadius(); -} - -template < typename DATA_TYPE > -LLVector3 LLPrimLinkInfo< DATA_TYPE >::getCenter() const -{ - return mBoundingSphere.getCenter(); -} - -template < typename DATA_TYPE > -F32 LLPrimLinkInfo< DATA_TYPE >::get_max_linkable_span(const LLSphere& first, const LLSphere& second) -{ - F32 max_span = 3.f * (first.getRadius() + second.getRadius()) + OBJECT_SPAN_BONUS; - if (max_span > MAX_OBJECT_SPAN) - { - max_span = MAX_OBJECT_SPAN; - } - - return max_span; -} - -template < typename DATA_TYPE > -F32 LLPrimLinkInfo< DATA_TYPE >::get_span(const LLSphere& first, const LLSphere& second) -{ - F32 span = (first.getCenter() - second.getCenter()).length() - + first.getRadius() + second.getRadius(); - return span; -} - -// static -// returns 'true' if this info can link with any part of other_info -template < typename DATA_TYPE > -bool LLPrimLinkInfo< DATA_TYPE >::canLink(const LLPrimLinkInfo& other_info) -{ - F32 max_span = get_max_linkable_span(mBoundingSphere, other_info.mBoundingSphere); - - F32 span = get_span(mBoundingSphere, other_info.mBoundingSphere); - - if (span <= max_span) - { - // The entire other_info fits inside the max span. - return TRUE; - } - else if (span > max_span + 2.f * other_info.mBoundingSphere.getRadius()) - { - // there is no way any piece of other_info could link with this one - return FALSE; - } - - // there may be a piece of other_info that is linkable - typename std::map< DATA_TYPE, LLSphere >::const_iterator map_itr; - for (map_itr = other_info.mDataMap.begin(); map_itr != other_info.mDataMap.end(); ++map_itr) - { - const LLSphere& other_sphere = (*map_itr).second; - max_span = get_max_linkable_span(mBoundingSphere, other_sphere); - - span = get_span(mBoundingSphere, other_sphere); - - if (span <= max_span) - { - // found one piece that is linkable - return TRUE; - } - } - return FALSE; -} - -// merges elements of 'unlinked' -// returns number of links made (NOT final prim count, NOR linked prim count) -// and removes any linkable infos from 'unlinked' -template < typename DATA_TYPE > -void LLPrimLinkInfo< DATA_TYPE >::mergeLinkableSet(std::list< LLPrimLinkInfo< DATA_TYPE > > & unlinked) -{ - bool linked_something = true; - while (linked_something) - { - linked_something = false; - - typename std::list< LLPrimLinkInfo< DATA_TYPE > >::iterator other_itr = unlinked.begin(); - while ( other_itr != unlinked.end() - && getPrimCount() < MAX_PRIMS_PER_OBJECT ) - { - S32 merge_count = merge(*other_itr); - if (merge_count > 0) - { - linked_something = true; - } - if (0 == (*other_itr).getPrimCount()) - { - unlinked.erase(other_itr++); - } - else - { - ++other_itr; - } - } - if (!linked_something - && unlinked.size() > 1) - { - S32 collapse_count = collapse(unlinked); - if (collapse_count > 0) - { - linked_something = true; - } - } - } -} - -// transforms all of the spheres into a new reference frame -template < typename DATA_TYPE > -void LLPrimLinkInfo< DATA_TYPE >::transform(const LLVector3& position, const LLQuaternion& rotation) -{ - typename std::map< DATA_TYPE, LLSphere >::iterator map_itr; - for (map_itr = mDataMap.begin(); map_itr != mDataMap.end(); ++map_itr) - { - (*map_itr).second.setCenter((*map_itr).second.getCenter() * rotation + position); - } - mBoundingSphere.setCenter(mBoundingSphere.getCenter() * rotation + position); -} - -// private -// returns number of links made -template < typename DATA_TYPE > -S32 LLPrimLinkInfo< DATA_TYPE >::merge(LLPrimLinkInfo& other_info) -{ - S32 link_count = 0; - -// F32 other_radius = other_info.mBoundingSphere.getRadius(); -// other_info.computeBoundingSphere(); -// if ( other_radius != other_info.mBoundingSphere.getRadius() ) -// { -// LL_INFOS() << "Other bounding sphere changed!!" << LL_ENDL; -// } - -// F32 this_radius = mBoundingSphere.getRadius(); -// computeBoundingSphere(); -// if ( this_radius != mBoundingSphere.getRadius() ) -// { -// LL_INFOS() << "This bounding sphere changed!!" << LL_ENDL; -// } - - - F32 max_span = get_max_linkable_span(mBoundingSphere, other_info.mBoundingSphere); - - // F32 center_dist = (mBoundingSphere.getCenter() - other_info.mBoundingSphere.getCenter()).length(); - // LL_INFOS() << "objects are " << center_dist << "m apart" << LL_ENDL; - F32 span = get_span(mBoundingSphere, other_info.mBoundingSphere); - - F32 span_limit = max_span + (2.f * other_info.mBoundingSphere.getRadius()); - if (span > span_limit) - { - // there is no way any piece of other_info could link with this one - // LL_INFOS() << "span too large: " << span << " vs. " << span_limit << LL_ENDL; - return 0; - } - - bool completely_linkable = (span <= max_span) ? true : false; - - typename std::map< DATA_TYPE, LLSphere >::iterator map_itr = other_info.mDataMap.begin(); - while (map_itr != other_info.mDataMap.end() - && getPrimCount() < MAX_PRIMS_PER_OBJECT ) - { - DATA_TYPE other_data = (*map_itr).first; - LLSphere& other_sphere = (*map_itr).second; - - if (!completely_linkable) - { - max_span = get_max_linkable_span(mBoundingSphere, other_sphere); - - F32 span = get_span(mBoundingSphere, other_sphere); - - if (span > max_span) - { - ++map_itr; - continue; - } - } - - mDataMap[other_data] = other_sphere; - ++link_count; - - if (!mBoundingSphere.contains(other_sphere) ) - { - computeBoundingSphere(); - } - - // remove from the other info - other_info.mDataMap.erase(map_itr++); - } - - if (link_count > 0 && other_info.getPrimCount() > 0) - { - other_info.computeBoundingSphere(); - } - return link_count; -} - -// links any linkable elements of unlinked -template < typename DATA_TYPE > -S32 LLPrimLinkInfo< DATA_TYPE >::collapse(std::list< LLPrimLinkInfo< DATA_TYPE > > & unlinked) -{ - S32 link_count = 0; - bool linked_something = true; - while (linked_something) - { - linked_something = false; - - typename std::list< LLPrimLinkInfo< DATA_TYPE > >::iterator this_itr = unlinked.begin(); - typename std::list< LLPrimLinkInfo< DATA_TYPE > >::iterator other_itr = this_itr; - ++other_itr; - while ( other_itr != unlinked.end() ) - - { - S32 merge_count = (*this_itr).merge(*other_itr); - if (merge_count > 0) - { - linked_something = true; - link_count += merge_count; - } - if (0 == (*other_itr).getPrimCount()) - { - unlinked.erase(other_itr++); - } - else - { - ++other_itr; - } - } - } - return link_count; -} - - -template < typename DATA_TYPE > -void LLPrimLinkInfo< DATA_TYPE >::computeBoundingSphere() -{ - std::vector< LLSphere > sphere_list; - typename std::map< DATA_TYPE, LLSphere >::const_iterator map_itr; - for (map_itr = mDataMap.begin(); map_itr != mDataMap.end(); ++map_itr) - { - sphere_list.push_back(map_itr->second); - } - mBoundingSphere = LLSphere::getBoundingSphere(sphere_list); -} - - -#endif - diff --git a/indra/test/CMakeLists.txt b/indra/test/CMakeLists.txt index 87b4e5e454..c1e63a7470 100644 --- a/indra/test/CMakeLists.txt +++ b/indra/test/CMakeLists.txt @@ -17,128 +17,34 @@ set(test_lib_SOURCE_FILES set(test_lib_HEADER_FILES CMakeLists.txt - lltut.h - ) - -list(APPEND test_lib_SOURCE_FILES ${test_lib_HEADER_FILES}) - -add_library(lltut_runner_lib ${test_lib_SOURCE_FILES}) - -target_link_libraries(lltut_runner_lib PRIVATE llcommon) - -set_target_properties(lltut_runner_lib - PROPERTIES - FOLDER "Tests" - ) - -set(test_SOURCE_FILES - io.cpp - llapp_tut.cpp - llbuffer_tut.cpp - lldoubledispatch_tut.cpp - llevents_tut.cpp - llhttpdate_tut.cpp - llhttpnode_tut.cpp - lliohttpserver_tut.cpp - llmessageconfig_tut.cpp - llpermissions_tut.cpp - llpipeutil.cpp - llsaleinfo_tut.cpp - llsdmessagebuilder_tut.cpp - llsdmessagereader_tut.cpp - llsd_new_tut.cpp - llsdutil_tut.cpp - llservicebuilder_tut.cpp - llstreamtools_tut.cpp - lltemplatemessagebuilder_tut.cpp - message_tut.cpp - ) - -set(test_HEADER_FILES - CMakeLists.txt + catch_and_store_what_in.h + chained_callback.h debug.h - llpipeutil.h llsdtraits.h + lltestapp.h lltut.h + namedtempfile.h + print.h + setenv.h sync.h + test.h ) -if (NOT WINDOWS) - list(APPEND test_SOURCE_FILES - llmessagetemplateparser_tut.cpp - ) -endif (NOT WINDOWS) - -list(APPEND test_SOURCE_FILES ${test_HEADER_FILES}) +list(APPEND test_lib_SOURCE_FILES ${test_lib_HEADER_FILES}) -add_executable(lltest ${test_SOURCE_FILES}) +add_library(lltut_runner_lib ${test_lib_SOURCE_FILES}) -target_link_libraries(lltest - lltut_runner_lib - llinventory - llmessage - llmath - llfilesystem - llxml - llcommon - llcorehttp - ) +target_link_libraries(lltut_runner_lib PRIVATE llcommon) -set_target_properties(lltest +set_target_properties(lltut_runner_lib PROPERTIES FOLDER "Tests" ) -if (WINDOWS) - set_target_properties(lltest - PROPERTIES - LINK_FLAGS "/NODEFAULTLIB:LIBCMT" - LINK_FLAGS_DEBUG "/NODEFAULTLIB:\"LIBCMT;LIBCMTD;MSVCRT\"" - RUNTIME_OUTPUT_DIRECTORY "${EXE_STAGING_DIR}" - ) -elseif (DARWIN) +if (DARWIN) set_target_properties(lltut_runner_lib PROPERTIES OSX_ARCHITECTURES ${LL_MACOS_TEST_ARCHITECTURE} ) - set_target_properties(lltest - PROPERTIES - OSX_ARCHITECTURES ${LL_MACOS_TEST_ARCHITECTURE} - ) - # Support our "@executable_path/../Resources" load path for our test - # executable. This SHOULD properly be "$/Resources", - # but the CMake $ generator expression isn't evaluated by - # CREATE_LINK, so fudge it. - file(CREATE_LINK "../sharedlibs/Release/Resources" "${CMAKE_BINARY_DIR}/test/Resources" - SYMBOLIC) -endif (WINDOWS) - -# This should cause the test executable to be built, but not -# run if LL_TESTS is disabled. This will hopefully keep the -# tests up to date with any code changes changes even if -# developers choose to disable LL_TESTS. -if (LL_TESTS) - set(TEST_EXE $) - - SET_TEST_PATH(LD_LIBRARY_PATH) - - LL_TEST_COMMAND(command - "${LD_LIBRARY_PATH}" - "${TEST_EXE}" - "--output=${CMAKE_CURRENT_BINARY_DIR}/cpp_test_results.txt" - "--touch=${CMAKE_CURRENT_BINARY_DIR}/cpp_tests_ok.txt") - - add_test(NAME "C++ unit tests" COMMAND ${command} WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}) - - add_dependencies(BUILD_TESTS lltest) - if(DARWIN) - # Support our "@executable_path/../Resources" load path for our test - # executable. This SHOULD properly be "$/Resources", - # but the CMake $ generator expression isn't evaluated by - # CREATE_LINK, so fudge it. - add_custom_command( TARGET lltest POST_BUILD - COMMAND ${CMAKE_COMMAND} -E create_symlink ${SHARED_LIB_STAGING_DIR} ${CMAKE_BINARY_DIR}/test/Resources - ) - endif() -endif (LL_TESTS) +endif () diff --git a/indra/test/hexdump.h b/indra/test/hexdump.h deleted file mode 100644 index 95f1e297c3..0000000000 --- a/indra/test/hexdump.h +++ /dev/null @@ -1,97 +0,0 @@ -/** - * @file hexdump.h - * @author Nat Goodspeed - * @date 2023-09-08 - * @brief Provide hexdump() and hexmix() ostream formatters - * - * $LicenseInfo:firstyear=2023&license=viewerlgpl$ - * Copyright (c) 2023, Linden Research, Inc. - * $/LicenseInfo$ - */ - -#if ! defined(LL_HEXDUMP_H) -#define LL_HEXDUMP_H - -#include -#include -#include -#include - -// Format a given byte string as 2-digit hex values, no separators -// Usage: std::cout << hexdump(somestring) << ... -class hexdump -{ -public: - hexdump(const std::string_view& data): - hexdump(data.data(), data.length()) - {} - - hexdump(const char* data, size_t len): - hexdump(reinterpret_cast(data), len) - {} - - hexdump(const unsigned char* data, size_t len): - mData(data, data + len) - {} - - friend std::ostream& operator<<(std::ostream& out, const hexdump& self) - { - auto oldfmt{ out.flags() }; - auto oldfill{ out.fill() }; - out.setf(std::ios_base::hex, std::ios_base::basefield); - out.fill('0'); - for (auto c : self.mData) - { - out << std::setw(2) << unsigned(c); - } - out.setf(oldfmt, std::ios_base::basefield); - out.fill(oldfill); - return out; - } - -private: - std::vector mData; -}; - -// Format a given byte string as a mix of printable characters and, for each -// non-printable character, "\xnn" -// Usage: std::cout << hexmix(somestring) << ... -class hexmix -{ -public: - hexmix(const std::string_view& data): - mData(data) - {} - - hexmix(const char* data, size_t len): - mData(data, len) - {} - - friend std::ostream& operator<<(std::ostream& out, const hexmix& self) - { - auto oldfmt{ out.flags() }; - auto oldfill{ out.fill() }; - out.setf(std::ios_base::hex, std::ios_base::basefield); - out.fill('0'); - for (auto c : self.mData) - { - // std::isprint() must be passed an unsigned char! - if (std::isprint(static_cast(c))) - { - out << c; - } - else - { - out << "\\x" << std::setw(2) << unsigned(c); - } - } - out.setf(oldfmt, std::ios_base::basefield); - out.fill(oldfill); - return out; - } - -private: - std::string mData; -}; - -#endif /* ! defined(LL_HEXDUMP_H) */ diff --git a/indra/test/io.cpp b/indra/test/io.cpp deleted file mode 100644 index f77402065a..0000000000 --- a/indra/test/io.cpp +++ /dev/null @@ -1,1181 +0,0 @@ -/** - * @file io.cpp - * @author Phoenix - * @date 2005-10-02 - * @brief Tests for io classes and helpers - * - * $LicenseInfo:firstyear=2005&license=viewerlgpl$ - * Second Life Viewer Source Code - * Copyright (C) 2010, Linden Research, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; - * version 2.1 of the License only. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA - * $/LicenseInfo$ - */ - -#include "linden_common.h" -#include "lltut.h" - -#include - -#include "apr_pools.h" - -#include "llbuffer.h" -#include "llbufferstream.h" -#include "lliosocket.h" -#include "llioutil.h" -#include "llmemorystream.h" -#include "llpipeutil.h" -#include "llpumpio.h" -#include "llsd.h" -#include "llsdserialize.h" -#include "llcommon.h" -#include "lluuid.h" -#include "llinstantmessage.h" - -namespace tut -{ - struct heap_buffer_data - { - heap_buffer_data() : mBuffer(NULL) {} - ~heap_buffer_data() { if(mBuffer) delete mBuffer; } - LLHeapBuffer* mBuffer; - }; - typedef test_group heap_buffer_test; - typedef heap_buffer_test::object heap_buffer_object; - tut::heap_buffer_test thb("heap_buffer"); - - template<> template<> - void heap_buffer_object::test<1>() - { - const S32 BUF_SIZE = 100; - mBuffer = new LLHeapBuffer(BUF_SIZE); - ensure_equals("empty buffer capacity", mBuffer->capacity(), BUF_SIZE); - const S32 SEGMENT_SIZE = 50; - LLSegment segment; - mBuffer->createSegment(0, SEGMENT_SIZE, segment); - ensure_equals("used buffer capacity", mBuffer->capacity(), BUF_SIZE); - } - - template<> template<> - void heap_buffer_object::test<2>() - { - const S32 BUF_SIZE = 10; - mBuffer = new LLHeapBuffer(BUF_SIZE); - LLSegment segment; - mBuffer->createSegment(0, BUF_SIZE, segment); - ensure("segment is in buffer", mBuffer->containsSegment(segment)); - ensure_equals("buffer consumed", mBuffer->bytesLeft(), 0); - bool created; - created = mBuffer->createSegment(0, 0, segment); - ensure("Create zero size segment fails", !created); - created = mBuffer->createSegment(0, BUF_SIZE, segment); - ensure("Create segment fails", !created); - } - - template<> template<> - void heap_buffer_object::test<3>() - { - const S32 BUF_SIZE = 10; - mBuffer = new LLHeapBuffer(BUF_SIZE); - LLSegment segment; - mBuffer->createSegment(0, BUF_SIZE, segment); - ensure("segment is in buffer", mBuffer->containsSegment(segment)); - ensure_equals("buffer consumed", mBuffer->bytesLeft(), 0); - bool reclaimed = mBuffer->reclaimSegment(segment); - ensure("buffer reclaimed.", reclaimed); - ensure_equals("buffer available", mBuffer->bytesLeft(), BUF_SIZE); - bool created; - created = mBuffer->createSegment(0, 0, segment); - ensure("Create zero size segment fails", !created); - created = mBuffer->createSegment(0, BUF_SIZE, segment); - ensure("Create another segment succeeds", created); - } - - template<> template<> - void heap_buffer_object::test<4>() - { - const S32 BUF_SIZE = 10; - const S32 SEGMENT_SIZE = 4; - mBuffer = new LLHeapBuffer(BUF_SIZE); - LLSegment seg1; - mBuffer->createSegment(0, SEGMENT_SIZE, seg1); - ensure("segment is in buffer", mBuffer->containsSegment(seg1)); - LLSegment seg2; - mBuffer->createSegment(0, SEGMENT_SIZE, seg2); - ensure("segment is in buffer", mBuffer->containsSegment(seg2)); - LLSegment seg3; - mBuffer->createSegment(0, SEGMENT_SIZE, seg3); - ensure("segment is in buffer", mBuffer->containsSegment(seg3)); - ensure_equals("segment is truncated", seg3.size(), 2); - LLSegment seg4; - bool created; - created = mBuffer->createSegment(0, SEGMENT_SIZE, seg4); - ensure("Create segment fails", !created); - bool reclaimed; - reclaimed = mBuffer->reclaimSegment(seg1); - ensure("buffer reclaim succeed.", reclaimed); - ensure_equals("no buffer available", mBuffer->bytesLeft(), 0); - reclaimed = mBuffer->reclaimSegment(seg2); - ensure("buffer reclaim succeed.", reclaimed); - ensure_equals("buffer reclaimed", mBuffer->bytesLeft(), 0); - reclaimed = mBuffer->reclaimSegment(seg3); - ensure("buffer reclaim succeed.", reclaimed); - ensure_equals("buffer reclaimed", mBuffer->bytesLeft(), BUF_SIZE); - created = mBuffer->createSegment(0, SEGMENT_SIZE, seg1); - ensure("segment is in buffer", mBuffer->containsSegment(seg1)); - ensure("Create segment succeds", created); - } -} - -namespace tut -{ - struct buffer_data - { - LLBufferArray mBuffer; - }; - typedef test_group buffer_test; - typedef buffer_test::object buffer_object; - tut::buffer_test tba("buffer_array"); - - template<> template<> - void buffer_object::test<1>() - { - const char HELLO_WORLD[] = "hello world"; - const S32 str_len = static_cast(strlen(HELLO_WORLD)); - LLChannelDescriptors ch = mBuffer.nextChannel(); - mBuffer.append(ch.in(), (U8*)HELLO_WORLD, str_len); - S32 count = mBuffer.countAfter(ch.in(), NULL); - ensure_equals("total append size", count, str_len); - LLBufferArray::segment_iterator_t it = mBuffer.beginSegment(); - U8* first = (*it).data(); - count = mBuffer.countAfter(ch.in(), first); - ensure_equals("offset append size", count, str_len - 1); - } - - template<> template<> - void buffer_object::test<2>() - { - const char HELLO_WORLD[] = "hello world"; - const S32 str_len = static_cast(strlen(HELLO_WORLD)); /* Flawfinder: ignore */ - LLChannelDescriptors ch = mBuffer.nextChannel(); - mBuffer.append(ch.in(), (U8*)HELLO_WORLD, str_len); - mBuffer.append(ch.in(), (U8*)HELLO_WORLD, str_len); - S32 count = mBuffer.countAfter(ch.in(), NULL); - ensure_equals("total append size", count, 2 * str_len); - LLBufferArray::segment_iterator_t it = mBuffer.beginSegment(); - U8* first = (*it).data(); - count = mBuffer.countAfter(ch.in(), first); - ensure_equals("offset append size", count, (2 * str_len) - 1); - } - - template<> template<> - void buffer_object::test<3>() - { - const char ONE[] = "one"; - const char TWO[] = "two"; - std::string expected(ONE); - expected.append(TWO); - LLChannelDescriptors ch = mBuffer.nextChannel(); - mBuffer.append(ch.in(), (U8*)ONE, 3); - mBuffer.append(ch.in(), (U8*)TWO, 3); - char buffer[255]; /* Flawfinder: ignore */ - S32 len = 6; - mBuffer.readAfter(ch.in(), NULL, (U8*)buffer, len); - ensure_equals(len, 6); - buffer[len] = '\0'; - std::string actual(buffer); - ensure_equals("read", actual, expected); - } - - template<> template<> - void buffer_object::test<4>() - { - const char ONE[] = "one"; - const char TWO[] = "two"; - std::string expected(ONE); - expected.append(TWO); - LLChannelDescriptors ch = mBuffer.nextChannel(); - mBuffer.append(ch.in(), (U8*)TWO, 3); - mBuffer.prepend(ch.in(), (U8*)ONE, 3); - char buffer[255]; /* Flawfinder: ignore */ - S32 len = 6; - mBuffer.readAfter(ch.in(), NULL, (U8*)buffer, len); - ensure_equals(len, 6); - buffer[len] = '\0'; - std::string actual(buffer); - ensure_equals("read", actual, expected); - } - - template<> template<> - void buffer_object::test<5>() - { - const char ONE[] = "one"; - const char TWO[] = "two"; - std::string expected("netwo"); - LLChannelDescriptors ch = mBuffer.nextChannel(); - mBuffer.append(ch.in(), (U8*)TWO, 3); - mBuffer.prepend(ch.in(), (U8*)ONE, 3); - char buffer[255]; /* Flawfinder: ignore */ - S32 len = 5; - LLBufferArray::segment_iterator_t it = mBuffer.beginSegment(); - U8* addr = (*it).data(); - mBuffer.readAfter(ch.in(), addr, (U8*)buffer, len); - ensure_equals(len, 5); - buffer[len] = '\0'; - std::string actual(buffer); - ensure_equals("read", actual, expected); - } - - template<> template<> - void buffer_object::test<6>() - { - std::string request("The early bird catches the worm."); - std::string response("If you're a worm, sleep late."); - std::ostringstream expected; - expected << "ContentLength: " << response.length() << "\r\n\r\n" - << response; - LLChannelDescriptors ch = mBuffer.nextChannel(); - mBuffer.append(ch.in(), (U8*)request.c_str(), static_cast(request.length())); - mBuffer.append(ch.out(), (U8*)response.c_str(), static_cast(response.length())); - S32 count = mBuffer.countAfter(ch.out(), NULL); - std::ostringstream header; - header << "ContentLength: " << count << "\r\n\r\n"; - std::string head(header.str()); - mBuffer.prepend(ch.out(), (U8*)head.c_str(), static_cast(head.length())); - char buffer[1024]; /* Flawfinder: ignore */ - S32 len = static_cast(response.size() + head.length()); - ensure_equals("same length", len, (S32)expected.str().length()); - mBuffer.readAfter(ch.out(), NULL, (U8*)buffer, len); - buffer[len] = '\0'; - std::string actual(buffer); - ensure_equals("threaded writes", actual, expected.str()); - } - - template<> template<> - void buffer_object::test<7>() - { - const S32 LINE_COUNT = 3; - std::string lines[LINE_COUNT] = - { - std::string("GET /index.htm HTTP/1.0\r\n"), - std::string("User-Agent: Wget/1.9.1\r\n"), - std::string("Host: localhost:8008\r\n") - }; - std::string text; - S32 i; - for(i = 0; i < LINE_COUNT; ++i) - { - text.append(lines[i]); - } - LLChannelDescriptors ch = mBuffer.nextChannel(); - mBuffer.append(ch.in(), (U8*)text.c_str(), static_cast(text.length())); - const S32 BUFFER_LEN = 1024; - char buf[BUFFER_LEN]; - S32 len; - U8* last = NULL; - std::string last_line; - for(i = 0; i < LINE_COUNT; ++i) - { - len = BUFFER_LEN; - last = mBuffer.readAfter(ch.in(), last, (U8*)buf, len); - char* newline = strchr((char*)buf, '\n'); - S32 offset = -((len - 1) - (S32)(newline - buf)); - ++newline; - *newline = '\0'; - last_line.assign(buf); - std::ostringstream message; - message << "line reads in line[" << i << "]"; - ensure_equals(message.str().c_str(), last_line, lines[i]); - last = mBuffer.seek(ch.in(), last, offset); - } - } - - template<> template<> - void buffer_object::test<8>() - { - LLChannelDescriptors ch = mBuffer.nextChannel(); - mBuffer.append(ch.in(), (U8*)"1", 1); - LLBufferArray buffer; - buffer.append(ch.in(), (U8*)"2", 1); - mBuffer.takeContents(buffer); - mBuffer.append(ch.in(), (U8*)"3", 1); - S32 count = mBuffer.countAfter(ch.in(), NULL); - ensure_equals("buffer size", count, 3); - U8* temp = new U8[count]; - mBuffer.readAfter(ch.in(), NULL, temp, count); - ensure("buffer content", (0 == memcmp(temp, (void*)"123", 3))); - delete[] temp; - } - - template<> template<> - void buffer_object::test<9>() - { - LLChannelDescriptors ch = mBuffer.nextChannel(); - mBuffer.append(ch.in(), (U8*)"1", 1); - S32 capacity = mBuffer.capacity(); - ensure("has capacity", capacity > 0); - U8* temp = new U8[capacity - 1]; - mBuffer.append(ch.in(), temp, capacity - 1); - capacity = mBuffer.capacity(); - ensure("has capacity when full", capacity > 0); - S32 used = mBuffer.countAfter(ch.in(), NULL); - ensure_equals("used equals capacity", used, capacity); - - LLBufferArray::segment_iterator_t iter = mBuffer.beginSegment(); - while(iter != mBuffer.endSegment()) - { - mBuffer.eraseSegment(iter++); - } - - used = mBuffer.countAfter(ch.in(), NULL); - ensure_equals("used is zero", used, 0); - S32 capacity2 = mBuffer.capacity(); - ensure_equals("capacity the same after erase", capacity2, capacity); - mBuffer.append(ch.in(), temp, capacity - 1); - capacity2 = mBuffer.capacity(); - ensure_equals("capacity the same after append", capacity2, capacity); - - delete[] temp; - } - -#if 0 - template<> template<> - void buffer_object::test<9>() - { - char buffer[1024]; /* Flawfinder: ignore */ - S32 size = sprintf(buffer, - "%d|%d|%s|%s|%s|%s|%s|%x|%x|%x|%x|%x|%s|%s|%d|%d|%x", - 7, - 7, - "Hang Glider INFO", - "18e84d1e-04a4-4c0d-8cb6-6c73477f0a9a", - "0e346d8b-4433-4d66-a6b0-fd37083abc4c", - "0e346d8b-4433-4d66-a6b0-fd37083abc4c", - "00000000-0000-0000-0000-000000000000", - 0x7fffffff, - 0x7fffffff, - 0, - 0, - 0x7fffffff, - "69e0d357-2e7c-8990-a2bc-7f61c868e5a3", - "2004-06-04 16:09:17 note card", - 0, - 10, - 0) + 1; - - //const char* expected = "7|7|Hang Glider INFO|18e84d1e-04a4-4c0d-8cb6-6c73477f0a9a|0e346d8b-4433-4d66-a6b0-fd37083abc4c|0e346d8b-4433-4d66-a6b0-fd37083abc4c|00000000-0000-0000-0000-000000000000|7fffffff|7fffffff|0|0|7fffffff|69e0d357-2e7c-8990-a2bc-7f61c868e5a3|2004-06-04 16:09:17 note card|0|10|0\0"; - - LLSD* bin_bucket = LLIMInfo::buildSDfrombuffer((U8*)buffer,size); - - char post_buffer[1024]; - U32 post_size; - LLIMInfo::getBinaryBucket(bin_bucket,(U8*)post_buffer,post_size); - ensure_equals("Buffer sizes",size,(S32)post_size); - ensure("Buffer content",!strcmp(buffer,post_buffer)); - } -#endif - - /* - template<> template<> - void buffer_object::test<>() - { - } - */ -} - -namespace tut -{ - struct buffer_and_stream_data - { - LLBufferArray mBuffer; - }; - typedef test_group bas_test; - typedef bas_test::object bas_object; - tut::bas_test tbs("buffer_stream"); - - template<> template<> - void bas_object::test<1>() - { - const char HELLO_WORLD[] = "hello world"; - const S32 str_len = static_cast(strlen(HELLO_WORLD)); /* Flawfinder: ignore */ - LLChannelDescriptors ch = mBuffer.nextChannel(); - LLBufferStream str(ch, &mBuffer); - mBuffer.append(ch.in(), (U8*)HELLO_WORLD, str_len); - std::string hello; - std::string world; - str >> hello >> world; - ensure_equals("first word", hello, std::string("hello")); - ensure_equals("second word", world, std::string("world")); - } - - template<> template<> - void bas_object::test<2>() - { - std::string part1("Eat my shor"); - std::string part2("ts ho"); - std::string part3("mer"); - std::string ignore("ignore me"); - LLChannelDescriptors ch = mBuffer.nextChannel(); - LLBufferStream str(ch, &mBuffer); - mBuffer.append(ch.in(), (U8*)part1.c_str(), static_cast(part1.length())); - mBuffer.append(ch.in(), (U8*)part2.c_str(), static_cast(part2.length())); - mBuffer.append(ch.out(), (U8*)ignore.c_str(), static_cast(ignore.length())); - mBuffer.append(ch.in(), (U8*)part3.c_str(), static_cast(part3.length())); - std::string eat; - std::string my; - std::string shorts; - std::string homer; - str >> eat >> my >> shorts >> homer; - ensure_equals("word1", eat, std::string("Eat")); - ensure_equals("word2", my, std::string("my")); - ensure_equals("word3", shorts, std::string("shorts")); - ensure_equals("word4", homer, std::string("homer")); - } - - template<> template<> - void bas_object::test<3>() - { - std::string part1("junk in "); - std::string part2("the trunk"); - const S32 CHANNEL = 0; - mBuffer.append(CHANNEL, (U8*)part1.c_str(), static_cast(part1.length())); - mBuffer.append(CHANNEL, (U8*)part2.c_str(), static_cast(part2.length())); - U8* last = 0; - const S32 BUF_LEN = 128; - char buf[BUF_LEN]; - S32 len = 11; - last = mBuffer.readAfter(CHANNEL, last, (U8*)buf, len); - buf[len] = '\0'; - std::string actual(buf); - ensure_equals("first read", actual, std::string("junk in the")); - last = mBuffer.seek(CHANNEL, last, -6); - len = 12; - last = mBuffer.readAfter(CHANNEL, last, (U8*)buf, len); - buf[len] = '\0'; - actual.assign(buf); - ensure_equals("seek and read", actual, std::string("in the trunk")); - } - - template<> template<> - void bas_object::test<4>() - { - std::string phrase("zippity do da!"); - const S32 CHANNEL = 0; - mBuffer.append(CHANNEL, (U8*)phrase.c_str(), static_cast(phrase.length())); - const S32 BUF_LEN = 128; - char buf[BUF_LEN]; - S32 len = 7; - U8* last = mBuffer.readAfter(CHANNEL, NULL, (U8*)buf, len); - mBuffer.splitAfter(last); - LLBufferArray::segment_iterator_t it = mBuffer.beginSegment(); - LLBufferArray::segment_iterator_t end = mBuffer.endSegment(); - std::string first((char*)((*it).data()), (*it).size()); - ensure_equals("first part", first, std::string("zippity")); - ++it; - std::string second((char*)((*it).data()), (*it).size()); - ensure_equals("second part", second, std::string(" do da!")); - ++it; - ensure("iterators equal", (it == end)); - } - - template<> template<> - void bas_object::test<5>() - { - LLChannelDescriptors ch = mBuffer.nextChannel(); - LLBufferStream str(ch, &mBuffer); - std::string h1("hello"); - std::string h2(", how are you doing?"); - std::string expected(h1); - expected.append(h2); - str << h1 << h2; - str.flush(); - const S32 BUF_LEN = 128; - char buf[BUF_LEN]; - S32 actual_len = BUF_LEN; - S32 expected_len = static_cast(h1.size() + h2.size()); - (void) mBuffer.readAfter(ch.out(), NULL, (U8*)buf, actual_len); - ensure_equals("streamed size", actual_len, expected_len); - buf[actual_len] = '\0'; - std::string actual(buf); - ensure_equals("streamed to buf", actual, expected); - } - - template<> template<> - void bas_object::test<6>() - { - LLChannelDescriptors ch = mBuffer.nextChannel(); - LLBufferStream bstr(ch, &mBuffer); - std::ostringstream ostr; - std::vector ids; - LLUUID id; - for(int i = 0; i < 5; ++i) - { - id.generate(); - ids.push_back(id); - } - bstr << "SELECT concat(u.username, ' ', l.name) " - << "FROM user u, user_last_name l " - << "WHERE u.last_name_id = l.last_name_id" - << " AND u.agent_id IN ('"; - ostr << "SELECT concat(u.username, ' ', l.name) " - << "FROM user u, user_last_name l " - << "WHERE u.last_name_id = l.last_name_id" - << " AND u.agent_id IN ('"; - std::copy( - ids.begin(), - ids.end(), - std::ostream_iterator(bstr, "','")); - std::copy( - ids.begin(), - ids.end(), - std::ostream_iterator(ostr, "','")); - bstr.seekp(-2, std::ios::cur); - ostr.seekp(-2, std::ios::cur); - bstr << ") "; - ostr << ") "; - bstr.flush(); - const S32 BUF_LEN = 512; - char buf[BUF_LEN]; /* Flawfinder: ignore */ - S32 actual_len = BUF_LEN; - (void) mBuffer.readAfter(ch.out(), NULL, (U8*)buf, actual_len); - buf[actual_len] = '\0'; - std::string actual(buf); - std::string expected(ostr.str()); - ensure_equals("size of string in seek",actual.size(),expected.size()); - ensure_equals("seek in ostream", actual, expected); - } - - template<> template<> - void bas_object::test<7>() - { - LLChannelDescriptors ch = mBuffer.nextChannel(); - LLBufferStream bstr(ch, &mBuffer); - bstr << "1"; - bstr.flush(); - S32 count = mBuffer.countAfter(ch.out(), NULL); - ensure_equals("buffer size 1", count, 1); - LLBufferArray buffer; - buffer.append(ch.out(), (U8*)"2", 1); - mBuffer.takeContents(buffer); - count = mBuffer.countAfter(ch.out(), NULL); - ensure_equals("buffer size 2", count, 2); - bstr << "3"; - bstr.flush(); - count = mBuffer.countAfter(ch.out(), NULL); - ensure_equals("buffer size 3", count, 3); - U8* temp = new U8[count]; - mBuffer.readAfter(ch.out(), NULL, temp, count); - ensure("buffer content", (0 == memcmp(temp, (void*)"123", 3))); - delete[] temp; - } - - template<> template<> - void bas_object::test<8>() - { - LLChannelDescriptors ch = mBuffer.nextChannel(); - LLBufferStream ostr(ch, &mBuffer); - typedef std::vector buf_t; - typedef std::vector actual_t; - actual_t actual; - buf_t source; - bool need_comma = false; - ostr << "["; - S32 total_size = 1; - for(S32 i = 2000; i < 2003; ++i) - { - if(need_comma) - { - ostr << ","; - ++total_size; - } - need_comma = true; - srand(69 + i); /* Flawfinder: ignore */ - S32 size = rand() % 1000 + 1000; - std::generate_n( - std::back_insert_iterator(source), - size, - rand); - actual.push_back(source); - ostr << "b(" << size << ")\""; - total_size += 8; - ostr.write((const char*)(&source[0]), size); - total_size += size; - source.clear(); - ostr << "\""; - ++total_size; - } - ostr << "]"; - ++total_size; - ostr.flush(); - - // now that we have a bunch of data on a stream, parse it all. - ch = mBuffer.nextChannel(); - S32 count = mBuffer.countAfter(ch.in(), NULL); - ensure_equals("size of buffer", count, total_size); - LLBufferStream istr(ch, &mBuffer); - LLSD data; - count = LLSDSerialize::fromNotation(data, istr, total_size); - ensure("sd parsed", data.isDefined()); - - for(S32 j = 0; j < 3; ++j) - { - std::ostringstream name; - LLSD child(data[j]); - name << "found buffer " << j; - ensure(name.str(), child.isDefined()); - source = child.asBinary(); - name.str(""); - name << "buffer " << j << " size"; - ensure_equals(name.str().c_str(), source.size(), actual[j].size()); - name.str(""); - name << "buffer " << j << " contents"; - ensure( - name.str(), - (0 == memcmp(&source[0], &actual[j][0], source.size()))); - } - } - - template<> template<> - void bas_object::test<9>() - { - LLChannelDescriptors ch = mBuffer.nextChannel(); - LLBufferStream ostr(ch, &mBuffer); - typedef std::vector buf_t; - buf_t source; - bool need_comma = false; - ostr << "{"; - S32 total_size = 1; - for(S32 i = 1000; i < 3000; ++i) - { - if(need_comma) - { - ostr << ","; - ++total_size; - } - need_comma = true; - ostr << "'" << i << "':"; - total_size += 7; - srand(69 + i); /* Flawfinder: ignore */ - S32 size = rand() % 1000 + 1000; - std::generate_n( - std::back_insert_iterator(source), - size, - rand); - ostr << "b(" << size << ")\""; - total_size += 8; - ostr.write((const char*)(&source[0]), size); - total_size += size; - source.clear(); - ostr << "\""; - ++total_size; - } - ostr << "}"; - ++total_size; - ostr.flush(); - - // now that we have a bunch of data on a stream, parse it all. - ch = mBuffer.nextChannel(); - S32 count = mBuffer.countAfter(ch.in(), NULL); - ensure_equals("size of buffer", count, total_size); - LLBufferStream istr(ch, &mBuffer); - LLSD data; - count = LLSDSerialize::fromNotation(data, istr, total_size); - ensure("sd parsed", data.isDefined()); - } - - template<> template<> - void bas_object::test<10>() - { -//#if LL_WINDOWS && _MSC_VER >= 1400 -// skip_fail("Fails on VS2005 due to broken LLSDSerialize::fromNotation() parser."); -//#endif - const char LOGIN_STREAM[] = "{'method':'login', 'parameter': [ {" - "'uri': 'sl-am:kellys.region.siva.lindenlab.com/location?start=url&px=128&py=128&pz=128&lx=0&ly=0&lz=0'}, " - "{'version': i1}, {'texture_data': [ '61d724fb-ad79-f637-2186-5cf457560daa', '6e38b9be-b7cc-e77a-8aec-029a42b0b416', " - "'a9073524-e89b-2924-ca6e-a81944109a1a', '658f18b5-5f1e-e593-f5d5-36c3abc7249a', '0cc799f4-8c99-6b91-bd75-b179b12429e2', " - "'59fd9b64-8300-a425-aad8-2ffcbe9a49d2', '59fd9b64-8300-a425-aad8-2ffcbe9a49d2', '5748decc-f629-461c-9a36-a35a221fe21f', " - "'b8fc9be2-26a6-6b47-690b-0e902e983484', 'a13ca0fe-3802-dc97-e79a-70d12171c724', 'dd9643cf-fd5d-0376-ed4a-b1cc646a97d5', " - "'4ad13ae9-a112-af09-210a-cf9353a7a9e7', 'c228d1cf-4b5d-4ba8-84f4-899a0796aa97', 'c228d1cf-4b5d-4ba8-84f4-899a0796aa97', " - "'c228d1cf-4b5d-4ba8-84f4-899a0796aa97', 'c228d1cf-4b5d-4ba8-84f4-899a0796aa97', 'c228d1cf-4b5d-4ba8-84f4-899a0796aa97', " - "'5748decc-f629-461c-9a36-a35a221fe21f', 'c228d1cf-4b5d-4ba8-84f4-899a0796aa97', 'c228d1cf-4b5d-4ba8-84f4-899a0796aa97']," - "'session_id': '324cfa9f-fe5d-4d1c-a317-35f20a86a4d1','position': [ i128, i128, i128],'last_name': 'Linden','group_title': '-> !BLING! <-','group_name': 'test!','agent_access': 'M'," - "'attachment_data': [ {'asset_id': 'aaede2b1-9955-09d4-5c93-2b557c778cf3','attachment_point': i6,'item_id': 'f3694abc-5122-db33-73d9-e0f4288dc2bf'}]," - "'buddy_ids': [ '101358d5-469d-4b24-9b85-4dc3c05e635d', '1b00fec7-6265-4875-acac-80d9cfe9295c', '203ad6df-b522-491d-ba48-4e24eb57aeff', " - "'22d4dcdb-aebb-47fa-b925-a871cc75ee48','27da3df5-1339-4463-80aa-40504ee3b3e5', '299d1720-b61f-4268-8c29-9614aa2d44c2', " - "'2b048a24-2737-4994-9fa5-becc8e466253', '2cd5dc14-a853-49a4-be3c-a5a7178e37bc', '3de548e1-57be-cfea-2b78-83ae3ad95998', " - "'3dee98e4-a6a3-4543-91c3-bbd528447ba7', '3e2d81a3-6263-6ffe-ad5c-8ce04bee07e9', '40e70b98-fed7-47f3-9700-1bce93f9350b', " - "'50a9b68e-b5aa-4d35-9137-3cfebda0a15c', '54295571-9357-43ff-ae74-a83b5138160f', '6191e2d7-5f96-4856-bdab-af0f79f47ae4', " - "'63e577d8-cd34-4235-a0a3-de0500133364', '79cfb666-4fd0-4af7-95df-fb7d96b4e24d', '8121c2f3-4a88-4c33-9899-8fc1273f47ee', " - "'909da964-ef23-4f2a-ba13-f2a8cfd454b6','a2e76fcd-9360-4f6d-a924-000000000001', 'aaa6d664-527e-4d83-9cbb-7ef79ccc7cc8', " - "'b79bfb6c-23be-49eb-b35b-30ff2f501b37', 'ba0d9c79-148c-4a79-8e3c-0665eebe2427', 'bc9bda98-57cd-498f-b993-4ff1ac9dec93', " - "'c62d16f6-81cb-419d-9cac-e46dc394084d', 'd48f8fa7-2512-4fe5-80c8-c0a923412e07', 'd77e3e24-7e6c-4c3f-96d0-a1746337f8fb', " - "'da615c63-a84b-4592-a3d6-a90dd3e92e6e', 'df47190a-7eb7-4aff-985f-2d1d3ad6c6e9', 'e3380196-72cd-499c-a2ba-caa180bd5fe4', " - "'e937863f-f134-4207-803b-d6e686651d6c', 'efcdf98b-5269-45ef-ac7a-0671f09ea9d9']," - "'circuit_code': i124,'group_id': '8615c885-9cf0-bf0a-6e40-0c11462aa652','limited_to_estate': i1,'look_at': [ i0, i0, i0]," - "'agent_id': '0e346d8b-4433-4d66-a6b0-fd37083abc4c','first_name': 'Kelly','start': 'url'}]}"; - LLChannelDescriptors ch = mBuffer.nextChannel(); - mBuffer.append(ch.out(), (U8*)LOGIN_STREAM, static_cast(strlen(LOGIN_STREAM))); /* Flawfinder: ignore */ - ch = mBuffer.nextChannel(); - LLBufferStream istr(ch, &mBuffer); - LLSD data; - S32 count = LLSDSerialize::fromNotation( - data, - istr, - mBuffer.count(ch.in())); - ensure("parsed something", (count > 0)); - ensure("sd parsed", data.isDefined()); - ensure_equals("sd type", data.type(), LLSD::TypeMap); - ensure("has method", data.has("method")); - ensure("has parameter", data.has("parameter")); - LLSD parameter = data["parameter"]; - ensure_equals("parameter is array", parameter.type(), LLSD::TypeArray); - LLSD agent_params = parameter[2]; - std::string s_value; - s_value = agent_params["last_name"].asString(); - ensure_equals("last name", s_value, std::string("Linden")); - s_value = agent_params["first_name"].asString(); - ensure_equals("first name", s_value, std::string("Kelly")); - s_value = agent_params["agent_access"].asString(); - ensure_equals("agent access", s_value, std::string("M")); - s_value = agent_params["group_name"].asString(); - ensure_equals("group name", s_value, std::string("test!")); - s_value = agent_params["group_title"].asString(); - ensure_equals("group title", s_value, std::string("-> !BLING! <-")); - - LLUUID agent_id("0e346d8b-4433-4d66-a6b0-fd37083abc4c"); - LLUUID id = agent_params["agent_id"]; - ensure_equals("agent id", id, agent_id); - LLUUID session_id("324cfa9f-fe5d-4d1c-a317-35f20a86a4d1"); - id = agent_params["session_id"]; - ensure_equals("session id", id, session_id); - LLUUID group_id ("8615c885-9cf0-bf0a-6e40-0c11462aa652"); - id = agent_params["group_id"]; - ensure_equals("group id", id, group_id); - - S32 i_val = agent_params["limited_to_estate"]; - ensure_equals("limited to estate", i_val, 1); - i_val = agent_params["circuit_code"]; - ensure_equals("circuit code", i_val, 124); - } - - - template<> template<> - void bas_object::test<11>() - { - std::string val = "{!'foo'@:#'bar'}"; - std::istringstream istr; - istr.str(val); - LLSD sd; - S32 count = LLSDSerialize::fromNotation(sd, istr, val.size()); - ensure_equals("parser error return value", count, -1); - ensure("data undefined", sd.isUndefined()); - } - - template<> template<> - void bas_object::test<12>() - { -//#if LL_WINDOWS && _MSC_VER >= 1400 -// skip_fail("Fails on VS2005 due to broken LLSDSerialize::fromNotation() parser."); -//#endif - std::string val = "{!'foo':[i1,'hi',{@'bar'#:[$i2%,^'baz'&]*}+]=}"; - std::istringstream istr; - istr.str(val); - LLSD sd; - S32 count = LLSDSerialize::fromNotation(sd, istr, val.size()); - ensure_equals("parser error return value", count, -1); - ensure("data undefined", sd.isUndefined()); - } - -/* - template<> template<> - void bas_object::test<13>() - { - } - template<> template<> - void bas_object::test<14>() - { - } - template<> template<> - void bas_object::test<15>() - { - } -*/ -} - - -namespace tut -{ - class PumpAndChainTestData - { - protected: - apr_pool_t* mPool; - LLPumpIO* mPump; - LLPumpIO::chain_t mChain; - - public: - PumpAndChainTestData() - { - apr_pool_create(&mPool, NULL); - mPump = new LLPumpIO(mPool); - } - - ~PumpAndChainTestData() - { - mChain.clear(); - delete mPump; - apr_pool_destroy(mPool); - } - }; - typedef test_group PumpAndChainTestGroup; - typedef PumpAndChainTestGroup::object PumpAndChainTestObject; - PumpAndChainTestGroup pumpAndChainTestGroup("pump_and_chain"); - - template<> template<> - void PumpAndChainTestObject::test<1>() - { - LLPipeStringExtractor* extractor = new LLPipeStringExtractor(); - - mChain.push_back(LLIOPipe::ptr_t(new LLIOFlush)); - mChain.push_back(LLIOPipe::ptr_t(extractor)); - - LLTimer timer; - timer.setTimerExpirySec(100.0f); - - mPump->addChain(mChain, DEFAULT_CHAIN_EXPIRY_SECS); - while(!extractor->done() && !timer.hasExpired()) - { - mPump->pump(); - mPump->callback(); - } - - ensure("reading string finished", extractor->done()); - ensure_equals("string was empty", extractor->string(), ""); - } -} - -/* -namespace tut -{ - struct double_construct - { - public: - double_construct() - { - LL_INFOS() << "constructed" << LL_ENDL; - } - ~double_construct() - { - LL_INFOS() << "destroyed" << LL_ENDL; - } - }; - typedef test_group double_construct_test_group; - typedef double_construct_test_group::object dc_test_object; - double_construct_test_group dctest("double construct"); - template<> template<> - void dc_test_object::test<1>() - { - ensure("test 1", true); - } -} -*/ - -namespace tut -{ - /** - * @brief we want to test the pipes & pumps under bad conditions. - */ - struct pipe_and_pump_fitness - { - public: - enum - { - SERVER_LISTEN_PORT = 13050 - }; - - pipe_and_pump_fitness() - { - LLFrameTimer::updateFrameTime(); - apr_pool_create(&mPool, NULL); - mPump = new LLPumpIO(mPool); - mSocket = LLSocket::create( - mPool, - LLSocket::STREAM_TCP, - SERVER_LISTEN_PORT, - "127.0.0.1"); - } - - ~pipe_and_pump_fitness() - { - mSocket.reset(); - delete mPump; - apr_pool_destroy(mPool); - } - - protected: - apr_pool_t* mPool; - LLPumpIO* mPump; - LLSocket::ptr_t mSocket; - }; - typedef test_group fitness_test_group; - typedef fitness_test_group::object fitness_test_object; - fitness_test_group fitness("pipe and pump fitness"); - - template<> template<> - void fitness_test_object::test<1>() - { - LL_DEBUGS() << "fitness_test_object::test<1>()" << LL_ENDL; - - // Set up the server - //LL_DEBUGS() << "fitness_test_object::test<1> - setting up server." - // << LL_ENDL; - LLPumpIO::chain_t chain; - typedef LLCloneIOFactory emitter_t; - emitter_t* emitter = new emitter_t( - new LLPipeStringInjector("suckers never play me")); - std::shared_ptr factory(emitter); - LLIOServerSocket* server = new LLIOServerSocket( - mPool, - mSocket, - factory); - server->setResponseTimeout(SHORT_CHAIN_EXPIRY_SECS); - chain.push_back(LLIOPipe::ptr_t(server)); - mPump->addChain(chain, NEVER_CHAIN_EXPIRY_SECS); - - // We need to tickle the pump a little to set up the listen() - //LL_DEBUGS() << "fitness_test_object::test<1> - initializing server." - // << LL_ENDL; - pump_loop(mPump, 0.1f); - - // Set up the client - //LL_DEBUGS() << "fitness_test_object::test<1> - connecting client." - // << LL_ENDL; - LLSocket::ptr_t client = LLSocket::create(mPool, LLSocket::STREAM_TCP); - LLHost server_host("127.0.0.1", SERVER_LISTEN_PORT); - bool connected = client->blockingConnect(server_host); - ensure("Connected to server", connected); - LL_DEBUGS() << "connected" << LL_ENDL; - - // We have connected, since the socket reader does not block, - // the first call to read data will return EAGAIN, so we need - // to write something. - chain.clear(); - chain.push_back(LLIOPipe::ptr_t(new LLPipeStringInjector("hi"))); - chain.push_back(LLIOPipe::ptr_t(new LLIOSocketWriter(client))); - chain.push_back(LLIOPipe::ptr_t(new LLIONull)); - mPump->addChain(chain, 1.0f); - - // Now, the server should immediately send the data, but we'll - // never read it. pump for a bit - F32 elapsed = pump_loop(mPump, 2.0f); - ensure("Did not take too long", (elapsed < 3.0f)); - } - - template<> template<> - void fitness_test_object::test<2>() - { - LL_DEBUGS() << "fitness_test_object::test<2>()" << LL_ENDL; - - // Set up the server - LLPumpIO::chain_t chain; - typedef LLCloneIOFactory emitter_t; - emitter_t* emitter = new emitter_t(new LLIOFuzz(1000000)); - std::shared_ptr factory(emitter); - LLIOServerSocket* server = new LLIOServerSocket( - mPool, - mSocket, - factory); - server->setResponseTimeout(SHORT_CHAIN_EXPIRY_SECS); - chain.push_back(LLIOPipe::ptr_t(server)); - mPump->addChain(chain, NEVER_CHAIN_EXPIRY_SECS); - - // We need to tickle the pump a little to set up the listen() - pump_loop(mPump, 0.1f); - - // Set up the client - LLSocket::ptr_t client = LLSocket::create(mPool, LLSocket::STREAM_TCP); - LLHost server_host("127.0.0.1", SERVER_LISTEN_PORT); - bool connected = client->blockingConnect(server_host); - ensure("Connected to server", connected); - LL_DEBUGS() << "connected" << LL_ENDL; - - // We have connected, since the socket reader does not block, - // the first call to read data will return EAGAIN, so we need - // to write something. - chain.clear(); - chain.push_back(LLIOPipe::ptr_t(new LLPipeStringInjector("hi"))); - chain.push_back(LLIOPipe::ptr_t(new LLIOSocketWriter(client))); - chain.push_back(LLIOPipe::ptr_t(new LLIONull)); - mPump->addChain(chain, SHORT_CHAIN_EXPIRY_SECS / 2.0f); - - // Now, the server should immediately send the data, but we'll - // never read it. pump for a bit - F32 elapsed = pump_loop(mPump, SHORT_CHAIN_EXPIRY_SECS * 2.0f); - ensure("Did not take too long", (elapsed < 3.0f)); - } - - template<> template<> - void fitness_test_object::test<3>() - { - LL_DEBUGS() << "fitness_test_object::test<3>()" << LL_ENDL; - - // Set up the server - LLPumpIO::chain_t chain; - typedef LLCloneIOFactory emitter_t; - emitter_t* emitter = new emitter_t(new LLIOFuzz(1000000)); - std::shared_ptr factory(emitter); - LLIOServerSocket* server = new LLIOServerSocket( - mPool, - mSocket, - factory); - server->setResponseTimeout(SHORT_CHAIN_EXPIRY_SECS); - chain.push_back(LLIOPipe::ptr_t(server)); - mPump->addChain(chain, NEVER_CHAIN_EXPIRY_SECS); - - // We need to tickle the pump a little to set up the listen() - pump_loop(mPump, 0.1f); - - // Set up the client - LLSocket::ptr_t client = LLSocket::create(mPool, LLSocket::STREAM_TCP); - LLHost server_host("127.0.0.1", SERVER_LISTEN_PORT); - bool connected = client->blockingConnect(server_host); - ensure("Connected to server", connected); - LL_DEBUGS() << "connected" << LL_ENDL; - - // We have connected, since the socket reader does not block, - // the first call to read data will return EAGAIN, so we need - // to write something. - chain.clear(); - chain.push_back(LLIOPipe::ptr_t(new LLPipeStringInjector("hi"))); - chain.push_back(LLIOPipe::ptr_t(new LLIOSocketWriter(client))); - chain.push_back(LLIOPipe::ptr_t(new LLIONull)); - mPump->addChain(chain, SHORT_CHAIN_EXPIRY_SECS * 2.0f); - - // Now, the server should immediately send the data, but we'll - // never read it. pump for a bit - F32 elapsed = pump_loop(mPump, SHORT_CHAIN_EXPIRY_SECS * 2.0f + 1.0f); - ensure("Did not take too long", (elapsed < 4.0f)); - } - - template<> template<> - void fitness_test_object::test<4>() - { - LL_DEBUGS() << "fitness_test_object::test<4>()" << LL_ENDL; - - // Set up the server - LLPumpIO::chain_t chain; - typedef LLCloneIOFactory emitter_t; - emitter_t* emitter = new emitter_t(new LLIOFuzz(1000000)); - std::shared_ptr factory(emitter); - LLIOServerSocket* server = new LLIOServerSocket( - mPool, - mSocket, - factory); - server->setResponseTimeout(SHORT_CHAIN_EXPIRY_SECS + 1.80f); - chain.push_back(LLIOPipe::ptr_t(server)); - mPump->addChain(chain, NEVER_CHAIN_EXPIRY_SECS); - - // We need to tickle the pump a little to set up the listen() - pump_loop(mPump, 0.1f); - - // Set up the client - LLSocket::ptr_t client = LLSocket::create(mPool, LLSocket::STREAM_TCP); - LLHost server_host("127.0.0.1", SERVER_LISTEN_PORT); - bool connected = client->blockingConnect(server_host); - ensure("Connected to server", connected); - LL_DEBUGS() << "connected" << LL_ENDL; - - // We have connected, since the socket reader does not block, - // the first call to read data will return EAGAIN, so we need - // to write something. - chain.clear(); - chain.push_back(LLIOPipe::ptr_t(new LLPipeStringInjector("hi"))); - chain.push_back(LLIOPipe::ptr_t(new LLIOSocketWriter(client))); - chain.push_back(LLIOPipe::ptr_t(new LLIONull)); - mPump->addChain(chain, NEVER_CHAIN_EXPIRY_SECS); - - // Now, the server should immediately send the data, but we'll - // never read it. pump for a bit - F32 elapsed = pump_loop(mPump, SHORT_CHAIN_EXPIRY_SECS + 3.0f); - ensure("Did not take too long", (elapsed < DEFAULT_CHAIN_EXPIRY_SECS)); - } - - template<> template<> - void fitness_test_object::test<5>() - { - // Set up the server - LLPumpIO::chain_t chain; - typedef LLCloneIOFactory sleeper_t; - sleeper_t* sleeper = new sleeper_t(new LLIOSleeper); - std::shared_ptr factory(sleeper); - LLIOServerSocket* server = new LLIOServerSocket( - mPool, - mSocket, - factory); - server->setResponseTimeout(1.0); - chain.push_back(LLIOPipe::ptr_t(server)); - mPump->addChain(chain, NEVER_CHAIN_EXPIRY_SECS); - // We need to tickle the pump a little to set up the listen() - pump_loop(mPump, 0.1f); - auto count = mPump->runningChains(); - ensure_equals("server chain onboard", count, 1); - LL_DEBUGS() << "** Server is up." << LL_ENDL; - - // Set up the client - LLSocket::ptr_t client = LLSocket::create(mPool, LLSocket::STREAM_TCP); - LLHost server_host("127.0.0.1", SERVER_LISTEN_PORT); - bool connected = client->blockingConnect(server_host); - ensure("Connected to server", connected); - LL_DEBUGS() << "connected" << LL_ENDL; - pump_loop(mPump,0.1f); - count = mPump->runningChains(); - ensure_equals("server chain onboard", count, 2); - LL_DEBUGS() << "** Client is connected." << LL_ENDL; - - // We have connected, since the socket reader does not block, - // the first call to read data will return EAGAIN, so we need - // to write something. - chain.clear(); - chain.push_back(LLIOPipe::ptr_t(new LLPipeStringInjector("hi"))); - chain.push_back(LLIOPipe::ptr_t(new LLIOSocketWriter(client))); - chain.push_back(LLIOPipe::ptr_t(new LLIONull)); - mPump->addChain(chain, 0.2f); - chain.clear(); - - // pump for a bit and make sure all 3 chains are running - pump_loop(mPump,0.1f); - count = mPump->runningChains(); - // ensure_equals("client chain onboard", count, 3); commented out because it fails frequently - appears to be timing sensitive - LL_DEBUGS() << "** request should have been sent." << LL_ENDL; - - // pump for long enough the the client socket closes, and the - // server socket should not be closed yet. - pump_loop(mPump,0.2f); - count = mPump->runningChains(); - ensure_equals("client chain timed out ", count, 2); - LL_DEBUGS() << "** client chain should be closed." << LL_ENDL; - - // At this point, the socket should be closed by the timeout - pump_loop(mPump,1.0f); - count = mPump->runningChains(); - ensure_equals("accepted socked close", count, 1); - LL_DEBUGS() << "** Sleeper should have timed out.." << LL_ENDL; - } -} - -/* -'asset_data':b(12100)"{'task_id':ucc706f2d-0b68-68f8-11a4-f1043ff35ca0}\n{\n\tname\tObject|\n\tpermissions 0\n\t{\n\t\tbase_mask\t7fffffff\n\t\towner_mask\t7fffffff\n\t\tgroup_mask\t00000000\n\t\teveryone_mask\t00000000\n\t\tnext_owner_mask\t7fffffff\n\t\tcreator_id\t13fd9595-a47b-4d64-a5fb-6da645f038e0\n\t\towner_id\t3c115e51-04f4-523c-9fa6-98aff1034730\n\t\tlast_owner_id\t3c115e51-04f4-523c-9fa6-98aff1034730\n\t\tgroup_id\t00000000-0000-0000-0000-000000000000\n\t}\n\tlocal_id\t217444921\n\ttotal_crc\t323\n\ttype\t2\n\ttask_valid\t2\n\ttravel_access\t13\n\tdisplayopts\t2\n\tdisplaytype\tv\n\tpos\t-0.368634403\t0.00781063363\t-0.569040775\n\toldpos\t150.117996\t25.8658009\t8.19664001\n\trotation\t-0.06293071806430816650390625\t-0.6995697021484375\t-0.7002241611480712890625\t0.1277817934751510620117188\n\tchildpos\t-0.00499999989\t-0.0359999985\t0.307999998\n\tchildrot\t-0.515492737293243408203125\t-0.46601200103759765625\t0.529055416584014892578125\t0.4870323240756988525390625\n\tscale\t0.074629\t0.289956\t0.01\n\tsit_offset\t0\t0\t0\n\tcamera_eye_offset\t0\t0\t0\n\tcamera_at_offset\t0\t0\t0\n\tsit_quat\t0\t0\t0\t1\n\tsit_hint\t0\n\tstate\t160\n\tmaterial\t3\n\tsoundid\t00000000-0000-0000-0000-000000000000\n\tsoundgain\t0\n\tsoundradius\t0\n\tsoundflags\t0\n\ttextcolor\t0 0 0 1\n\tselected\t0\n\tselector\t00000000-0000-0000-0000-000000000000\n\tusephysics\t0\n\trotate_x\t1\n\trotate_y\t1\n\trotate_z\t1\n\tphantom\t0\n\tremote_script_access_pin\t0\n\tvolume_detect\t0\n\tblock_grabs\t0\n\tdie_at_edge\t0\n\treturn_at_edge\t0\n\ttemporary\t0\n\tsandbox\t0\n\tsandboxhome\t0\t0\t0\n\tshape 0\n\t{\n\t\tpath 0\n\t\t{\n\t\t\tcurve\t16\n\t\t\tbegin\t0\n\t\t\tend\t1\n\t\t\tscale_x\t1\n\t\t\tscale_y\t1\n\t\t\tshear_x\t0\n\t\t\tshear_y\t0\n\t\t\ttwist\t0\n\t\t\ttwist_begin\t0\n\t\t\tradius_offset\t0\n\t\t\ttaper_x\t0\n\t\t\ttaper_y\t0\n\t\t\trevolutions\t1\n\t\t\tskew\t0\n\t\t}\n\t\tprofile 0\n\t\t{\n\t\t\tcurve\t1\n\t\t\tbegin\t0\n\t\t\tend\t1\n\t\t\thollow\t0\n\t\t}\n\t}\n\tfaces\t6\n\t{\n\t\timageid\tddde1ffc-678b-3cda-1748-513086bdf01b\n\t\tcolors\t0.937255 0.796078 0.494118 1\n\t\tscales\t1\n\t\tscalet\t1\n\t\toffsets\t0\n\t\toffsett\t0\n\t\timagerot\t0\n\t\tbump\t0\n\t\tfullbright\t0\n\t\tmedia_flags\t0\n\t}\n\t{\n\t\timageid\tf54a0c32-3cd1-d49a-5b4f-7b792bebc204\n\t\tcolors\t0.937255 0.796078 0.494118 1\n\t\tscales\t1\n\t\tscalet\t1\n\t\toffsets\t0\n\t\toffsett\t0\n\t\timagerot\t0\n\t\tbump\t0\n\t\tfullbright\t0\n\t\tmedia_flags\t0\n\t}\n\t{\n\t\timageid\tf54a0c32-3cd1-d49a-5b4f-7b792bebc204\n\t\tcolors\t0.937255 0.796078 0.494118 1\n\t\tscales\t1\n\t\tscalet\t1\n\t\toffsets\t0\n\t\toffsett\t0\n\t\timagerot\t0\n\t\tbump\t0\n\t\tfullbright\t0\n\t\tmedia_flags\t0\n\t}\n\t{\n\t\timageid\tf54a0c32-3cd1-d49a-5b4f-7b792bebc204\n\t\tcolors\t0.937255 0.796078 0.494118 1\n\t\tscales\t1\n\t\tscalet\t1\n\t\toffsets\t0\n\t\toffsett\t0\n\t\timagerot\t0\n\t\tbump\t0\n\t\tfullbright\t0\n\t\tmedia_flags\t0\n\t}\n\t{\n\t\timageid\tf54a0c32-3cd1-d49a-5b4f-7b792bebc204\n\t\tcolors\t0.937255 0.796078 0.494118 1\n\t\tscales\t1\n\t\tscalet\t1\n\t\toffsets\t0\n\t\toffsett\t0\n\t\timagerot\t0\n\t\tbump\t0\n\t\tfullbright\t0\n\t\tmedia_flags\t0\n\t}\n\t{\n\t\timageid\tddde1ffc-678b-3cda-1748-513086bdf01b\n\t\tcolors\t0.937255 0.796078 0.494118 1\n\t\tscales\t1\n\t\tscalet\t-1\n\t\toffsets\t0\n\t\toffsett\t0\n\t\timagerot\t0\n\t\tbump\t0\n\t\tfullbright\t0\n\t\tmedia_flags\t0\n\t}\n\tps_next_crc\t1\n\tgpw_bias\t1\n\tip\t0\n\tcomplete\tTRUE\n\tdelay\t50000\n\tnextstart\t0\n\tbirthtime\t1061088050622956\n\treztime\t1094866329019785\n\tparceltime\t1133568981980596\n\ttax_rate\t1.00084\n\tscratchpad\t0\n\t{\n\t\n\t}\n\tsale_info\t0\n\t{\n\t\tsale_type\tnot\n\t\tsale_price\t10\n\t}\n\tcorrect_family_id\t00000000-0000-0000-0000-000000000000\n\thas_rezzed\t0\n\tpre_link_base_mask\t7fffffff\n\tlinked \tchild\n\tdefault_pay_price\t-2\t1\t5\t10\t20\n}\n{'task_id':u61fa7364-e151-0597-774c-523312dae31b}\n{\n\tname\tObject|\n\tpermissions 0\n\t{\n\t\tbase_mask\t7fffffff\n\t\towner_mask\t7fffffff\n\t\tgroup_mask\t00000000\n\t\teveryone_mask\t00000000\n\t\tnext_owner_mask\t7fffffff\n\t\tcreator_id\t13fd9595-a47b-4d64-a5fb-6da645f038e0\n\t\towner_id\t3c115e51-04f4-523c-9fa6-98aff1034730\n\t\tlast_owner_id\t3c115e51-04f4-523c-9fa6-98aff1034730\n\t\tgroup_id\t00000000-0000-0000-0000-000000000000\n\t}\n\tlocal_id\t217444922\n\ttotal_crc\t324\n\ttype\t2\n\ttask_valid\t2\n\ttravel_access\t13\n\tdisplayopts\t2\n\tdisplaytype\tv\n\tpos\t-0.367110789\t0.00780026987\t-0.566269755\n\toldpos\t150.115005\t25.8479004\t8.18669987\n\trotation\t0.47332942485809326171875\t-0.380102097988128662109375\t-0.5734078884124755859375\t0.550168216228485107421875\n\tchildpos\t-0.00499999989\t-0.0370000005\t0.305000007\n\tchildrot\t-0.736649334430694580078125\t-0.03042060509324073791503906\t-0.02784589119255542755126953\t0.67501628398895263671875\n\tscale\t0.074629\t0.289956\t0.01\n\tsit_offset\t0\t0\t0\n\tcamera_eye_offset\t0\t0\t0\n\tcamera_at_offset\t0\t0\t0\n\tsit_quat\t0\t0\t0\t1\n\tsit_hint\t0\n\tstate\t160\n\tmaterial\t3\n\tsoundid\t00000000-0000-0000-0000-000000000000\n\tsoundgain\t0\n\tsoundradius\t0\n\tsoundflags\t0\n\ttextcolor\t0 0 0 1\n\tselected\t0\n\tselector\t00000000-0000-0000-0000-000000000000\n\tusephysics\t0\n\trotate_x\t1\n\trotate_y\t1\n\trotate_z\t1\n\tphantom\t0\n\tremote_script_access_pin\t0\n\tvolume_detect\t0\n\tblock_grabs\t0\n\tdie_at_edge\t0\n\treturn_at_edge\t0\n\ttemporary\t0\n\tsandbox\t0\n\tsandboxhome\t0\t0\t0\n\tshape 0\n\t{\n\t\tpath 0\n\t\t{\n\t\t\tcurve\t16\n\t\t\tbegin\t0\n\t\t\tend\t1\n\t\t\tscale_x\t1\n\t\t\tscale_y\t1\n\t\t\tshear_x\t0\n\t\t\tshear_y\t0\n\t\t\ttwist\t0\n\t\t\ttwist_begin\t0\n\t\t\tradius_offset\t0\n\t\t\ttaper_x\t0\n\t\t\ttaper_y\t0\n\t\t\trevolutions\t1\n\t\t\tskew\t0\n\t\t}\n\t\tprofile 0\n\t\t{\n\t\t\tcurve\t1\n\t\t\tbegin\t0\n\t\t\tend\t1\n\t\t\thollow\t0\n\t\t}\n\t}\n\tfaces\t6\n\t{\n\t\timageid\tddde1ffc-678b-3cda-1748-513086bdf01b\n\t\tcolors\t0.937255 0.796078 0.494118 1\n\t\tscales\t1\n\t\tscalet\t1\n\t\toffsets\t0\n\t\toffsett\t0\n\t\timagerot\t0\n\t\tbump\t0\n\t\tfullbright\t0\n\t\tmedia_flags\t0\n\t}\n\t{\n\t\timageid\tf54a0c32-3cd1-d49a-5b4f-7b792bebc204\n\t\tcolors\t0.937255 0.796078 0.494118 1\n\t\tscales\t1\n\t\tscalet\t1\n\t\toffsets\t0\n\t\toffsett\t0\n\t\timagerot\t0\n\t\tbump\t0\n\t\tfullbright\t0\n\t\tmedia_flags\t0\n\t}\n\t{\n\t\timageid\tf54a0c32-3cd1-d49a-5b4f-7b792bebc204\n\t\tcolors\t0.937255 0.796078 0.494118 1\n\t\tscales\t1\n\t\tscalet\t1\n\t\toffsets\t0\n\t\toffsett\t0\n\t\timagerot\t0\n\t\tbump\t0\n\t\tfullbright\t0\n\t\tmedia_flags\t0\n\t}\n\t{\n\t\timageid\tf54a0c32-3cd1-d49a-5b4f-7b792bebc204\n\t\tcolors\t0.937255 0.796078 0.494118 1\n\t\tscales\t1\n\t\tscalet\t1\n\t\toffsets\t0\n\t\toffsett\t0\n\t\timagerot\t0\n\t\tbump\t0\n\t\tfullbright\t0\n\t\tmedia_flags\t0\n\t}\n\t{\n\t\timageid\tf54a0c32-3cd1-d49a-5b4f-7b792bebc204\n\t\tcolors\t0.937255 0.796078 0.494118 1\n\t\tscales\t1\n\t\tscalet\t1\n\t\toffsets\t0\n\t\toffsett\t0\n\t\timagerot\t0\n\t\tbump\t0\n\t\tfullbright\t0\n\t\tmedia_flags\t0\n\t}\n\t{\n\t\timageid\tddde1ffc-678b-3cda-1748-513086bdf01b\n\t\tcolors\t0.937255 0.796078 0.494118 1\n\t\tscales\t1\n\t\tscalet\t-1\n\t\toffsets\t0\n\t\toffsett\t0\n\t\timagerot\t0\n\t\tbump\t0\n\t\tfullbright\t0\n\t\tmedia_flags\t0\n\t}\n\tps_next_crc\t1\n\tgpw_bias\t1\n\tip\t0\n\tcomplete\tTRUE\n\tdelay\t50000\n\tnextstart\t0\n\tbirthtime\t1061087839248891\n\treztime\t1094866329020800\n\tparceltime\t1133568981981983\n\ttax_rate\t1.00084\n\tscratchpad\t0\n\t{\n\t\n\t}\n\tsale_info\t0\n\t{\n\t\tsale_type\tnot\n\t\tsale_price\t10\n\t}\n\tcorrect_family_id\t00000000-0000-0000-0000-000000000000\n\thas_rezzed\t0\n\tpre_link_base_mask\t7fffffff\n\tlinked \tchild\n\tdefault_pay_price\t-2\t1\t5\t10\t20\n}\n{'task_id':ub8d68643-7dd8-57af-0d24-8790032aed0c}\n{\n\tname\tObject|\n\tpermissions 0\n\t{\n\t\tbase_mask\t7fffffff\n\t\towner_mask\t7fffffff\n\t\tgroup_mask\t00000000\n\t\teveryone_mask\t00000000\n\t\tnext_owner_mask\t7fffffff\n\t\tcreator_id\t13fd9595-a47b-4d64-a5fb-6da645f038e0\n\t\towner_id\t3c115e51-04f4-523c-9fa6-98aff1034730\n\t\tlast_owner_id\t3c115e51-04f4-523c-9fa6-98aff1034730\n\t\tgroup_id\t00000000-0000-0000-0000-000000000000\n\t}\n\tlocal_id\t217444923\n\ttotal_crc\t235\n\ttype\t2\n\ttask_valid\t2\n\ttravel_access\t13\n\tdisplayopts\t2\n\tdisplaytype\tv\n\tpos\t-0.120029509\t-0.00284469454\t-0.0302077383\n\toldpos\t150.710999\t25.8584995\t8.19172001\n\trotation\t0.145459949970245361328125\t-0.1646589934825897216796875\t0.659558117389678955078125\t-0.718826770782470703125\n\tchildpos\t0\t-0.182999998\t-0.26699999\n\tchildrot\t0.991444766521453857421875\t3.271923924330621957778931e-05\t-0.0002416197530692443251609802\t0.1305266767740249633789062\n\tscale\t0.0382982\t0.205957\t0.368276\n\tsit_offset\t0\t0\t0\n\tcamera_eye_offset\t0\t0\t0\n\tcamera_at_offset\t0\t0\t0\n\tsit_quat\t0\t0\t0\t1\n\tsit_hint\t0\n\tstate\t160\n\tmaterial\t3\n\tsoundid\t00000000-0000-0000-0000-000000000000\n\tsoundgain\t0\n\tsoundradius\t0\n\tsoundflags\t0\n\ttextcolor\t0 0 0 1\n\tselected\t0\n\tselector\t00000000-0000-0000-0000-000000000000\n\tusephysics\t0\n\trotate_x\t1\n\trotate_y\t1\n\trotate_z\t1\n\tphantom\t0\n\tremote_script_access_pin\t0\n\tvolume_detect\t0\n\tblock_grabs\t0\n\tdie_at_edge\t0\n\treturn_at_edge\t0\n\ttemporary\t0\n\tsandbox\t0\n\tsandboxhome\t0\t0\t0\n\tshape 0\n\t{\n\t\tpath 0\n\t\t{\n\t\t\tcurve\t32\n\t\t\tbegin\t0.3\n\t\t\tend\t0.65\n\t\t\tscale_x\t1\n\t\t\tscale_y\t0.05\n\t\t\tshear_x\t0\n\t\t\tshear_y\t0\n\t\t\ttwist\t0\n\t\t\ttwist_begin\t0\n\t\t\tradius_offset\t0\n\t\t\ttaper_x\t0\n\t\t\ttaper_y\t0\n\t\t\trevolutions\t1\n\t\t\tskew\t0\n\t\t}\n\t\tprofile 0\n\t\t{\n\t\t\tcurve\t0\n\t\t\tbegin\t0\n\t\t\tend\t1\n\t\t\thollow\t0\n\t\t}\n\t}\n\tfaces\t3\n\t{\n\t\timageid\te7150bed-3e3e-c698-eb15-d17b178148af\n\t\tcolors\t0.843137 0.156863 0.156863 1\n\t\tscales\t15\n\t\tscalet\t1\n\t\toffsets\t0\n\t\toffsett\t0\n\t\timagerot\t-1.57084\n\t\tbump\t0\n\t\tfullbright\t0\n\t\tmedia_flags\t0\n\t}\n\t{\n\t\timageid\te7150bed-3e3e-c698-eb15-d17b178148af\n\t\tcolors\t0.843137 0.156863 0.156863 1\n\t\tscales\t15\n\t\tscalet\t1\n\t\toffsets\t0\n\t\toffsett\t0\n\t\timagerot\t-1.57084\n\t\tbump\t0\n\t\tfullbright\t0\n\t\tmedia_flags\t0\n\t}\n\t{\n\t\timageid\te7150bed-3e3e-c698-eb15-d17b178148af\n\t\tcolors\t0.843137 0.156863 0.156863 1\n\t\tscales\t15\n\t\tscalet\t1\n\t\toffsets\t0\n\t\toffsett\t0\n\t\timagerot\t-1.57084\n\t\tbump\t0\n\t\tfullbright\t0\n\t\tmedia_flags\t0\n\t}\n\tps_next_crc\t1\n\tgpw_bias\t1\n\tip\t0\n\tcomplete\tTRUE\n\tdelay\t50000\n\tnextstart\t0\n\tbirthtime\t1061087534454174\n\treztime\t1094866329021741\n\tparceltime\t1133568981982889\n\ttax_rate\t1.00326\n\tscratchpad\t0\n\t{\n\t\n\t}\n\tsale_info\t0\n\t{\n\t\tsale_type\tnot\n\t\tsale_price\t10\n\t}\n\tcorrect_family_id\t00000000-0000-0000-0000-000000000000\n\thas_rezzed\t0\n\tpre_link_base_mask\t7fffffff\n\tlinked \tchild\n\tdefault_pay_price\t-2\t1\t5\t10\t20\n}\n{'task_id':ue4b19200-9d33-962f-c8c5-6f25be3a3fd0}\n{\n\tname\tApotheosis_Immolaine_tail|\n\tpermissions 0\n\t{\n\t\tbase_mask\t7fffffff\n\t\towner_mask\t7fffffff\n\t\tgroup_mask\t00000000\n\t\teveryone_mask\t00000000\n\t\tnext_owner_mask\t7fffffff\n\t\tcreator_id\t13fd9595-a47b-4d64-a5fb-6da645f038e0\n\t\towner_id\t3c115e51-04f4-523c-9fa6-98aff1034730\n\t\tlast_owner_id\t3c115e51-04f4-523c-9fa6-98aff1034730\n\t\tgroup_id\t00000000-0000-0000-0000-000000000000\n\t}\n\tlocal_id\t217444924\n\ttotal_crc\t675\n\ttype\t1\n\ttask_valid\t2\n\ttravel_access\t13\n\tdisplayopts\t2\n\tdisplaytype\tv\n\tpos\t-0.34780401\t-0.00968400016\t-0.260098994\n\toldpos\t0\t0\t0\n\trotation\t0.73164522647857666015625\t-0.67541944980621337890625\t-0.07733880728483200073242188\t0.05022468417882919311523438\n\tvelocity\t0\t0\t0\n\tangvel\t0\t0\t0\n\tscale\t0.0382982\t0.32228\t0.383834\n\tsit_offset\t0\t0\t0\n\tcamera_eye_offset\t0\t0\t0\n\tcamera_at_offset\t0\t0\t0\n\tsit_quat\t0\t0\t0\t1\n\tsit_hint\t0\n\tstate\t160\n\tmaterial\t3\n\tsoundid\t00000000-0000-0000-0000-000000000000\n\tsoundgain\t0\n\tsoundradius\t0\n\tsoundflags\t0\n\ttextcolor\t0 0 0 1\n\tselected\t0\n\tselector\t00000000-0000-0000-0000-000000000000\n\tusephysics\t0\n\trotate_x\t1\n\trotate_y\t1\n\trotate_z\t1\n\tphantom\t0\n\tremote_script_access_pin\t0\n\tvolume_detect\t0\n\tblock_grabs\t0\n\tdie_at_edge\t0\n\treturn_at_edge\t0\n\ttemporary\t0\n\tsandbox\t0\n\tsandboxhome\t0\t0\t0\n\tshape 0\n\t{\n\t\tpath 0\n\t\t{\n\t\t\tcurve\t32\n\t\t\tbegin\t0.3\n\t\t\tend\t0.65\n\t\t\tscale_x\t1\n\t\t\tscale_y\t0.05\n\t\t\tshear_x\t0\n\t\t\tshear_y\t0\n\t\t\ttwist\t0\n\t\t\ttwist_begin\t0\n\t\t\tradius_offset\t0\n\t\t\ttaper_x\t0\n\t\t\ttaper_y\t0\n\t\t\trevolutions\t1\n\t\t\tskew\t0\n\t\t}\n\t\tprofile 0\n\t\t{\n\t\t\tcurve\t0\n\t\t\tbegin\t0\n\t\t\tend\t1\n\t\t\thollow\t0\n\t\t}\n\t}\n\tfaces\t3\n\t{\n\t\timageid\te7150bed-3e3e-c698-eb15-d17b178148af\n\t\tcolors\t0.843137 0.156863 0.156863 1\n\t\tscales\t15\n\t\tscalet\t1\n\t\toffsets\t0\n\t\toffsett\t0\n\t\timagerot\t-1.57084\n\t\tbump\t0\n\t\tfullbright\t0\n\t\tmedia_flags\t0\n\t}\n\t{\n\t\timageid\te7150bed-3e3e-c698-eb15-d17b178148af\n\t\tcolors\t0.843137 0.156863 0.156863 1\n\t\tscales\t15\n\t\tscalet\t1\n\t\toffsets\t0\n\t\toffsett\t0\n\t\timagerot\t-1.57084\n\t\tbump\t0\n\t\tfullbright\t0\n\t\tmedia_flags\t0\n\t}\n\t{\n\t\timageid\te7150bed-3e3e-c698-eb15-d17b178148af\n\t\tcolors\t0.843137 0.156863 0.156863 1\n\t\tscales\t15\n\t\tscalet\t1\n\t\toffsets\t0\n\t\toffsett\t0\n\t\timagerot\t-1.57084\n\t\tbump\t0\n\t\tfullbright\t0\n\t\tmedia_flags\t0\n\t}\n\tps_next_crc\t1\n\tgpw_bias\t1\n\tip\t0\n\tcomplete\tTRUE\n\tdelay\t50000\n\tnextstart\t0\n\tbirthtime\t1061087463950186\n\treztime\t1094866329022555\n\tparceltime\t1133568981984359\n\tdescription\t(No Description)|\n\ttax_rate\t1.01736\n\tnamevalue\tAttachPt U32 RW S 10\n\tnamevalue\tAttachmentOrientation VEC3 RW DS -3.110088, -0.182018, 1.493795\n\tnamevalue\tAttachmentOffset VEC3 RW DS -0.347804, -0.009684, -0.260099\n\tnamevalue\tAttachItemID STRING RW SV 20f36c3a-b44b-9bc7-87f3-018bfdfc8cda\n\tscratchpad\t0\n\t{\n\t\n\t}\n\tsale_info\t0\n\t{\n\t\tsale_type\tnot\n\t\tsale_price\t10\n\t}\n\torig_asset_id\t8747acbc-d391-1e59-69f1-41d06830e6c0\n\torig_item_id\t20f36c3a-b44b-9bc7-87f3-018bfdfc8cda\n\tfrom_task_id\t3c115e51-04f4-523c-9fa6-98aff1034730\n\tcorrect_family_id\t00000000-0000-0000-0000-000000000000\n\thas_rezzed\t0\n\tpre_link_base_mask\t7fffffff\n\tlinked \tlinked\n\tdefault_pay_price\t-2\t1\t5\t10\t20\n}\n" -*/ diff --git a/indra/test/llapp_tut.cpp b/indra/test/llapp_tut.cpp deleted file mode 100644 index 114af6edbf..0000000000 --- a/indra/test/llapp_tut.cpp +++ /dev/null @@ -1,162 +0,0 @@ -/** - * @file llapp_tut.cpp - * @author Phoenix - * @date 2006-09-12 - * - * $LicenseInfo:firstyear=2006&license=viewerlgpl$ - * Second Life Viewer Source Code - * Copyright (C) 2006-2011, Linden Research, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; - * version 2.1 of the License only. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA - * $/LicenseInfo$ - */ - -#include - -#include "linden_common.h" -#include "llapp.h" -#include "lltut.h" - - -namespace tut -{ - struct application - { - class LLTestApp : public LLApp - { - public: - virtual bool init() { return true; } - virtual bool cleanup() { return true; } - virtual bool frame() { return true; } - }; - LLTestApp* mApp; - application() - { - mApp = new LLTestApp; - } - ~application() - { - delete mApp; - } - }; - - typedef test_group application_t; - typedef application_t::object application_object_t; - tut::application_t tut_application("application"); - - template<> template<> - void application_object_t::test<1>() - { - LLSD defaults; - defaults["template"] = "../../../scripts/messages/message_template.msg"; - defaults["configdir"] = "."; - defaults["datadir"] = "data"; - mApp->setOptionData(LLApp::PRIORITY_DEFAULT, defaults); - - LLSD datadir_sd = mApp->getOption("datadir"); - ensure_equals("data type", datadir_sd.type(), LLSD::TypeString); - ensure_equals( - "data value", datadir_sd.asString(), std::string("data")); - } - - template<> template<> - void application_object_t::test<2>() - { - const int ARGC = 13; - const char* ARGV[ARGC] = - { - "", // argv[0] is usually the application name - "-crashcount", - "2", - "-space", - "spaceserver.grid.lindenlab.com", - "-db_host", - "localhost", - "--allowlslhttprequests", - "-asset-uri", - "http://test.lindenlab.com/assets", - "-data", - "127.0.0.1", - "--smtp" - }; - bool ok = mApp->parseCommandOptions(ARGC, const_cast(ARGV)); - ensure("command line parsed", ok); - ensure_equals( - "crashcount", mApp->getOption("crashcount").asInteger(), 2); - ensure_equals( - "space", - mApp->getOption("space").asString(), - std::string("spaceserver.grid.lindenlab.com")); - ensure_equals( - "db_host", - mApp->getOption("db_host").asString(), - std::string("localhost")); - ensure("allowlshlttprequests", mApp->getOption("smtp")); - ensure_equals( - "asset-uri", - mApp->getOption("asset-uri").asString(), - std::string("http://test.lindenlab.com/assets")); - ensure_equals( - "data", - mApp->getOption("data").asString(), - std::string("127.0.0.1")); - ensure("smtp", mApp->getOption("smtp")); - } - - template<> template<> - void application_object_t::test<3>() - { - const int ARGC = 4; - const char* ARGV[ARGC] = - { - "", // argv[0] is usually the application name - "crashcount", - "2", - "--space" - }; - bool ok = mApp->parseCommandOptions(ARGC, const_cast(ARGV)); - ensure("command line parse failure", !ok); - } - - template<> template<> - void application_object_t::test<4>() - { - const int ARGC = 4; - const char* ARGV[ARGC] = - { - "", // argv[0] is usually the application name - "--crashcount", - "2", - "space" - }; - bool ok = mApp->parseCommandOptions(ARGC, const_cast(ARGV)); - ensure("command line parse failure", !ok); - } - - - template<> template<> - void application_object_t::test<5>() - { - LLSD options; - options["boolean-test"] = true; - mApp->setOptionData(LLApp::PRIORITY_GENERAL_CONFIGURATION, options); - ensure("bool set", mApp->getOption("boolean-test").asBoolean()); - options["boolean-test"] = false; - mApp->setOptionData(LLApp::PRIORITY_RUNTIME_OVERRIDE, options); - ensure("bool unset", !mApp->getOption("boolean-test").asBoolean()); - } -} diff --git a/indra/test/llassetuploadqueue_tut.cpp b/indra/test/llassetuploadqueue_tut.cpp deleted file mode 100644 index be5f9e4288..0000000000 --- a/indra/test/llassetuploadqueue_tut.cpp +++ /dev/null @@ -1,195 +0,0 @@ -/** - * @file asset_upload_queue_tut.cpp - * @brief Tests for newview/llassetuploadqueue.cpp - * - * $LicenseInfo:firstyear=2007&license=viewerlgpl$ - * Second Life Viewer Source Code - * Copyright (C) 2010, Linden Research, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; - * version 2.1 of the License only. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA - * $/LicenseInfo$ - */ - -#include "linden_common.h" -#include "lltut.h" - -#include "mock_http_client.h" -#include "../newview/llassetuploadqueue.cpp" - -// Mock implementation. -LLAssetUploadResponder::LLAssetUploadResponder(const LLSD& post_data, - const LLUUID& vfile_id, - LLAssetType::EType asset_type) -{ -} - -LLAssetUploadResponder::LLAssetUploadResponder(const LLSD& post_data, const std::string& file_name) -{ -} - -LLAssetUploadResponder::~LLAssetUploadResponder() -{ -} - -void LLAssetUploadResponder::httpFailure() -{ -} - -void LLAssetUploadResponder::httpSuccess() -{ -} - -void LLAssetUploadResponder::uploadUpload(const LLSD& content) -{ -} - -void LLAssetUploadResponder::uploadComplete(const LLSD& content) -{ -} - -void LLAssetUploadResponder::uploadFailure(const LLSD& content) -{ -} - -LLUpdateTaskInventoryResponder::LLUpdateTaskInventoryResponder(const LLSD& post_data, - const LLUUID& vfile_id, - LLAssetType::EType asset_type) : - LLAssetUploadResponder(post_data, vfile_id, asset_type) -{ -} - -LLUpdateTaskInventoryResponder::LLUpdateTaskInventoryResponder(const LLSD& post_data, - const std::string& file_name) : - LLAssetUploadResponder(post_data, file_name) -{ -} - -LLUpdateTaskInventoryResponder::LLUpdateTaskInventoryResponder(const LLSD& post_data, - const std::string& file_name, - const LLUUID& queue_id) : - LLAssetUploadResponder(post_data, file_name) -{ -} - -void LLUpdateTaskInventoryResponder::uploadComplete(const LLSD& content) -{ -} - -namespace tut -{ - class asset_upload_queue_test_data : public MockHttpClient {}; - typedef test_group asset_upload_queue_test; - typedef asset_upload_queue_test::object asset_upload_queue_object; - tut::asset_upload_queue_test asset_upload_queue("asset_upload_queue"); - - void queue(LLAssetUploadQueue& q, const std::string& filename) - { - LLUUID task_id; - LLUUID item_id; - BOOL is_running = FALSE; - BOOL is_target_mono = TRUE; - LLUUID queue_id; - q.queue(filename, task_id, item_id, is_running, is_target_mono, queue_id); - } - - class LLTestSupplier : public LLAssetUploadQueueSupplier - { - public: - - void set(LLAssetUploadQueue* queue) {mQueue = queue;} - - virtual LLAssetUploadQueue* get() const - { - return mQueue; - } - - private: - LLAssetUploadQueue* mQueue; - }; - - template<> template<> - void asset_upload_queue_object::test<1>() - { - setupTheServer(); - reset(); - LLTestSupplier* supplier = new LLTestSupplier(); - LLAssetUploadQueue q("http://localhost:8888/test/success", supplier); - supplier->set(&q); - queue(q, "foo.bar"); - ensure("upload queue not empty before request", q.isEmpty()); - runThePump(10); - ensure("upload queue not empty after request", q.isEmpty()); - } - - template<> template<> - void asset_upload_queue_object::test<2>() - { - reset(); - LLTestSupplier* supplier = new LLTestSupplier(); - LLAssetUploadQueue q("http://localhost:8888/test/error", supplier); - supplier->set(&q); - queue(q, "foo.bar"); - ensure("upload queue not empty before request", q.isEmpty()); - runThePump(10); - ensure("upload queue not empty after request", q.isEmpty()); - } - - template<> template<> - void asset_upload_queue_object::test<3>() - { - reset(); - LLTestSupplier* supplier = new LLTestSupplier(); - LLAssetUploadQueue q("http://localhost:8888/test/timeout", supplier); - supplier->set(&q); - queue(q, "foo.bar"); - ensure("upload queue not empty before request", q.isEmpty()); - runThePump(10); - ensure("upload queue not empty after request", q.isEmpty()); - } - - template<> template<> - void asset_upload_queue_object::test<4>() - { - reset(); - LLTestSupplier* supplier = new LLTestSupplier(); - LLAssetUploadQueue q("http://localhost:8888/test/success", supplier); - supplier->set(&q); - queue(q, "foo.bar"); - queue(q, "baz.bar"); - ensure("upload queue empty before request", !q.isEmpty()); - runThePump(10); - ensure("upload queue not empty before request", q.isEmpty()); - runThePump(10); - ensure("upload queue not empty after request", q.isEmpty()); - } - - template<> template<> - void asset_upload_queue_object::test<5>() - { - reset(); - LLTestSupplier* supplier = new LLTestSupplier(); - LLAssetUploadQueue q("http://localhost:8888/test/success", supplier); - supplier->set(&q); - queue(q, "foo.bar"); - runThePump(10); - ensure("upload queue not empty before request", q.isEmpty()); - queue(q, "baz.bar"); - ensure("upload queue not empty after request", q.isEmpty()); - runThePump(10); - killServer(); - } -} diff --git a/indra/test/llbuffer_tut.cpp b/indra/test/llbuffer_tut.cpp deleted file mode 100644 index 330a4f288f..0000000000 --- a/indra/test/llbuffer_tut.cpp +++ /dev/null @@ -1,271 +0,0 @@ -/** - * @file llbuffer_tut.cpp - * @author Adroit - * @date 2007-03 - * @brief llbuffer test cases. - * - * $LicenseInfo:firstyear=2007&license=viewerlgpl$ - * Second Life Viewer Source Code - * Copyright (C) 2010, Linden Research, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; - * version 2.1 of the License only. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA - * $/LicenseInfo$ - */ - -#include - -#include "linden_common.h" -#include "lltut.h" -#include "llbuffer.h" -#include "llerror.h" - - -namespace tut -{ - struct buffer - { - }; - - typedef test_group buffer_t; - typedef buffer_t::object buffer_object_t; - tut::buffer_t tut_buffer("buffer"); - - template<> template<> - void buffer_object_t::test<1>() - { - LLChannelDescriptors channelDescriptors; - ensure("in() and out() functions Failed", (0 == channelDescriptors.in() && 1 == channelDescriptors.out())); - - S32 val = 50; - LLChannelDescriptors channelDescriptors1(val); - ensure("LLChannelDescriptors in() and out() functions Failed", (50 == channelDescriptors1.in() && 51 == channelDescriptors1.out())); - } - - template<> template<> - void buffer_object_t::test<2>() - { - LLSegment segment; - ensure("LLSegment get functions failed", (0 == segment.getChannel() && NULL == segment.data() && 0 == segment.size())); - segment.setChannel(50); - ensure_equals("LLSegment setChannel() function failed", segment.getChannel(), 50); - ensure("LLSegment isOnChannel() function failed", (true == segment.isOnChannel(50))); - } - - template<> template<> - void buffer_object_t::test<3>() - { - S32 channel = 30; - const char str[] = "SecondLife"; - S32 len = sizeof(str); - LLSegment segment(channel, (U8*)str, len); - ensure("LLSegment get functions failed", (30 == segment.getChannel() && len == segment.size() && (U8*)str == segment.data())); - ensure_memory_matches("LLSegment::data() failed", segment.data(), segment.size(), (U8*)str, len); - ensure("LLSegment isOnChannel() function failed", (true == segment.isOnChannel(channel))); - } - - template<> template<> - void buffer_object_t::test<4>() - { - S32 channel = 50; - S32 bigSize = 16384*2; - char str[] = "SecondLife"; - S32 smallSize = sizeof(str); - - LLSegment segment; - LLHeapBuffer buf; // use default size of DEFAULT_HEAP_BUFFER_SIZE = 16384 - - S32 requestSize; - - requestSize = 16384-1; - ensure("1. LLHeapBuffer createSegment failed", (true == buf.createSegment(channel, requestSize, segment)) && segment.size() == requestSize); - // second request for remainign 1 byte - - requestSize = 1; - ensure("2. LLHeapBuffer createSegment failed", (true == buf.createSegment(channel, requestSize, segment)) && segment.size() == requestSize); - - // it should fail now. - requestSize = 1; - ensure("3. LLHeapBuffer createSegment failed", (false == buf.createSegment(channel, requestSize, segment))); - - LLHeapBuffer buf1(bigSize); - - // requst for more than default size but less than total sizeit should fail now. - requestSize = 16384 + 1; - ensure("4. LLHeapBuffer createSegment failed", (true == buf1.createSegment(channel, requestSize, segment)) && segment.size() == requestSize); - - LLHeapBuffer buf2((U8*) str, smallSize); - requestSize = smallSize; - ensure("5. LLHeapBuffer createSegment failed", (true == buf2.createSegment(channel, requestSize, segment)) && segment.size() == requestSize && memcmp(segment.data(), (U8*) str, requestSize) == 0); - requestSize = smallSize+1; - ensure("6. LLHeapBuffer createSegment failed", (false == buf2.createSegment(channel, requestSize, segment))); - } - - //makeChannelConsumer() - template<> template<> - void buffer_object_t::test<5>() - { - LLChannelDescriptors inchannelDescriptors(20); - LLChannelDescriptors outchannelDescriptors = LLBufferArray::makeChannelConsumer(inchannelDescriptors); - ensure("LLBufferArray::makeChannelConsumer() function Failed", (21 == outchannelDescriptors.in())); - } - - template<> template<> - void buffer_object_t::test<6>() - { - LLBufferArray bufferArray; - const char array[] = "SecondLife"; - S32 len = static_cast(strlen(array)); - LLChannelDescriptors channelDescriptors = bufferArray.nextChannel(); - bufferArray.append(channelDescriptors.in(), (U8*)array, len); - S32 count = bufferArray.countAfter(channelDescriptors.in(), NULL); - ensure_equals("Appended size is:", count, len); - } - - //append() and prepend() - template<> template<> - void buffer_object_t::test<7>() - { - LLBufferArray bufferArray; - const char array[] = "SecondLife"; - S32 len = static_cast(strlen(array)); - const char array1[] = "LindenLabs"; - S32 len1 = static_cast(strlen(array1)); - - std::string str(array1); - str.append(array); - - LLChannelDescriptors channelDescriptors = bufferArray.nextChannel(); - bufferArray.append(channelDescriptors.in(), (U8*)array, len); - bufferArray.prepend(channelDescriptors.in(), (U8*)array1, len1); - char buf[100]; - S32 len2 = 20; - bufferArray.readAfter(channelDescriptors.in(), NULL, (U8*)buf, len2); - ensure_equals("readAfter length failed", len2, 20); - - buf[len2] = '\0'; - ensure_equals("readAfter/prepend/append failed", buf, str); - } - - //append() - template<> template<> - void buffer_object_t::test<8>() - { - LLBufferArray bufferArray; - const char array[] = "SecondLife"; - S32 len = static_cast(strlen(array)); - const char array1[] = "LindenLabs"; - S32 len1 = static_cast(strlen(array1)); - - std::string str(array); - str.append(array1); - - LLChannelDescriptors channelDescriptors = bufferArray.nextChannel(); - bufferArray.append(channelDescriptors.in(), (U8*)array, len); - bufferArray.append(channelDescriptors.in(), (U8*)array1, len1); - char buf[100]; - S32 len2 = 20; - bufferArray.readAfter(channelDescriptors.in(), NULL, (U8*)buf, len2); - ensure_equals("readAfter length failed", len2, 20); - - buf[len2] = '\0'; - ensure_equals("readAfter/append/append failed", buf, str); - } - - template<> template<> - void buffer_object_t::test<9>() - { - LLBufferArray bufferArray; - const char array[] = "SecondLife"; - S32 len = static_cast(strlen(array)) + 1; - std::string str(array); - LLChannelDescriptors channelDescriptors = bufferArray.nextChannel(); - bufferArray.append(channelDescriptors.in(), (U8*)array, len); - LLBufferArray bufferArray1; - ensure("Contents are not copied and the source buffer is not empty", (1 == bufferArray1.takeContents(bufferArray))); - - char buf[100]; - S32 len2 = len; - bufferArray1.readAfter(channelDescriptors.in(), NULL, (U8*)buf, len2); - ensure_equals("takeContents failed to copy", buf, str); - } - - //seek() - template<> template<> - void buffer_object_t::test<10>() - { - const char array[] = "SecondLife is a Virtual World"; - S32 len = static_cast(strlen(array)); - LLBufferArray bufferArray; - bufferArray.append(0, (U8*)array, len); - - char buf[255]; - S32 len1 = 16; - U8* last = bufferArray.readAfter(0, 0, (U8*)buf, len1); - buf[len1] = '\0'; - last = bufferArray.seek(0, last, -2); - - len1 = 15; - last = bufferArray.readAfter(0, last, (U8*)buf, len1); - buf[len1] = '\0'; - std::string str(buf); - ensure_equals("Seek does'nt worked", str, std::string("a Virtual World")); - } - - template<> template<> - void buffer_object_t::test<11>() - { - const char array[] = "SecondLife is a Virtual World"; - S32 len = static_cast(strlen(array)); - LLBufferArray bufferArray; - bufferArray.append(0, (U8*)array, len); - - char buf[255]; - S32 len1 = 10; - U8* last = bufferArray.readAfter(0, 0, (U8*)buf, len1); - bufferArray.splitAfter(last); - LLBufferArray::segment_iterator_t iterator = bufferArray.beginSegment(); - ++iterator; - std::string str(((char*)(*iterator).data()), (*iterator).size()); - ensure_equals("Strings are not equal;splitAfter() operation failed", str, std::string(" is a Virtual World")); - } - - //makeSegment()->eraseSegment() - template<> template<> - void buffer_object_t::test<12>() - { - LLBufferArray bufferArray; - LLChannelDescriptors channelDescriptors; - LLBufferArray::segment_iterator_t it; - S32 length = 1000; - it = bufferArray.makeSegment(channelDescriptors.out(), length); - ensure("makeSegment() function failed", (it != bufferArray.endSegment())); - ensure("eraseSegment() function failed", bufferArray.eraseSegment(it)); - ensure("eraseSegment() begin/end should now be same", bufferArray.beginSegment() == bufferArray.endSegment()); - } - - // constructSegmentAfter() - template<> template<> - void buffer_object_t::test<13>() - { - LLBufferArray bufferArray; - LLBufferArray::segment_iterator_t it; - LLSegment segment; - LLBufferArray::segment_iterator_t end = bufferArray.endSegment(); - it = bufferArray.constructSegmentAfter(NULL, segment); - ensure("constructSegmentAfter() function failed", (it == end)); - } -} diff --git a/indra/test/lldatapacker_tut.cpp b/indra/test/lldatapacker_tut.cpp deleted file mode 100644 index 2e975ee637..0000000000 --- a/indra/test/lldatapacker_tut.cpp +++ /dev/null @@ -1,570 +0,0 @@ -/** - * @file lldatapacker_tut.cpp - * @author Adroit - * @date 2007-02 - * @brief LLDataPacker test cases. - * - * $LicenseInfo:firstyear=2007&license=viewerlgpl$ - * Second Life Viewer Source Code - * Copyright (C) 2010, Linden Research, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; - * version 2.1 of the License only. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA - * $/LicenseInfo$ - */ - -#include -#include "lltut.h" -#include "linden_common.h" -#include "lldatapacker.h" -#include "v4color.h" -#include "v4coloru.h" -#include "v2math.h" -#include "v3math.h" -#include "v4math.h" -#include "llsdserialize.h" - -#define TEST_FILE_NAME "datapacker_test.txt" -namespace tut -{ - struct datapacker_test - { - }; - typedef test_group datapacker_test_t; - typedef datapacker_test_t::object datapacker_test_object_t; - tut::datapacker_test_t tut_datapacker_test("datapacker_test"); - - //*********LLDataPackerBinaryBuffer - template<> template<> - void datapacker_test_object_t::test<1>() - { - U8 packbuf[128]; - F32 f_val1 = 44.44f, f_unpkval1; - F32 f_val2 = 12344.443232f, f_unpkval2; - F32 f_val3 = 44.4456789f, f_unpkval3; - LLDataPackerBinaryBuffer lldp(packbuf,128); - lldp.packFixed( f_val1, "linden_lab", FALSE, 8, 8); - lldp.packFixed( f_val2, "linden_lab", FALSE, 14, 16); - lldp.packFixed( f_val3, "linden_lab", FALSE, 8, 23); - - LLDataPackerBinaryBuffer lldp1(packbuf, lldp.getCurrentSize()); - lldp1.unpackFixed(f_unpkval1, "linden_lab", FALSE, 8, 8); - lldp1.unpackFixed(f_unpkval2, "linden_lab", FALSE, 14, 16); - lldp1.unpackFixed(f_unpkval3, "linden_lab", FALSE, 8, 23); - ensure_approximately_equals("LLDataPackerBinaryBuffer::packFixed 8 failed", f_val1, f_unpkval1, 8); - ensure_approximately_equals("LLDataPackerBinaryBuffer::packFixed 16 failed", f_val2, f_unpkval2, 16); - ensure_approximately_equals("LLDataPackerBinaryBuffer::packFixed 23 failed", f_val3, f_unpkval3, 31); - } - - template<> template<> - void datapacker_test_object_t::test<2>() - { - U8 packbuf[1024]; - - char str[] = "SecondLife is virtual World\0"; - char strBinary[] = "SecondLife is virtual World"; - char strBinaryFixed[] = "Fixed Data"; - S32 sizeBinaryFixed = sizeof(strBinaryFixed); - U8 valU8 = 'C'; - U16 valU16 = 0xFFFF; - U32 valU32 = 0xFFFFFFFF; - S32 valS32 = -94967295; - F32 valF32 = 4354355.44f ; - LLColor4 llcol4(3.3f, 0, 4.4f, 5.5f); - LLColor4U llcol4u(3, 128, 24, 33); - LLVector2 llvec2(333.33f, 444.44f); - LLVector3 llvec3(333.33f, 444.44f, 555.55f); - LLVector4 llvec4(333.33f, 444.44f, 555.55f, 666.66f); - LLUUID uuid; - - std::string unpkstr; - char unpkstrBinary[256]; - char unpkstrBinaryFixed[256]; - S32 unpksizeBinary; - U8 unpkvalU8; - U16 unpkvalU16; - U32 unpkvalU32; - S32 unpkvalS32; - F32 unpkvalF32; - LLColor4 unpkllcol4; - LLColor4U unpkllcol4u; - LLVector2 unpkllvec2; - LLVector3 unpkllvec3; - LLVector4 unpkllvec4; - LLUUID unpkuuid; - - LLDataPackerBinaryBuffer lldp(packbuf,1024); - lldp.packString(str , "linden_lab_str"); - lldp.packBinaryData((U8*)strBinary, sizeof(strBinary), "linden_lab_bd"); - lldp.packBinaryDataFixed((U8*)strBinaryFixed, sizeBinaryFixed, "linden_lab_bdf"); - lldp.packU8(valU8,"linden_lab_u8"); - lldp.packU16(valU16,"linden_lab_u16"); - lldp.packU32(valU32, "linden_lab_u32"); - lldp.packS32(valS32, "linden_lab_s32"); - lldp.packF32(valF32, "linden_lab_f32"); - lldp.packColor4(llcol4, "linden_lab_col4"); - lldp.packColor4U(llcol4u, "linden_lab_col4u"); - lldp.packVector2(llvec2, "linden_lab_vec2"); - lldp.packVector3(llvec3, "linden_lab_vec3"); - lldp.packVector4(llvec4, "linden_lab_vec4"); - uuid.generate(); - lldp.packUUID(uuid, "linden_lab_uuid"); - - S32 cur_size = lldp.getCurrentSize(); - - LLDataPackerBinaryBuffer lldp1(packbuf, cur_size); - lldp1.unpackString(unpkstr , "linden_lab_str"); - lldp1.unpackBinaryData((U8*)unpkstrBinary, unpksizeBinary, "linden_lab_bd"); - lldp1.unpackBinaryDataFixed((U8*)unpkstrBinaryFixed, sizeBinaryFixed, "linden_lab_bdf"); - lldp1.unpackU8(unpkvalU8,"linden_lab_u8"); - lldp1.unpackU16(unpkvalU16,"linden_lab_u16"); - lldp1.unpackU32(unpkvalU32, "linden_lab_u32"); - lldp1.unpackS32(unpkvalS32, "linden_lab_s32"); - lldp1.unpackF32(unpkvalF32, "linden_lab_f32"); - lldp1.unpackColor4(unpkllcol4, "linden_lab_col4"); - lldp1.unpackColor4U(unpkllcol4u, "linden_lab_col4u"); - lldp1.unpackVector2(unpkllvec2, "linden_lab_vec2"); - lldp1.unpackVector3(unpkllvec3, "linden_lab_vec3"); - lldp1.unpackVector4(unpkllvec4, "linden_lab_vec4"); - lldp1.unpackUUID(unpkuuid, "linden_lab_uuid"); - - ensure("LLDataPackerBinaryBuffer::packString failed", strcmp(str, unpkstr.c_str()) == 0); - ensure("LLDataPackerBinaryBuffer::packBinaryData failed", strcmp(strBinary, unpkstrBinary) == 0); - ensure("LLDataPackerBinaryBuffer::packBinaryDataFixed failed", strcmp(strBinaryFixed, unpkstrBinaryFixed) == 0); - ensure_equals("LLDataPackerBinaryBuffer::packU8 failed", valU8, unpkvalU8); - ensure_equals("LLDataPackerBinaryBuffer::packU16 failed", valU16, unpkvalU16); - ensure_equals("LLDataPackerBinaryBuffer::packU32 failed", valU32, unpkvalU32); - ensure_equals("LLDataPackerBinaryBuffer::packS32 failed", valS32, unpkvalS32); - ensure("LLDataPackerBinaryBuffer::packF32 failed", is_approx_equal(valF32, unpkvalF32)); - ensure_equals("LLDataPackerBinaryBuffer::packColor4 failed", llcol4, unpkllcol4); - ensure_equals("LLDataPackerBinaryBuffer::packColor4U failed", llcol4u, unpkllcol4u); - ensure_equals("LLDataPackerBinaryBuffer::packVector2 failed", llvec2, unpkllvec2); - ensure_equals("LLDataPackerBinaryBuffer::packVector3 failed", llvec3, unpkllvec3); - ensure_equals("LLDataPackerBinaryBuffer::packVector4 failed", llvec4, unpkllvec4); - ensure_equals("LLDataPackerBinaryBuffer::packUUID failed", uuid, unpkuuid); - } - - template<> template<> - void datapacker_test_object_t::test<3>() - { - U8 packbuf[128]; - char str[] = "SecondLife is virtual World"; - S32 strSize = sizeof(str); // include '\0' - LLDataPackerBinaryBuffer lldp(packbuf, 128); - lldp.packString(str , "linden_lab"); - - ensure("LLDataPackerBinaryBuffer: current size is wrong", strSize == lldp.getCurrentSize()); - ensure("LLDataPackerBinaryBuffer: buffer size is wrong", 128 == lldp.getBufferSize()); - - lldp.reset(); - ensure("LLDataPackerBinaryBuffer::reset failed",0 == lldp.getCurrentSize()); - } - - template<> template<> - void datapacker_test_object_t::test<4>() - { - U8* packbuf = new U8[128]; - char str[] = "SecondLife is virtual World"; - LLDataPackerBinaryBuffer lldp(packbuf, 128); - lldp.packString(str , "linden_lab"); - lldp.freeBuffer(); - ensure("LLDataPackerBinaryBuffer.freeBuffer failed" , 0 == lldp.getBufferSize()); - - } - - template<> template<> - void datapacker_test_object_t::test<5>() - { - U8 buf[] = "SecondLife is virtual World"; - S32 size = sizeof(buf); - LLDataPackerBinaryBuffer lldp(buf, size); - U8 new_buf[] = "Its Amazing"; - size = sizeof(new_buf); - lldp.assignBuffer(new_buf, size); - ensure("LLDataPackerBinaryBuffer::assignBuffer failed" , ((lldp.getBufferSize() == size) && (0 == lldp.getCurrentSize()))) ; - } - - template<> template<> - void datapacker_test_object_t::test<6>() - { - U8 packbuf[128]; - char str[] = "SecondLife is virtual World"; - LLDataPackerBinaryBuffer lldp(packbuf, 128); - lldp.packString(str , "linden_lab"); - U8 new_buffer[128]; - std::string unpkbuf; - LLDataPackerBinaryBuffer lldp1(new_buffer,128); - lldp1 = lldp; - lldp1.unpackString(unpkbuf, "linden_lab"); - ensure("1. LLDataPackerBinaryBuffer::operator= failed" , lldp1.getBufferSize() == lldp.getBufferSize()); - ensure_equals("2.LLDataPackerBinaryBuffer::operator= failed", str,unpkbuf); - } - - //*********LLDataPackerAsciiBuffer - - template<> template<> - void datapacker_test_object_t::test<7>() - { - char packbuf[128]; - F32 f_val = 44.44f, f_unpkval; - LLDataPackerAsciiBuffer lldp(packbuf,128); - lldp.packFixed( f_val, "linden_lab", FALSE, 8, 8); - - LLDataPackerAsciiBuffer lldp1(packbuf, lldp.getCurrentSize()); - lldp1.unpackFixed(f_unpkval, "linden_lab", FALSE, 8, 8); - ensure_approximately_equals("LLDataPackerAsciiBuffer::packFixed failed", f_val, f_unpkval, 8); - } - - template<> template<> - void datapacker_test_object_t::test<8>() - { - char packbuf[1024]; - - char str[] = "SecondLife is virtual World\0"; - char strBinary[] = "SecondLife is virtual World"; - char strBinaryFixed[] = "Fixed Data"; - S32 sizeBinaryFixed = sizeof(strBinaryFixed); - U8 valU8 = 'C'; - U16 valU16 = 0xFFFF; - U32 valU32 = 0xFFFFFFFF; - S32 valS32 = -94967295; - F32 valF32 = 4354355.44f ; - LLColor4 llcol4(3.3f, 0, 4.4f, 5.5f); - LLColor4U llcol4u(3, 128, 24, 33); - LLVector2 llvec2(333.33f, 444.44f); - LLVector3 llvec3(333.33f, 444.44f, 555.55f); - LLVector4 llvec4(4354355.44f, 444.44f, 555.55f, 666.66f); - LLUUID uuid; - - std::string unpkstr; - char unpkstrBinary[256]; - char unpkstrBinaryFixed[256]; - S32 unpksizeBinary; - U8 unpkvalU8; - U16 unpkvalU16; - U32 unpkvalU32; - S32 unpkvalS32; - F32 unpkvalF32; - LLColor4 unpkllcol4; - LLColor4U unpkllcol4u; - LLVector2 unpkllvec2; - LLVector3 unpkllvec3; - LLVector4 unpkllvec4; - LLUUID unpkuuid; - - LLDataPackerAsciiBuffer lldp(packbuf,1024); - lldp.packString(str , "linden_lab_str"); - lldp.packBinaryData((U8*)strBinary, sizeof(strBinary), "linden_lab_bd"); - lldp.packBinaryDataFixed((U8*)strBinaryFixed, sizeBinaryFixed, "linden_lab_bdf"); - lldp.packU8(valU8,"linden_lab_u8"); - lldp.packU16(valU16,"linden_lab_u16"); - lldp.packU32(valU32, "linden_lab_u32"); - lldp.packS32(valS32, "linden_lab_s32"); - lldp.packF32(valF32, "linden_lab_f32"); - lldp.packColor4(llcol4, "linden_lab_col4"); - lldp.packColor4U(llcol4u, "linden_lab_col4u"); - lldp.packVector2(llvec2, "linden_lab_vec2"); - lldp.packVector3(llvec3, "linden_lab_vec3"); - lldp.packVector4(llvec4, "linden_lab_vec4"); - uuid.generate(); - lldp.packUUID(uuid, "linden_lab_uuid"); - - S32 cur_size = lldp.getCurrentSize(); - - LLDataPackerAsciiBuffer lldp1(packbuf, cur_size); - lldp1.unpackString(unpkstr , "linden_lab_str"); - lldp1.unpackBinaryData((U8*)unpkstrBinary, unpksizeBinary, "linden_lab_bd"); - lldp1.unpackBinaryDataFixed((U8*)unpkstrBinaryFixed, sizeBinaryFixed, "linden_lab_bdf"); - lldp1.unpackU8(unpkvalU8,"linden_lab_u8"); - lldp1.unpackU16(unpkvalU16,"linden_lab_u16"); - lldp1.unpackU32(unpkvalU32, "linden_lab_u32"); - lldp1.unpackS32(unpkvalS32, "linden_lab_s32"); - lldp1.unpackF32(unpkvalF32, "linden_lab_f32"); - lldp1.unpackColor4(unpkllcol4, "linden_lab_col4"); - lldp1.unpackColor4U(unpkllcol4u, "linden_lab_col4u"); - lldp1.unpackVector2(unpkllvec2, "linden_lab_vec2"); - lldp1.unpackVector3(unpkllvec3, "linden_lab_vec3"); - lldp1.unpackVector4(unpkllvec4, "linden_lab_vec4"); - lldp1.unpackUUID(unpkuuid, "linden_lab_uuid"); - - ensure("LLDataPackerAsciiBuffer::packString failed", strcmp(str, unpkstr.c_str()) == 0); - ensure("LLDataPackerAsciiBuffer::packBinaryData failed", strcmp(strBinary, unpkstrBinary) == 0); - ensure("LLDataPackerAsciiBuffer::packBinaryDataFixed failed", strcmp(strBinaryFixed, unpkstrBinaryFixed) == 0); - ensure_equals("LLDataPackerAsciiBuffer::packU8 failed", valU8, unpkvalU8); - ensure_equals("LLDataPackerAsciiBuffer::packU16 failed", valU16, unpkvalU16); - ensure_equals("LLDataPackerAsciiBuffer::packU32 failed", valU32, unpkvalU32); - ensure_equals("LLDataPackerAsciiBuffer::packS32 failed", valS32, unpkvalS32); - ensure("LLDataPackerAsciiBuffer::packF32 failed", is_approx_equal(valF32, unpkvalF32)); - ensure_equals("LLDataPackerAsciiBuffer::packColor4 failed", llcol4, unpkllcol4); - ensure_equals("LLDataPackerAsciiBuffer::packColor4U failed", llcol4u, unpkllcol4u); - ensure_equals("LLDataPackerAsciiBuffer::packVector2 failed", llvec2, unpkllvec2); - ensure_equals("LLDataPackerAsciiBuffer::packVector3 failed", llvec3, unpkllvec3); - ensure_equals("LLDataPackerAsciiBuffer::packVector4 failed", llvec4, unpkllvec4); - ensure_equals("LLDataPackerAsciiBuffer::packUUID failed", uuid, unpkuuid); - } - - template<> template<> - void datapacker_test_object_t::test<9>() - { - char* packbuf = new char[128]; - char str[] = "SecondLife is virtual World"; - LLDataPackerAsciiBuffer lldp(packbuf, 128); - lldp.packString(str , "linden_lab"); - lldp.freeBuffer(); - ensure("LLDataPackerAsciiBuffer::freeBuffer failed" , 0 == lldp.getBufferSize()); - } - - template<> template<> - void datapacker_test_object_t::test<10>() - { - char buf[] = "SecondLife is virtual World"; - S32 size = sizeof(buf); - LLDataPackerAsciiBuffer lldp(buf, size); - char new_buf[] = "Its Amazing"; - size = sizeof(new_buf); - lldp.assignBuffer(new_buf, size); - ensure("LLDataPackerAsciiBuffer::assignBuffer failed" , ((lldp.getBufferSize() == size) && (1 == lldp.getCurrentSize()))) ; - } - - //*********LLDataPackerAsciiFile - - template<> template<> - void datapacker_test_object_t::test<11>() - { - F32 f_val = 44.44f, f_unpkval; - - LLFILE* fp = LLFile::fopen(TEST_FILE_NAME, "w+"); - if(!fp) - { - LL_ERRS() << "File couldnt be open" << LL_ENDL; - return; - } - - LLDataPackerAsciiFile lldp(fp,2); - lldp.packFixed( f_val, "linden_lab", FALSE, 8, 8); - - fflush(fp); - fseek(fp,0,SEEK_SET); - LLDataPackerAsciiFile lldp1(fp,2); - - lldp1.unpackFixed(f_unpkval, "linden_lab", FALSE, 8, 8); - fclose(fp); - - ensure_approximately_equals("LLDataPackerAsciiFile::packFixed failed", f_val, f_unpkval, 8); - } - - template<> template<> - void datapacker_test_object_t::test<12>() - { - char str[] = "SecondLife is virtual World\0"; - char strBinary[] = "SecondLife is virtual World"; - char strBinaryFixed[] = "Fixed Data"; - S32 sizeBinaryFixed = sizeof(strBinaryFixed); - U8 valU8 = 'C'; - U16 valU16 = 0xFFFF; - U32 valU32 = 0xFFFFFFFF; - S32 valS32 = -94967295; - F32 valF32 = 4354355.44f ; - LLColor4 llcol4(3.3f, 0, 4.4f, 5.5f); - LLColor4U llcol4u(3, 128, 24, 33); - LLVector2 llvec2(333.33f, 444.44f); - LLVector3 llvec3(333.33f, 444.44f, 555.55f); - LLVector4 llvec4(333.33f, 444.44f, 555.55f, 666.66f); - LLUUID uuid; - - std::string unpkstr; - char unpkstrBinary[256]; - char unpkstrBinaryFixed[256]; - S32 unpksizeBinary; - U8 unpkvalU8; - U16 unpkvalU16; - U32 unpkvalU32; - S32 unpkvalS32; - F32 unpkvalF32; - LLColor4 unpkllcol4; - LLColor4U unpkllcol4u; - LLVector2 unpkllvec2; - LLVector3 unpkllvec3; - LLVector4 unpkllvec4; - LLUUID unpkuuid; - - LLFILE* fp = LLFile::fopen(TEST_FILE_NAME,"w+"); - if(!fp) - { - LL_ERRS() << "File couldnt be open" << LL_ENDL; - return; - } - - LLDataPackerAsciiFile lldp(fp,2); - - lldp.packString(str , "linden_lab_str"); - lldp.packBinaryData((U8*)strBinary, sizeof(strBinary), "linden_lab_bd"); - lldp.packBinaryDataFixed((U8*)strBinaryFixed, sizeBinaryFixed, "linden_lab_bdf"); - lldp.packU8(valU8,"linden_lab_u8"); - lldp.packU16(valU16,"linden_lab_u16"); - lldp.packU32(valU32, "linden_lab_u32"); - lldp.packS32(valS32, "linden_lab_s32"); - lldp.packF32(valF32, "linden_lab_f32"); - lldp.packColor4(llcol4, "linden_lab_col4"); - lldp.packColor4U(llcol4u, "linden_lab_col4u"); - lldp.packVector2(llvec2, "linden_lab_vec2"); - lldp.packVector3(llvec3, "linden_lab_vec3"); - lldp.packVector4(llvec4, "linden_lab_vec4"); - uuid.generate(); - lldp.packUUID(uuid, "linden_lab_uuid"); - - fflush(fp); - fseek(fp,0,SEEK_SET); - LLDataPackerAsciiFile lldp1(fp,2); - - lldp1.unpackString(unpkstr , "linden_lab_str"); - lldp1.unpackBinaryData((U8*)unpkstrBinary, unpksizeBinary, "linden_lab_bd"); - lldp1.unpackBinaryDataFixed((U8*)unpkstrBinaryFixed, sizeBinaryFixed, "linden_lab_bdf"); - lldp1.unpackU8(unpkvalU8,"linden_lab_u8"); - lldp1.unpackU16(unpkvalU16,"linden_lab_u16"); - lldp1.unpackU32(unpkvalU32, "linden_lab_u32"); - lldp1.unpackS32(unpkvalS32, "linden_lab_s32"); - lldp1.unpackF32(unpkvalF32, "linden_lab_f32"); - lldp1.unpackColor4(unpkllcol4, "linden_lab_col4"); - lldp1.unpackColor4U(unpkllcol4u, "linden_lab_col4u"); - lldp1.unpackVector2(unpkllvec2, "linden_lab_vec2"); - lldp1.unpackVector3(unpkllvec3, "linden_lab_vec3"); - lldp1.unpackVector4(unpkllvec4, "linden_lab_vec4"); - lldp1.unpackUUID(unpkuuid, "linden_lab_uuid"); - - fclose(fp); - - ensure("LLDataPackerAsciiFile::packString failed", strcmp(str, unpkstr.c_str()) == 0); - ensure("LLDataPackerAsciiFile::packBinaryData failed", strcmp(strBinary, unpkstrBinary) == 0); - ensure("LLDataPackerAsciiFile::packBinaryDataFixed failed", strcmp(strBinaryFixed, unpkstrBinaryFixed) == 0); - ensure_equals("LLDataPackerAsciiFile::packU8 failed", valU8, unpkvalU8); - ensure_equals("LLDataPackerAsciiFile::packU16 failed", valU16, unpkvalU16); - ensure_equals("LLDataPackerAsciiFile::packU32 failed", valU32, unpkvalU32); - ensure_equals("LLDataPackerAsciiFile::packS32 failed", valS32, unpkvalS32); - ensure("LLDataPackerAsciiFile::packF32 failed", is_approx_equal(valF32, unpkvalF32)); - ensure_equals("LLDataPackerAsciiFile::packColor4 failed", llcol4, unpkllcol4); - ensure_equals("LLDataPackerAsciiFile::packColor4U failed", llcol4u, unpkllcol4u); - ensure_equals("LLDataPackerAsciiFile::packVector2 failed", llvec2, unpkllvec2); - ensure_equals("LLDataPackerAsciiFile::packVector3 failed", llvec3, unpkllvec3); - ensure_equals("LLDataPackerAsciiFile::packVector4 failed", llvec4, unpkllvec4); - ensure_equals("LLDataPackerAsciiFile::packUUID failed", uuid, unpkuuid); - } - - template<> template<> - void datapacker_test_object_t::test<13>() - { - F32 f_val = 44.44f, f_unpkval; - - std::ostringstream ostr; - LLDataPackerAsciiFile lldp(ostr,2); - lldp.packFixed( f_val, "linden_lab", FALSE, 8, 8); - - std::istringstream istr(ostr.str()); - LLDataPackerAsciiFile lldp1(istr,2); - - lldp1.unpackFixed(f_unpkval, "linden_lab", FALSE, 8, 8); - - ensure_approximately_equals("LLDataPackerAsciiFile::packFixed (iostring) failed", f_val, f_unpkval, 8); - } - - template<> template<> - void datapacker_test_object_t::test<14>() - { - char str[] = "SecondLife is virtual World\0"; - char strBinary[] = "SecondLife is virtual World"; - char strBinaryFixed[] = "Fixed Data"; - S32 sizeBinaryFixed = sizeof(strBinaryFixed); - U8 valU8 = 'C'; - U16 valU16 = 0xFFFF; - U32 valU32 = 0xFFFFFFFF; - S32 valS32 = -94967295; - F32 valF32 = 4354355.44f ; - LLColor4 llcol4(3.3f, 0, 4.4f, 5.5f); - LLColor4U llcol4u(3, 128, 24, 33); - LLVector2 llvec2(3333333.33f, 444.333344f); - LLVector3 llvec3(3323233.33f, 444.4324f, 555.553232f); - LLVector4 llvec4(333.33233f, 444.4323234f, 55323225.55f, 6323236.66f); - LLUUID uuid; - - std::string unpkstr; - char unpkstrBinary[256]; - char unpkstrBinaryFixed[256]; - S32 unpksizeBinary; - U8 unpkvalU8; - U16 unpkvalU16; - U32 unpkvalU32; - S32 unpkvalS32; - F32 unpkvalF32; - LLColor4 unpkllcol4; - LLColor4U unpkllcol4u; - LLVector2 unpkllvec2; - LLVector3 unpkllvec3; - LLVector4 unpkllvec4; - LLUUID unpkuuid; - - std::ostringstream ostr; - LLDataPackerAsciiFile lldp(ostr,2); - - lldp.packString(str , "linden_lab_str"); - lldp.packBinaryData((U8*)strBinary, sizeof(strBinary), "linden_lab_bd"); - lldp.packBinaryDataFixed((U8*)strBinaryFixed, sizeBinaryFixed, "linden_lab_bdf"); - lldp.packU8(valU8,"linden_lab_u8"); - lldp.packU16(valU16,"linden_lab_u16"); - lldp.packU32(valU32, "linden_lab_u32"); - lldp.packS32(valS32, "linden_lab_s32"); - lldp.packF32(valF32, "linden_lab_f32"); - lldp.packColor4(llcol4, "linden_lab_col4"); - lldp.packColor4U(llcol4u, "linden_lab_col4u"); - lldp.packVector2(llvec2, "linden_lab_vec2"); - lldp.packVector3(llvec3, "linden_lab_vec3"); - lldp.packVector4(llvec4, "linden_lab_vec4"); - uuid.generate(); - lldp.packUUID(uuid, "linden_lab_uuid"); - - std::istringstream istr(ostr.str()); - LLDataPackerAsciiFile lldp1(istr,2); - - lldp1.unpackString(unpkstr , "linden_lab_str"); - lldp1.unpackBinaryData((U8*)unpkstrBinary, unpksizeBinary, "linden_lab_bd"); - lldp1.unpackBinaryDataFixed((U8*)unpkstrBinaryFixed, sizeBinaryFixed, "linden_lab_bdf"); - lldp1.unpackU8(unpkvalU8,"linden_lab_u8"); - lldp1.unpackU16(unpkvalU16,"linden_lab_u16"); - lldp1.unpackU32(unpkvalU32, "linden_lab_u32"); - lldp1.unpackS32(unpkvalS32, "linden_lab_s32"); - lldp1.unpackF32(unpkvalF32, "linden_lab_f32"); - lldp1.unpackColor4(unpkllcol4, "linden_lab_col4"); - lldp1.unpackColor4U(unpkllcol4u, "linden_lab_col4u"); - lldp1.unpackVector2(unpkllvec2, "linden_lab_vec2"); - lldp1.unpackVector3(unpkllvec3, "linden_lab_vec3"); - lldp1.unpackVector4(unpkllvec4, "linden_lab_vec4"); - lldp1.unpackUUID(unpkuuid, "linden_lab_uuid"); - - ensure("LLDataPackerAsciiFile::packString (iostring) failed", strcmp(str, unpkstr.c_str()) == 0); - ensure("LLDataPackerAsciiFile::packBinaryData (iostring) failed", strcmp(strBinary, unpkstrBinary) == 0); - ensure("LLDataPackerAsciiFile::packBinaryDataFixed (iostring) failed", strcmp(strBinaryFixed, unpkstrBinaryFixed) == 0); - ensure_equals("LLDataPackerAsciiFile::packU8 (iostring) failed", valU8, unpkvalU8); - ensure_equals("LLDataPackerAsciiFile::packU16 (iostring) failed", valU16, unpkvalU16); - ensure_equals("LLDataPackerAsciiFile::packU32 (iostring) failed", valU32, unpkvalU32); - ensure_equals("LLDataPackerAsciiFile::packS32 (iostring) failed", valS32, unpkvalS32); - ensure("LLDataPackerAsciiFile::packF32 (iostring) failed", is_approx_equal(valF32, unpkvalF32)); - ensure_equals("LLDataPackerAsciiFile::packColor4 (iostring) failed", llcol4, unpkllcol4); - ensure_equals("LLDataPackerAsciiFile::packColor4U (iostring) failed", llcol4u, unpkllcol4u); - ensure_equals("LLDataPackerAsciiFile::packVector2 (iostring) failed", llvec2, unpkllvec2); - ensure_equals("LLDataPackerAsciiFile::packVector3 (iostring) failed", llvec3, unpkllvec3); - ensure_equals("LLDataPackerAsciiFile::packVector4 (iostring) failed", llvec4, unpkllvec4); - ensure_equals("LLDataPackerAsciiFile::packUUID (iostring) failed", uuid, unpkuuid); - } -} diff --git a/indra/test/lldoubledispatch_tut.cpp b/indra/test/lldoubledispatch_tut.cpp deleted file mode 100644 index 79c4edc058..0000000000 --- a/indra/test/lldoubledispatch_tut.cpp +++ /dev/null @@ -1,240 +0,0 @@ -/** - * @file lldoubledispatch_tut.cpp - * @author Nat Goodspeed - * @date 2008-11-13 - * @brief Test for lldoubledispatch.h - * - * This program tests the DoubleDispatch class, using a variation on the example - * from Scott Meyers' "More Effective C++", Item 31. - * - * $LicenseInfo:firstyear=2008&license=viewerlgpl$ - * Second Life Viewer Source Code - * Copyright (C) 2010, Linden Research, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; - * version 2.1 of the License only. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA - * $/LicenseInfo$ - */ - -// Precompiled header -#include "linden_common.h" -// associated header -#include "lldoubledispatch.h" -// STL headers -// std headers -#include -#include -#include -#include -// external library headers -// other Linden headers -#include "lltut.h" - - -/*---------------------------- Class hierarchy -----------------------------*/ -// All objects are GameObjects. -class GameObject -{ -public: - GameObject(const std::string& name): mName(name) {} - virtual ~GameObject() {} - virtual std::string stringize() { return std::string(typeid(*this).name()) + " " + mName; } - -protected: - std::string mName; -}; - -// SpaceStation, Asteroid and SpaceShip are peer GameObjects. -struct SpaceStation: public GameObject -{ - SpaceStation(const std::string& name): GameObject(name) {} - // Only a dummy SpaceStation is constructed without a name - SpaceStation(): GameObject("dummy") {} -}; - -struct Asteroid: public GameObject -{ - Asteroid(const std::string& name): GameObject(name) {} - Asteroid(): GameObject("dummy") {} -}; - -struct SpaceShip: public GameObject -{ - SpaceShip(const std::string& name): GameObject(name) {} - SpaceShip(): GameObject("dummy") {} -}; - -// SpaceShip is specialized further into CommercialShip and MilitaryShip. -struct CommercialShip: public SpaceShip -{ - CommercialShip(const std::string& name): SpaceShip(name) {} - CommercialShip(): SpaceShip("dummy") {} -}; - -struct MilitaryShip: public SpaceShip -{ - MilitaryShip(const std::string& name): SpaceShip(name) {} - MilitaryShip(): SpaceShip("dummy") {} -}; - -/*-------------------------- Collision functions ---------------------------*/ -// This mechanism permits us to overcome a limitation of Meyers' approach: we -// can declare the parameter types exactly as we want, rather than having to -// make them all GameObject& parameters. -std::string shipAsteroid(SpaceShip& ship, Asteroid& rock) -{ -// std::cout << rock.stringize() << " has pulverized " << ship.stringize() << std::endl; - return "shipAsteroid"; -} - -std::string militaryShipAsteroid(MilitaryShip& ship, Asteroid& rock) -{ -// std::cout << rock.stringize() << " has severely damaged " << ship.stringize() << std::endl; - return "militaryShipAsteroid"; -} - -std::string shipStation(SpaceShip& ship, SpaceStation& dock) -{ -// std::cout << ship.stringize() << " has docked at " << dock.stringize() << std::endl; - return "shipStation"; -} - -std::string asteroidStation(Asteroid& rock, SpaceStation& dock) -{ -// std::cout << rock.stringize() << " has damaged " << dock.stringize() << std::endl; - return "asteroidStation"; -} - -/*------------------------------- Test code --------------------------------*/ -namespace tut -{ - struct dispatch_data - { - dispatch_data(): - home(new SpaceStation("Terra Station")), - obstacle(new Asteroid("Ganymede")), - tug(new CommercialShip("Pilotfish")), - patrol(new MilitaryShip("Enterprise")) - {} - - // Instantiate and populate the DoubleDispatch object. - typedef LLDoubleDispatch DD; - DD dispatcher; - - // Instantiate a few GameObjects. Make sure we refer to them - // polymorphically, and don't let them leak. - std::unique_ptr home; - std::unique_ptr obstacle; - std::unique_ptr tug; - std::unique_ptr patrol; - - // prototype objects - Asteroid dummyAsteroid; - SpaceShip dummyShip; - MilitaryShip dummyMilitary; - CommercialShip dummyCommercial; - SpaceStation dummyStation; - }; - typedef test_group dispatch_group; - typedef dispatch_group::object dispatch_object; - tut::dispatch_group ddgr("double dispatch"); - - template<> template<> - void dispatch_object::test<1>() - { - // Describe param types using explicit DD::Type objects - // (order-sensitive add() variant) - dispatcher.add(DD::Type(), DD::Type(), shipAsteroid, true); - // naive adding, won't work - dispatcher.add(DD::Type(), DD::Type(), militaryShipAsteroid, true); - dispatcher.add(DD::Type(), DD::Type(), shipStation, true); - dispatcher.add(DD::Type(), DD::Type(), asteroidStation, true); - - // Try colliding them. - ensure_equals(dispatcher(*home, *tug), // reverse params, SpaceShip subclass - "shipStation"); - ensure_equals(dispatcher(*patrol, *home), // forward params, SpaceShip subclass - "shipStation"); - ensure_equals(dispatcher(*obstacle, *home), // forward params - "asteroidStation"); - ensure_equals(dispatcher(*home, *obstacle), // reverse params - "asteroidStation"); - ensure_equals(dispatcher(*tug, *obstacle), // forward params, SpaceShip subclass - "shipAsteroid"); - ensure_equals(dispatcher(*obstacle, *patrol), // reverse params, SpaceShip subclass - // won't use militaryShipAsteroid() because it was added - // in wrong order - "shipAsteroid"); - } - - template<> template<> - void dispatch_object::test<2>() - { - // Describe param types using explicit DD::Type objects - // (order-sensitive add() variant) - // adding in correct order - dispatcher.add(DD::Type(), DD::Type(), militaryShipAsteroid, true); - dispatcher.add(DD::Type(), DD::Type(), shipAsteroid, true); - dispatcher.add(DD::Type(), DD::Type(), shipStation, true); - dispatcher.add(DD::Type(), DD::Type(), asteroidStation, true); - - ensure_equals(dispatcher(*patrol, *obstacle), "militaryShipAsteroid"); - ensure_equals(dispatcher(*tug, *obstacle), "shipAsteroid"); - } - - template<> template<> - void dispatch_object::test<3>() - { - // Describe param types with actual prototype instances - // (order-insensitive add() variant) - dispatcher.add(dummyMilitary, dummyAsteroid, militaryShipAsteroid); - dispatcher.add(dummyShip, dummyAsteroid, shipAsteroid); - dispatcher.add(dummyShip, dummyStation, shipStation); - dispatcher.add(dummyAsteroid, dummyStation, asteroidStation); - - ensure_equals(dispatcher(*patrol, *obstacle), "militaryShipAsteroid"); - ensure_equals(dispatcher(*tug, *obstacle), "shipAsteroid"); - ensure_equals(dispatcher(*obstacle, *patrol), ""); - } - - template<> template<> - void dispatch_object::test<4>() - { - // Describe param types with actual prototype instances - // (order-insensitive add() variant) - dispatcher.add(dummyShip, dummyAsteroid, shipAsteroid); - // Even if we add the militaryShipAsteroid in the wrong order, it - // should still work. - dispatcher.add(dummyMilitary, dummyAsteroid, militaryShipAsteroid); - dispatcher.add(dummyShip, dummyStation, shipStation); - dispatcher.add(dummyAsteroid, dummyStation, asteroidStation); - - ensure_equals(dispatcher(*patrol, *obstacle), "militaryShipAsteroid"); - ensure_equals(dispatcher(*tug, *obstacle), "shipAsteroid"); - } - - template<> template<> - void dispatch_object::test<5>() - { - dispatcher.add(shipAsteroid); - dispatcher.add(militaryShipAsteroid); - dispatcher.add(shipStation); - dispatcher.add(asteroidStation); - - ensure_equals(dispatcher(*patrol, *obstacle), "militaryShipAsteroid"); - ensure_equals(dispatcher(*tug, *obstacle), "shipAsteroid"); - } -} // namespace tut diff --git a/indra/test/llevents_tut.cpp b/indra/test/llevents_tut.cpp deleted file mode 100644 index c5d5dcb9d4..0000000000 --- a/indra/test/llevents_tut.cpp +++ /dev/null @@ -1,506 +0,0 @@ -/** - * @file llevents_tut.cpp - * @author Nat Goodspeed - * @date 2008-09-12 - * @brief Test of llevents.h - * - * $LicenseInfo:firstyear=2008&license=viewerlgpl$ - * Second Life Viewer Source Code - * Copyright (C) 2010, Linden Research, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; - * version 2.1 of the License only. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA - * $/LicenseInfo$ - */ - -#if LL_WINDOWS -#pragma warning (disable : 4675) // "resolved by ADL" -- just as I want! -#endif - -// Precompiled header -#include "linden_common.h" -// associated header -// UGLY HACK! We want to verify state internal to the classes without -// providing public accessors. -#define testable public -#include "llevents.h" -#undef testable -// STL headers -// std headers -#include -#include -// external library headers -#include -// other Linden headers -#include "tests/listener.h" // must PRECEDE lltut.h -#include "lltut.h" -#include "catch_and_store_what_in.h" -#include "stringize.h" - -template -T make(const T& value) -{ - return value; -} - -/***************************************************************************** - * tut test group - *****************************************************************************/ -namespace tut -{ -struct events_data -{ - events_data() : - pumps(LLEventPumps::instance()), - listener0("first"), - listener1("second") - { - } - LLEventPumps& pumps; - Listener listener0; - Listener listener1; - - void check_listener(const std::string& desc, const Listener& listener, LLSD::Integer got) - { - ensure_equals(STRINGIZE(listener << ' ' << desc), - listener.getLastEvent().asInteger(), got); - } -}; -typedef test_group events_group; -typedef events_group::object events_object; -tut::events_group evgr("events"); - -template<> template<> -void events_object::test<1>() -{ - set_test_name("basic operations"); - // Having to modify this to track the statically- - // constructed pumps in other TUT modules in this giant monolithic test - // executable isn't such a hot idea. - // ensure_equals("initial pump", pumps.mPumpMap.size(), 1); - size_t initial_pumps(pumps.mPumpMap.size()); - LLEventPump& per_frame(pumps.obtain("per-frame")); - ensure_equals("first explicit pump", pumps.mPumpMap.size(), initial_pumps + 1); - // Verify that per_frame was instantiated as an LLEventStream. - ensure("LLEventStream leaf class", dynamic_cast (&per_frame)); - ensure("enabled", per_frame.enabled()); - // Trivial test, but posting an event to an EventPump with no - // listeners should not blow up. The test is relevant because defining - // a boost::signal with a non-void return signature, using the default - // combiner, blows up if there are no listeners. This is because the - // default combiner is defined to return the value returned by the - // last listener, which is meaningless if there were no listeners. - per_frame.post(0); - LLBoundListener connection = listener0.listenTo(per_frame); - ensure("connected", connection.connected()); - ensure("not blocked", !connection.blocked()); - per_frame.post(1); - check_listener("received", listener0, 1); - { // block the connection - LLEventPump::Blocker block(connection); - ensure("blocked", connection.blocked()); - per_frame.post(2); - check_listener("not updated", listener0, 1); - } // unblock - ensure("unblocked", !connection.blocked()); - per_frame.post(3); - check_listener("unblocked", listener0, 3); - LLBoundListener sameConnection = per_frame.getListener(listener0.getName()); - ensure("still connected", sameConnection.connected()); - ensure("still not blocked", !sameConnection.blocked()); - { // block it again - LLEventPump::Blocker block(sameConnection); - ensure("re-blocked", sameConnection.blocked()); - per_frame.post(4); - check_listener("re-blocked", listener0, 3); - } // unblock - std::string threw = catch_what( - [&per_frame, this](){ - // NOTE: boost::bind() saves its arguments by VALUE! If you pass - // an object instance rather than a pointer, you'll end up binding - // to an internal copy of that instance! Use boost::ref() to - // capture a reference instead. - per_frame.listen(listener0.getName(), // note bug, dup name - boost::bind(&Listener::call, boost::ref(listener1), _1)); - }); - ensure_equals(threw, - std::string("DupListenerName: " - "Attempt to register duplicate listener name '") + - listener0.getName() + "' on " + typeid(per_frame).name() + - " '" + per_frame.getName() + "'"); - // do it right this time - listener1.listenTo(per_frame); - per_frame.post(5); - check_listener("got", listener0, 5); - check_listener("got", listener1, 5); - per_frame.enable(false); - per_frame.post(6); - check_listener("didn't get", listener0, 5); - check_listener("didn't get", listener1, 5); - per_frame.enable(); - per_frame.post(7); - check_listener("got", listener0, 7); - check_listener("got", listener1, 7); - per_frame.stopListening(listener0.getName()); - ensure("disconnected 0", ! connection.connected()); - ensure("disconnected 1", ! sameConnection.connected()); - per_frame.post(8); - check_listener("disconnected", listener0, 7); - check_listener("still connected", listener1, 8); - per_frame.stopListening(listener1.getName()); - per_frame.post(9); - check_listener("disconnected", listener1, 8); -} - -template<> template<> -void events_object::test<2>() -{ - set_test_name("callstop() returning true"); - LLEventPump& per_frame(pumps.obtain("per-frame")); - listener0.reset(0); - listener1.reset(0); - LLBoundListener bound0 = listener0.listenTo(per_frame, &Listener::callstop); - LLBoundListener bound1 = listener1.listenTo(per_frame, &Listener::call, - // after listener0 - make(LLEventPump::NameList{ listener0.getName() })); - ensure("enabled", per_frame.enabled()); - ensure("connected 0", bound0.connected()); - ensure("unblocked 0", !bound0.blocked()); - ensure("connected 1", bound1.connected()); - ensure("unblocked 1", !bound1.blocked()); - per_frame.post(1); - check_listener("got", listener0, 1); - // Because listener0.callstop() returns true, control never reaches listener1.call(). - check_listener("got", listener1, 0); -} - -bool chainEvents(Listener& someListener, const LLSD& event) -{ - // Make this call so we can watch for side effects for test purposes. - someListener.call(event); - // This function represents a recursive event chain -- or some other - // scenario in which an event handler raises additional events. - int value = event.asInteger(); - if (value) - { - LLEventPumps::instance().obtain("login").post(value - 1); - } - return false; -} - -template<> template<> -void events_object::test<3>() -{ - set_test_name("explicitly-instantiated LLEventStream"); - // Explicitly instantiate an LLEventStream, and verify that it - // self-registers with LLEventPumps - size_t registered = pumps.mPumpMap.size(); - size_t owned = pumps.mOurPumps.size(); - LLEventPump* localInstance; - { - LLEventStream myEventStream("stream"); - localInstance = &myEventStream; - LLEventPump& stream(pumps.obtain("stream")); - ensure("found named LLEventStream instance", &stream == localInstance); - ensure_equals("registered new instance", pumps.mPumpMap.size(), registered + 1); - ensure_equals("explicit instance not owned", pumps.mOurPumps.size(), owned); - } // destroy myEventStream -- should unregister - ensure_equals("destroyed instance unregistered", pumps.mPumpMap.size(), registered); - ensure_equals("destroyed instance not owned", pumps.mOurPumps.size(), owned); - LLEventPump& stream(pumps.obtain("stream")); - ensure("new LLEventStream instance", &stream != localInstance); - ensure_equals("obtain()ed instance registered", pumps.mPumpMap.size(), registered + 1); - ensure_equals("obtain()ed instance owned", pumps.mOurPumps.size(), owned + 1); -} - -template<> template<> -void events_object::test<4>() -{ - set_test_name("stopListening()"); - LLEventPump& login(pumps.obtain("login")); - listener0.listenTo(login); - login.stopListening(listener0.getName()); - // should not throw because stopListening() should have removed name - listener0.listenTo(login, &Listener::callstop); - LLBoundListener wrong = login.getListener("bogus"); - ensure("bogus connection disconnected", !wrong.connected()); - ensure("bogus connection blocked", wrong.blocked()); -} - -template<> template<> -void events_object::test<5>() -{ - set_test_name("chaining LLEventPump instances"); - LLEventPump& upstream(pumps.obtain("upstream")); - // One potentially-useful construct is to chain LLEventPumps together. - // Among other things, this allows you to turn subsets of listeners on - // and off in groups. - LLEventPump& filter0(pumps.obtain("filter0")); - LLEventPump& filter1(pumps.obtain("filter1")); - upstream.listen(filter0.getName(), boost::bind(&LLEventPump::post, boost::ref(filter0), _1)); - upstream.listen(filter1.getName(), boost::bind(&LLEventPump::post, boost::ref(filter1), _1)); - listener0.listenTo(filter0); - listener1.listenTo(filter1); - listener0.reset(0); - listener1.reset(0); - upstream.post(1); - check_listener("got unfiltered", listener0, 1); - check_listener("got unfiltered", listener1, 1); - filter0.enable(false); - upstream.post(2); - check_listener("didn't get filtered", listener0, 1); - check_listener("got filtered", listener1, 2); -} - -template<> template<> -void events_object::test<6>() -{ - set_test_name("listener dependency order"); - typedef LLEventPump::NameList NameList; - LLEventPump& button(pumps.obtain("button")); - Collect collector; - button.listen("Mary", - boost::bind(&Collect::add, boost::ref(collector), "Mary", _1), - // state that "Mary" must come after "checked" - make(NameList{ "checked" })); - button.listen("checked", - boost::bind(&Collect::add, boost::ref(collector), "checked", _1), - // "checked" must come after "spot" - make(NameList{ "spot" })); - button.listen("spot", - boost::bind(&Collect::add, boost::ref(collector), "spot", _1)); - button.post(1); - ensure_equals(collector.result, make(StringVec{ "spot", "checked", "Mary" })); - collector.clear(); - button.stopListening("Mary"); - button.listen("Mary", - boost::bind(&Collect::add, boost::ref(collector), "Mary", _1), - LLEventPump::empty, // no after dependencies - // now "Mary" must come before "spot" - make(NameList{ "spot" })); - button.post(2); - ensure_equals(collector.result, make(StringVec{ "Mary", "spot", "checked" })); - collector.clear(); - button.stopListening("spot"); - std::string threw = catch_what( - [&button, &collector](){ - button.listen("spot", - boost::bind(&Collect::add, boost::ref(collector), "spot", _1), - // after "Mary" and "checked" -- whoops! - make(NameList{ "Mary", "checked" })); - }); - // Obviously the specific wording of the exception text can - // change; go ahead and change the test to match. - // Establish that it contains: - // - the name and runtime type of the LLEventPump - ensure_contains("LLEventPump type", threw, typeid(button).name()); - ensure_contains("LLEventPump name", threw, "'button'"); - // - the name of the new listener that caused the problem - ensure_contains("new listener name", threw, "'spot'"); - // - a synopsis of the problematic dependencies. - ensure_contains("cyclic dependencies", threw, - "\"Mary\" -> before (\"spot\")"); - ensure_contains("cyclic dependencies", threw, - "after (\"spot\") -> \"checked\""); - ensure_contains("cyclic dependencies", threw, - "after (\"Mary\", \"checked\") -> \"spot\""); - button.listen("yellow", - boost::bind(&Collect::add, boost::ref(collector), "yellow", _1), make(NameList{ "checked" })); - button.listen("shoelaces", - boost::bind(&Collect::add, boost::ref(collector), "shoelaces", _1), make(NameList{ "checked" })); - button.post(3); - ensure_equals(collector.result, make(StringVec{ "Mary", "checked", "yellow", "shoelaces" })); - collector.clear(); - threw = catch_what( - [&button, &collector](){ - button.listen("of", - boost::bind(&Collect::add, boost::ref(collector), "of", _1), - make(NameList{ "shoelaces" }), - make(NameList{ "yellow" })); - }); - // Same remarks about the specific wording of the exception. Just - // ensure that it contains enough information to clarify the - // problem and what must be done to resolve it. - ensure_contains("LLEventPump type", threw, typeid(button).name()); - ensure_contains("LLEventPump name", threw, "'button'"); - ensure_contains("new listener name", threw, "'of'"); - ensure_contains("prev listener name", threw, "'yellow'"); - // std::cout << "Thrown Exception: " << threw << std::endl; - ensure_contains("old order", threw, "was: Mary, checked, yellow, shoelaces"); - ensure_contains("new order", threw, "now: Mary, checked, shoelaces, of, yellow"); - button.post(4); - ensure_equals(collector.result, make(StringVec{ "Mary", "checked", "yellow", "shoelaces" })); -} - -template<> template<> -void events_object::test<7>() -{ - set_test_name("tweaked and untweaked LLEventPump instance names"); - { // nested scope - // Hand-instantiate an LLEventStream... - LLEventStream bob("bob"); - std::string threw = catch_what( - [](){ - // then another with a duplicate name. - LLEventStream bob2("bob"); - }); - ensure("Caught DupPumpName", !threw.empty()); - } // delete first 'bob' - LLEventStream bob("bob"); // should work, previous one unregistered - LLEventStream bob1("bob", true);// allowed to tweak name - ensure_equals("tweaked LLEventStream name", bob1.getName(), "bob1"); - std::vector > streams; - for (int i = 2; i <= 10; ++i) - { - streams.push_back(std::shared_ptr(new LLEventStream("bob", true))); - } - ensure_equals("last tweaked LLEventStream name", streams.back()->getName(), "bob10"); -} - -// Define a function that accepts an LLListenerOrPumpName -void eventSource(const LLListenerOrPumpName& listener) -{ - // Pretend that some time has elapsed. Call listener immediately. - listener(17); -} - -template<> template<> -void events_object::test<8>() -{ - set_test_name("LLListenerOrPumpName"); - // Passing a boost::bind() expression to LLListenerOrPumpName - listener0.reset(0); - eventSource(boost::bind(&Listener::call, boost::ref(listener0), _1)); - check_listener("got by listener", listener0, 17); - // Passing a string LLEventPump name to LLListenerOrPumpName - listener0.reset(0); - LLEventStream random("random"); - listener0.listenTo(random); - eventSource("random"); - check_listener("got by pump name", listener0, 17); - std::string threw = catch_what( - [](){ - LLListenerOrPumpName empty; - empty(17); - }); - - ensure("threw Empty", !threw.empty()); -} - -class TempListener: public Listener -{ -public: - TempListener(const std::string& name, bool& liveFlag) : - Listener(name), mLiveFlag(liveFlag) - { - mLiveFlag = true; - } - - virtual ~TempListener() - { - mLiveFlag = false; - } - -private: - bool& mLiveFlag; -}; - -template<> template<> -void events_object::test<9>() -{ - set_test_name("listen(boost::bind(...TempListener...))"); - // listen() can't do anything about a plain TempListener instance: - // it's not managed with shared_ptr, nor is it an LLEventTrackable subclass - bool live = false; - LLEventPump& heaptest(pumps.obtain("heaptest")); - LLBoundListener connection; - { - TempListener tempListener("temp", live); - ensure("TempListener constructed", live); - connection = heaptest.listen(tempListener.getName(), - boost::bind(&Listener::call, - boost::ref(tempListener), - _1)); - heaptest.post(1); - check_listener("received", tempListener, 1); - } // presumably this will make newListener go away? - // verify that - ensure("TempListener destroyed", !live); - // This is the case against which we can't defend. Don't even try to - // post to heaptest -- that would engage Undefined Behavior. - // Cautiously inspect connection... - ensure("misleadingly connected", connection.connected()); - // then disconnect by hand. - heaptest.stopListening("temp"); -} - -class TempTrackableListener: public TempListener, public LLEventTrackable -{ -public: - TempTrackableListener(const std::string& name, bool& liveFlag): - TempListener(name, liveFlag) - {} -}; - -template<> template<> -void events_object::test<10>() -{ - set_test_name("listen(boost::bind(...TempTrackableListener ref...))"); - bool live = false; - LLEventPump& heaptest(pumps.obtain("heaptest")); - LLBoundListener connection; - { - TempTrackableListener tempListener("temp", live); - ensure("TempTrackableListener constructed", live); - connection = heaptest.listen(tempListener.getName(), - boost::bind(&TempTrackableListener::call, - boost::ref(tempListener), _1)); - heaptest.post(1); - check_listener("received", tempListener, 1); - } // presumably this will make tempListener go away? - // verify that - ensure("TempTrackableListener destroyed", ! live); - ensure("implicit disconnect", ! connection.connected()); - // now just make sure we don't blow up trying to access a freed object! - heaptest.post(2); -} - -template<> template<> -void events_object::test<11>() -{ - set_test_name("listen(boost::bind(...TempTrackableListener pointer...))"); - bool live = false; - LLEventPump& heaptest(pumps.obtain("heaptest")); - LLBoundListener connection; - { - TempTrackableListener* newListener(new TempTrackableListener("temp", live)); - ensure("TempTrackableListener constructed", live); - connection = heaptest.listen(newListener->getName(), - boost::bind(&TempTrackableListener::call, - newListener, _1)); - heaptest.post(1); - check_listener("received", *newListener, 1); - // explicitly destroy newListener - delete newListener; - } - // verify that - ensure("TempTrackableListener destroyed", ! live); - ensure("implicit disconnect", ! connection.connected()); - // now just make sure we don't blow up trying to access a freed object! - heaptest.post(2); -} - -} // namespace tut diff --git a/indra/test/llhttpdate_tut.cpp b/indra/test/llhttpdate_tut.cpp deleted file mode 100644 index b580b09a9f..0000000000 --- a/indra/test/llhttpdate_tut.cpp +++ /dev/null @@ -1,162 +0,0 @@ -/** - * @file llhttpdate_tut.cpp - * @author Kartic Krishnamurthy - * @date Wednesday, 18 Jul 2007 17:00:00 GMT :) - * - * $LicenseInfo:firstyear=2007&license=viewerlgpl$ - * Second Life Viewer Source Code - * Copyright (C) 2010, Linden Research, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; - * version 2.1 of the License only. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA - * $/LicenseInfo$ - */ - -#include "linden_common.h" -#include "lltut.h" - -#include "lldate.h" -#include "llcommon.h" -#include "llframetimer.h" - -#include -#include - -namespace tut -{ - struct httpdate_data - { - httpdate_data() - { - } - ~httpdate_data() - { - } - LLDate some_date; - }; - typedef test_group httpdate_test; - typedef httpdate_test::object httpdate_object; - tut::httpdate_test httpdate("httpdate"); - - template<> template<> - void httpdate_object::test<1>() - { - - static std::string epoch_expected = "Thursday, 01 Jan 1970 00:00:00 GMT" ; - ensure("Check Epoch in RFC 1123", ( epoch_expected == some_date.asRFC1123())); - } - - template<> template<> - void httpdate_object::test<2>() - { - - static std::string expected = "Wednesday, 18 Jul 2007 22:17:24 GMT" ; - some_date = LLDate(1184797044.037586); - ensure("Check some timestamp in RFC 1123", ( expected == some_date.asRFC1123())); - } - - // This test of course most generic.. runs off current time - template<> template<> - void httpdate_object::test<3>() - { - - //F64 sometime = LLFrameTimer::getTotalSeconds(); - time_t sometime; - time(&sometime); - some_date = LLDate((F64) sometime); - struct tm *result; - char expected[255]; - std::string actual; - - result = gmtime(&sometime); - /* - std::cout << " seconds: "<< result->tm_sec - << ", minutes: " << result->tm_min - << ", hours: " << result->tm_hour - << ", day of the month: " << result->tm_mday - << ", month: " << result->tm_mon - << ", year: " << result->tm_year - << ", day of the week: " << result->tm_wday - << ", day in the year: " << result->tm_yday - << ", DST: " << result->tm_isdst << std::endl; - */ - strftime(expected, 255, "%A, %d %b %Y %H:%M:%S GMT", result); - actual = some_date.asRFC1123(); - // probably not a good idea to use strcmp but this is just a unit test - ensure("Current time in RFC 1123", (strcmp(expected, actual.c_str()) == 0)); - } - - void test_date_string(const std::string &locale, struct tm *t, - const std::string &fmt, const std::string &expected) - { - std::string result = LLDate::toHTTPDateString(t, fmt); - LLStringUtil::toLower(result); - std::string label = std::string("toHTTPDateString - ") + locale; - ensure_equals(label.c_str(), result, expected); - } - - template<> template<> - void httpdate_object::test<4>() - { - // test localization of http dates - const char *en_locale = "en_US.UTF-8"; - const char *fr_locale = "fr_FR.UTF-8"; - - std::string prev_locale = LLStringUtil::getLocale(); - std::string prev_clocale = std::string(setlocale(LC_TIME, NULL)); - time_t test_time = 1252374030; // 8 Sep 2009 01:40:01 - struct tm *t = gmtime(&test_time); - - setlocale(LC_TIME, en_locale); - if (strcmp(setlocale(LC_TIME, NULL), en_locale) != 0) - { - setlocale(LC_TIME, prev_clocale.c_str()); - skip("Cannot set English locale"); - } - - LLStringUtil::setLocale(en_locale); - test_date_string(en_locale, t, "%d %B %Y - %H:%M", "08 september 2009 - 01:40"); - test_date_string(en_locale, t, "%H", "01"); - test_date_string(en_locale, t, "%M", "40"); - test_date_string(en_locale, t, "%I", "01"); - test_date_string(en_locale, t, "%d", "08"); - test_date_string(en_locale, t, "%Y", "2009"); - test_date_string(en_locale, t, "%p", "am"); - test_date_string(en_locale, t, "%A", "tuesday"); - test_date_string(en_locale, t, "%B", "september"); - - setlocale(LC_TIME, fr_locale); - if (strcmp(setlocale(LC_TIME, NULL), fr_locale) != 0) - { - LLStringUtil::setLocale(prev_locale); - setlocale(LC_TIME, prev_clocale.c_str()); - skip("Cannot set French locale"); - } - - LLStringUtil::setLocale(fr_locale); - test_date_string(fr_locale, t, "%d %B %Y - %H:%M", "08 septembre 2009 - 01:40"); - test_date_string(fr_locale, t, "%H", "01"); - test_date_string(fr_locale, t, "%M", "40"); - test_date_string(fr_locale, t, "%I", "01"); - test_date_string(fr_locale, t, "%d", "08"); - test_date_string(fr_locale, t, "%Y", "2009"); - test_date_string(fr_locale, t, "%A", "mardi"); - test_date_string(fr_locale, t, "%B", "septembre"); - - LLStringUtil::setLocale(prev_locale); - setlocale(LC_TIME, prev_clocale.c_str()); - } -} diff --git a/indra/test/llhttpnode_tut.cpp b/indra/test/llhttpnode_tut.cpp deleted file mode 100644 index c38dee120b..0000000000 --- a/indra/test/llhttpnode_tut.cpp +++ /dev/null @@ -1,428 +0,0 @@ -/** - * @file lliohttpnode_tut.cpp - * @date May 2006 - * @brief HTTP server unit tests - * - * $LicenseInfo:firstyear=2006&license=viewerlgpl$ - * Second Life Viewer Source Code - * Copyright (C) 2010, Linden Research, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; - * version 2.1 of the License only. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA - * $/LicenseInfo$ - */ - -#include "linden_common.h" -#include "lltut.h" -#include "llhttpnode.h" -#include "llsdhttpserver.h" - -namespace tut -{ - struct HTTPNodeTestData - { - LLHTTPNode mRoot; - LLSD mContext; - - const LLSD& context() { return mContext; } - - std::string remainderPath() - { - std::ostringstream pathOutput; - bool addSlash = false; - - LLSD& remainder = mContext[CONTEXT_REQUEST]["remainder"]; - for (LLSD::array_const_iterator i = remainder.beginArray(); - i != remainder.endArray(); - ++i) - { - if (addSlash) { pathOutput << '/'; } - pathOutput << i->asString(); - addSlash = true; - } - - return pathOutput.str(); - } - - void ensureRootTraversal(const std::string& path, - const LLHTTPNode* expectedNode, - const char* expectedRemainder) - { - mContext.clear(); - - const LLHTTPNode* actualNode = mRoot.traverse(path, mContext); - - ensure_equals("traverse " + path + " node", - actualNode, expectedNode); - ensure_equals("traverse " + path + " remainder", - remainderPath(), expectedRemainder); - } - - class Response : public LLHTTPNode::Response - { - public: - static LLPointer create() {return new Response();} - - LLSD mResult; - - void result(const LLSD& result) { mResult = result; } - void status(S32 code, const std::string& message) { } - void extendedResult(S32 code, const std::string& message, const LLSD& headers) { } - void extendedResult(S32 code, const LLSD& result, const LLSD& headers) { } - - private: - Response() {;} // Must be accessed through LLPointer. - }; - - typedef LLPointer ResponsePtr; - - LLSD get(const std::string& path) - { - mContext.clear(); - const LLHTTPNode* node = mRoot.traverse(path, mContext); - ensure(path + " found", node != NULL); - - ResponsePtr response = Response::create(); - node->get(LLHTTPNode::ResponsePtr(response), mContext); - return response->mResult; - } - - LLSD post(const std::string& path, const LLSD& input) - { - mContext.clear(); - const LLHTTPNode* node = mRoot.traverse(path, mContext); - ensure(path + " found", node != NULL); - - ResponsePtr response = Response::create(); - node->post(LLHTTPNode::ResponsePtr(response), mContext, input); - return response->mResult; - } - - void ensureMemberString(const std::string& name, - const LLSD& actualMap, const std::string& member, - const std::string& expectedValue) - { - ensure_equals(name + " " + member, - actualMap[member].asString(), expectedValue); - } - - - void ensureInArray(const LLSD& actualArray, - const std::string& expectedValue) - { - LLSD::array_const_iterator i = actualArray.beginArray(); - LLSD::array_const_iterator end = actualArray.endArray(); - - for (; i != end; ++i) - { - std::string path = i->asString(); - - if (path == expectedValue) - { - return; - } - } - - fail("didn't find " + expectedValue); - } - - }; - - typedef test_group HTTPNodeTestGroup; - typedef HTTPNodeTestGroup::object HTTPNodeTestObject; - HTTPNodeTestGroup httpNodeTestGroup("http node"); - - template<> template<> - void HTTPNodeTestObject::test<1>() - { - // traversal of the lone node - - ensureRootTraversal("", &mRoot, ""); - ensureRootTraversal("/", &mRoot, ""); - ensureRootTraversal("foo", NULL, "foo"); - ensureRootTraversal("foo/bar", NULL, "foo/bar"); - - ensure_equals("root of root", mRoot.rootNode(), &mRoot); - } - - template<> template<> - void HTTPNodeTestObject::test<2>() - { - // simple traversal of a single node - - LLHTTPNode* helloNode = new LLHTTPNode; - mRoot.addNode("hello", helloNode); - - ensureRootTraversal("hello", helloNode, ""); - ensureRootTraversal("/hello", helloNode, ""); - ensureRootTraversal("hello/", helloNode, ""); - ensureRootTraversal("/hello/", helloNode, ""); - - ensureRootTraversal("hello/there", NULL, "there"); - - ensure_equals("root of hello", helloNode->rootNode(), &mRoot); - } - - template<> template<> - void HTTPNodeTestObject::test<3>() - { - // traversal of mutli-branched tree - - LLHTTPNode* greekNode = new LLHTTPNode; - LLHTTPNode* alphaNode = new LLHTTPNode; - LLHTTPNode* betaNode = new LLHTTPNode; - LLHTTPNode* gammaNode = new LLHTTPNode; - - greekNode->addNode("alpha", alphaNode); - greekNode->addNode("beta", betaNode); - greekNode->addNode("gamma", gammaNode); - mRoot.addNode("greek", greekNode); - - LLHTTPNode* hebrewNode = new LLHTTPNode; - LLHTTPNode* alephNode = new LLHTTPNode; - - hebrewNode->addNode("aleph", alephNode); - mRoot.addNode("hebrew", hebrewNode); - - ensureRootTraversal("greek/alpha", alphaNode, ""); - ensureRootTraversal("greek/beta", betaNode, ""); - ensureRootTraversal("greek/delta", NULL, "delta"); - ensureRootTraversal("greek/gamma", gammaNode, ""); - ensureRootTraversal("hebrew/aleph", alephNode, ""); - - ensure_equals("root of greek", greekNode->rootNode(), &mRoot); - ensure_equals("root of alpha", alphaNode->rootNode(), &mRoot); - ensure_equals("root of beta", betaNode->rootNode(), &mRoot); - ensure_equals("root of gamma", gammaNode->rootNode(), &mRoot); - ensure_equals("root of hebrew", hebrewNode->rootNode(), &mRoot); - ensure_equals("root of aleph", alephNode->rootNode(), &mRoot); - } - - template<> template<> - void HTTPNodeTestObject::test<4>() - { - // automatic creation of parent nodes and not overriding existing nodes - - LLHTTPNode* alphaNode = new LLHTTPNode; - LLHTTPNode* betaNode = new LLHTTPNode; - LLHTTPNode* gammaNode = new LLHTTPNode; - LLHTTPNode* gamma2Node = new LLHTTPNode; - - mRoot.addNode("greek/alpha", alphaNode); - mRoot.addNode("greek/beta", betaNode); - - mRoot.addNode("greek/gamma", gammaNode); - mRoot.addNode("greek/gamma", gamma2Node); - - LLHTTPNode* alephNode = new LLHTTPNode; - - mRoot.addNode("hebrew/aleph", alephNode); - - ensureRootTraversal("greek/alpha", alphaNode, ""); - ensureRootTraversal("greek/beta", betaNode, ""); - ensureRootTraversal("greek/delta", NULL, "delta"); - ensureRootTraversal("greek/gamma", gammaNode, ""); - ensureRootTraversal("hebrew/aleph", alephNode, ""); - - ensure_equals("root of alpha", alphaNode->rootNode(), &mRoot); - ensure_equals("root of beta", betaNode->rootNode(), &mRoot); - ensure_equals("root of gamma", gammaNode->rootNode(), &mRoot); - ensure_equals("root of aleph", alephNode->rootNode(), &mRoot); - } - - class IntegerNode : public LLHTTPNode - { - public: - virtual void get(ResponsePtr response, const LLSD& context) const - { - int n = context["extra"]["value"]; - - LLSD info; - info["value"] = n; - info["positive"] = n > 0; - info["zero"] = n == 0; - info["negative"] = n < 0; - - response->result(info); - } - - virtual bool validate(const std::string& name, LLSD& context) const - { - int n; - std::istringstream i_stream(name); - i_stream >> n; - - if (i_stream.fail() || i_stream.get() != EOF) - { - return false; - } - - context["extra"]["value"] = n; - return true; - } - }; - - class SquareNode : public LLHTTPNode - { - public: - virtual void get(ResponsePtr response, const LLSD& context) const - { - int n = context["extra"]["value"]; - response->result(n*n); - } - }; - - template<> template<> - void HTTPNodeTestObject::test<5>() - { - // wildcard nodes - - LLHTTPNode* miscNode = new LLHTTPNode; - LLHTTPNode* iNode = new IntegerNode; - LLHTTPNode* sqNode = new SquareNode; - - mRoot.addNode("test/misc", miscNode); - mRoot.addNode("test/", iNode); - mRoot.addNode("test//square", sqNode); - - ensureRootTraversal("test/42", iNode, ""); - ensure_equals("stored integer", - context()["extra"]["value"].asInteger(), 42); - - ensureRootTraversal("test/bob", NULL, "bob"); - ensure("nothing stored", - context()["extra"]["value"].isUndefined()); - - ensureRootTraversal("test/3/square", sqNode, ""); - ResponsePtr response = Response::create(); - sqNode->get(LLHTTPNode::ResponsePtr(response), context()); - ensure_equals("square result", response->mResult.asInteger(), 9); - } - - class AlphaNode : public LLHTTPNode - { - public: - virtual bool handles(const LLSD& remainder, LLSD& context) const - { - LLSD::array_const_iterator i = remainder.beginArray(); - LLSD::array_const_iterator end = remainder.endArray(); - - for (; i != end; ++i) - { - std::string s = i->asString(); - if (s.empty() || s[0] != 'a') - { - return false; - } - } - - return true; - } - }; - - template<> template<> - void HTTPNodeTestObject::test<6>() - { - // nodes that handle remainders - - LLHTTPNode* miscNode = new LLHTTPNode; - LLHTTPNode* aNode = new AlphaNode; - LLHTTPNode* zNode = new LLHTTPNode; - - mRoot.addNode("test/misc", miscNode); - mRoot.addNode("test/alpha", aNode); - mRoot.addNode("test/alpha/zebra", zNode); - - ensureRootTraversal("test/alpha", aNode, ""); - ensureRootTraversal("test/alpha/abe", aNode, "abe"); - ensureRootTraversal("test/alpha/abe/amy", aNode, "abe/amy"); - ensureRootTraversal("test/alpha/abe/bea", NULL, "abe/bea"); - ensureRootTraversal("test/alpha/bob", NULL, "bob"); - ensureRootTraversal("test/alpha/zebra", zNode, ""); - } - - template<> template<> - void HTTPNodeTestObject::test<7>() - { - // test auto registration - - LLHTTPStandardServices::useServices(); - LLHTTPRegistrar::buildAllServices(mRoot); - - { - LLSD result = get("web/hello"); - ensure_equals("hello result", result.asString(), "hello"); - } - { - LLSD stuff = 3.14159; - LLSD result = post("web/echo", stuff); - ensure_equals("echo result", result, stuff); - } - } - - template<> template<> - void HTTPNodeTestObject::test<8>() - { - // test introspection - - LLHTTPRegistrar::buildAllServices(mRoot); - - mRoot.addNode("test/misc", new LLHTTPNode); - mRoot.addNode("test/", new IntegerNode); - mRoot.addNode("test//square", new SquareNode); - - const LLSD result = get("web/server/api"); - - ensure("result is array", result.isArray()); - ensure("result size", result.size() >= 2); - - ensureInArray(result, "web/echo"); - ensureInArray(result, "web/hello"); - ensureInArray(result, "test/misc"); - ensureInArray(result, "test/"); - ensureInArray(result, "test//square"); - } - - template<> template<> - void HTTPNodeTestObject::test<9>() - { - // test introspection details - - LLHTTPRegistrar::buildAllServices(mRoot); - - const LLSD helloDetails = get("web/server/api/web/hello"); - - ensure_contains("hello description", - helloDetails["description"].asString(), "hello"); - ensure_equals("method name", helloDetails["api"][0].asString(), std::string("GET")); - ensureMemberString("hello", helloDetails, "output", "\"hello\""); - ensure_contains("hello __file__", - helloDetails["__file__"].asString(), "llsdhttpserver.cpp"); - ensure("hello line", helloDetails["__line__"].isInteger()); - - - const LLSD echoDetails = get("web/server/api/web/echo"); - - ensure_contains("echo description", - echoDetails["description"].asString(), "echo"); - ensure_equals("method name", echoDetails["api"][0].asString(), std::string("POST")); - ensureMemberString("echo", echoDetails, "input", ""); - ensureMemberString("echo", echoDetails, "output", ""); - ensure_contains("echo __file__", - echoDetails["__file__"].asString(), "llsdhttpserver.cpp"); - ensure("echo", echoDetails["__line__"].isInteger()); - } -} diff --git a/indra/test/lliohttpserver_tut.cpp b/indra/test/lliohttpserver_tut.cpp deleted file mode 100644 index 7034f4a063..0000000000 --- a/indra/test/lliohttpserver_tut.cpp +++ /dev/null @@ -1,350 +0,0 @@ -/** - * @file lliohttpserver_tut.cpp - * @date May 2006 - * @brief HTTP server unit tests - * - * $LicenseInfo:firstyear=2006&license=viewerlgpl$ - * Second Life Viewer Source Code - * Copyright (C) 2010, Linden Research, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; - * version 2.1 of the License only. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA - * $/LicenseInfo$ - */ - -#include "linden_common.h" -#include "lltut.h" -#include "llbufferstream.h" -#include "lliohttpserver.h" -#include "llsdhttpserver.h" -#include "llsdserialize.h" -#include "llcommon.h" - -#include "llpipeutil.h" - - -namespace tut -{ - class HTTPServiceTestData - { - public: - class DelayedEcho : public LLHTTPNode - { - HTTPServiceTestData* mTester; - - public: - DelayedEcho(HTTPServiceTestData* tester) : mTester(tester) { } - - void post(ResponsePtr response, const LLSD& context, const LLSD& input) const - { - ensure("response already set", mTester->mResponse == ResponsePtr(NULL)); - mTester->mResponse = response; - mTester->mResult = input; - } - }; - - class WireHello : public LLIOPipe - { - protected: - virtual EStatus process_impl( - const LLChannelDescriptors& channels, - buffer_ptr_t& buffer, - bool& eos, - LLSD& context, - LLPumpIO* pump) - { - if(!eos) return STATUS_BREAK; - LLSD sd = "yo!"; - LLBufferStream ostr(channels, buffer.get()); - ostr << LLSDXMLStreamer(sd); - return STATUS_DONE; - } - }; - - HTTPServiceTestData() - : mResponse(NULL) - { - LLHTTPStandardServices::useServices(); - LLHTTPRegistrar::buildAllServices(mRoot); - mRoot.addNode("/delayed/echo", new DelayedEcho(this)); - mRoot.addNode("/wire/hello", new LLHTTPNodeForPipe); - } - - ~HTTPServiceTestData() - { - } - - LLHTTPNode mRoot; - LLHTTPNode::ResponsePtr mResponse; - LLSD mResult; - - void pumpPipe(LLPumpIO* pump, S32 iterations) - { - while(iterations > 0) - { - pump->pump(); - pump->callback(); - --iterations; - } - } - - std::string makeRequest( - const std::string& name, - const std::string& httpRequest, - bool timeout = false) - { - LLPipeStringInjector* injector = new LLPipeStringInjector(httpRequest); - LLPipeStringExtractor* extractor = new LLPipeStringExtractor(); - - apr_pool_t* pool; - apr_pool_create(&pool, NULL); - - LLPumpIO* pump; - pump = new LLPumpIO(pool); - - LLPumpIO::chain_t chain; - LLSD context; - - chain.push_back(LLIOPipe::ptr_t(injector)); - LLIOHTTPServer::createPipe(chain, mRoot, LLSD()); - chain.push_back(LLIOPipe::ptr_t(extractor)); - - pump->addChain(chain, DEFAULT_CHAIN_EXPIRY_SECS); - - pumpPipe(pump, 10); - if(mResponse.notNull() && (! timeout)) - { - mResponse->result(mResult); - mResponse = NULL; - } - pumpPipe(pump, 10); - - std::string httpResult = extractor->string(); - - chain.clear(); - delete pump; - apr_pool_destroy(pool); - - if(mResponse.notNull() && timeout) - { - mResponse->result(mResult); - mResponse = NULL; - } - - return httpResult; - } - - std::string httpGET(const std::string& uri, - bool timeout = false) - { - std::string httpRequest = "GET " + uri + " HTTP/1.0\r\n\r\n"; - return makeRequest(uri, httpRequest, timeout); - } - - std::string httpPOST(const std::string& uri, - const std::string& body, - bool timeout, - const std::string& evilExtra = "") - { - std::ostringstream httpRequest; - httpRequest << "POST " + uri + " HTTP/1.0\r\n"; - httpRequest << "Content-Length: " << body.size() << "\r\n"; - httpRequest << "\r\n"; - httpRequest << body; - httpRequest << evilExtra; - - return makeRequest(uri, httpRequest.str(), timeout); - } - - std::string httpPOST(const std::string& uri, - const std::string& body, - const std::string& evilExtra = "") - { - bool timeout = false; - return httpPOST(uri, body, timeout, evilExtra); - } - }; - - typedef test_group HTTPServiceTestGroup; - typedef HTTPServiceTestGroup::object HTTPServiceTestObject; - HTTPServiceTestGroup httpServiceTestGroup("http service"); - - template<> template<> - void HTTPServiceTestObject::test<1>() - { - std::string result = httpGET("web/hello"); - - ensure_starts_with("web/hello status", result, - "HTTP/1.0 200 OK\r\n"); - - ensure_contains("web/hello content type", result, - "Content-Type: application/llsd+xml\r\n"); - - ensure_contains("web/hello content length", result, - "Content-Length: 36\r\n"); - - ensure_contains("web/hello content", result, - "\r\n" - "hello" - ); - } - - template<> template<> - void HTTPServiceTestObject::test<2>() - { - // test various HTTP errors - - std::string actual; - - actual = httpGET("web/missing"); - ensure_starts_with("web/missing 404", actual, - "HTTP/1.0 404 Not Found\r\n"); - - actual = httpGET("web/echo"); - ensure_starts_with("web/echo 405", actual, - "HTTP/1.0 405 Method Not Allowed\r\n"); - } - - template<> template<> - void HTTPServiceTestObject::test<3>() - { - // test POST & content-length handling - - std::string result; - - result = httpPOST("web/echo", - "42"); - - ensure_starts_with("web/echo status", result, - "HTTP/1.0 200 OK\r\n"); - - ensure_contains("web/echo content type", result, - "Content-Type: application/llsd+xml\r\n"); - - ensure_contains("web/echo content length", result, - "Content-Length: 35\r\n"); - - ensure_contains("web/hello content", result, - "\r\n" - "42" - ); - -/* TO DO: this test doesn't pass!! - - result = httpPOST("web/echo", - "evil", - "really! evil!!!"); - - ensure_equals("web/echo evil result", result, - "HTTP/1.0 200 OK\r\n" - "Content-Length: 34\r\n" - "\r\n" - "evil" - ); -*/ - } - - template<> template<> - void HTTPServiceTestObject::test<4>() - { - // test calling things based on pipes - - std::string result; - - result = httpGET("wire/hello"); - - ensure_contains("wire/hello", result, "yo!"); - } - - template<> template<> - void HTTPServiceTestObject::test<5>() - { - // test timeout before async response - std::string result; - - bool timeout = true; - result = httpPOST("delayed/echo", - "agent99", timeout); - - ensure_equals("timeout delayed/echo status", result, std::string("")); - } - - template<> template<> - void HTTPServiceTestObject::test<6>() - { - // test delayed service - std::string result; - - result = httpPOST("delayed/echo", - "agent99"); - - ensure_starts_with("delayed/echo status", result, - "HTTP/1.0 200 OK\r\n"); - - ensure_contains("delayed/echo content", result, - "\r\n" - "agent99" - ); - } - - template<> template<> - void HTTPServiceTestObject::test<7>() - { - // test large request - std::stringstream stream; - - //U32 size = 36 * 1024 * 1024; - //U32 size = 36 * 1024; - //std::vector data(size); - //memset(&(data[0]), '1', size); - //data[size - 1] = '\0'; - - - //std::string result = httpPOST("web/echo", &(data[0])); - - stream << ""; - for(U32 i = 0; i < 1000000; ++i) - { - stream << "42"; - } - stream << ""; - LL_INFOS() << "HTTPServiceTestObject::test<7>" - << stream.str().length() << LL_ENDL; - std::string result = httpPOST("web/echo", stream.str()); - ensure_starts_with("large echo status", result, "HTTP/1.0 200 OK\r\n"); - } - - template<> template<> - void HTTPServiceTestObject::test<8>() - { - // test the OPTIONS http method -- the default implementation - // should return the X-Documentation-URL - std::ostringstream http_request; - http_request << "OPTIONS / HTTP/1.0\r\nHost: localhost\r\n\r\n"; - bool timeout = false; - std::string result = makeRequest("/", http_request.str(), timeout); - ensure_starts_with("OPTIONS verb ok", result, "HTTP/1.0 200 OK\r\n"); - ensure_contains( - "Doc url header exists", - result, - "X-Documentation-URL: http://localhost"); - } - - - /* TO DO: - test generation of not found and method not allowed errors - */ -} diff --git a/indra/test/llmessageconfig_tut.cpp b/indra/test/llmessageconfig_tut.cpp deleted file mode 100644 index 93443467a2..0000000000 --- a/indra/test/llmessageconfig_tut.cpp +++ /dev/null @@ -1,236 +0,0 @@ -/** - * @file llmessageconfig_tut.cpp - * @date March 2007 - * @brief LLMessageConfig unit tests - * - * $LicenseInfo:firstyear=2006&license=viewerlgpl$ - * Second Life Viewer Source Code - * Copyright (C) 2010, Linden Research, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; - * version 2.1 of the License only. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA - * $/LicenseInfo$ - */ - -#include "linden_common.h" -#include "llmessageconfig.h" -#include "lltut.h" -#include "llsdserialize.h" -#include "llfile.h" -#include "lltimer.h" -#include "llframetimer.h" -#include "llsdutil.h" - -namespace tut -{ - struct LLMessageConfigTestData { - std::string mTestConfigDir; - - LLMessageConfigTestData() - { - LLUUID random; - random.generate(); - // generate temp dir - std::ostringstream oStr; -#if LL_WINDOWS - oStr << "llmessage-config-test-" << random; -#else - oStr << "/tmp/llmessage-config-test-" << random; -#endif - mTestConfigDir = oStr.str(); - LLFile::mkdir(mTestConfigDir); - writeConfigFile(LLSD()); - LLMessageConfig::initClass("simulator", mTestConfigDir); - } - - ~LLMessageConfigTestData() - { - // rm contents of temp dir - int rmfile = LLFile::remove((mTestConfigDir + "/message.xml")); - ensure_equals("rmfile value", rmfile, 0); - // rm temp dir - int rmdir = LLFile::rmdir(mTestConfigDir); - ensure_equals("rmdir value", rmdir, 0); - } - - void writeConfigFile(const LLSD& config) - { - llofstream file((mTestConfigDir + "/message.xml").c_str()); - if (file.is_open()) - { - LLSDSerialize::toPrettyXML(config, file); - } - file.close(); - } - }; - - typedef test_group LLMessageConfigTestGroup; - typedef LLMessageConfigTestGroup::object LLMessageConfigTestObject; - LLMessageConfigTestGroup llMessageConfigTestGroup("LLMessageConfig"); - - template<> template<> - void LLMessageConfigTestObject::test<1>() - // tests server defaults - { - LLSD config; - config["serverDefaults"]["simulator"] = "template"; - LLMessageConfig::useConfig(config); - ensure_equals("Ensure server default is not template", - LLMessageConfig::getServerDefaultFlavor(), - LLMessageConfig::TEMPLATE_FLAVOR); - } - - template<> template<> - void LLMessageConfigTestObject::test<2>() - // tests message flavors - { - LLSD config; - config["serverDefaults"]["simulator"] = "template"; - config["messages"]["msg1"]["flavor"] = "template"; - config["messages"]["msg2"]["flavor"] = "llsd"; - LLMessageConfig::useConfig(config); - ensure_equals("Ensure msg template flavor", - LLMessageConfig::getMessageFlavor("msg1"), - LLMessageConfig::TEMPLATE_FLAVOR); - ensure_equals("Ensure msg llsd flavor", - LLMessageConfig::getMessageFlavor("msg2"), - LLMessageConfig::LLSD_FLAVOR); - } - - template<> template<> - void LLMessageConfigTestObject::test<4>() - // tests message flavor defaults - { - LLSD config; - config["serverDefaults"]["simulator"] = "llsd"; - config["messages"]["msg1"]["trusted-sender"] = true; - LLMessageConfig::useConfig(config); - ensure_equals("Ensure missing message gives no flavor", - LLMessageConfig::getMessageFlavor("Test"), - LLMessageConfig::NO_FLAVOR); - ensure_equals("Ensure missing flavor is NO_FLAVOR even with sender trustedness set", - LLMessageConfig::getMessageFlavor("msg1"), - LLMessageConfig::NO_FLAVOR); - ensure_equals("Ensure server default is llsd", - LLMessageConfig::getServerDefaultFlavor(), - LLMessageConfig::LLSD_FLAVOR); - } - - template<> template<> - void LLMessageConfigTestObject::test<3>() - // tests trusted/untrusted senders - { - LLSD config; - config["serverDefaults"]["simulator"] = "template"; - config["messages"]["msg1"]["flavor"] = "llsd"; - config["messages"]["msg1"]["trusted-sender"] = false; - config["messages"]["msg2"]["flavor"] = "llsd"; - config["messages"]["msg2"]["trusted-sender"] = true; - LLMessageConfig::useConfig(config); - ensure_equals("Ensure untrusted is untrusted", - LLMessageConfig::getSenderTrustedness("msg1"), - LLMessageConfig::UNTRUSTED); - ensure_equals("Ensure trusted is trusted", - LLMessageConfig::getSenderTrustedness("msg2"), - LLMessageConfig::TRUSTED); - ensure_equals("Ensure missing trustedness is NOT_SET", - LLMessageConfig::getSenderTrustedness("msg3"), - LLMessageConfig::NOT_SET); - } - - template<> template<> - void LLMessageConfigTestObject::test<5>() - // tests trusted/untrusted without flag, only flavor - { - LLSD config; - config["serverDefaults"]["simulator"] = "template"; - config["messages"]["msg1"]["flavor"] = "llsd"; - LLMessageConfig::useConfig(config); - ensure_equals("Ensure msg1 exists, has llsd flavor", - LLMessageConfig::getMessageFlavor("msg1"), - LLMessageConfig::LLSD_FLAVOR); - ensure_equals("Ensure missing trusted is not set", - LLMessageConfig::getSenderTrustedness("msg1"), - LLMessageConfig::NOT_SET); - } - - template<> template<> - void LLMessageConfigTestObject::test<6>() - { - LLSD config; - config["capBans"]["MapLayer"] = true; - config["capBans"]["MapLayerGod"] = false; - LLMessageConfig::useConfig(config); - ensure_equals("Ensure cap ban true MapLayer", - LLMessageConfig::isCapBanned("MapLayer"), - true); - ensure_equals("Ensure cap ban false", - LLMessageConfig::isCapBanned("MapLayerGod"), - false); - } - - template<> template<> - void LLMessageConfigTestObject::test<7>() - // tests that config changes are picked up/refreshed periodically - { - LLSD config; - config["serverDefaults"]["simulator"] = "llsd"; - writeConfigFile(config); - - // wait for it to reload after N seconds - ms_sleep(6*1000); - LLFrameTimer::updateFrameTime(); - ensure_equals("Ensure reload after 6 seconds", - LLMessageConfig::getServerDefaultFlavor(), - LLMessageConfig::LLSD_FLAVOR); - } - - template<> template<> - void LLMessageConfigTestObject::test<8>() - // tests that config changes are picked up/refreshed periodically - { - LLSD config; - config["serverDefaults"]["simulator"] = "template"; - config["messages"]["msg1"]["flavor"] = "llsd"; - config["messages"]["msg1"]["only-send-latest"] = true; - config["messages"]["msg2"]["flavor"] = "llsd"; - config["messages"]["msg2"]["only-send-latest"] = false; - LLMessageConfig::useConfig(config); - ensure_equals("Ensure msg1 exists, sent latest-only", - LLMessageConfig::onlySendLatest("msg1"), - true); - ensure_equals("Ensure msg2 exists, sent latest-only", - LLMessageConfig::onlySendLatest("msg2"), - false); - } - - template<> template<> - void LLMessageConfigTestObject::test<9>() - // tests that event queue max is reloaded - { - LLSD config; - config["maxQueuedEvents"] = 200; - LLMessageConfig::useConfig(config); - ensure_equals("Ensure setting maxQueuedEvents", - LLMessageConfig::getMaxQueuedEvents(), - 200); - - LLMessageConfig::useConfig(LLSD()); - ensure_equals("Ensure default of event queue max 100", - LLMessageConfig::getMaxQueuedEvents(), - 100); - } -} diff --git a/indra/test/llmessagetemplateparser_tut.cpp b/indra/test/llmessagetemplateparser_tut.cpp deleted file mode 100644 index f665fdde4d..0000000000 --- a/indra/test/llmessagetemplateparser_tut.cpp +++ /dev/null @@ -1,368 +0,0 @@ -/** - * @file llmessagetemplateparser_tut.cpp - * @date April 2007 - * @brief LLMessageTemplateParser unit tests - * - * $LicenseInfo:firstyear=2006&license=viewerlgpl$ - * Second Life Viewer Source Code - * Copyright (C) 2010, Linden Research, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; - * version 2.1 of the License only. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA - * $/LicenseInfo$ - */ - -#include "linden_common.h" -#include "llmessagetemplateparser.h" -#include "lltut.h" - -namespace tut -{ - struct LLMessageTemplateParserTestData { - LLMessageTemplateParserTestData() : mMessage("unset message") - { - } - - ~LLMessageTemplateParserTestData() - { - } - - void ensure_next(LLTemplateTokenizer & tokens, - std::string value, - U32 line) - { - std::string next = tokens.next(); - ensure_equals(mMessage + " token matches", next, value); - ensure_equals(mMessage + " line matches", tokens.line(), line); - } - - char * prehash(const char * name) - { - return LLMessageStringTable::getInstance()->getString(name); - } - - void ensure_block_attributes(std::string identifier, - const LLMessageTemplate * message, - const char * name, - EMsgBlockType type, - S32 number, - S32 total_size) - { - const LLMessageBlock * block = message->getBlock(prehash(name)); - identifier = identifier + ":" + message->mName + ":" + name + " block"; - ensure(identifier + " exists", block != NULL); - ensure_equals(identifier + " name", block->mName, prehash(name)); - ensure_equals(identifier + " type", block->mType, type); - ensure_equals(identifier + " number", block->mNumber, number); - ensure_equals(identifier + " total size", block->mTotalSize, total_size); - } - - void ensure_variable_attributes(std::string identifier, - const LLMessageBlock * block, - const char * name, - EMsgVariableType type, - S32 size) - { - const LLMessageVariable * var = block->getVariable(prehash(name)); - identifier = identifier + ":" + block->mName + ":" + name + " variable"; - ensure(identifier + " exists", var != NULL); - ensure_equals( - identifier + " name", var->getName(), prehash(name)); - ensure_equals( - identifier + " type", var->getType(), type); - ensure_equals(identifier + " size", var->getSize(), size); - } - - std::string mMessage; - - }; - - typedef test_group LLMessageTemplateParserTestGroup; - typedef LLMessageTemplateParserTestGroup::object LLMessageTemplateParserTestObject; - LLMessageTemplateParserTestGroup llMessageTemplateParserTestGroup("LLMessageTemplateParser"); - - template<> template<> - void LLMessageTemplateParserTestObject::test<1>() - // tests tokenizer constructor and next methods - { - mMessage = "test method 1 walkthrough"; - LLTemplateTokenizer tokens("first line\nnext\t line\n\nfourth"); - ensure_next(tokens, "first", 1); - ensure_next(tokens, "line", 1); - ensure_next(tokens, "next", 2); - ensure_next(tokens, "line", 2); - ensure_next(tokens, "fourth", 4); - - tokens = LLTemplateTokenizer("\n\t{ \t Test1 Fixed \n 523 }\n\n"); - ensure(tokens.want("{")); - ensure_next(tokens, "Test1", 2); - ensure_next(tokens, "Fixed", 2); - ensure_next(tokens, "523", 3); - ensure(tokens.want("}")); - - tokens = LLTemplateTokenizer("first line\nnext\t line\n\nfourth"); - ensure(tokens.want("first")); - ensure_next(tokens, "line", 1); - ensure_next(tokens, "next", 2); - ensure_next(tokens, "line", 2); - ensure(tokens.want("fourth")); - } - - template<> template<> - void LLMessageTemplateParserTestObject::test<2>() - // tests tokenizer want method - { - // *NOTE: order matters - LLTemplateTokenizer tokens("first line\nnext\t line\n\nfourth"); - ensure_equals("wants first token", tokens.want("first"), true); - ensure_equals("doesn't want blar token", tokens.want("blar"), false); - ensure_equals("wants line token", tokens.want("line"), true); - } - - template<> template<> - void LLMessageTemplateParserTestObject::test<3>() - // tests tokenizer eof methods - { - LLTemplateTokenizer tokens("single\n\n"); - ensure_equals("is not at eof at beginning", tokens.atEOF(), false); - ensure_equals("doesn't want eof", tokens.wantEOF(), false); - ensure_equals("wants the first token just to consume it", - tokens.want("single"), true); - ensure_equals("is not at eof in middle", tokens.atEOF(), false); - ensure_equals("wants eof", tokens.wantEOF(), true); - ensure_equals("is at eof at end", tokens.atEOF(), true); - } - - template<> template<> - void LLMessageTemplateParserTestObject::test<4>() - // tests variable parsing method - { - LLTemplateTokenizer tokens(std::string("{ Test0 \n\t\n U32 \n\n }")); - LLMessageVariable * var = LLTemplateParser::parseVariable(tokens); - - ensure("test0 var parsed", var != 0); - ensure_equals("name of variable", std::string(var->getName()), std::string("Test0")); - ensure_equals("type of variable is U32", var->getType(), MVT_U32); - ensure_equals("size of variable", var->getSize(), 4); - - delete var; - - std::string message_string("\n\t{ \t Test1 Fixed \n 523 }\n\n"); - tokens = LLTemplateTokenizer(message_string); - var = LLTemplateParser::parseVariable(tokens); - - ensure("test1 var parsed", var != 0); - ensure_equals("name of variable", std::string(var->getName()), std::string("Test1")); - ensure_equals("type of variable is Fixed", var->getType(), MVT_FIXED); - ensure_equals("size of variable", var->getSize(), 523); - - delete var; - - // *NOTE: the parsers call LL_ERRS() on invalid input, so we can't really - // test that :-( - } - - template<> template<> - void LLMessageTemplateParserTestObject::test<5>() - // tests block parsing method - { - LLTemplateTokenizer tokens("{ BlockA Single { VarX F32 } }"); - LLMessageBlock * block = LLTemplateParser::parseBlock(tokens); - - ensure("blockA block parsed", block != 0); - ensure_equals("name of block", std::string(block->mName), std::string("BlockA")); - ensure_equals("type of block is Single", block->mType, MBT_SINGLE); - ensure_equals("total size of block", block->mTotalSize, 4); - ensure_equals("number of block defaults to 1", block->mNumber, 1); - ensure_equals("variable type of VarX is F32", - block->getVariableType(prehash("VarX")), MVT_F32); - ensure_equals("variable size of VarX", - block->getVariableSize(prehash("VarX")), 4); - - delete block; - - tokens = LLTemplateTokenizer("{ Stuff Variable { Id LLUUID } }"); - block = LLTemplateParser::parseBlock(tokens); - - ensure("stuff block parsed", block != 0); - ensure_equals("name of block", std::string(block->mName), std::string("Stuff")); - ensure_equals("type of block is Multiple", block->mType, MBT_VARIABLE); - ensure_equals("total size of block", block->mTotalSize, 16); - ensure_equals("number of block defaults to 1", block->mNumber, 1); - ensure_equals("variable type of Id is LLUUID", - block->getVariableType(prehash("Id")), MVT_LLUUID); - ensure_equals("variable size of Id", - block->getVariableSize(prehash("Id")), 16); - - delete block; - - tokens = LLTemplateTokenizer("{ Stuff2 Multiple 45 { Shid LLVector3d } }"); - block = LLTemplateParser::parseBlock(tokens); - - ensure("stuff2 block parsed", block != 0); - ensure_equals("name of block", std::string(block->mName), std::string("Stuff2")); - ensure_equals("type of block is Multiple", block->mType, MBT_MULTIPLE); - ensure_equals("total size of block", block->mTotalSize, 24); - ensure_equals("number of blocks", block->mNumber, 45); - ensure_equals("variable type of Shid is Vector3d", - block->getVariableType(prehash("Shid")), MVT_LLVector3d); - ensure_equals("variable size of Shid", - block->getVariableSize(prehash("Shid")), 24); - - delete block; - } - - template<> template<> - void LLMessageTemplateParserTestObject::test<6>() - // tests message parsing method on a simple message - { - std::string message_skel( - "{\n" - "TestMessage Low 1 NotTrusted Zerocoded\n" - "// comment \n" - " {\n" - "TestBlock1 Single\n" - " { Test1 U32 }\n" - " }\n" - " {\n" - " NeighborBlock Multiple 4\n" - " { Test0 U32 }\n" - " { Test1 U32 }\n" - " { Test2 U32 }\n" - " }\n" - "}"); - LLTemplateTokenizer tokens(message_skel); - LLMessageTemplate * message = LLTemplateParser::parseMessage(tokens); - - ensure("simple message parsed", message != 0); - ensure_equals("name of message", std::string(message->mName), std::string("TestMessage")); - ensure_equals("frequency is Low", message->mFrequency, MFT_LOW); - ensure_equals("trust is untrusted", message->mTrust, MT_NOTRUST); - ensure_equals("message number", message->mMessageNumber, (U32)((255 << 24) | (255 << 16) | 1)); - ensure_equals("message encoding is zerocoded", message->mEncoding, ME_ZEROCODED); - ensure_equals("message deprecation is notdeprecated", message->mDeprecation, MD_NOTDEPRECATED); - - LLMessageBlock * block = message->getBlock(prehash("NonexistantBlock")); - ensure("Nonexistant block does not exist", block == 0); - - delete message; - } - - template<> template<> - void LLMessageTemplateParserTestObject::test<7>() - // tests message parsing method on a deprecated message - { - std::string message_skel( - "{\n" - "TestMessageDeprecated High 34 Trusted Unencoded Deprecated\n" - " {\n" - "TestBlock2 Single\n" - " { Test2 S32 }\n" - " }\n" - "}"); - LLTemplateTokenizer tokens(message_skel); - LLMessageTemplate * message = LLTemplateParser::parseMessage(tokens); - - ensure("deprecated message parsed", message != 0); - ensure_equals("name of message", std::string(message->mName), std::string("TestMessageDeprecated")); - ensure_equals("frequency is High", message->mFrequency, MFT_HIGH); - ensure_equals("trust is trusted", message->mTrust, MT_TRUST); - ensure_equals("message number", message->mMessageNumber, (U32)34); - ensure_equals("message encoding is unencoded", message->mEncoding, ME_UNENCODED); - ensure_equals("message deprecation is deprecated", message->mDeprecation, MD_DEPRECATED); - - delete message; - } - - template<> template<> void LLMessageTemplateParserTestObject::test<8>() - // tests message parsing on RezMultipleAttachmentsFromInv, a possibly-faulty message - { - std::string message_skel( - "{\n\ - RezMultipleAttachmentsFromInv Low 452 NotTrusted Zerocoded\n\ - {\n\ - AgentData Single\n\ - { AgentID LLUUID }\n\ - { SessionID LLUUID }\n\ - } \n\ - {\n\ - HeaderData Single\n\ - { CompoundMsgID LLUUID } // All messages a single \"compound msg\" must have the same id\n\ - { TotalObjects U8 }\n\ - { FirstDetachAll BOOL }\n\ - }\n\ - {\n\ - ObjectData Variable // 1 to 4 of these per packet\n\ - { ItemID LLUUID }\n\ - { OwnerID LLUUID }\n\ - { AttachmentPt U8 } // 0 for default\n\ - { ItemFlags U32 }\n\ - { GroupMask U32 }\n\ - { EveryoneMask U32 }\n\ - { NextOwnerMask U32 }\n\ - { Name Variable 1 }\n\ - { Description Variable 1 }\n\ - }\n\ - }\n\ - "); - LLTemplateTokenizer tokens(message_skel); - LLMessageTemplate * message = LLTemplateParser::parseMessage(tokens); - - ensure("RezMultipleAttachmentsFromInv message parsed", message != 0); - ensure_equals("name of message", message->mName, prehash("RezMultipleAttachmentsFromInv")); - ensure_equals("frequency is low", message->mFrequency, MFT_LOW); - ensure_equals("trust is not trusted", message->mTrust, MT_NOTRUST); - ensure_equals("message number", message->mMessageNumber, (U32)((255 << 24) | (255 << 16) | 452)); - ensure_equals("message encoding is zerocoded", message->mEncoding, ME_ZEROCODED); - - ensure_block_attributes( - "RMAFI", message, "AgentData", MBT_SINGLE, 1, 16+16); - LLMessageBlock * block = message->getBlock(prehash("AgentData")); - ensure_variable_attributes("RMAFI", - block, "AgentID", MVT_LLUUID, 16); - ensure_variable_attributes("RMAFI", - block, "SessionID", MVT_LLUUID, 16); - - ensure_block_attributes( - "RMAFI", message, "HeaderData", MBT_SINGLE, 1, 16+1+1); - block = message->getBlock(prehash("HeaderData")); - ensure_variable_attributes( - "RMAFI", block, "CompoundMsgID", MVT_LLUUID, 16); - ensure_variable_attributes( - "RMAFI", block, "TotalObjects", MVT_U8, 1); - ensure_variable_attributes( - "RMAFI", block, "FirstDetachAll", MVT_BOOL, 1); - - - ensure_block_attributes( - "RMAFI", message, "ObjectData", MBT_VARIABLE, 1, -1); - block = message->getBlock(prehash("ObjectData")); - ensure_variable_attributes("RMAFI", block, "ItemID", MVT_LLUUID, 16); - ensure_variable_attributes("RMAFI", block, "OwnerID", MVT_LLUUID, 16); - ensure_variable_attributes("RMAFI", block, "AttachmentPt", MVT_U8, 1); - ensure_variable_attributes("RMAFI", block, "ItemFlags", MVT_U32, 4); - ensure_variable_attributes("RMAFI", block, "GroupMask", MVT_U32, 4); - ensure_variable_attributes("RMAFI", block, "EveryoneMask", MVT_U32, 4); - ensure_variable_attributes("RMAFI", block, "NextOwnerMask", MVT_U32, 4); - ensure_variable_attributes("RMAFI", block, "Name", MVT_VARIABLE, 1); - ensure_variable_attributes("RMAFI", block, "Description", MVT_VARIABLE, 1); - - delete message; - } - - - -} diff --git a/indra/test/llpermissions_tut.cpp b/indra/test/llpermissions_tut.cpp deleted file mode 100644 index 1328939004..0000000000 --- a/indra/test/llpermissions_tut.cpp +++ /dev/null @@ -1,491 +0,0 @@ -/** - * @file llpermissions_tut.cpp - * @author Adroit - * @date March 2007 - * @brief llpermissions test cases. - * - * $LicenseInfo:firstyear=2007&license=viewerlgpl$ - * Second Life Viewer Source Code - * Copyright (C) 2010, Linden Research, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; - * version 2.1 of the License only. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA - * $/LicenseInfo$ - */ - -#include -#include "linden_common.h" - -#include "lltut.h" - -#include "message.h" -#include "llpermissions.h" - - -namespace tut -{ - struct permission - { - }; - typedef test_group permission_t; - typedef permission_t::object permission_object_t; - tut::permission_t tut_permission("permission"); - - template<> template<> - void permission_object_t::test<1>() - { - LLPermissions permissions; - LLUUID uuid = permissions.getCreator(); - LLUUID uuid1 = permissions.getOwner(); - LLUUID uuid2 = permissions.getGroup(); - LLUUID uuid3 = permissions.getLastOwner(); - - ensure("LLPermission Get Functions failed", (uuid == LLUUID::null && uuid1 == LLUUID::null && - uuid2 == LLUUID::null && uuid3 == LLUUID::null)); - ensure("LLPermission Get Functions failed", (permissions.getMaskBase() == PERM_ALL && permissions.getMaskOwner() == PERM_ALL && - permissions.getMaskGroup() == PERM_ALL && permissions.getMaskEveryone() == PERM_ALL && permissions.getMaskNextOwner() == PERM_ALL)); - ensure("Ownership functions failed", ((! permissions.isGroupOwned()) && (! permissions.isOwned()))); - } - - template<> template<> - void permission_object_t::test<2>() - { - LLPermissions permissions; - LLUUID creator("abf0d56b-82e5-47a2-a8ad-74741bb2c29e"); - LLUUID owner("68edcf47-ccd7-45b8-9f90-1649d7f12806"); - LLUUID lastOwner("5e47a0dc-97bf-44e0-8b40-de06718cee9d"); - LLUUID group("9c8eca51-53d5-42a7-bb58-cef070395db8"); - permissions.init(creator, owner, lastOwner, group); - - ensure_equals("init/getCreator():failed to return the creator ", creator, permissions.getCreator()); - ensure_equals("init/getOwner():failed to return the owner ", owner, permissions.getOwner()); - ensure_equals("init/getLastOwner():failed to return the group ", lastOwner, permissions.getLastOwner()); - ensure_equals("init/getGroup():failed to return the group ", group, permissions.getGroup()); - } - - template<> template<> - void permission_object_t::test<3>() - { - LLPermissions permissions; - U32 base = PERM_ALL; - U32 owner = PERM_ITEM_UNRESTRICTED; //PERM_ITEM_UNRESTRICTED = PERM_MODIFY | PERM_COPY | PERM_TRANSFER; - U32 group = PERM_TRANSFER | PERM_MOVE | PERM_COPY|PERM_MODIFY; - U32 everyone = PERM_TRANSFER | PERM_MOVE | PERM_MODIFY; - U32 next = PERM_NONE; - - U32 fixedbase = base; - U32 fixedowner = PERM_ITEM_UNRESTRICTED; //owner & fixedbase - U32 fixedgroup = PERM_ITEM_UNRESTRICTED; // no PERM_MOVE as owner does not have that perm either - U32 fixedeveryone = PERM_TRANSFER; // no PERM_MOVE. Everyone can never modify. - U32 fixednext = PERM_NONE; - - permissions.initMasks(base, owner, everyone, group, next); // will fix perms if not allowed. - ensure_equals("initMasks/getMaskBase():failed to return the MaskBase ", fixedbase, permissions.getMaskBase()); - ensure_equals("initMasks/getMaskOwner():failed to return the MaskOwner ", fixedowner, permissions.getMaskOwner()); - ensure_equals("initMasks/getMaskEveryone():failed to return the MaskGroup ", fixedgroup, permissions.getMaskGroup()); - ensure_equals("initMasks/getMaskEveryone():failed to return the MaskEveryone ", fixedeveryone, permissions.getMaskEveryone()); - ensure_equals("initMasks/getMaskNextOwner():failed to return the MaskNext ", fixednext, permissions.getMaskNextOwner()); - - // explictly set should maintain the values - permissions.setMaskBase(base); //no fixing - ensure_equals("setMaskBase/getMaskBase():failed to return the MaskBase ", base, permissions.getMaskBase()); - - permissions.setMaskOwner(owner); - ensure_equals("setMaskOwner/getMaskOwner():failed to return the MaskOwner ", owner, permissions.getMaskOwner()); - - permissions.setMaskEveryone(everyone); - ensure_equals("setMaskEveryone/getMaskEveryone():failed to return the MaskEveryone ", everyone, permissions.getMaskEveryone()); - - permissions.setMaskGroup(group); - ensure_equals("setMaskGroup/getMaskEveryone():failed to return the MaskGroup ", group, permissions.getMaskGroup()); - - permissions.setMaskNext(next); - ensure_equals("setMaskNext/getMaskNextOwner():failed to return the MaskNext ", next, permissions.getMaskNextOwner()); - - // further tests can be added to ensure perms for owner/group/everyone etc. get properly fixed. - // code however suggests that there is no explict check if the perms are correct and the user of this - // class is expected to know how to use them correctly. skipping further test cases for now for various - // perm combinations. - } - - template<> template<> - void permission_object_t::test<4>() - { - LLPermissions perm,perm1; - LLUUID creator("abf0d56b-82e5-47a2-a8ad-74741bb2c29e"); - LLUUID owner("68edcf47-ccd7-45b8-9f90-1649d7f12806"); - LLUUID lastOwner("5e47a0dc-97bf-44e0-8b40-de06718cee9d"); - LLUUID group("9c8eca51-53d5-42a7-bb58-cef070395db8"); - perm1.init(creator,owner,lastOwner,group); - perm.set(perm1); - ensure("set():failed to set ", (creator == perm.getCreator()) && (owner == perm.getOwner())&& - (lastOwner == perm.getLastOwner())&& (group == perm.getGroup())); - } - - template<> template<> - void permission_object_t::test<5>() - { - LLPermissions perm,perm1; - LLUUID creator("abf0d56b-82e5-47a2-a8ad-74741bb2c29e"); - LLUUID owner("68edcf47-ccd7-45b8-9f90-1649d7f12806"); - LLUUID lastOwner("5e47a0dc-97bf-44e0-8b40-de06718cee9d"); - LLUUID group("9c8eca51-53d5-42a7-bb58-cef070395db8"); - perm1.init(creator,owner,lastOwner,group); - - U32 base = PERM_TRANSFER; - U32 ownerp = PERM_TRANSFER; - U32 groupp = PERM_TRANSFER; - U32 everyone = PERM_TRANSFER; - U32 next = PERM_NONE; - - perm1.initMasks(base, ownerp, everyone, groupp, next); - - base = PERM_ALL; - ownerp = PERM_ITEM_UNRESTRICTED; //PERM_ITEM_UNRESTRICTED = PERM_MODIFY | PERM_COPY | PERM_TRANSFER; - groupp = PERM_TRANSFER | PERM_COPY|PERM_MODIFY; - everyone = PERM_TRANSFER; - next = PERM_NONE; - - perm.init(creator,owner,lastOwner,group); - perm.initMasks(base, ownerp, everyone, groupp, next); - - // restrict permissions by accumulation - perm.accumulate(perm1); - - U32 fixedbase = PERM_TRANSFER | PERM_MOVE; - U32 fixedowner = PERM_TRANSFER; - U32 fixedgroup = PERM_TRANSFER; - U32 fixedeveryone = PERM_TRANSFER; - U32 fixednext = PERM_NONE; - - ensure_equals("accumulate failed ", fixedbase, perm.getMaskBase()); - ensure_equals("accumulate failed ", fixedowner, perm.getMaskOwner()); - ensure_equals("accumulate failed ", fixedgroup, perm.getMaskGroup()); - ensure_equals("accumulate failed ", fixedeveryone, perm.getMaskEveryone()); - ensure_equals("accumulate failed ", fixednext, perm.getMaskNextOwner()); - } - - template<> template<> - void permission_object_t::test<6>() - { - LLPermissions perm; - LLUUID creator("abf0d56b-82e5-47a2-a8ad-74741bb2c29e"); - LLUUID owner("68edcf47-ccd7-45b8-9f90-1649d7f12806"); - LLUUID lastOwner("5e47a0dc-97bf-44e0-8b40-de06718cee9d"); - LLUUID group("9c8eca51-53d5-42a7-bb58-cef070395db8"); - perm.init(creator,owner,lastOwner,group); - ensure_equals("getSafeOwner:failed ", owner,perm.getSafeOwner()); - - ///NULL Owner - perm.init(creator,LLUUID::null,lastOwner,group); - ensure_equals("getSafeOwner:failed ", group, perm.getSafeOwner()); - } - - template<> template<> - void permission_object_t::test<7>() - { - LLPermissions perm1; - LLUUID uuid; - bool is_group_owned = false; - ensure("1:getOwnership:failed ", ! perm1.getOwnership(uuid,is_group_owned)); - - LLPermissions perm; - LLUUID creator("abf0d56b-82e5-47a2-a8ad-74741bb2c29e"); - LLUUID owner("68edcf47-ccd7-45b8-9f90-1649d7f12806"); - LLUUID lastOwner("5e47a0dc-97bf-44e0-8b40-de06718cee9d"); - LLUUID group("9c8eca51-53d5-42a7-bb58-cef070395db8"); - perm.init(creator,owner,lastOwner,group); - perm.getOwnership(uuid,is_group_owned); - ensure("2:getOwnership:failed ", ((uuid == owner) && (! is_group_owned))); - - perm.init(creator,LLUUID::null,lastOwner,group); - perm.getOwnership(uuid,is_group_owned); - ensure("3:getOwnership:failed ", ((uuid == group) && is_group_owned)); - } - - template<> template<> - void permission_object_t::test<8>() - { - LLPermissions perm,perm1; - LLUUID creator("abf0d56b-82e5-47a2-a8ad-74741bb2c29e"); - LLUUID owner("68edcf47-ccd7-45b8-9f90-1649d7f12806"); - LLUUID lastOwner("5e47a0dc-97bf-44e0-8b40-de06718cee9d"); - LLUUID group("9c8eca51-53d5-42a7-bb58-cef070395db8"); - perm.init(creator,owner,lastOwner,group); - perm1.init(creator,owner,lastOwner,group); - ensure_equals("getCRC32:failed ", perm.getCRC32(),perm1.getCRC32()); - } - - template<> template<> - void permission_object_t::test<9>() - { - LLPermissions perm; - LLUUID agent("abf0d56b-82e5-47a2-a8ad-74741bb2c29e"); - LLUUID owner("68edcf47-ccd7-45b8-9f90-1649d7f12806"); - LLUUID group("9c8eca51-53d5-42a7-bb58-cef070395db8"); - bool is_atomic = true; - ensure("setOwnerAndGroup():failed ", perm.setOwnerAndGroup(agent,owner,group,is_atomic)); - - LLUUID owner2("68edcf47-ccd7-45b8-9f90-1649d7f12807"); - LLUUID group2("9c8eca51-53d5-42a7-bb58-cef070395db9"); - - // cant change - agent need to be current owner - ensure("setOwnerAndGroup():failed ", ! perm.setOwnerAndGroup(agent,owner2,group2,is_atomic)); - - // should be able to change - agent and owner same as current owner - ensure("setOwnerAndGroup():failed ", perm.setOwnerAndGroup(owner,owner,group2,is_atomic)); - } - - template<> template<> - void permission_object_t::test<10>() - { - LLPermissions perm; - LLUUID agent; - LLUUID group("9c8eca51-53d5-42a7-bb58-cef070395db8"); - ensure("deedToGroup():failed ", perm.deedToGroup(agent,group)); - } - template<> template<> - void permission_object_t::test<11>() - { - LLPermissions perm; - LLUUID agent; - bool set = true; - U32 bits = PERM_TRANSFER | PERM_MODIFY; - ensure("setBaseBits():failed ", perm.setBaseBits(agent, set, bits)); - ensure("setOwnerBits():failed ", perm.setOwnerBits(agent, set, bits)); - - LLUUID agent1("9c8eca51-53d5-42a7-bb58-cef070395db8"); - ensure("setBaseBits():failed ", ! perm.setBaseBits(agent1, set, bits)); - ensure("setOwnerBits():failed ", ! perm.setOwnerBits(agent1, set, bits)); - } - - template<> template<> - void permission_object_t::test<12>() - { - LLPermissions perm; - LLUUID agent; - LLUUID group("9c8eca51-53d5-42a7-bb58-cef070395db8"); - bool set = true; - U32 bits = 10; - ensure("setGroupBits():failed ", perm.setGroupBits(agent,group, set, bits)); - ensure("setEveryoneBits():failed ", perm.setEveryoneBits(agent,group, set, bits)); - ensure("setNextOwnerBits():failed ", perm.setNextOwnerBits(agent,group, set, bits)); - - LLUUID agent1("abf0d56b-82e5-47a2-a8ad-74741bb2c29e"); - ensure("setGroupBits():failed ", ! perm.setGroupBits(agent1,group, set, bits)); - ensure("setEveryoneBits():failed ", ! perm.setEveryoneBits(agent1,group, set, bits)); - ensure("setNextOwnerBits():failed ", ! perm.setNextOwnerBits(agent1,group, set, bits)); - } - - template<> template<> - void permission_object_t::test<13>() - { - LLPermissions perm; - LLUUID agent; - LLUUID group("9c8eca51-53d5-42a7-bb58-cef070395db8"); - U32 bits = 10; - ensure("allowOperationBy():failed ", perm.allowOperationBy(bits,agent,group)); - - LLUUID agent1("abf0d56b-82e5-47a2-a8ad-74741bb2c29e"); - LLUUID creator("abf0d56b-82e5-47a2-a8ad-74741bb2c29e"); - LLUUID owner("68edcf47-ccd7-45b8-9f90-1649d7f12806"); - LLUUID lastOwner("5e47a0dc-97bf-44e0-8b40-de06718cee9d"); - perm.init(creator,owner,lastOwner,group); - ensure("allowOperationBy():failed ", perm.allowOperationBy(bits,agent1,group)); - } - - template<> template<> - void permission_object_t::test<14>() - { - LLPermissions perm; - LLUUID creator("abf0d56b-82e5-47a2-a8ad-74741bb2c29e"); - LLUUID owner; - LLUUID lastOwner("5e47a0dc-97bf-44e0-8b40-de06718cee9d"); - LLUUID group("9c8eca51-53d5-42a7-bb58-cef070395db8"); - perm.init(creator,owner,lastOwner,group); - LLUUID agent; - ensure("1:allowModifyBy():failed ", perm.allowModifyBy(agent)); - ensure("2:allowModifyBy():failed ", perm.allowModifyBy(agent,group)); - - LLUUID agent1("9c8eca51-53d5-42a7-bb58-cef070395db8"); - ensure("3:allowModifyBy():failed ", perm.allowModifyBy(agent1)); - ensure("4:allowModifyBy():failed ", perm.allowModifyBy(agent1,group)); - } - - template<> template<> - void permission_object_t::test<15>() - { - LLPermissions perm; - LLUUID creator("abf0d56b-82e5-47a2-a8ad-74741bb2c29e"); - LLUUID owner; - LLUUID lastOwner("5e47a0dc-97bf-44e0-8b40-de06718cee9d"); - LLUUID group("9c8eca51-53d5-42a7-bb58-cef070395db8"); - perm.init(creator,owner,lastOwner,group); - LLUUID agent; - ensure("1:allowCopyBy():failed ", perm.allowModifyBy(agent)); - ensure("2:allowCopyBy():failed ", perm.allowModifyBy(agent,group)); - - LLUUID agent1("9c8eca51-53d5-42a7-bb58-cef070395db8"); - ensure("3:allowCopyBy():failed ", perm.allowCopyBy(agent1)); - ensure("4:allowCopyBy():failed ", perm.allowCopyBy(agent1,group)); - } - - template<> template<> - void permission_object_t::test<16>() - { - LLPermissions perm; - LLUUID creator("abf0d56b-82e5-47a2-a8ad-74741bb2c29e"); - LLUUID owner; - LLUUID lastOwner("5e47a0dc-97bf-44e0-8b40-de06718cee9d"); - LLUUID group("9c8eca51-53d5-42a7-bb58-cef070395db8"); - perm.init(creator,owner,lastOwner,group); - LLUUID agent; - ensure("1:allowMoveBy():failed ", perm.allowMoveBy(agent)); - ensure("2:allowMoveBy():failed ", perm.allowMoveBy(agent,group)); - - LLUUID agent1("9c8eca51-53d5-42a7-bb58-cef070395db8"); - ensure("3:allowMoveBy():failed ", perm.allowMoveBy(agent1)); - ensure("4:allowMoveBy():failed ", perm.allowMoveBy(agent1,group)); - } - - template<> template<> - void permission_object_t::test<17>() - { - LLPermissions perm; - LLUUID creator("abf0d56b-82e5-47a2-a8ad-74741bb2c29e"); - LLUUID owner; - LLUUID lastOwner("5e47a0dc-97bf-44e0-8b40-de06718cee9d"); - LLUUID group("9c8eca51-53d5-42a7-bb58-cef070395db8"); - LLUUID agent; - ensure("1:allowMoveBy():failed ", perm.allowTransferTo(agent)); - - perm.init(creator,owner,lastOwner,group); - ensure("2:allowMoveBy():failed ", perm.allowTransferTo(agent)); - } - - template<> template<> - void permission_object_t::test<18>() - { - LLPermissions perm,perm1; - ensure_equals("1:Operator==:failed ", perm, perm1); - - LLUUID creator("abf0d56b-82e5-47a2-a8ad-74741bb2c29e"); - LLUUID owner("68edcf47-ccd7-45b8-9f90-1649d7f12806"); - LLUUID lastOwner("5e47a0dc-97bf-44e0-8b40-de06718cee9d"); - LLUUID group("9c8eca51-53d5-42a7-bb58-cef070395db8"); - perm.init(creator,owner,lastOwner,group); - perm = perm1; - ensure_equals("2:Operator==:failed ", perm, perm1); - } - - template<> template<> - void permission_object_t::test<19>() - { - LLPermissions perm,perm1; - LLUUID creator("abf0d56b-82e5-47a2-a8ad-74741bb2c29e"); - LLUUID owner("68edcf47-ccd7-45b8-9f90-1649d7f12806"); - LLUUID lastOwner("5e47a0dc-97bf-44e0-8b40-de06718cee9d"); - LLUUID group("9c8eca51-53d5-42a7-bb58-cef070395db8"); - perm.init(creator,owner,lastOwner,group); - ensure_not_equals("2:Operator==:failed ", perm, perm1); - } - - template<> template<> - void permission_object_t::test<20>() - { - LLPermissions perm,perm1; - LLUUID creator("abf0d56b-82e5-47a2-a8ad-74741bb2c29e"); - LLUUID owner("68edcf47-ccd7-45b8-9f90-1649d7f12806"); - LLUUID lastOwner("5e47a0dc-97bf-44e0-8b40-de06718cee9d"); - LLUUID group("9c8eca51-53d5-42a7-bb58-cef070395db8"); - perm.init(creator,owner,lastOwner,group); - - U32 base = PERM_TRANSFER | PERM_COPY; - U32 ownerp = PERM_TRANSFER; - U32 groupp = PERM_TRANSFER; - U32 everyone = PERM_TRANSFER; - U32 next = PERM_NONE; - - perm.initMasks(base, ownerp, everyone, groupp, next); - - std::ostringstream ostream; - perm.exportLegacyStream(ostream); - std::istringstream istream(ostream.str()); - perm1.importLegacyStream(istream); - - ensure_equals("exportStream()/importStream():failed to export and import the data ", perm1, perm); - } - - template<> template<> - void permission_object_t::test<21>() - { - LLPermissions perm,perm1; - LLUUID creator("abf0d56b-82e5-47a2-a8ad-74741bb2c29e"); - LLUUID owner("68edcf47-ccd7-45b8-9f90-1649d7f12806"); - LLUUID lastOwner("5e47a0dc-97bf-44e0-8b40-de06718cee9d"); - LLUUID group("9c8eca51-53d5-42a7-bb58-cef070395db8"); - perm.init(creator,owner,lastOwner,group); - std::ostringstream stream1, stream2; - stream1 << perm; - perm1.init(creator,owner,lastOwner,group); - stream2 << perm1; - ensure_equals("1:operator << failed", stream1.str(), stream2.str()); - } - - template<> template<> - void permission_object_t::test<22>() - { - LLPermissions perm,perm1; - LLUUID creator("abf0d56b-82e5-47a2-a8ad-74741bb2c29e"); - LLUUID owner("68edcf47-ccd7-45b8-9f90-1649d7f12806"); - LLUUID lastOwner("5e47a0dc-97bf-44e0-8b40-de06718cee9d"); - LLUUID group("9c8eca51-53d5-42a7-bb58-cef070395db8"); - perm.init(creator,owner,lastOwner,group); - - U32 base = PERM_TRANSFER | PERM_COPY; - U32 ownerp = PERM_TRANSFER; - U32 groupp = PERM_TRANSFER; - U32 everyone = PERM_TRANSFER; - U32 next = PERM_NONE; - - perm.initMasks(base, ownerp, everyone, groupp, next); - - LLSD sd = ll_create_sd_from_permissions(perm); - perm1 = ll_permissions_from_sd(sd); - ensure_equals("ll_permissions_from_sd() and ll_create_sd_from_permissions()functions failed", perm, perm1); - } - - template<> template<> - void permission_object_t::test<23>() - { - LLAggregatePermissions AggrPermission; - LLAggregatePermissions AggrPermission1; - ensure_equals("getU8() function failed", AggrPermission.getU8(), 0); - ensure("isEmpty() function failed", AggrPermission.isEmpty()); - AggrPermission.getValue(PERM_TRANSFER); - ensure_equals("getValue() function failed", AggrPermission.getValue(PERM_TRANSFER), 0x00); - - AggrPermission.aggregate(PERM_ITEM_UNRESTRICTED); - ensure("aggregate() function failed", ! AggrPermission.isEmpty()); - - AggrPermission1.aggregate(AggrPermission); - ensure("aggregate() function failed", ! AggrPermission1.isEmpty()); - - std::ostringstream stream1; - stream1 << AggrPermission; - ensure_equals("operator<< failed", stream1.str(), "{PI_COPY=All, PI_MODIFY=All, PI_TRANSFER=All}"); - } -} diff --git a/indra/test/llpipeutil.cpp b/indra/test/llpipeutil.cpp deleted file mode 100644 index 1dd4bdfa3c..0000000000 --- a/indra/test/llpipeutil.cpp +++ /dev/null @@ -1,183 +0,0 @@ -/** - * @file llpipeutil.cpp - * @date 2006-05-18 - * @brief Utility pipe fittings for injecting and extracting strings - * - * $LicenseInfo:firstyear=2006&license=viewerlgpl$ - * Second Life Viewer Source Code - * Copyright (C) 2010, Linden Research, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; - * version 2.1 of the License only. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA - * $/LicenseInfo$ - */ - - -#include "linden_common.h" -#include "llpipeutil.h" - -#include -#include - -#include "llbufferstream.h" -#include "lldefs.h" -#include "llframetimer.h" -#include "llpumpio.h" -#include "llrand.h" -#include "lltimer.h" - -F32 pump_loop(LLPumpIO* pump, F32 seconds) -{ - LLTimer timer; - timer.setTimerExpirySec(seconds); - while(!timer.hasExpired()) - { - LLFrameTimer::updateFrameTime(); - pump->pump(); - pump->callback(); - } - return timer.getElapsedTimeF32(); -} - -//virtual -LLIOPipe::EStatus LLPipeStringInjector::process_impl( - const LLChannelDescriptors& channels, - buffer_ptr_t& buffer, - bool& eos, - LLSD& context, - LLPumpIO* pump) -{ - buffer->append(channels.out(), (U8*) mString.data(), static_cast(mString.size())); - eos = true; - return STATUS_DONE; -} - - -LLIOPipe::EStatus LLPipeStringExtractor::process_impl( - const LLChannelDescriptors& channels, - buffer_ptr_t& buffer, - bool& eos, - LLSD& context, - LLPumpIO* pump) -{ - if(!eos) return STATUS_BREAK; - if(!pump || !buffer) return STATUS_PRECONDITION_NOT_MET; - - LLBufferStream istr(channels, buffer.get()); - std::ostringstream ostr; - while (istr.good()) - { - char buf[1024]; /* Flawfinder: ignore */ - istr.read(buf, sizeof(buf)); /* Flawfinder: ignore */ - ostr.write(buf, istr.gcount()); - } - mString = ostr.str(); - mDone = true; - - return STATUS_DONE; -} - - -// virtual -LLIOPipe::EStatus LLIOFuzz::process_impl( - const LLChannelDescriptors& channels, - buffer_ptr_t& buffer, - bool& eos, - LLSD& context, - LLPumpIO* pump) -{ - while(mByteCount) - { - std::vector data; - data.reserve(10000); - int size = llmin(10000, mByteCount); - std::generate_n( - std::back_insert_iterator< std::vector >(data), - size, - rand); - buffer->append(channels.out(), &data[0], size); - mByteCount -= size; - } - return STATUS_OK; -} - -struct random_ascii_generator -{ - random_ascii_generator() {} - U8 operator()() - { - int rv = rand(); - rv %= (127 - 32); - rv += 32; - return rv; - } -}; - -// virtual -LLIOPipe::EStatus LLIOASCIIFuzz::process_impl( - const LLChannelDescriptors& channels, - buffer_ptr_t& buffer, - bool& eos, - LLSD& context, - LLPumpIO* pump) -{ - while(mByteCount) - { - std::vector data; - data.reserve(10000); - int size = llmin(10000, mByteCount); - std::generate_n( - std::back_insert_iterator< std::vector >(data), - size, - random_ascii_generator()); - buffer->append(channels.out(), &data[0], size); - mByteCount -= size; - } - return STATUS_OK; -} - -// virtual -LLIOPipe::EStatus LLIONull::process_impl( - const LLChannelDescriptors& channels, - buffer_ptr_t& buffer, - bool& eos, - LLSD& context, - LLPumpIO* pump) -{ - return STATUS_OK; -} - -// virtual -LLIOPipe::EStatus LLIOSleeper::process_impl( - const LLChannelDescriptors& channels, - buffer_ptr_t& buffer, - bool& eos, - LLSD& context, - LLPumpIO* pump) -{ - if(!mRespond) - { - LL_DEBUGS() << "LLIOSleeper::process_impl() sleeping." << LL_ENDL; - mRespond = true; - static const F64 SLEEP_TIME = 2.0; - pump->sleepChain(SLEEP_TIME); - return STATUS_BREAK; - } - LL_DEBUGS() << "LLIOSleeper::process_impl() responding." << LL_ENDL; - LLBufferStream ostr(channels, buffer.get()); - ostr << "huh? sorry, I was sleeping." << std::endl; - return STATUS_DONE; -} diff --git a/indra/test/llpipeutil.h b/indra/test/llpipeutil.h deleted file mode 100644 index 97d9e1c85c..0000000000 --- a/indra/test/llpipeutil.h +++ /dev/null @@ -1,163 +0,0 @@ -/** - * @file llpipeutil.h - * @date 2006-05-18 - * @brief Utility pipe fittings for injecting and extracting strings - * - * $LicenseInfo:firstyear=2006&license=viewerlgpl$ - * Second Life Viewer Source Code - * Copyright (C) 2010, Linden Research, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; - * version 2.1 of the License only. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA - * $/LicenseInfo$ - */ - -#ifndef LL_LLPIPEUTIL_H -#define LL_LLPIPEUTIL_H - -#include "lliopipe.h" - - -/** - * @brief Simple function which pumps for the specified time. - */ -F32 pump_loop(LLPumpIO* pump, F32 seconds); - -/** - * @brief Simple class which writes a string and then marks the stream - * as done. - */ -class LLPipeStringInjector : public LLIOPipe -{ -public: - LLPipeStringInjector(const std::string& string) - : mString(string) - { } - -protected: - virtual EStatus process_impl( - const LLChannelDescriptors& channels, - buffer_ptr_t& buffer, - bool& eos, - LLSD& context, - LLPumpIO* pump); - -private: - std::string mString; -}; - - -class LLPipeStringExtractor : public LLIOPipe -{ -public: - LLPipeStringExtractor() : mDone(false) { } - - bool done() { return mDone; } - std::string string() { return mString; } - -protected: - // LLIOPipe API implementation. - virtual EStatus process_impl( - const LLChannelDescriptors& channels, - LLIOPipe::buffer_ptr_t& buffer, - bool& eos, - LLSD& context, - LLPumpIO* pump); - -private: - bool mDone; - std::string mString; -}; - -/** - * @brief Generate a specified number of bytes of random data - */ -class LLIOFuzz : public LLIOPipe -{ -public: - LLIOFuzz(int byte_count) : mByteCount(byte_count) {} - -protected: - virtual EStatus process_impl( - const LLChannelDescriptors& channels, - buffer_ptr_t& buffer, - bool& eos, - LLSD& context, - LLPumpIO* pump); - -private: - int mByteCount; -}; - -/** - * @brief Generate some ascii fuz - */ -class LLIOASCIIFuzz : public LLIOPipe -{ -public: - LLIOASCIIFuzz(int byte_count) : mByteCount(byte_count) {} - -protected: - virtual EStatus process_impl( - const LLChannelDescriptors& channels, - buffer_ptr_t& buffer, - bool& eos, - LLSD& context, - LLPumpIO* pump); - -private: - int mByteCount; -}; - - -/** - * @brief Pipe that does nothing except return STATUS_OK - */ -class LLIONull : public LLIOPipe -{ -public: - LLIONull() {} - -protected: - virtual EStatus process_impl( - const LLChannelDescriptors& channels, - buffer_ptr_t& buffer, - bool& eos, - LLSD& context, - LLPumpIO* pump); -}; - -/** - * @brief Pipe that sleeps, and then responds later. - */ -class LLIOSleeper : public LLIOPipe -{ -public: - LLIOSleeper() : mRespond(false) {} - -protected: - virtual EStatus process_impl( - const LLChannelDescriptors& channels, - buffer_ptr_t& buffer, - bool& eos, - LLSD& context, - LLPumpIO* pump); -private: - bool mRespond; - -}; - -#endif // LL_LLPIPEUTIL_H diff --git a/indra/test/llsaleinfo_tut.cpp b/indra/test/llsaleinfo_tut.cpp deleted file mode 100644 index 1da7101aa3..0000000000 --- a/indra/test/llsaleinfo_tut.cpp +++ /dev/null @@ -1,194 +0,0 @@ -/** - * @file LLSaleInfo_tut.cpp - * @author Adroit - * @date 2007-03 - * @brief Test cases of llsaleinfo.h - * - * $LicenseInfo:firstyear=2007&license=viewerlgpl$ - * Second Life Viewer Source Code - * Copyright (C) 2010, Linden Research, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; - * version 2.1 of the License only. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA - * $/LicenseInfo$ - */ - -#include -#include "linden_common.h" -#include "lltut.h" -#include "llsaleinfo.h" - -namespace tut -{ - struct llsaleinfo_tut - { - }; - typedef test_group llsaleinfo_tut_t; - typedef llsaleinfo_tut_t::object llsaleinfo_test_t; - tut::llsaleinfo_tut_t tut_llsaleinfo_test("llsaleinfo"); - - template<> template<> - void llsaleinfo_test_t::test<1>() - { - //test case for getSaleType(), getSalePrice(), getCRC32() fn. - //test case for setSaleType(), setSalePrice() fn. - - S32 sale_price = 10000; - LLSaleInfo llsaleinfo(LLSaleInfo::FS_COPY, sale_price); - const char* sale= "copy"; - - LLSD llsd_obj1 = ll_create_sd_from_sale_info(llsaleinfo); - LLSaleInfo saleinfo1 = ll_sale_info_from_sd(llsd_obj1); - - ensure("1. The getSaleType() fn failed", LLSaleInfo::FS_COPY == llsaleinfo.getSaleType()); - ensure("2. LLSaleInfo::isForSale() fn failed", true == llsaleinfo.isForSale()); - ensure("3. The getSalePrice() fn failed", sale_price == llsaleinfo.getSalePrice()); - ensure("4. The getCRC32() fn failed", 235833404 == llsaleinfo.getCRC32()); - ensure("5. LLSaleInfo::lookup(const char* name) fn failed", LLSaleInfo::FS_COPY == llsaleinfo.lookup(sale)); - ensure_equals("6. ll_create_sd_from_sale_info() fn failed", llsaleinfo.getSalePrice(), saleinfo1.getSalePrice()); - ensure_equals("7. ll_create_sd_from_sale_info() fn failed", llsaleinfo.getSaleType(), saleinfo1.getSaleType()); - - llsaleinfo.setSalePrice(10000000); - llsaleinfo.setSaleType(LLSaleInfo::FS_ORIGINAL); - sale = "cntn"; - llsd_obj1 = ll_create_sd_from_sale_info(llsaleinfo); - saleinfo1 = ll_sale_info_from_sd(llsd_obj1); - - ensure("8. The getSaleType() and setSaleType() fn failed", LLSaleInfo::FS_ORIGINAL == llsaleinfo.getSaleType()); - ensure("9. LLSaleInfo::isForSale() fn failed", true == llsaleinfo.isForSale()); - ensure("10. The getSalePrice() fn failed", 10000000 == llsaleinfo.getSalePrice()); - ensure("11. The getCRC32() fn failed", 127911702 == llsaleinfo.getCRC32()); - ensure("12. LLSaleInfo::lookup(const char* name) fn failed", LLSaleInfo::FS_CONTENTS == llsaleinfo.lookup(sale)); - ensure_equals("13. ll_create_sd_from_sale_info() fn failed", llsaleinfo.getSalePrice(), saleinfo1.getSalePrice()); - ensure_equals("14. ll_create_sd_from_sale_info() fn failed", llsaleinfo.getSaleType(), saleinfo1.getSaleType()); - - llsaleinfo.setSalePrice(55000550); - llsaleinfo.setSaleType(LLSaleInfo::FS_CONTENTS); - sale = "orig"; - llsd_obj1 = ll_create_sd_from_sale_info(llsaleinfo); - saleinfo1 = ll_sale_info_from_sd(llsd_obj1); - - ensure("15. The getSaleType() and setSaleType() fn failed", LLSaleInfo::FS_CONTENTS == llsaleinfo.getSaleType()); - ensure("16. LLSaleInfo::isForSale() fn failed", true == llsaleinfo.isForSale()); - ensure("17. The getSalePrice() fn failed", 55000550 == llsaleinfo.getSalePrice()); - ensure("18. The getCRC32() fn failed", 408735656 == llsaleinfo.getCRC32()); - ensure("19. LLSaleInfo::lookup(const char* name) fn failed", LLSaleInfo::FS_ORIGINAL == llsaleinfo.lookup(sale)); - ensure_equals("20. ll_create_sd_from_sale_info() fn failed", llsaleinfo.getSalePrice(), saleinfo1.getSalePrice()); - ensure_equals("21. ll_create_sd_from_sale_info() fn failed", llsaleinfo.getSaleType(), saleinfo1.getSaleType()); - - llsaleinfo.setSalePrice(-6432); - llsaleinfo.setSaleType(LLSaleInfo::FS_NOT); - sale = "not"; - llsd_obj1 = ll_create_sd_from_sale_info(llsaleinfo); - saleinfo1 = ll_sale_info_from_sd(llsd_obj1); - - ensure("22. The getSaleType() and setSaleType() fn failed", LLSaleInfo::FS_NOT == llsaleinfo.getSaleType()); - ensure("23. LLSaleInfo::isForSale() fn failed", false == llsaleinfo.isForSale()); - ensure("24. The getSalePrice() fn failed", 0 == llsaleinfo.getSalePrice()); - ensure("25. The getCRC32() fn failed", 0 == llsaleinfo.getCRC32()); - ensure("26. LLSaleInfo::lookup(const char* name) fn failed", LLSaleInfo::FS_NOT == llsaleinfo.lookup(sale)); - ensure_equals("27. ll_create_sd_from_sale_info() fn failed", llsaleinfo.getSalePrice(), saleinfo1.getSalePrice()); - ensure_equals("28. ll_create_sd_from_sale_info() fn failed", llsaleinfo.getSaleType(), saleinfo1.getSaleType()); - } - - template<> template<> - void llsaleinfo_test_t::test<2>() - { - S32 sale_price = 525452; - LLSaleInfo llsaleinfo(LLSaleInfo::FS_ORIGINAL, sale_price); - - std::ostringstream ostream; - llsaleinfo.exportLegacyStream(ostream); - - std::istringstream istream(ostream.str()); - LLSaleInfo llsaleinfo1; - U32 perm_mask = 0; - bool has_perm_mask = false; - llsaleinfo1.importLegacyStream(istream, has_perm_mask, perm_mask); - - ensure("importStream() fn failed ", - llsaleinfo.getSalePrice() == llsaleinfo1.getSalePrice() && - llsaleinfo.getSaleType() == llsaleinfo1.getSaleType()); - } - - template<> template<> - void llsaleinfo_test_t::test<3>() - { - S32 sale_price = 99000; - LLSaleInfo saleinfo(LLSaleInfo::FS_ORIGINAL, sale_price); - - LLSD sd_result = saleinfo.asLLSD(); - - U32 perm_mask = 0 ; - bool has_perm_mask = false; - - LLSaleInfo saleinfo1; - saleinfo1.fromLLSD( sd_result, has_perm_mask, perm_mask); - - ensure_equals("asLLSD and fromLLSD failed", saleinfo.getSalePrice(), saleinfo1.getSalePrice()); - ensure_equals("asLLSD and fromLLSD failed", saleinfo.getSaleType(), saleinfo1.getSaleType()); - } - - //static EForSale lookup(const char* name) fn test - template<> template<> - void llsaleinfo_test_t::test<4>() - { - S32 sale_price = 233223; - LLSaleInfo::EForSale ret_type = LLSaleInfo::lookup("orig"); - - ensure_equals("lookup(const char* name) fn failed", ret_type, LLSaleInfo::FS_ORIGINAL); - - LLSaleInfo saleinfo(LLSaleInfo::FS_COPY, sale_price); - const char* result = LLSaleInfo::lookup(LLSaleInfo::FS_COPY); - ensure("char* lookup(EForSale type) fn failed", 0 == strcmp("copy", result)); - } - - //void LLSaleInfo::accumulate(const LLSaleInfo& sale_info) fn test - template<> template<> - void llsaleinfo_test_t::test<5>() - { - S32 sale_price = 20; - LLSaleInfo saleinfo(LLSaleInfo::FS_COPY, sale_price); - LLSaleInfo saleinfo1(LLSaleInfo::FS_COPY, sale_price); - saleinfo1.accumulate(saleinfo); - ensure_equals("LLSaleInfo::accumulate(const LLSaleInfo& sale_info) fn failed", saleinfo1.getSalePrice(), 40); - - } - - // test cases of bool operator==(const LLSaleInfo &rhs) fn - // test case of bool operator!=(const LLSaleInfo &rhs) fn - template<> template<> - void llsaleinfo_test_t::test<6>() - { - S32 sale_price = 55000; - LLSaleInfo saleinfo(LLSaleInfo::FS_ORIGINAL, sale_price); - LLSaleInfo saleinfoequal(LLSaleInfo::FS_ORIGINAL, sale_price); - LLSaleInfo saleinfonotequal(LLSaleInfo::FS_ORIGINAL, sale_price*2); - - ensure("operator == fn. failed", true == (saleinfo == saleinfoequal)); - ensure("operator != fn. failed", true == (saleinfo != saleinfonotequal)); - } - - template<> template<> - void llsaleinfo_test_t::test<7>() - { - - //TBD: void LLSaleInfo::packMessage(LLMessageSystem* msg) const - //TBD: void LLSaleInfo::unpackMessage(LLMessageSystem* msg, const char* block) - //TBD: void LLSaleInfo::unpackMultiMessage(LLMessageSystem* msg, const char* block, S32 block_num) - } - -} diff --git a/indra/test/llsd_new_tut.cpp b/indra/test/llsd_new_tut.cpp deleted file mode 100644 index cc084df045..0000000000 --- a/indra/test/llsd_new_tut.cpp +++ /dev/null @@ -1,830 +0,0 @@ -/** - * @file llsd_new_tut.cpp - * @date February 2006 - * @brief LLSD unit tests - * - * $LicenseInfo:firstyear=2006&license=viewerlgpl$ - * Second Life Viewer Source Code - * Copyright (C) 2006-2011, Linden Research, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; - * version 2.1 of the License only. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA - * $/LicenseInfo$ - */ - -#define LLSD_DEBUG_INFO -#include -#include "linden_common.h" -#include "lltut.h" - -#include "llsdtraits.h" -#include "llstring.h" - -using std::fpclassify; - -namespace tut -{ - class SDCleanupCheck - { - private: - U32 mOutstandingAtStart; - public: - SDCleanupCheck() : mOutstandingAtStart(llsd::outstandingCount()) { } - ~SDCleanupCheck() - { - ensure_equals("SDCleanupCheck", - llsd::outstandingCount(), mOutstandingAtStart); - } - }; - - class SDAllocationCheck : public SDCleanupCheck - { - private: - std::string mMessage; - U32 mExpectedAllocations; - U32 mAllocationAtStart; - public: - SDAllocationCheck(const std::string& message, int expectedAllocations) - : mMessage(message), - mExpectedAllocations(expectedAllocations), - mAllocationAtStart(llsd::allocationCount()) - { } - ~SDAllocationCheck() - { - ensure_equals(mMessage + " SDAllocationCheck", - llsd::allocationCount() - mAllocationAtStart, - mExpectedAllocations); - } - }; - - struct SDTestData { - template - static void ensureTypeAndValue(const char* msg, const LLSD& actual, - T expectedValue) - { - LLSDTraits traits; - - std::string s(msg); - - ensure( s + " type", traits.checkType(actual)); - ensure_equals( s + " value", traits.get(actual), expectedValue); - } - - template - static void ensureTypeAndRefValue(const char* msg, const LLSD& actual, - const T& expectedValue) - { - LLSDTraits traits; - - std::string s(msg); - - ensure( s + " type", traits.checkType(actual)); - ensure_equals( s + " value", traits.get(actual), expectedValue); - } - }; - - typedef test_group SDTestGroup; - typedef SDTestGroup::object SDTestObject; - - SDTestGroup sdTestGroup("LLSD(new)"); - - // template<> template<> - // void SDTestObject::test<1>() - // // construction and test of undefined - // { - // SDCleanupCheck check; - - // LLSD u; - // ensure("is undefined", u.isUndefined()); - // } - - template<> template<> - void SDTestObject::test<2>() - // setting and fetching scalar types - { - SDCleanupCheck check; - - LLSD v; - - v = true; ensureTypeAndValue("set true", v, true); - v = false; ensureTypeAndValue("set false", v, false); - v = true; ensureTypeAndValue("set true again", v, true); - - v = 42; ensureTypeAndValue("set to 42", v, 42); - v = 0; ensureTypeAndValue("set to zero", v, 0); - v = -12345; ensureTypeAndValue("set to neg", v, -12345); - v = 2000000000; ensureTypeAndValue("set to big", v, 2000000000); - - v = 3.14159265359; - ensureTypeAndValue("set to pi", v, 3.14159265359); - ensure_not_equals("isn't float", v.asReal(), - (float)3.14159265359); - v = 6.7e256; ensureTypeAndValue("set to big", v, 6.7e256); - - LLUUID nullUUID; - LLUUID newUUID; - newUUID.generate(); - - v = nullUUID; ensureTypeAndValue("set to null UUID", v, nullUUID); - v = newUUID; ensureTypeAndValue("set to new UUID", v, newUUID); - v = nullUUID; ensureTypeAndValue("set to null again", v, nullUUID); - - // strings must be tested with two types of string objects - std::string s = "now is the time"; - const char* cs = "for all good zorks"; - - v = s; ensureTypeAndValue("set to std::string", v, s); - v = cs; ensureTypeAndValue("set to const char*", v, cs); - - LLDate epoch; - LLDate aDay("2001-10-22T10:11:12.00Z"); - - v = epoch; ensureTypeAndValue("set to epoch", v, epoch); - v = aDay; ensureTypeAndValue("set to a day", v, aDay); - - LLURI path("http://slurl.com/secondlife/Ambleside/57/104/26/"); - - v = path; ensureTypeAndValue("set to a uri", v, path); - - const char source[] = "once in a blue moon"; - std::vector data; - copy(&source[0], &source[sizeof(source)], back_inserter(data)); - - v = data; ensureTypeAndRefValue("set to data", v, data); - - v.clear(); - ensure("reset to undefined", v.type() == LLSD::TypeUndefined); - } - - template<> template<> - void SDTestObject::test<3>() - // construction via scalar values - // tests both constructor and initialize forms - { - SDCleanupCheck check; - - LLSD b1(true); ensureTypeAndValue("construct boolean", b1, true); - LLSD b2 = true; ensureTypeAndValue("initialize boolean", b2, true); - LLSD i1(42); ensureTypeAndValue("construct int", i1, 42); - LLSD i2 =42; ensureTypeAndValue("initialize int", i2, 42); - LLSD d1(1.2); ensureTypeAndValue("construct double", d1, 1.2); - LLSD d2 = 1.2; ensureTypeAndValue("initialize double", d2, 1.2); - - LLUUID newUUID; - newUUID.generate(); - LLSD u1(newUUID); - ensureTypeAndValue("construct UUID", u1, newUUID); - LLSD u2 = newUUID; - ensureTypeAndValue("initialize UUID", u2, newUUID); - - LLSD ss1(std::string("abc")); - ensureTypeAndValue("construct std::string", ss1, "abc"); - LLSD ss2 = std::string("abc"); - ensureTypeAndValue("initialize std::string",ss2, "abc"); - LLSD sl1(std::string("def")); - ensureTypeAndValue("construct std::string", sl1, "def"); - LLSD sl2 = std::string("def"); - ensureTypeAndValue("initialize std::string", sl2, "def"); - LLSD sc1("ghi"); - ensureTypeAndValue("construct const char*", sc1, "ghi"); - LLSD sc2 = "ghi"; - ensureTypeAndValue("initialize const char*",sc2, "ghi"); - - LLDate aDay("2001-10-22T10:11:12.00Z"); - LLSD t1(aDay); ensureTypeAndValue("construct LLDate", t1, aDay); - LLSD t2 = aDay; ensureTypeAndValue("initialize LLDate", t2, aDay); - - LLURI path("http://slurl.com/secondlife/Ambleside/57/104/26/"); - LLSD p1(path); ensureTypeAndValue("construct LLURI", p1, path); - LLSD p2 = path; ensureTypeAndValue("initialize LLURI", p2, path); - - const char source[] = "once in a blue moon"; - std::vector data; - copy(&source[0], &source[sizeof(source)], back_inserter(data)); - LLSD x1(data); ensureTypeAndRefValue("construct vector", x1, data); - LLSD x2 = data; ensureTypeAndRefValue("initialize vector", x2, data); - } - - void checkConversions(const char* msg, const LLSD& v, - LLSD::Boolean eBoolean, LLSD::Integer eInteger, - LLSD::Real eReal, const LLSD::String& eString) - { - std::string s(msg); - - ensure_equals(s+" to bool", v.asBoolean(), eBoolean); - ensure_equals(s+" to int", v.asInteger(), eInteger); - if (eReal == eReal) - { - ensure_equals(s+" to real", v.asReal(), eReal); - ensure_equals(s+" to string", v.asString(), eString); - } - else - { - int left = fpclassify(v.asReal()); - int right = fpclassify(eReal); - - ensure_equals(s+" to real", left, right); - // ensure_equals(s+" to string", v.asString(), eString); - // I've commented this check out, since there doesn't - // seem to be uniform string representation for NaN on - // all platforms. For example, on my Ubuntu 8.10 laptop - // with libc 2.11.1, sqrt(-1.0) will return '-nan', not - // 'nan'. - } - } - - template<> template<> - void SDTestObject::test<4>() - // conversion between undefined and basic scalar types: - // boolean, integer, real and string - { - SDCleanupCheck check; - - LLSD v; checkConversions("untitled", v, false, 0, 0.0, ""); - - v = false; checkConversions("false", v, false, 0, 0.0, ""); - v = true; checkConversions("true", v, true, 1, 1.0, "true"); - - v = 0; checkConversions("zero", v, false, 0, 0.0, "0"); - v = 1; checkConversions("one", v, true, 1, 1.0, "1"); - v = -33; checkConversions("neg33", v, true, -33, -33.0, "-33"); - - v = 0.0; checkConversions("0.0", v, false, 0, 0.0, "0"); - v = 0.5; checkConversions("point5", v, true, 0, 0.5, "0.5"); - v = 0.9; checkConversions("point9", v, true, 0, 0.9, "0.9"); - v = -3.9; checkConversions("neg3dot9", v, true, -3, -3.9, "-3.9"); - // Get rid of NaN test. First, some libraries don't reliably return - // NaN for sqrt(-1.0) -- meaning that I don't even know how to - // portably, reliably produce a NaN value. Second, we observe failures - // on different platforms in the asString() test. But LLSD's - // ImplReal::asString() does not itself recognize NaN! It merely - // passes the value through to llformat(), which passes it through to - // the library vsnprintf(). That is, even when we do produce NaN, - // we're not testing any LLSD code: we're testing the local library's - // vsnprintf() function, which (empirically) produces idiosyncratic - // results. This is just not a good test case. -// v = sqrt(-1.0); checkConversions("NaN", v, false, 0, sqrt(-1.0), "nan"); - - v = ""; checkConversions("empty", v, false, 0, 0.0, ""); - v = "0"; checkConversions("digit0", v, true, 0, 0.0, "0"); - v = "10"; checkConversions("digit10", v, true, 10, 10.0, "10"); - v = "-2.345"; checkConversions("decdigits", v, - true, -2, -2.345, "-2.345"); - v = "apple"; checkConversions("apple", v, true, 0, 0.0, "apple"); - v = "33bob"; checkConversions("digialpha", v, true, 0, 0.0, "33bob"); - v = " "; checkConversions("space", v, true, 0, 0.0, " "); - v = "\n"; checkConversions("newline", v, true, 0, 0.0, "\n"); - } - - template - void checkRoundTrip(const std::string& msg, const LLSD& actual, - const char* sExpected, T vExpected) - { - std::string str = actual.asString(); - - if (sExpected) { - ensure_equals(msg + " string", str, sExpected); - } - - LLSD u(str); - LLSDTraits traits; - - ensure_equals(msg + " value", traits.get(u), vExpected); - } - - - template<> template<> - void SDTestObject::test<5>() - // conversion of String to and from UUID, Date and URI. - { - SDCleanupCheck check; - - LLSD v; - - LLUUID nullUUID; - LLUUID someUUID; - someUUID.generate(); - - v = nullUUID; checkRoundTrip("null uuid", v, - "00000000-0000-0000-0000-000000000000", nullUUID); - v = someUUID; checkRoundTrip("random uuid", v, 0, someUUID); - - LLDate epoch; - LLDate beta("2003-04-30T04:00:00Z"); - LLDate oneOh("2003-06-23T04:00:00Z"); - - v = epoch; checkRoundTrip("epoch date", v, 0, epoch); - v = beta; checkRoundTrip("beta date", v, - "2003-04-30T04:00:00Z", beta); - v = oneOh; checkRoundTrip("1.0 date", v, - "2003-06-23T04:00:00Z", oneOh); - - LLURI empty; - LLURI path("http://slurl.com/secondlife/Ambleside/57/104/26/"); - LLURI mail("mailto:zero.linden@secondlife.com"); - - v = empty; checkRoundTrip("empty URI", v, 0, empty); - v = path; checkRoundTrip("path URI", v, - "http://slurl.com/secondlife/Ambleside/57/104/26/", - path); - v = mail; checkRoundTrip("mail URI", v, - "mailto:zero.linden@secondlife.com", mail); - } - - template<> template<> - void SDTestObject::test<6>() - // copy construction and assignment - // checking for shared values after constr. or assignment - // checking in both the same type and change of type case - { - SDCleanupCheck check; - - { - LLSD v = 42; - - LLSD w0(v); - ensureTypeAndValue("int constr.", w0, 42); - - LLSD w1(v); - w1 = 13; - ensureTypeAndValue("int constr. change case 1", w1, 13); - ensureTypeAndValue("int constr. change case 2", v, 42); - - LLSD w2(v); - v = 7; - ensureTypeAndValue("int constr. change case 3", w2, 42); - ensureTypeAndValue("int constr. change case 4", v, 7); - } - - { - LLSD v = 42; - - LLSD w1(v); - w1 = "bob"; - ensureTypeAndValue("string constr. change case 1", w1, "bob"); - ensureTypeAndValue("string constr. change case 2", v, 42); - - LLSD w2(v); - v = "amy"; - ensureTypeAndValue("string constr. change case 3", w2, 42); - ensureTypeAndValue("string constr. change case 4", v, "amy"); - } - - { - LLSD v = 42; - - LLSD w0; - w0 = v; - ensureTypeAndValue("int assign", w0, 42); - - LLSD w1; - w1 = v; - w1 = 13; - ensureTypeAndValue("int assign change case 1", w1, 13); - ensureTypeAndValue("int assign change case 2", v, 42); - - LLSD w2; - w2 = v; - v = 7; - ensureTypeAndValue("int assign change case 3", w2, 42); - ensureTypeAndValue("int assign change case 4", v, 7); - } - - { - LLSD v = 42; - - LLSD w1; - w1 = v; - w1 = "bob"; - ensureTypeAndValue("string assign change case 1", w1, "bob"); - ensureTypeAndValue("string assign change case 2", v, 42); - - LLSD w2; - w2 = v; - v = "amy"; - ensureTypeAndValue("string assign change case 3", w2, 42); - ensureTypeAndValue("string assign change case 4", v, "amy"); - } - } - - - template<> template<> - void SDTestObject::test<7>() - // Test assignment and casting to various scalar types. These - // assignments should invoke the right conversion without it being - // mentioned explicitly. The few exceptions are marked SAD. - { - SDCleanupCheck check; - - LLSD v(" 42.375"); - - bool b = false; - b = v; ensure_equals("assign to bool", b, true); - b = (bool)v; ensure_equals("cast to bool", b, true); - - int i = 99; - i = v; ensure_equals("assign to int", i, 42); - i = (int)v; ensure_equals("cast to int", i, 42); - - double d = 3.14159; - d = v; ensure_equals("assign to double", d, 42.375); - d = (double)v; ensure_equals("cast to double", d, 42.375); - - std::string s = "yo"; -// SAD s = v; ensure_equals("assign to string", s, " 42.375"); - s = (std::string)v; ensure_equals("cast to string", s, " 42.375"); - - std::string uuidStr = "b1e50c2b-b627-4d23-8a86-a65d97b6319b"; - v = uuidStr; - LLUUID u; - u = v; - ensure_equals("assign to LLUUID", u, LLUUID(uuidStr)); -// SAD u = (LLUUID)v; -// ensure_equals("cast to LLUUID", u, LLUUID(uuidStr)); - - std::string dateStr = "2005-10-24T15:00:00Z"; - v = dateStr; - LLDate date; - date = v; - ensure_equals("assign to LLDate", date.asString(), dateStr); -// SAD date = (LLDate)v; -// ensure_equals("cast to LLDate", date.asString(), dateStr); - - std::string uriStr = "http://secondlife.com"; - v = uriStr; - LLURI uri; - uri = v; - ensure_equals("assign to LLURI", uri.asString(), uriStr); -// SAD uri = (LLURI)v; -// ensure_equals("cast to LLURI", uri.asString(), uriStr); - } - - template<> template<> - void SDTestObject::test<8>() - // Test construction of various scalar types from LLSD. - // Test both construction and initialization forms. - // These should invoke the right conversion without it being - // mentioned explicitly. The few exceptions are marked SAD. - { - SDCleanupCheck check; - - LLSD v(" 42.375"); - - bool b1(v); ensure_equals("contruct bool", b1, true); - bool b2 = v; ensure_equals("initialize bool", b2, true); - - int i1(v); ensure_equals("contruct int", i1, 42); - int i2 = v; ensure_equals("initialize int", i2, 42); - - double d1(v); ensure_equals("contruct double", d1, 42.375); - double d2 = v; ensure_equals("initialize double", d2, 42.375); - - std::string s1(v); - std::string s2 = v; - ensure_equals("contruct string", s1, " 42.375"); - ensure_equals("initialize string", s2, " 42.375"); - - std::string t1(v); - std::string t2 = v.asString(); // SAD - ensure_equals("contruct std::string", t1, " 42.375"); - ensure_equals("initialize std::string", t2, " 42.375"); - - std::string uuidStr = "b1e50c2b-b627-4d23-8a86-a65d97b6319b"; - v = uuidStr; - LLUUID uuid1(v.asUUID()); // SAD - LLUUID uuid2 = v; - ensure_equals("contruct LLUUID", uuid1, LLUUID(uuidStr)); - ensure_equals("initialize LLUUID", uuid2, LLUUID(uuidStr)); - - std::string dateStr = "2005-10-24T15:00:00Z"; - v = dateStr; - LLDate date1(v.asDate()); // SAD - LLDate date2 = v; - ensure_equals("contruct LLDate", date1.asString(), dateStr); - ensure_equals("initialize LLDate", date2.asString(), dateStr); - - std::string uriStr = "http://secondlife.com"; - v = uriStr; - LLURI uri1(v.asURI()); // SAD - LLURI uri2 = v; - ensure_equals("contruct LLURI", uri1.asString(), uriStr); - ensure_equals("initialize LLURI", uri2.asString(), uriStr); - } - - - template<> template<> - void SDTestObject::test<9>() - // test to make sure v is interpreted as a bool in a various - // scenarios. - { - SDCleanupCheck check; - - LLSD v = "0"; - // magic value that is interpreted as boolean true, but integer false! - - ensure_equals("trinary operator bool", (v ? true : false), true); - ensure_equals("convert to int, then bool", - ((int)v ? true : false), false); - - if(v) - { - ensure("if converted to bool", true); - } - else - { - fail("bool did not convert to a bool in if statement."); - } - - if(!v) - { - fail("bool did not convert to a bool in negated if statement."); - } - } - - template<> template<> - void SDTestObject::test<10>() - // map operations - { - SDCleanupCheck check; - - LLSD v; - ensure("undefined has no members", !v.has("amy")); - ensure("undefined get() is undefined", v.get("bob").isUndefined()); - - v = LLSD::emptyMap(); - ensure("empty map is a map", v.isMap()); - ensure("empty map has no members", !v.has("cam")); - ensure("empty map get() is undefined", v.get("don").isUndefined()); - - v.clear(); - v.insert("eli", 43); - ensure("insert converts to map", v.isMap()); - ensure("inserted key is present", v.has("eli")); - ensureTypeAndValue("inserted value", v.get("eli"), 43); - - v.insert("fra", false); - ensure("first key still present", v.has("eli")); - ensure("second key is present", v.has("fra")); - ensureTypeAndValue("first value", v.get("eli"), 43); - ensureTypeAndValue("second value", v.get("fra"), false); - - v.erase("eli"); - ensure("first key now gone", !v.has("eli")); - ensure("second key still present", v.has("fra")); - ensure("first value gone", v.get("eli").isUndefined()); - ensureTypeAndValue("second value sill there", v.get("fra"), false); - - v.erase("fra"); - ensure("second key now gone", !v.has("fra")); - ensure("second value gone", v.get("fra").isUndefined()); - - v["gil"] = (std::string)"good morning"; - ensure("third key present", v.has("gil")); - ensureTypeAndValue("third key value", v.get("gil"), "good morning"); - - const LLSD& cv = v; // FIX ME IF POSSIBLE - ensure("missing key", cv["ham"].isUndefined()); - ensure("key not present", !v.has("ham")); - - LLSD w = 43; - const LLSD& cw = w; // FIX ME IF POSSIBLE - int i = cw["ian"]; - ensureTypeAndValue("other missing value", i, 0); - ensure("other missing key", !w.has("ian")); - ensure("no conversion", w.isInteger()); - - LLSD x; - x = v; - ensure("copy map type", x.isMap()); - ensureTypeAndValue("copy map value gil", x.get("gil"), "good morning"); - } - - - template<> template<> - void SDTestObject::test<11>() - // array operations - { - SDCleanupCheck check; - - LLSD v; - ensure_equals("undefined has no size", v.size(), 0); - ensure("undefined get() is undefined", v.get(0).isUndefined()); - - v = LLSD::emptyArray(); - ensure("empty array is an array", v.isArray()); - ensure_equals("empty array has no size", v.size(), 0); - ensure("empty map get() is undefined", v.get(0).isUndefined()); - - v.clear(); - v.append(88); - v.append("noodle"); - v.append(true); - ensure_equals("appened array size", v.size(), 3); - ensure("append array is an array", v.isArray()); - ensureTypeAndValue("append 0", v[0], 88); - ensureTypeAndValue("append 1", v[1], "noodle"); - ensureTypeAndValue("append 2", v[2], true); - - v.insert(0, 77); - v.insert(2, "soba"); - v.insert(4, false); - ensure_equals("inserted array size", v.size(), 6); - ensureTypeAndValue("post insert 0", v[0], 77); - ensureTypeAndValue("post insert 1", v[1], 88); - ensureTypeAndValue("post insert 2", v[2], "soba"); - ensureTypeAndValue("post insert 3", v[3], "noodle"); - ensureTypeAndValue("post insert 4", v[4], false); - ensureTypeAndValue("post insert 5", v[5], true); - - ensureTypeAndValue("get 1", v.get(1), 88); - v.set(1, "hot"); - ensureTypeAndValue("set 1", v.get(1), "hot"); - - v.erase(3); - ensure_equals("post erase array size", v.size(), 5); - ensureTypeAndValue("post erase 0", v[0], 77); - ensureTypeAndValue("post erase 1", v[1], "hot"); - ensureTypeAndValue("post erase 2", v[2], "soba"); - ensureTypeAndValue("post erase 3", v[3], false); - ensureTypeAndValue("post erase 4", v[4], true); - - v.append(34); - ensure_equals("size after append", v.size(), 6); - ensureTypeAndValue("post append 5", v[5], 34); - - LLSD w; - w = v; - ensure("copy array type", w.isArray()); - ensure_equals("copy array size", w.size(), 6); - ensureTypeAndValue("copy array 0", w[0], 77); - ensureTypeAndValue("copy array 1", w[1], "hot"); - ensureTypeAndValue("copy array 2", w[2], "soba"); - ensureTypeAndValue("copy array 3", w[3], false); - ensureTypeAndValue("copy array 4", w[4], true); - ensureTypeAndValue("copy array 5", w[5], 34); - } - - - template<> template<> - void SDTestObject::test<12>() - // no sharing - { - SDCleanupCheck check; - - LLSD a = 99; - LLSD b = a; - a = 34; - ensureTypeAndValue("top level original changed", a, 34); - ensureTypeAndValue("top level copy unaltered", b, 99); - b = a; - b = 66; - ensureTypeAndValue("top level original unaltered", a, 34); - ensureTypeAndValue("top level copy changed", b, 66); - - a[0] = "uno"; - a[1] = 99; - a[2] = 1.414; - b = a; - a[1] = 34; - ensureTypeAndValue("array member original changed", a[1], 34); - ensureTypeAndValue("array member copy unaltered", b[1], 99); - b = a; - b[1] = 66; - ensureTypeAndValue("array member original unaltered", a[1], 34); - ensureTypeAndValue("array member copy changed", b[1], 66); - - a["alpha"] = "uno"; - a["beta"] = 99; - a["gamma"] = 1.414; - b = a; - a["beta"] = 34; - ensureTypeAndValue("map member original changed", a["beta"], 34); - ensureTypeAndValue("map member copy unaltered", b["beta"], 99); - b = a; - b["beta"] = 66; - ensureTypeAndValue("map member original unaltered", a["beta"], 34); - ensureTypeAndValue("map member copy changed", b["beta"], 66); - } - - template<> template<> - void SDTestObject::test<13>() - // sharing implementation - { - SDCleanupCheck check; - - { - SDAllocationCheck check("copy construct undefinded", 0); - LLSD v; - LLSD w = v; - } - - { - SDAllocationCheck check("assign undefined", 0); - LLSD v; - LLSD w; - w = v; - } - - { - SDAllocationCheck check("assign integer value", 1); - LLSD v = 45; - v = 33; - v = 0; - } - - { - SDAllocationCheck check("copy construct integer", 1); - LLSD v = 45; - LLSD w = v; - } - - { - SDAllocationCheck check("assign integer", 1); - LLSD v = 45; - LLSD w; - w = v; - } - - { - SDAllocationCheck check("avoids extra clone", 2); - LLSD v = 45; - LLSD w = v; - w = "nice day"; - } - - { - SDAllocationCheck check("shared values test for threaded work", 9); - - //U32 start_llsd_count = LLSD::outstandingCount(); - - LLSD m = LLSD::emptyMap(); - - m["one"] = 1; - m["two"] = 2; - m["one_copy"] = m["one"]; // 3 (m, "one" and "two") - - m["undef_one"] = LLSD(); - m["undef_two"] = LLSD(); - m["undef_one_copy"] = m["undef_one"]; - - { // Ensure first_array gets freed to avoid counting it - LLSD first_array = LLSD::emptyArray(); - first_array.append(1.0f); - first_array.append(2.0f); - first_array.append(3.0f); // 7 - - m["array"] = first_array; - m["array_clone"] = first_array; - m["array_copy"] = m["array"]; // 7 - } - - m["string_one"] = "string one value"; - m["string_two"] = "string two value"; - m["string_one_copy"] = m["string_one"]; // 9 - - //U32 llsd_object_count = LLSD::outstandingCount(); - //std::cout << "Using " << (llsd_object_count - start_llsd_count) << " LLSD objects" << std::endl; - - //m.dumpStats(); - } - } - - template<> template<> - void SDTestObject::test<14>() - // make sure that assignment of char* NULL in a string does not crash. - { - LLSD v; - v = (const char*)NULL; - ensure("type is a string", v.isString()); - } - - /* TO DO: - conversion of undefined to UUID, Date, URI and Binary - conversion of undefined to map and array - test map operations - test array operations - test array extension - - test copying and assign maps and arrays (clone) - test iteration over map - test iteration over array - test iteration over scalar - - test empty map and empty array are indeed shared - test serializations - */ -} - diff --git a/indra/test/llsdmessagebuilder_tut.cpp b/indra/test/llsdmessagebuilder_tut.cpp deleted file mode 100644 index 6804c3e29e..0000000000 --- a/indra/test/llsdmessagebuilder_tut.cpp +++ /dev/null @@ -1,837 +0,0 @@ -/** - * @file llsdmessagebuilder_tut.cpp - * @date February 2006 - * @brief LLSDMessageBuilder unit tests - * - * $LicenseInfo:firstyear=2006&license=viewerlgpl$ - * Second Life Viewer Source Code - * Copyright (C) 2010, Linden Research, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; - * version 2.1 of the License only. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA - * $/LicenseInfo$ - */ - -#include - -#include "linden_common.h" -#include "lltut.h" -#include "llmessagetemplate.h" -#include "llsdmessagebuilder.h" -#include "llsdmessagereader.h" -#include "llsdtraits.h" -#include "llmath.h" -#include "llquaternion.h" -#include "u64.h" -#include "v3dmath.h" -#include "v3math.h" -#include "v4math.h" -#include "llsdutil.h" -//#include "llsdutil.cpp" -#include "llsdutil_math.cpp" -#include "lltemplatemessagebuilder.h" - -namespace tut -{ - static LLTemplateMessageBuilder::message_template_name_map_t templateNameMap; - - LLMsgData* messageData = NULL; - LLMsgBlkData* messageBlockData = NULL; - - struct LLSDMessageBuilderTestData { - - LLSDMessageBuilderTestData() - { - messageData = new LLMsgData("testMessage"); - messageBlockData = new LLMsgBlkData("testBlock", 0); - } - - static LLSDMessageBuilder defaultBuilder() - { - LLSDMessageBuilder builder; - builder.newMessage("name"); - builder.nextBlock("block"); - return builder; - } - - static LLSDMessageReader setReader(const LLSDMessageBuilder& builder) - { - LLSDMessageReader reader; - reader.setMessage("name", builder.getMessage()); - return reader; - } - - static void addValue(LLMsgBlkData* mbd, char* name, void* v, EMsgVariableType type, int size, int data_size = -1) - { - LLMsgVarData tmp(name, type); - tmp.addData(v, size, type, data_size); - mbd->mMemberVarData[name] = tmp; - } - - - static LLMessageBlock* defaultTemplateBlock(const EMsgVariableType type = MVT_NULL, const S32 size = 0, EMsgBlockType block = MBT_VARIABLE) - { - return createTemplateBlock(_PREHASH_Test0, type, size, block); - } - - static LLMessageBlock* createTemplateBlock(const char* name, const EMsgVariableType type = MVT_NULL, const S32 size = 0, EMsgBlockType block = MBT_VARIABLE) - { - LLMessageBlock* result = new LLMessageBlock(name, block); - if(type != MVT_NULL) - { - result->addVariable(const_cast(_PREHASH_Test0), type, size); - } - return result; - } - - static LLTemplateMessageBuilder* defaultTemplateBuilder(LLMessageTemplate& messageTemplate, char* name = const_cast(_PREHASH_Test0)) - { - templateNameMap[_PREHASH_TestMessage] = &messageTemplate; - LLTemplateMessageBuilder* builder = new LLTemplateMessageBuilder(templateNameMap); - builder->newMessage(_PREHASH_TestMessage); - builder->nextBlock(name); - return builder; - } - - static LLMessageTemplate defaultTemplate() - { - return LLMessageTemplate(_PREHASH_TestMessage, 1, MFT_HIGH); - } - }; - - typedef test_group LLSDMessageBuilderTestGroup; - typedef LLSDMessageBuilderTestGroup::object LLSDMessageBuilderTestObject; - LLSDMessageBuilderTestGroup llsdMessageBuilderTestGroup("LLSDMessageBuilder"); - - template<> template<> - void LLSDMessageBuilderTestObject::test<1>() - // construction and test of undefined - { - LLSDMessageBuilder builder = defaultBuilder(); - LLSDMessageReader reader = setReader(builder); - } - - template<> template<> - void LLSDMessageBuilderTestObject::test<2>() - // bool - { - bool outValue, inValue = true; - LLSDMessageBuilder builder = defaultBuilder(); - builder.addBOOL("var", inValue); - LLSDMessageReader reader = setReader(builder); - reader.getBOOL("block", "var", outValue); - ensure_equals("Ensure bool", inValue, outValue); - } - - template<> template<> - void LLSDMessageBuilderTestObject::test<3>() - // U8 - { - U8 outValue, inValue = 2; - LLSDMessageBuilder builder = defaultBuilder(); - builder.addU8("var", inValue); - LLSDMessageReader reader = setReader(builder); - reader.getU8("block", "var", outValue); - ensure_equals("Ensure U8", inValue, outValue); - } - - template<> template<> - void LLSDMessageBuilderTestObject::test<4>() - // S16 - { - S16 outValue, inValue = 90; - LLSDMessageBuilder builder = defaultBuilder(); - builder.addS16("var", inValue); - LLSDMessageReader reader = setReader(builder); - reader.getS16("block", "var", outValue); - ensure_equals("Ensure S16", inValue, outValue); - } - - template<> template<> - void LLSDMessageBuilderTestObject::test<5>() - // U16 - { - U16 outValue, inValue = 3; - LLSDMessageBuilder builder = defaultBuilder(); - builder.addU16("var", inValue); - LLSDMessageReader reader = setReader(builder); - reader.getU16("block", "var", outValue); - ensure_equals("Ensure U16", inValue, outValue); - } - - template<> template<> - void LLSDMessageBuilderTestObject::test<6>() - // S32 - { - S32 outValue, inValue = 44; - LLSDMessageBuilder builder = defaultBuilder(); - builder.addS32("var", inValue); - LLSDMessageReader reader = setReader(builder); - reader.getS32("block", "var", outValue); - ensure_equals("Ensure S32", inValue, outValue); - } - - template<> template<> - void LLSDMessageBuilderTestObject::test<7>() - // F32 - { - F32 outValue, inValue = 121.44f; - LLSDMessageBuilder builder = defaultBuilder(); - builder.addF32("var", inValue); - LLSDMessageReader reader = setReader(builder); - reader.getF32("block", "var", outValue); - ensure_equals("Ensure F32", inValue, outValue); - } - - template<> template<> - void LLSDMessageBuilderTestObject::test<8>() - // U32 - { - U32 outValue, inValue = 88; - LLSDMessageBuilder builder = defaultBuilder(); - builder.addU32("var", inValue); - LLSDMessageReader reader = setReader(builder); - reader.getU32("block", "var", outValue); - ensure_equals("Ensure U32", inValue, outValue); - } - - template<> template<> - void LLSDMessageBuilderTestObject::test<9>() - // U64 - { - U64 outValue, inValue = 121; - LLSDMessageBuilder builder = defaultBuilder(); - builder.addU64("var", inValue); - LLSDMessageReader reader = setReader(builder); - reader.getU64("block", "var", outValue); - ensure_equals("Ensure U64", inValue, outValue); - } - - template<> template<> - void LLSDMessageBuilderTestObject::test<10>() - // F64 - { - F64 outValue, inValue = 3232143.33; - LLSDMessageBuilder builder = defaultBuilder(); - builder.addF64("var", inValue); - LLSDMessageReader reader = setReader(builder); - reader.getF64("block", "var", outValue); - ensure_equals("Ensure F64", inValue, outValue); - } - - template<> template<> - void LLSDMessageBuilderTestObject::test<11>() - // Vector3 - { - LLVector3 outValue, inValue = LLVector3(1,2,3); - LLSDMessageBuilder builder = defaultBuilder(); - builder.addVector3("var", inValue); - LLSDMessageReader reader = setReader(builder); - reader.getVector3("block", "var", outValue); - ensure_equals("Ensure Vector3", inValue, outValue); - } - - template<> template<> - void LLSDMessageBuilderTestObject::test<12>() - // Vector4 - { - LLVector4 outValue, inValue = LLVector4(1,2,3,4); - LLSDMessageBuilder builder = defaultBuilder(); - builder.addVector4("var", inValue); - LLSDMessageReader reader = setReader(builder); - reader.getVector4("block", "var", outValue); - ensure_equals("Ensure Vector4", inValue, outValue); - } - - template<> template<> - void LLSDMessageBuilderTestObject::test<13>() - // Vector3d - { - LLVector3d outValue, inValue = LLVector3d(1,2,3); - LLSDMessageBuilder builder = defaultBuilder(); - builder.addVector3d("var", inValue); - LLSDMessageReader reader = setReader(builder); - reader.getVector3d("block", "var", outValue); - ensure_equals("Ensure Vector3d", inValue, outValue); - } - - template<> template<> - void LLSDMessageBuilderTestObject::test<14>() - // Quaternion - { - LLQuaternion outValue, inValue = LLQuaternion(1,LLVector3(2,3,4)); - LLSDMessageBuilder builder = defaultBuilder(); - builder.addQuat("var", inValue); - LLSDMessageReader reader = setReader(builder); - reader.getQuat("block", "var", outValue); - ensure_equals("Ensure Quaternion", inValue, outValue); - } - - template<> template<> - void LLSDMessageBuilderTestObject::test<15>() - // UUID - { - LLUUID outValue, inValue; - inValue.generate(); - LLSDMessageBuilder builder = defaultBuilder(); - builder.addUUID("var", inValue); - LLSDMessageReader reader = setReader(builder); - reader.getUUID("block", "var", outValue); - ensure_equals("Ensure UUID", inValue, outValue); - } - - template<> template<> - void LLSDMessageBuilderTestObject::test<16>() - // IPAddr - { - U32 outValue, inValue = 12344556; - LLSDMessageBuilder builder = defaultBuilder(); - builder.addIPAddr("var", inValue); - LLSDMessageReader reader = setReader(builder); - reader.getIPAddr("block", "var", outValue); - ensure_equals("Ensure IPAddr", inValue, outValue); - } - - template<> template<> - void LLSDMessageBuilderTestObject::test<17>() - // IPPort - { - U16 outValue, inValue = 80; - LLSDMessageBuilder builder = defaultBuilder(); - builder.addIPPort("var", inValue); - LLSDMessageReader reader = setReader(builder); - reader.getIPPort("block", "var", outValue); - ensure_equals("Ensure IPPort", inValue, outValue); - } - - template<> template<> - void LLSDMessageBuilderTestObject::test<18>() - { - std::string outValue, inValue = "testing"; - LLSDMessageBuilder builder = defaultBuilder(); - builder.addString("var", inValue.c_str()); - LLSDMessageReader reader = setReader(builder); - char buffer[MAX_STRING]; - reader.getString("block", "var", MAX_STRING, buffer); - outValue = buffer; - ensure_equals("Ensure String", inValue, outValue); - } - - template<> template<> - void LLSDMessageBuilderTestObject::test<19>() - { - LLMsgBlkData* mbd = new LLMsgBlkData("testBlock", 0); - LLMsgData* md = new LLMsgData("testMessage"); - md->addBlock(mbd); - LLSDMessageBuilder builder = defaultBuilder(); - - builder.copyFromMessageData(*md); - LLSD output = builder.getMessage(); - - ensure("Ensure message block created when copied from legacy message to llsd", output["testBlock"].isDefined()); - } - - // MVT_FIXED - template<> template<> - void LLSDMessageBuilderTestObject::test<20>() - { - char binData[] = "abcdefghijklmnop"; - - addValue(messageBlockData, (char *)"testBinData", &binData, MVT_FIXED, sizeof(binData)); - messageData->addBlock(messageBlockData); - LLSDMessageBuilder builder = defaultBuilder(); - - builder.copyFromMessageData(*messageData); - LLSD output = builder.getMessage(); - - std::vector v = output["testBlock"][0]["testBinData"].asBinary(); - ensure("Ensure MVT_S16Array data copied from legacy to llsd give a valid vector", v.size() > 0); - - ensure_memory_matches("Ensure fixed binary data works in a message copied from legacy to llsd", - &v[0], sizeof(binData), binData, sizeof(binData)); - } - - // MVT_VARIABLE data_size 1 (U8's) - template<> template<> - void LLSDMessageBuilderTestObject::test<21>() - { - /* U8 binData[] = "abcdefghijklmnop"; - - addValue(messageBlockData, "testBinData", &binData, MVT_VARIABLE, sizeof(binData), 1); - messageData->addBlock(messageBlockData); - LLSDMessageBuilder builder = defaultBuilder(); - - builder.copyFromMessageData(*messageData); - LLSD output = builder.getMessage(); - - std::vector v = output["testBlock"][0]["testBinData"].asBinary(); - ensure("Ensure MVT_S16Array data copied from legacy to llsd give a valid vector", v.size() > 0); - - ensure_memory_matches("Ensure MVT_VARIABLE U8 binary data works in a message copied from legacy to llsd", - &v[0], sizeof(binData), binData, sizeof(binData));*/ - } - - // MVT_VARIABLE data_size 2 (U16's) - template<> template<> - void LLSDMessageBuilderTestObject::test<22>() - { - U16 binData[] = {1,2,3,4,5,6,7,8,9}; //9 shorts - - addValue(messageBlockData, (char *)"testBinData", &binData, MVT_VARIABLE, sizeof(binData) >> 1, 2); - messageData->addBlock(messageBlockData); - LLSDMessageBuilder builder = defaultBuilder(); - - builder.copyFromMessageData(*messageData); - LLSD output = builder.getMessage(); - - std::vector v = output["testBlock"][0]["testBinData"].asBinary(); - ensure("Ensure MVT_S16Array data copied from legacy to llsd give a valid vector", v.size() > 0); - - ensure_memory_matches("Ensure MVT_VARIABLE U16 binary data works in a message copied from legacy to llsd", - &v[0], sizeof(binData) >> 1, binData, sizeof(binData) >> 1); - } - - // MVT_VARIABLE data_size 4 (S32's) - template<> template<> - void LLSDMessageBuilderTestObject::test<23>() - { - U32 binData[] = {9,8,7,6,5,4,3,2,1}; - - addValue(messageBlockData, (char *)"testBinData", &binData, MVT_VARIABLE, sizeof(binData) >> 2, 4); - messageData->addBlock(messageBlockData); - LLSDMessageBuilder builder = defaultBuilder(); - - builder.copyFromMessageData(*messageData); - LLSD output = builder.getMessage(); - - std::vector v = output["testBlock"][0]["testBinData"].asBinary(); - ensure("Ensure MVT_S16Array data copied from legacy to llsd give a valid vector", v.size() > 0); - - ensure_memory_matches("Ensure MVT_VARIABLE S32 binary data works in a message copied from legacy to llsd", - &v[0], sizeof(binData) >> 2, binData, sizeof(binData) >> 2); - } - - // MVT_U8 - template<> template<> - void LLSDMessageBuilderTestObject::test<24>() - { - U8 data = 0xa5; - - addValue(messageBlockData, (char *)"testBinData", &data, MVT_U8, sizeof(data)); - messageData->addBlock(messageBlockData); - LLSDMessageBuilder builder = defaultBuilder(); - - builder.copyFromMessageData(*messageData); - LLSD output = builder.getMessage(); - - ensure_equals("Ensure MVT_U8 data works in a message copied from legacy to llsd", - output["testBlock"][0]["testBinData"].asInteger(), data); - } - - // MVT_U16 - template<> template<> - void LLSDMessageBuilderTestObject::test<25>() - { - U16 data = 0xa55a; - - addValue(messageBlockData, (char *)"testBinData", &data, MVT_U16, sizeof(data)); - messageData->addBlock(messageBlockData); - LLSDMessageBuilder builder = defaultBuilder(); - - builder.copyFromMessageData(*messageData); - LLSD output = builder.getMessage(); - - ensure_equals("Ensure MVT_U16 data works in a message copied from legacy to llsd", - output["testBlock"][0]["testBinData"].asInteger(), data); - } - - // MVT_U32 - template<> template<> - void LLSDMessageBuilderTestObject::test<26>() - { - U32 data = 0xa55a7117; - - addValue(messageBlockData, (char *)"testBinData", &data, MVT_U32, sizeof(data)); - messageData->addBlock(messageBlockData); - LLSDMessageBuilder builder = defaultBuilder(); - - builder.copyFromMessageData(*messageData); - LLSD output = builder.getMessage(); - - ensure_equals("Ensure MVT_U32 data works in a message copied from legacy to llsd", - ll_U32_from_sd(output["testBlock"][0]["testBinData"]), data); - } - - // MVT_U64 - crush into an s32: LLSD does not support 64 bit values - template<> template<> - void LLSDMessageBuilderTestObject::test<27>() - { - U64 data = U64L(0xa55a711711223344); - addValue(messageBlockData, (char *)"testBinData", &data, MVT_U64, sizeof(data)); - messageData->addBlock(messageBlockData); - LLSDMessageBuilder builder = defaultBuilder(); - - builder.copyFromMessageData(*messageData); - LLSD output = builder.getMessage(); - - ensure_equals("Ensure MVT_U64 data works in a message copied from legacy to llsd", - ll_U64_from_sd(output["testBlock"][0]["testBinData"]), data); - } - - // MVT_S8 - template<> template<> - void LLSDMessageBuilderTestObject::test<28>() - { - S8 data = -31; - - addValue(messageBlockData, (char *)"testBinData", &data, MVT_S8, sizeof(data)); - messageData->addBlock(messageBlockData); - LLSDMessageBuilder builder = defaultBuilder(); - - builder.copyFromMessageData(*messageData); - LLSD output = builder.getMessage(); - - ensure_equals("Ensure MVT_S8 data works in a message copied from legacy to llsd", - output["testBlock"][0]["testBinData"].asInteger(), data); - } - - // MVT_S16 - template<> template<> - void LLSDMessageBuilderTestObject::test<29>() - { - S16 data = -31; - - addValue(messageBlockData, (char *)"testBinData", &data, MVT_S16, sizeof(data)); - messageData->addBlock(messageBlockData); - LLSDMessageBuilder builder = defaultBuilder(); - - builder.copyFromMessageData(*messageData); - LLSD output = builder.getMessage(); - - ensure_equals("Ensure MVT_S16 data works in a message copied from legacy to llsd", - output["testBlock"][0]["testBinData"].asInteger(), data); - } - - // MVT_S32 - template<> template<> - void LLSDMessageBuilderTestObject::test<30>() - { - S32 data = -3100; - - addValue(messageBlockData, (char *)"testBinData", &data, MVT_S32, sizeof(data)); - messageData->addBlock(messageBlockData); - LLSDMessageBuilder builder = defaultBuilder(); - - builder.copyFromMessageData(*messageData); - LLSD output = builder.getMessage(); - - ensure_equals("Ensure MVT_S32 data works in a message copied from legacy to llsd", - output["testBlock"][0]["testBinData"].asInteger(), data); - } - - // MVT_S64 - crush into an s32: LLSD does not support 64 bit values - template<> template<> - void LLSDMessageBuilderTestObject::test<31>() - { - S64 data = -31003100; - - addValue(messageBlockData, (char *)"testBinData", &data, MVT_S64, sizeof(data)); - messageData->addBlock(messageBlockData); - LLSDMessageBuilder builder = defaultBuilder(); - - builder.copyFromMessageData(*messageData); - LLSD output = builder.getMessage(); - - ensure_equals("Ensure MVT_S64 data works in a message copied from legacy to llsd", - output["testBlock"][0]["testBinData"].asInteger(), (S32)data); - } - - // MVT_F32 - template<> template<> - void LLSDMessageBuilderTestObject::test<32>() - { - F32 data = 1234.1234f; - - addValue(messageBlockData, (char *)"testBinData", &data, MVT_F32, sizeof(data)); - messageData->addBlock(messageBlockData); - LLSDMessageBuilder builder = defaultBuilder(); - - builder.copyFromMessageData(*messageData); - LLSD output = builder.getMessage(); - - ensure_equals("Ensure MVT_F32 data works in a message copied from legacy to llsd", - output["testBlock"][0]["testBinData"].asReal(), data); - } - - // MVT_F64 - template<> template<> - void LLSDMessageBuilderTestObject::test<33>() - { - F64 data = 1234.1234; - - addValue(messageBlockData, (char *)"testBinData", &data, MVT_F64, sizeof(data)); - messageData->addBlock(messageBlockData); - LLSDMessageBuilder builder = defaultBuilder(); - - builder.copyFromMessageData(*messageData); - LLSD output = builder.getMessage(); - - ensure_equals("Ensure MVT_F64 data works in a message copied from legacy to llsd", - output["testBlock"][0]["testBinData"].asReal(), data); - } - - // MVT_LLVector3 - template<> template<> - void LLSDMessageBuilderTestObject::test<34>() - { - LLVector3 data(1,2,3); - - addValue(messageBlockData, (char *)"testBinData", &data, MVT_LLVector3, sizeof(data)); - messageData->addBlock(messageBlockData); - LLSDMessageBuilder builder = defaultBuilder(); - - builder.copyFromMessageData(*messageData); - LLSD output = builder.getMessage(); - - ensure_equals("Ensure MVT_LLVector3 data works in a message copied from legacy to llsd", - ll_vector3_from_sd(output["testBlock"][0]["testBinData"]), data); - } - - // MVT_LLVector3d - template<> template<> - void LLSDMessageBuilderTestObject::test<35>() - { - LLVector3d data(1,2,3); - - addValue(messageBlockData, (char *)"testBinData", &data, MVT_LLVector3d, sizeof(data)); - messageData->addBlock(messageBlockData); - LLSDMessageBuilder builder = defaultBuilder(); - - builder.copyFromMessageData(*messageData); - LLSD output = builder.getMessage(); - - ensure_equals("Ensure MVT_LLVector3 data works in a message copied from legacy to llsd", - ll_vector3d_from_sd(output["testBlock"][0]["testBinData"]), data); - } - - // MVT_LLVector4 - template<> template<> - void LLSDMessageBuilderTestObject::test<36>() - { - LLVector4 data(1,2,3,4); - LLSD v = ll_sd_from_vector4(data); - - addValue(messageBlockData, (char *)"testBinData", &data, MVT_LLVector4, sizeof(data)); - messageData->addBlock(messageBlockData); - LLSDMessageBuilder builder = defaultBuilder(); - - builder.copyFromMessageData(*messageData); - LLSD output = builder.getMessage(); - - ensure_equals("Ensure MVT_LLVector4 data works in a message copied from legacy to llsd", - output["testBlock"][0]["testBinData"], v); - } - - // MVT_LLQuaternion - template<> template<> - void LLSDMessageBuilderTestObject::test<37>() - { - LLQuaternion data(0.3713907f, 0.5570861f, 0.7427813f,0.0f); - - //we send a quaternion packed into a vec3 (w is infered) - so sizeof(vec) == 12 bytes not 16. - LLVector3 vec = data.packToVector3(); - - addValue(messageBlockData, (char *)"testBinData", &vec, MVT_LLQuaternion, sizeof(vec)); - messageData->addBlock(messageBlockData); - LLSDMessageBuilder builder = defaultBuilder(); - - builder.copyFromMessageData(*messageData); - LLSD output = builder.getMessage(); - - ensure_equals("Ensure MVT_LLQuaternion data works in a message copied from legacy to llsd", - ll_quaternion_from_sd(output["testBlock"][0]["testBinData"]), data); - } - - // MVT_LLUUID - template<> template<> - void LLSDMessageBuilderTestObject::test<38>() - { - LLUUID data("01234567-0123-0123-0123-234567abcdef"); - - addValue(messageBlockData, (char *)"testBinData", &data, MVT_LLUUID, sizeof(data)); - messageData->addBlock(messageBlockData); - LLSDMessageBuilder builder = defaultBuilder(); - - builder.copyFromMessageData(*messageData); - LLSD output = builder.getMessage(); - - std::string v = output["testBlock"][0]["testBinData"].asUUID().asString(); - - ensure_equals("Ensure MVT_LLUUID data works in a message copied from legacy to llsd", - output["testBlock"][0]["testBinData"].asUUID(), data); - } - - // MVT_BOOL - template<> template<> - void LLSDMessageBuilderTestObject::test<39>() - { - bool valueTrue = true; - bool valueFalse = false; - - LLMsgData* md = new LLMsgData("testMessage"); - LLMsgBlkData* mbd = new LLMsgBlkData("testBlock", 0); - addValue(mbd, (char *)"testBoolFalse", &valueFalse, MVT_BOOL, sizeof(bool)); - addValue(mbd, (char *)"testBoolTrue", &valueTrue, MVT_BOOL, sizeof(bool)); - md->addBlock(mbd); - LLSDMessageBuilder builder = defaultBuilder(); - - builder.copyFromMessageData(*md); - LLSD output = builder.getMessage(); - - ensure("Ensure bools work in a message copied from legacy to llsd", - output["testBlock"][0]["testBoolTrue"].asBoolean() && !output["testBlock"][0]["testBoolFalse"].asBoolean()); - } - - // MVT_IP_ADDR - template<> template<> - void LLSDMessageBuilderTestObject::test<40>() - { - U32 data(0xff887766); - LLSD v = ll_sd_from_ipaddr(data); - - addValue(messageBlockData, (char *)"testBinData", &data, MVT_IP_ADDR, sizeof(data)); - messageData->addBlock(messageBlockData); - LLSDMessageBuilder builder = defaultBuilder(); - - builder.copyFromMessageData(*messageData); - LLSD output = builder.getMessage(); - - ensure_equals("Ensure MVT_IP_ADDR data works in a message copied from legacy to llsd", - output["testBlock"][0]["testBinData"], v); - } - - // MVT_IP_PORT - template<> template<> - void LLSDMessageBuilderTestObject::test<41>() - { - U16 data = 0xff88; - - addValue(messageBlockData, (char *)"testBinData", &data, MVT_IP_PORT, sizeof(data)); - messageData->addBlock(messageBlockData); - LLSDMessageBuilder builder = defaultBuilder(); - - builder.copyFromMessageData(*messageData); - LLSD output = builder.getMessage(); - - ensure_equals("Ensure MVT_IP_PORT data works in a message copied from legacy to llsd", - output["testBlock"][0]["testBinData"].asInteger(), data); - } - - // MVT_U16Vec3 - template<> template<> - void LLSDMessageBuilderTestObject::test<42>() - { - U16 data[3] = {0,1,2}; - - addValue(messageBlockData, (char *)"testBinData", &data, MVT_U16Vec3, sizeof(data)); - messageData->addBlock(messageBlockData); - LLSDMessageBuilder builder = defaultBuilder(); - - builder.copyFromMessageData(*messageData); - LLSD output = builder.getMessage(); - - std::vector v = output["testBlock"][0]["testBinData"].asBinary(); - ensure("Ensure MVT_U16Vec3 data copied from legacy to llsd give a valid vector", v.size() > 0); - - ensure_memory_matches("Ensure MVT_U16Vec3 data works in a message copied from legacy to llsd", - (U16*)&v[0], 6, data, 6); - } - - // MVT_U16Quat - template<> template<> - void LLSDMessageBuilderTestObject::test<43>() - { - U16 data[4] = {0,1,2,4}; - - addValue(messageBlockData, (char *)"testBinData", &data, MVT_U16Quat, sizeof(data)); - messageData->addBlock(messageBlockData); - LLSDMessageBuilder builder = defaultBuilder(); - - builder.copyFromMessageData(*messageData); - LLSD output = builder.getMessage(); - - std::vector v = output["testBlock"][0]["testBinData"].asBinary(); - ensure("Ensure MVT_U16Quat data copied from legacy to llsd give a valid vector", v.size() > 0); - - ensure_memory_matches("Ensure MVT_U16Quat data works in a message copied from legacy to llsd", - (U16*)&v[0], 8, data, 8); - } - - // MVT_S16Array - template<> template<> - void LLSDMessageBuilderTestObject::test<44>() - { - S16 data[19] = {0,-1,2,-4,5,-6,7,-8,9,-10,11,-12,13,-14,15,16,17,18}; - - addValue(messageBlockData, (char *)"testBinData", &data, MVT_S16Array, sizeof(data)); - messageData->addBlock(messageBlockData); - LLSDMessageBuilder builder = defaultBuilder(); - - builder.copyFromMessageData(*messageData); - LLSD output = builder.getMessage(); - - std::vector v = output["testBlock"][0]["testBinData"].asBinary(); - ensure("Ensure MVT_S16Array data copied from legacy to llsd give a valid vector", v.size() > 0); - - ensure_memory_matches("Ensure MVT_S16Array data works in a message copied from legacy to llsd", - (U16*)&v[0], 19, data, 19); - } - - template<> template<> - void LLSDMessageBuilderTestObject::test<45>() - { - LLMessageTemplate messageTemplate = defaultTemplate(); - messageTemplate.addBlock(defaultTemplateBlock(MVT_U8, 1)); - U8 inValue = 2; - LLTemplateMessageBuilder* template_builder = defaultTemplateBuilder(messageTemplate); - template_builder->addU8(_PREHASH_Test0, inValue); - - LLSDMessageBuilder builder; - builder.copyFromMessageData(*template_builder->getCurrentMessage()); - LLSD output = builder.getMessage(); - - ensure_equals(output["Test0"][0]["Test0"].asInteger(), 2); - - } - - template<> template<> - void LLSDMessageBuilderTestObject::test<46>() - { - LLMessageTemplate messageTemplate = defaultTemplate(); - messageTemplate.addBlock(defaultTemplateBlock(MVT_VARIABLE, 1)); - std::string inValue = "testing"; - LLTemplateMessageBuilder* builder = defaultTemplateBuilder(messageTemplate); - builder->addString(_PREHASH_Test0, inValue.c_str()); - - LLSDMessageBuilder sd_builder; - sd_builder.copyFromMessageData(*builder->getCurrentMessage()); - LLSD output = sd_builder.getMessage(); - - ensure_equals(output["Test0"][0]["Test0"].asString(), std::string("testing")); - } - -} - diff --git a/indra/test/llsdmessagereader_tut.cpp b/indra/test/llsdmessagereader_tut.cpp deleted file mode 100644 index dd6520ea33..0000000000 --- a/indra/test/llsdmessagereader_tut.cpp +++ /dev/null @@ -1,324 +0,0 @@ -/** - * @file llsdmessagereader_tut.cpp - * @date February 2006 - * @brief LLSDMessageReader unit tests - * - * $LicenseInfo:firstyear=2006&license=viewerlgpl$ - * Second Life Viewer Source Code - * Copyright (C) 2010, Linden Research, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; - * version 2.1 of the License only. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA - * $/LicenseInfo$ - */ - -#include -#include "linden_common.h" -#include "lltut.h" -#include "v3dmath.h" -#include "v3math.h" -#include "v4math.h" -#include "llquaternion.h" - -#include "message.h" -#include "llsdmessagereader.h" -#include "llsdutil.h" -#include "llsdutil_math.h" - -namespace tut -{ - struct LLSDMessageReaderTestData { - static void ensureMessageName(const std::string& msg_name, - const LLSD& msg_data, - const std::string& expected_name) - { - LLSDMessageReader msg; - msg.setMessage(LLMessageStringTable::getInstance()->getString(msg_name.c_str()), msg_data); - ensure_equals("Ensure name", std::string(msg.getMessageName()), - expected_name); - } - - static void ensureNumberOfBlocks(const LLSD& msg_data, - const std::string& block, - S32 expected_number) - { - LLSDMessageReader msg; - msg.setMessage("fakename", msg_data); - ensure_equals("Ensure number of blocks", msg.getNumberOfBlocks(block.c_str()), - expected_number); - } - - static void ensureMessageSize(const LLSD& msg_data, - S32 expected_size) - { - LLSDMessageReader msg; - msg.setMessage("fakename", msg_data); - ensure_equals( "Ensure size", msg.getMessageSize(), expected_size); - } - - static void ensureBool(const LLSD& msg_data, - const std::string& block, - const std::string& var, - S32 blocknum, - bool expected) - { - LLSDMessageReader msg; - msg.setMessage("fakename", msg_data); - bool test_data; - msg.getBOOL(block.c_str(), var.c_str(), test_data, blocknum); - ensure_equals( "Ensure bool field", test_data, expected); - } - }; - - typedef test_group LLSDMessageReaderTestGroup; - typedef LLSDMessageReaderTestGroup::object LLSDMessageReaderTestObject; - LLSDMessageReaderTestGroup llsdMessageReaderTestGroup("LLSDMessageReader"); - - template<> template<> - void LLSDMessageReaderTestObject::test<1>() - // construction and test of empty LLSD - { - LLSD message = LLSD::emptyMap(); - - ensureMessageName("", message, ""); - ensureNumberOfBlocks(message, "Fakeblock", 0); - ensureMessageSize(message, 0); - } - - template<> template<> - void LLSDMessageReaderTestObject::test<2>() - // construction and test of simple message with one block - { - LLSD message = LLSD::emptyMap(); - message["block1"] = LLSD::emptyArray(); - message["block1"][0] = LLSD::emptyMap(); - message["block1"][0]["Field1"] = 0; - - ensureMessageName("name2", message, "name2"); - ensureNumberOfBlocks(message, "block1", 1); - ensureMessageSize(message, 0); - } - - template<> template<> - void LLSDMessageReaderTestObject::test<3>() - // multiple blocks - { - LLSD message = LLSD::emptyMap(); - message["block1"] = LLSD::emptyArray(); - bool bool_true = true; - bool bool_false = false; - message["block1"][0] = LLSD::emptyMap(); - message["block1"][0]["BoolField1"] = bool_true; - message["block1"][1] = LLSD::emptyMap(); - message["block1"][1]["BoolField1"] = bool_false; - message["block1"][1]["BoolField2"] = bool_true; - - ensureMessageName("name3", message, "name3"); - ensureBool(message, "block1", "BoolField1", 0, true); - ensureBool(message, "block1", "BoolField1", 1, false); - ensureBool(message, "block1", "BoolField2", 1, true); - ensureNumberOfBlocks(message, "block1", 2); - ensureMessageSize(message, 0); - } - - template - LLSDMessageReader testType(const T& value) - { - LLSD message = LLSD::emptyMap(); - message["block"][0]["var"] = value; - LLSDMessageReader msg; - msg.setMessage("fakename", message); - return msg; - } - - template<> template<> - void LLSDMessageReaderTestObject::test<4>() - // S8 - { - S8 outValue, inValue = -3; - LLSDMessageReader msg = testType(inValue); - msg.getS8("block", "var", outValue); - ensure_equals("Ensure S8", outValue, inValue); - } - template<> template<> - void - LLSDMessageReaderTestObject::test<5>() - // U8 - { - U8 outValue, inValue = 2; - LLSDMessageReader msg = testType(inValue); - msg.getU8("block", "var", outValue); - ensure_equals("Ensure U8", outValue, inValue); - } - template<> template<> - void LLSDMessageReaderTestObject::test<6>() - // S16 - { - S16 outValue, inValue = 90; - LLSDMessageReader msg = testType(inValue); - msg.getS16("block", "var", outValue); - ensure_equals("Ensure S16", outValue, inValue); - } - template<> template<> - void LLSDMessageReaderTestObject::test<7>() - // U16 - { - U16 outValue, inValue = 3; - LLSDMessageReader msg = testType(inValue); - msg.getU16("block", "var", outValue); - ensure_equals("Ensure S16", outValue, inValue); - } - template<> template<> - void LLSDMessageReaderTestObject::test<8>() - // S32 - { - S32 outValue, inValue = 44; - LLSDMessageReader msg = testType(inValue); - msg.getS32("block", "var", outValue); - ensure_equals("Ensure S32", outValue, inValue); - } - template<> template<> - void LLSDMessageReaderTestObject::test<9>() - // F32 - { - F32 outValue, inValue = 121.44f; - LLSDMessageReader msg = testType(inValue); - msg.getF32("block", "var", outValue); - ensure_equals("Ensure F32", outValue, inValue); - } - template<> template<> - void LLSDMessageReaderTestObject::test<10>() - // U32 - { - U32 outValue, inValue = 88; - LLSD sdValue = ll_sd_from_U32(inValue); - LLSDMessageReader msg = testType(sdValue); - msg.getU32("block", "var", outValue); - ensure_equals("Ensure U32", outValue, inValue); - } - template<> template<> - void LLSDMessageReaderTestObject::test<11>() - // U64 - { - U64 outValue, inValue = 121; - LLSD sdValue = ll_sd_from_U64(inValue); - LLSDMessageReader msg = testType(sdValue); - msg.getU64("block", "var", outValue); - ensure_equals("Ensure U64", outValue, inValue); - } - template<> template<> - void LLSDMessageReaderTestObject::test<12>() - // F64 - { - F64 outValue, inValue = 3232143.33; - LLSDMessageReader msg = testType(inValue); - msg.getF64("block", "var", outValue); - ensure_equals("Ensure F64", outValue, inValue); - } - template<> template<> - void LLSDMessageReaderTestObject::test<13>() - // String - { - std::string outValue, inValue = "testing"; - LLSDMessageReader msg = testType(inValue.c_str()); - - char buffer[MAX_STRING]; - msg.getString("block", "var", MAX_STRING, buffer); - outValue = buffer; - ensure_equals("Ensure String", outValue, inValue); - } - template<> template<> - void LLSDMessageReaderTestObject::test<14>() - // Vector3 - { - LLVector3 outValue, inValue = LLVector3(1,2,3); - LLSD sdValue = ll_sd_from_vector3(inValue); - LLSDMessageReader msg = testType(sdValue); - msg.getVector3("block", "var", outValue); - ensure_equals("Ensure Vector3", outValue, inValue); - } - template<> template<> - void LLSDMessageReaderTestObject::test<15>() - // Vector4 - { - LLVector4 outValue, inValue = LLVector4(1,2,3,4); - LLSD sdValue = ll_sd_from_vector4(inValue); - LLSDMessageReader msg = testType(sdValue); - msg.getVector4("block", "var", outValue); - ensure_equals("Ensure Vector4", outValue, inValue); - } - template<> template<> - void LLSDMessageReaderTestObject::test<16>() - // Vector3d - { - LLVector3d outValue, inValue = LLVector3d(1,2,3); - LLSD sdValue = ll_sd_from_vector3d(inValue); - LLSDMessageReader msg = testType(sdValue); - msg.getVector3d("block", "var", outValue); - ensure_equals("Ensure Vector3d", outValue, inValue); - } - template<> template<> - void LLSDMessageReaderTestObject::test<17>() - // Quaternion - { - LLQuaternion outValue, inValue = LLQuaternion(1,LLVector3(2,3,4)); - LLSD sdValue = ll_sd_from_quaternion(inValue); - LLSDMessageReader msg = testType(sdValue); - msg.getQuat("block", "var", outValue); - ensure_equals("Ensure Quaternion", outValue, inValue); - } - template<> template<> - void LLSDMessageReaderTestObject::test<18>() - // UUID - { - LLUUID outValue, inValue; - inValue.generate(); - LLSDMessageReader msg = testType(inValue); - msg.getUUID("block", "var", outValue); - ensure_equals("Ensure UUID", outValue, inValue); - } - template<> template<> - void LLSDMessageReaderTestObject::test<19>() - // IPAddr - { - U32 outValue, inValue = 12344556; - LLSD sdValue = ll_sd_from_ipaddr(inValue); - LLSDMessageReader msg = testType(sdValue); - msg.getIPAddr("block", "var", outValue); - ensure_equals("Ensure IPAddr", outValue, inValue); - } - template<> template<> - void LLSDMessageReaderTestObject::test<20>() - // IPPort - { - U16 outValue, inValue = 80; - LLSDMessageReader msg = testType(inValue); - msg.getIPPort("block", "var", outValue); - ensure_equals("Ensure IPPort", outValue, inValue); - } - template<> template<> - void LLSDMessageReaderTestObject::test<21>() - // Binary - { - std::vector outValue(2), inValue(2); - inValue[0] = 0; - inValue[1] = 1; - - LLSDMessageReader msg = testType(inValue); - msg.getBinaryData("block", "var", &(outValue[0]), static_cast(inValue.size())); - ensure_equals("Ensure Binary", outValue, inValue); - } -} diff --git a/indra/test/llsdutil_tut.cpp b/indra/test/llsdutil_tut.cpp deleted file mode 100644 index 4b25a02f30..0000000000 --- a/indra/test/llsdutil_tut.cpp +++ /dev/null @@ -1,434 +0,0 @@ -/** - * @file llsdutil_tut.cpp - * @author Adroit - * @date 2007-02 - * @brief LLSD conversion routines test cases. - * - * $LicenseInfo:firstyear=2007&license=viewerlgpl$ - * Second Life Viewer Source Code - * Copyright (C) 2010, Linden Research, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; - * version 2.1 of the License only. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA - * $/LicenseInfo$ - */ - -#include "linden_common.h" -#include "lltut.h" -#include "m4math.h" -#include "v2math.h" -#include "v2math.h" -#include "v3color.h" -#include "v3math.h" -#include "v3dmath.h" -#include "v4coloru.h" -#include "v4math.h" -#include "llquaternion.h" -#include "llsdutil.h" -#include "llsdutil_math.h" -#include "stringize.h" -#include -#include - -namespace tut -{ - struct llsdutil_data - { - void test_matches(const std::string& proto_key, const LLSD& possibles, - const char** begin, const char** end) - { - std::set succeed(begin, end); - LLSD prototype(possibles[proto_key]); - for (LLSD::map_const_iterator pi(possibles.beginMap()), pend(possibles.endMap()); - pi != pend; ++pi) - { - std::string match(llsd_matches(prototype, pi->second)); - std::set::const_iterator found = succeed.find(pi->first); - if (found != succeed.end()) - { - // This test is supposed to succeed. Comparing to the - // empty string ensures that if the test fails, it will - // display the string received so we can tell what failed. - ensure_equals("match", match, ""); - } - else - { - // This test is supposed to fail. If we get a false match, - // the string 'match' will be empty, which doesn't tell us - // much about which case went awry. So construct a more - // detailed description string. - ensure(proto_key + " shouldn't match " + pi->first, ! match.empty()); - } - } - } - }; - typedef test_group llsdutil_test;; - typedef llsdutil_test::object llsdutil_object; - tut::llsdutil_test tutil("llsdutil"); - - template<> template<> - void llsdutil_object::test<1>() - { - LLSD sd; - U64 valueIn , valueOut; - valueIn = U64L(0xFEDCBA9876543210); - sd = ll_sd_from_U64(valueIn); - valueOut = ll_U64_from_sd(sd); - ensure_equals("U64 valueIn->sd->valueOut", valueIn, valueOut); - } - - template<> template<> - void llsdutil_object::test<2>() - { - LLSD sd; - U32 valueIn, valueOut; - valueIn = 0x87654321; - sd = ll_sd_from_U32(valueIn); - valueOut = ll_U32_from_sd(sd); - ensure_equals("U32 valueIn->sd->valueOut", valueIn, valueOut); - } - - template<> template<> - void llsdutil_object::test<3>() - { - U32 valueIn, valueOut; - valueIn = 0x87654321; - LLSD sd; - sd = ll_sd_from_ipaddr(valueIn); - valueOut = ll_ipaddr_from_sd(sd); - ensure_equals("valueIn->sd->valueOut", valueIn, valueOut); - } - - template<> template<> - void llsdutil_object::test<4>() - { - LLSD sd; - LLVector3 vec1(-1.0, 2.0, -3.0); - sd = ll_sd_from_vector3(vec1); - LLVector3 vec2 = ll_vector3_from_sd(sd); - ensure_equals("vector3 -> sd -> vector3: 1", vec1, vec2); - - LLVector3 vec3(sd); - ensure_equals("vector3 -> sd -> vector3: 2", vec1, vec3); - - sd.clear(); - vec1.setVec(0., 0., 0.); - sd = ll_sd_from_vector3(vec1); - vec2 = ll_vector3_from_sd(sd); - ensure_equals("vector3 -> sd -> vector3: 3", vec1, vec2); - sd.clear(); - } - - template<> template<> - void llsdutil_object::test<5>() - { - LLSD sd; - LLVector3d vec1((F64)(U64L(0xFEDCBA9876543210) << 2), -1., 0); - sd = ll_sd_from_vector3d(vec1); - LLVector3d vec2 = ll_vector3d_from_sd(sd); - ensure_equals("vector3d -> sd -> vector3d: 1", vec1, vec2); - - LLVector3d vec3(sd); - ensure_equals("vector3d -> sd -> vector3d : 2", vec1, vec3); - } - - template<> template<> - void llsdutil_object::test<6>() - { - LLSD sd; - LLVector2 vec((F32) -3., (F32) 4.2); - sd = ll_sd_from_vector2(vec); - LLVector2 vec1 = ll_vector2_from_sd(sd); - ensure_equals("vector2 -> sd -> vector2", vec, vec1); - - LLSD sd2 = ll_sd_from_vector2(vec1); - ensure_equals("sd -> vector2 -> sd: 2", sd, sd2); - } - - template<> template<> - void llsdutil_object::test<7>() - { - LLSD sd; - LLQuaternion quat((F32) 1., (F32) -0.98, (F32) 2.3, (F32) 0xffff); - sd = ll_sd_from_quaternion(quat); - LLQuaternion quat1 = ll_quaternion_from_sd(sd); - ensure_equals("LLQuaternion -> sd -> LLQuaternion", quat, quat1); - - LLSD sd2 = ll_sd_from_quaternion(quat1); - ensure_equals("sd -> LLQuaternion -> sd ", sd, sd2); - } - - template<> template<> - void llsdutil_object::test<8>() - { - LLSD sd; - LLColor4 c(1.0f, 2.2f, 4.0f, 7.f); - sd = ll_sd_from_color4(c); - LLColor4 c1 =ll_color4_from_sd(sd); - ensure_equals("LLColor4 -> sd -> LLColor4", c, c1); - - LLSD sd1 = ll_sd_from_color4(c1); - ensure_equals("sd -> LLColor4 -> sd", sd, sd1); - } - - template<> template<> - void llsdutil_object::test<9>() - { - set_test_name("llsd_matches"); - - // for this test, construct a map of all possible LLSD types - LLSD map; - map.insert("empty", LLSD()); - map.insert("Boolean", LLSD::Boolean()); - map.insert("Integer", LLSD::Integer(0)); - map.insert("Real", LLSD::Real(0.0)); - map.insert("String", LLSD::String("bah")); - map.insert("NumString", LLSD::String("1")); - map.insert("UUID", LLSD::UUID()); - map.insert("Date", LLSD::Date()); - map.insert("URI", LLSD::URI()); - map.insert("Binary", LLSD::Binary()); - map.insert("Map", LLSD().with("foo", LLSD())); - // Only an empty array can be constructed on the fly - LLSD array; - array.append(LLSD()); - map.insert("Array", array); - - // These iterators are declared outside our various for loops to avoid - // fatal MSVC warning: "I used to be broken, but I'm all better now!" - LLSD::map_const_iterator mi, mend(map.endMap()); - - /*-------------------------- llsd_matches --------------------------*/ - - // empty prototype matches anything - for (mi = map.beginMap(); mi != mend; ++mi) - { - ensure_equals(std::string("empty matches ") + mi->first, llsd_matches(LLSD(), mi->second), ""); - } - - LLSD proto_array, data_array; - for (int i = 0; i < 3; ++i) - { - proto_array.append(LLSD()); - data_array.append(LLSD()); - } - - // prototype array matches only array - for (mi = map.beginMap(); mi != mend; ++mi) - { - ensure(std::string("array doesn't match ") + mi->first, - ! llsd_matches(proto_array, mi->second).empty()); - } - - // data array must be at least as long as prototype array - proto_array.append(LLSD()); - ensure_equals("data array too short", llsd_matches(proto_array, data_array), - "Array size 4 required instead of Array size 3"); - data_array.append(LLSD()); - ensure_equals("data array just right", llsd_matches(proto_array, data_array), ""); - data_array.append(LLSD()); - ensure_equals("data array longer", llsd_matches(proto_array, data_array), ""); - - // array element matching - data_array[0] = LLSD::String(); - ensure_equals("undefined prototype array entry", llsd_matches(proto_array, data_array), ""); - proto_array[0] = LLSD::Binary(); - ensure_equals("scalar prototype array entry", llsd_matches(proto_array, data_array), - "[0]: Binary required instead of String"); - data_array[0] = LLSD::Binary(); - ensure_equals("matching prototype array entry", llsd_matches(proto_array, data_array), ""); - - // build a coupla maps - LLSD proto_map, data_map; - data_map["got"] = LLSD(); - data_map["found"] = LLSD(); - for (LLSD::map_const_iterator dmi(data_map.beginMap()), dmend(data_map.endMap()); - dmi != dmend; ++dmi) - { - proto_map[dmi->first] = dmi->second; - } - proto_map["foo"] = LLSD(); - proto_map["bar"] = LLSD(); - - // prototype map matches only map - for (mi = map.beginMap(); mi != mend; ++mi) - { - ensure(std::string("map doesn't match ") + mi->first, - ! llsd_matches(proto_map, mi->second).empty()); - } - - // data map must contain all keys in prototype map - std::string error(llsd_matches(proto_map, data_map)); - ensure_contains("missing keys", error, "missing keys"); - ensure_contains("missing foo", error, "foo"); - ensure_contains("missing bar", error, "bar"); - ensure_does_not_contain("found found", error, "found"); - ensure_does_not_contain("got got", error, "got"); - data_map["bar"] = LLSD(); - error = llsd_matches(proto_map, data_map); - ensure_contains("missing foo", error, "foo"); - ensure_does_not_contain("got bar", error, "bar"); - data_map["foo"] = LLSD(); - ensure_equals("data map just right", llsd_matches(proto_map, data_map), ""); - data_map["extra"] = LLSD(); - ensure_equals("data map with extra", llsd_matches(proto_map, data_map), ""); - - // map element matching - data_map["foo"] = LLSD::String(); - ensure_equals("undefined prototype map entry", llsd_matches(proto_map, data_map), ""); - proto_map["foo"] = LLSD::Binary(); - ensure_equals("scalar prototype map entry", llsd_matches(proto_map, data_map), - "['foo']: Binary required instead of String"); - data_map["foo"] = LLSD::Binary(); - ensure_equals("matching prototype map entry", llsd_matches(proto_map, data_map), ""); - - // String - { - static const char* matches[] = { "String", "NumString", "Boolean", "Integer", - "Real", "UUID", "Date", "URI" }; - test_matches("String", map, boost::begin(matches), boost::end(matches)); - } - - // Boolean, Integer, Real - static const char* numerics[] = { "Boolean", "Integer", "Real" }; - for (const char **ni = boost::begin(numerics), **nend = boost::end(numerics); - ni != nend; ++ni) - { - static const char* matches[] = { "Boolean", "Integer", "Real", "String", "NumString" }; - test_matches(*ni, map, boost::begin(matches), boost::end(matches)); - } - - // UUID - { - static const char* matches[] = { "UUID", "String", "NumString" }; - test_matches("UUID", map, boost::begin(matches), boost::end(matches)); - } - - // Date - { - static const char* matches[] = { "Date", "String", "NumString" }; - test_matches("Date", map, boost::begin(matches), boost::end(matches)); - } - - // URI - { - static const char* matches[] = { "URI", "String", "NumString" }; - test_matches("URI", map, boost::begin(matches), boost::end(matches)); - } - - // Binary - { - static const char* matches[] = { "Binary" }; - test_matches("Binary", map, boost::begin(matches), boost::end(matches)); - } - - /*-------------------------- llsd_equals ---------------------------*/ - - // Cross-product of each LLSD type with every other - for (LLSD::map_const_iterator lmi(map.beginMap()), lmend(map.endMap()); - lmi != lmend; ++lmi) - { - for (LLSD::map_const_iterator rmi(map.beginMap()), rmend(map.endMap()); - rmi != rmend; ++rmi) - { - // Name this test based on the map keys naming the types of - // interest, e.g "String::Integer". - // We expect the values (xmi->second) to be equal if and only - // if the type names (xmi->first) are equal. - ensure(STRINGIZE(lmi->first << "::" << rmi->first), - bool(lmi->first == rmi->first) == - bool(llsd_equals(lmi->second, rmi->second))); - } - } - - // Array cases - LLSD rarray; - rarray.append(1.0); - rarray.append(2); - rarray.append("3"); - LLSD larray(rarray); - ensure("llsd_equals(equal arrays)", llsd_equals(larray, rarray)); - rarray[2] = "4"; - ensure("llsd_equals(different [2])", ! llsd_equals(larray, rarray)); - rarray = larray; - rarray.append(LLSD::Date()); - ensure("llsd_equals(longer right array)", ! llsd_equals(larray, rarray)); - rarray = larray; - rarray.erase(2); - ensure("llsd_equals(shorter right array)", ! llsd_equals(larray, rarray)); - - // Map cases - LLSD rmap; - rmap["San Francisco"] = 65; - rmap["Phoenix"] = 92; - rmap["Boston"] = 77; - LLSD lmap(rmap); - ensure("llsd_equals(equal maps)", llsd_equals(lmap, rmap)); - rmap["Boston"] = 80; - ensure("llsd_equals(different [\"Boston\"])", ! llsd_equals(lmap, rmap)); - rmap = lmap; - rmap["Atlanta"] = 95; - ensure("llsd_equals(superset right map)", ! llsd_equals(lmap, rmap)); - rmap = lmap; - lmap["Seattle"] = 72; - ensure("llsd_equals(superset left map)", ! llsd_equals(lmap, rmap)); - } - - template<> template<> - void llsdutil_object::test<10>() - { - set_test_name("llsd_hashing"); - - { - LLSD data_s1 = LLSD::String("The quick brown aardvark jumped over the lazy lemming."); - LLSD data_s2 = LLSD::String("The quick brown aardvark jumped over the lazy lemming."); - - ensure("hash: Identical string hashes match.", boost::hash{}(data_s1) == boost::hash{}(data_s2)); - } - { - LLSD data_r1 = LLSD::Real(3.0f); - LLSD data_i1 = LLSD::Integer(3); - ensure("hash: equivalent values but different types do not match.", boost::hash{}(data_r1) != boost::hash{}(data_i1)); - } - { - LLSD data_a1 = llsd::array("A", "B", "C"); - LLSD data_a2 = llsd::array("A", "B", "C"); - - ensure("hash: identical arrays produce identical results", boost::hash{}(data_a1) == boost::hash{}(data_a2)); - - data_a2.append(llsd::array(1, 2)); - - ensure("hash: changing the array changes the hash.", boost::hash{}(data_a1) != boost::hash{}(data_a2)); - - data_a1.append(llsd::array(1, 2)); - ensure("hash: identical arrays produce identical results with nested arrays", boost::hash{}(data_a1) == boost::hash{}(data_a2)); - } - { - LLSD data_m1 = LLSDMap("key1", LLSD::Real(3.0))("key2", "value2")("key3", llsd::array(1, 2, 3)); - LLSD data_m2 = LLSDMap("key1", LLSD::Real(3.0))("key2", "value2")("key3", llsd::array(1, 2, 3)); - - ensure("hash: identical maps produce identical results", boost::hash{}(data_m1) == boost::hash{}(data_m2)); - - LLSD data_m3 = LLSDMap("key1", LLSD::Real(5.0))("key2", "value2")("key3", llsd::array(1, 2, 3)); - ensure("hash: Different values in the map produce different hashes.", boost::hash{}(data_m1) != boost::hash{}(data_m3)); - - LLSD data_m4 = LLSDMap("keyA", LLSD::Real(3.0))("key2", "value2")("key3", llsd::array(1, 2, 3)); - ensure("hash: Different keys in the map produce different hashes.", boost::hash{}(data_m1) != boost::hash{}(data_m4)); - - } - } - -} diff --git a/indra/test/llservicebuilder_tut.cpp b/indra/test/llservicebuilder_tut.cpp deleted file mode 100644 index 0bc17865d6..0000000000 --- a/indra/test/llservicebuilder_tut.cpp +++ /dev/null @@ -1,173 +0,0 @@ -/** -* @file llservicebuilder_tut.cpp -* @brief LLServiceBuilder unit tests -* @date March 2007 -* -* $LicenseInfo:firstyear=2006&license=viewerlgpl$ -* Second Life Viewer Source Code -* Copyright (C) 2010, Linden Research, Inc. -* -* This library is free software; you can redistribute it and/or -* modify it under the terms of the GNU Lesser General Public -* License as published by the Free Software Foundation; -* version 2.1 of the License only. -* -* This library is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -* Lesser General Public License for more details. -* -* You should have received a copy of the GNU Lesser General Public -* License along with this library; if not, write to the Free Software -* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA -* -* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA -* $/LicenseInfo$ -*/ - -#include - -#include "linden_common.h" -#include "lltut.h" -#include "llsd.h" -#include "llservicebuilder.h" - -namespace tut -{ - - struct ServiceBuilderTestData { - LLServiceBuilder mServiceBuilder; - }; - - typedef test_group ServiceBuilderTestGroup; - typedef ServiceBuilderTestGroup::object ServiceBuilderTestObject; - - ServiceBuilderTestGroup serviceBuilderTestGroup("ServiceBuilder"); - - template<> template<> - void ServiceBuilderTestObject::test<1>() - { - //Simple service build and reply with no mapping - LLSD test_block; - test_block["service-builder"] = "/agent/name"; - mServiceBuilder.createServiceDefinition("ServiceBuilderTest", test_block["service-builder"]); - std::string test_url = mServiceBuilder.buildServiceURI("ServiceBuilderTest"); - ensure_equals("Basic URL Creation", test_url , "/agent/name"); - } - - template<> template<> - void ServiceBuilderTestObject::test<2>() - { - //Simple replace test - LLSD test_block; - test_block["service-builder"] = "/agent/{$agent-id}/name"; - mServiceBuilder.createServiceDefinition("ServiceBuilderTest", test_block["service-builder"]); - LLSD data_map; - data_map["agent-id"] = "257c631f-a0c5-4f29-8a9f-9031feaae6c6"; - std::string test_url = mServiceBuilder.buildServiceURI("ServiceBuilderTest", data_map); - ensure_equals("Replacement URL Creation", test_url , "/agent/257c631f-a0c5-4f29-8a9f-9031feaae6c6/name"); - } - - template<> template<> - void ServiceBuilderTestObject::test<3>() - { - //Incorrect service test - LLSD test_block; - test_block["service-builder"] = "/agent/{$agent-id}/name"; - mServiceBuilder.createServiceDefinition("ServiceBuilderTest", test_block["service-builder"]); - std::string test_url = mServiceBuilder.buildServiceURI("ServiceBuilder"); - ensure_equals("Replacement URL Creation for Non-existant Service", test_url , ""); - } - - template<> template<> - void ServiceBuilderTestObject::test<4>() - { - //Incorrect service test - LLSD test_block; - test_block["service-builder"] = "/agent/{$agent-id}/name"; - mServiceBuilder.createServiceDefinition("ServiceBuilderTest", test_block["service-builder"]); - LLSD data_map; - data_map["agent_id"] = "257c631f-a0c5-4f29-8a9f-9031feaae6c6"; - std::string test_url = mServiceBuilder.buildServiceURI("ServiceBuilderTest", data_map); - ensure_equals("Replacement URL Creation for Non-existant Service", test_url , "/agent/{$agent-id}/name"); - } - - template<> template<> - void ServiceBuilderTestObject::test<5>() - { - LLSD test_block; - test_block["service-builder"] = "/proc/{$proc}{%params}"; - mServiceBuilder.createServiceDefinition("ServiceBuilderTest", test_block["service-builder"]); - LLSD data_map; - data_map["proc"] = "do/something/useful"; - data_map["params"]["estate_id"] = 1; - data_map["params"]["query"] = "public"; - std::string test_url = mServiceBuilder.buildServiceURI("ServiceBuilderTest", data_map); - ensure_equals( - "two part URL Creation", - test_url , - "/proc/do/something/useful?estate_id=1&query=public"); - } - - template<> template<> - void ServiceBuilderTestObject::test<6>() - { - LLSD test_block; - test_block["service-builder"] = "Which way to the {${$baz}}?"; - mServiceBuilder.createServiceDefinition( - "ServiceBuilderTest", - test_block["service-builder"]); - - LLSD data_map; - data_map["foo"] = "bar"; - data_map["baz"] = "foo"; - std::string test_url = mServiceBuilder.buildServiceURI( - "ServiceBuilderTest", - data_map); - ensure_equals( - "recursive url creation", - test_url , - "Which way to the bar?"); - } - - template<> template<> - void ServiceBuilderTestObject::test<7>() - { - LLSD test_block; - test_block["service-builder"] = "Which way to the {$foo}?"; - mServiceBuilder.createServiceDefinition( - "ServiceBuilderTest", - test_block["service-builder"]); - - LLSD data_map; - data_map["baz"] = "foo"; - std::string test_url = mServiceBuilder.buildServiceURI( - "ServiceBuilderTest", - data_map); - ensure_equals( - "fails to do replacement", - test_url , - "Which way to the {$foo}?"); - } - - template<> template<> - void ServiceBuilderTestObject::test<8>() - { - LLSD test_block; - test_block["service-builder"] = "/proc/{$proc}{%params}"; - mServiceBuilder.createServiceDefinition( - "ServiceBuilderTest", - test_block["service-builder"]); - LLSD data_map; - data_map["proc"] = "do/something/useful"; - data_map["params"] = LLSD(); - std::string test_url = mServiceBuilder.buildServiceURI( - "ServiceBuilderTest", - data_map); - ensure_equals( - "strip params", - test_url , - "/proc/do/something/useful"); - } -} - diff --git a/indra/test/llstreamtools_tut.cpp b/indra/test/llstreamtools_tut.cpp deleted file mode 100644 index 970afb3b02..0000000000 --- a/indra/test/llstreamtools_tut.cpp +++ /dev/null @@ -1,883 +0,0 @@ -/** - * @file llstreamtools_tut.cpp - * @author Adroit - * @date February 2007 - * @brief llstreamtools test cases. - * - * $LicenseInfo:firstyear=2007&license=viewerlgpl$ - * Second Life Viewer Source Code - * Copyright (C) 2010, Linden Research, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; - * version 2.1 of the License only. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA - * $/LicenseInfo$ - */ - -#include - -#include "linden_common.h" -#include "llstreamtools.h" -#include "lltut.h" - - -namespace tut -{ - struct streamtools_data - { - }; - typedef test_group streamtools_test; - typedef streamtools_test::object streamtools_object; - tut::streamtools_test streamtools_testcase("streamtools"); - - //test cases for skip_whitespace() - template<> template<> - void streamtools_object::test<1>() - { - char arr[255]; - std::string str; - std::string expected_result; - std::string actual_result; - std::istringstream is; - - is.str(str = ""); - ensure("skip_whitespace: empty string", (false == skip_whitespace(is))); - - is.clear(); - is.str(str = " SecondLife is a 3D World"); - skip_whitespace(is); - is.get(arr, 255, '\0'); - expected_result = "SecondLife is a 3D World"; - ensure_equals("skip_whitespace: space", arr, expected_result); - - is.clear(); - is.str(str = "\t \tSecondLife is a 3D World"); - skip_whitespace(is); - is.get(arr, 255, '\0'); - expected_result = "SecondLife is a 3D World"; - ensure_equals("skip_whitespace: space and tabs", arr, expected_result); - - is.clear(); - is.str(str = "\t \tSecondLife is a 3D World "); - skip_whitespace(is); - is.get(arr, 255, '\0'); - expected_result = "SecondLife is a 3D World "; - ensure_equals("skip_whitespace: space at end", arr, expected_result); - - is.clear(); - is.str(str = "\t \r\nSecondLife is a 3D World"); - skip_whitespace(is); - is.get(arr, 255, '\0'); - expected_result = "\r\nSecondLife is a 3D World"; - ensure_equals("skip_whitespace: space at end", arr, expected_result); - } - - //testcases for skip_emptyspaces() - template<> template<> - void streamtools_object::test<2>() - { - char arr[255]; - std::string str; - std::string expected_result; - std::string actual_result; - std::istringstream is; - bool ret; - - is.clear(); - is.str(str = " \tSecondLife is a 3D World.\n"); - skip_emptyspace(is); - is.get(arr, 255, '\0'); - expected_result = "SecondLife is a 3D World.\n"; - ensure_equals("skip_emptyspace: space and tabs", arr, expected_result); - - is.clear(); - is.str(str = " \t\r\n \r SecondLife is a 3D World.\n"); - skip_emptyspace(is); - is.get(arr, 255, '\0'); - expected_result = "SecondLife is a 3D World.\n"; - ensure_equals("skip_emptyspace: space, tabs, carriage return, newline", arr, expected_result); - - is.clear(); - is.str(str = ""); - ret = skip_emptyspace(is); - is.get(arr, 255, '\0'); - ensure("skip_emptyspace: empty string", ret == false); - - is.clear(); - is.str(str = " \r\n \t "); - ret = skip_emptyspace(is); - is.get(arr, 255, '\0'); - ensure("skip_emptyspace: space newline empty", ret == false); - } - - //testcases for skip_comments_and_emptyspace() - template<> template<> - void streamtools_object::test<3>() - { - char arr[255]; - std::string str; - std::string expected_result; - std::string actual_result; - std::istringstream is; - bool ret; - - is.clear(); - is.str(str = " \t\r\n \r SecondLife is a 3D World.\n"); - skip_comments_and_emptyspace(is); - is.get(arr, 255, '\0'); - expected_result = "SecondLife is a 3D World.\n"; - ensure_equals("skip_comments_and_emptyspace: space, tabs, carriage return, newline", arr, expected_result); - - is.clear(); - is.str(str = "# \r\n SecondLife is a 3D World."); - skip_comments_and_emptyspace(is); - is.get(arr, 255, '\0'); - expected_result = "SecondLife is a 3D World."; - ensure_equals("skip_comments_and_emptyspace: skip comment - 1", arr, expected_result); - - is.clear(); - is.str(str = "# \r\n # SecondLife is a 3D World. ##"); - ensure("should not be good()", ! skip_comments_and_emptyspace(is)); - ensure("should be at eof()", is.eof()); - // don't get(): given bad state, we can't rely on results - - is.clear(); - is.str(str = " \r\n SecondLife is a 3D World. ##"); - skip_comments_and_emptyspace(is); - is.get(arr, 255, '\0'); - expected_result = "SecondLife is a 3D World. ##"; - ensure_equals("skip_comments_and_emptyspace: skip comment - 3", arr, expected_result); - - is.clear(); - is.str(str = ""); - ret = skip_comments_and_emptyspace(is); - ensure("skip_comments_and_emptyspace: empty string", ! ret); - - is.clear(); - is.str(str = " \r\n \t # SecondLife is a 3D World"); - ret = skip_comments_and_emptyspace(is); - ensure("skip_comments_and_emptyspace: space newline comment empty", ! ret); - } - - //testcases for skip_line() - template<> template<> - void streamtools_object::test<4>() - { - char arr[255]; - std::string str; - std::string expected_result; - std::string actual_result; - std::istringstream is; - bool ret; - - is.clear(); - is.str(str = "SecondLife is a 3D World.\n\n It provides an opportunity to the site \nuser to perform real life activities in virtual world."); - skip_line(is); - is.get(arr, 255, '\0'); - expected_result = "\n It provides an opportunity to the site \nuser to perform real life activities in virtual world."; - ensure_equals("skip_line: 1 newline", arr, expected_result); - - is.clear(); - is.str(expected_result); - skip_line(is); - is.get(arr, 255, '\0'); - expected_result = " It provides an opportunity to the site \nuser to perform real life activities in virtual world."; - ensure_equals("skip_line: 2 newline", arr, expected_result); - - is.clear(); - is.str(expected_result); - skip_line(is); - is.get(arr, 255, '\0'); - expected_result = "user to perform real life activities in virtual world."; - ensure_equals("skip_line: 3 newline", arr, expected_result); - - is.clear(); - is.str(str = ""); - ret = skip_line(is); - ensure("skip_line: empty string", ret == false); - } - - - // testcases for skip_to_next_word() - template<> template<> - void streamtools_object::test<5>() - { - char arr[255]; - std::string str; - std::string expected_result; - std::string actual_result; - std::istringstream is; - bool ret; - - is.clear(); - is.str(str = "SecondLife is a 3D_World.\n\n It-provides an opportunity to the site \nuser to perform real life activities in virtual world."); - skip_to_next_word(is); // get past SecondLife - is.get(arr, 255, '\0'); - expected_result = "is a 3D_World.\n\n It-provides an opportunity to the site \nuser to perform real life activities in virtual world."; - ensure_equals("skip_to_next_word: 1", arr, expected_result); - - is.clear(); - is.str(expected_result); - skip_to_next_word(is); // get past is - skip_to_next_word(is); // get past a - skip_to_next_word(is); // get past 3D_World.\n\n - is.get(arr, 255, '\0'); - expected_result = "It-provides an opportunity to the site \nuser to perform real life activities in virtual world."; - ensure_equals("skip_to_next_word: get past .\n\n 2", arr, expected_result); - - is.clear(); - is.str(expected_result); - skip_to_next_word(is); // get past It- - expected_result = "provides an opportunity to the site \nuser to perform real life activities in virtual world."; - is.get(arr, 255, '\0'); - ensure_equals("skip_to_next_word: get past -", arr, expected_result); - - is.clear(); - is.str(str = ""); - ret = skip_to_next_word(is); - ensure("skip_line: empty string", ret == false); - - is.clear(); - is.str(str = " \r\n\r\n"); - ret = skip_to_next_word(is); - ensure("skip_line: space new lines", ret == false); - } - - - //testcases for skip_to_end_of_next_keyword() - template<> template<> - void streamtools_object::test<6>() - { - char arr[255]; - std::string str; - std::string expected_result; - std::string actual_result; - std::istringstream is; - bool ret; - - is.clear(); - is.str(str = "FIRSTKEY followed by second delimiter\nSECONDKEY\t SecondValue followed by third delimiter \nSECONDKEY\nFOURTHKEY FOURTHVALUEis a 3DWorld."); - ret = skip_to_end_of_next_keyword("FIRSTKEY", is); - is.get(arr, 255, '\0'); - expected_result = " followed by second delimiter\nSECONDKEY\t SecondValue followed by third delimiter \nSECONDKEY\nFOURTHKEY FOURTHVALUEis a 3DWorld."; - ensure_equals("skip_to_end_of_next_keyword: 1", arr, expected_result); - - is.clear(); - is.str(expected_result); - ret = skip_to_end_of_next_keyword("SECONDKEY", is); - is.get(arr, 255, '\0'); - expected_result = "\t SecondValue followed by third delimiter \nSECONDKEY\nFOURTHKEY FOURTHVALUEis a 3DWorld."; - ensure_equals("skip_to_end_of_next_keyword: 2", arr, expected_result); - - is.clear(); - is.str(expected_result); - ret = skip_to_end_of_next_keyword("SECONDKEY", is); - is.get(arr, 255, '\0'); - expected_result = "\nFOURTHKEY FOURTHVALUEis a 3DWorld."; - ensure_equals("skip_to_end_of_next_keyword: 3", arr, expected_result); - - is.clear(); - is.str(expected_result); - ret = skip_to_end_of_next_keyword("FOURTHKEY", is); - is.get(arr, 255, '\0'); - expected_result = " FOURTHVALUEis a 3DWorld."; - ensure_equals("skip_to_end_of_next_keyword: 4", arr, expected_result); - - is.clear(); - is.str(str = "{should be skipped as newline/space/tab does not follow but this one should be picked\n { Does it?\n"); - ret = skip_to_end_of_next_keyword("{", is); - is.get(arr, 255, '\0'); - expected_result = " Does it?\n"; - ensure_equals("skip_to_end_of_next_keyword: multiple delim matches on same line", arr, expected_result); - - is.clear(); - is.str(str = "Delim { could not be found at start"); - ret = skip_to_end_of_next_keyword("{", is); - ensure("skip_to_end_of_next_keyword: delim should not be present", ret == false); - - is.clear(); - is.str(str = "Empty Delim"); - ret = skip_to_end_of_next_keyword("", is); - ensure("skip_to_end_of_next_keyword: empty delim should not be valid", ret == false); - - is.clear(); - is.str(str = ""); - ret = skip_to_end_of_next_keyword("}", is); - ensure("skip_to_end_of_next_keyword: empty string", ret == false); - } - - //testcases for get_word(std::string& output_string, std::istream& input_stream) - template<> template<> - void streamtools_object::test<7>() - { - std::string str; - std::string expected_result; - std::string actual_result; - std::istringstream is; - bool ret; - - is.clear(); - is.str(str = " First Second \t \r \n Third Fourth-ShouldThisBePartOfFourth Fifth\n"); - actual_result = ""; - ret = get_word(actual_result, is); - expected_result = "First"; - ensure_equals("get_word: 1", actual_result, expected_result); - - actual_result = ""; - ret = get_word(actual_result, is); - expected_result = "Second"; - ensure_equals("get_word: 2", actual_result, expected_result); - - actual_result = ""; - ret = get_word(actual_result, is); - expected_result = "Third"; - ensure_equals("get_word: 3", actual_result, expected_result); - - // the current implementation of get_word seems inconsistent with - // skip_to_next_word. skip_to_next_word treats any character other - // than alhpa-numeric and '_' as a delimter, while get_word() - // treats only isspace() (i.e. space, form-feed('\f'), newline ('\n'), - // carriage return ('\r'), horizontal tab ('\t'), and vertical tab ('\v') - // as delimiters - actual_result = ""; - ret = get_word(actual_result, is); // will copy Fourth-ShouldThisBePartOfFourth - expected_result = "Fourth-ShouldThisBePartOfFourth"; // as per current impl. - ensure_equals("get_word: 4", actual_result, expected_result); - - actual_result = ""; - ret = get_word(actual_result, is); // will copy Fifth - expected_result = "Fifth"; // as per current impl. - ensure_equals("get_word: 5", actual_result, expected_result); - - is.clear(); - is.str(str = " \t \r \n "); - actual_result = ""; - ret = get_word(actual_result, is); - ensure("get_word: empty all spaces, newline tabs", ret == false); - - is.clear(); - is.str(str = ""); - actual_result = ""; - ret = get_word(actual_result, is); - ensure("get_word: empty string", ret == false); - } - - // testcase for get_word and skip_to_next_word compatibility - template<> template<> - void streamtools_object::test<8>() - { - std::string str; - std::string expected_result; - std::string actual_result; - std::istringstream is; - - is.clear(); - is.str(str = " First Second \t \r \n Third Fourth-ShouldThisBePartOfFourth Fifth\n"); - actual_result = ""; - get_word(actual_result, is); // First - actual_result = ""; - get_word(actual_result, is); // Second - actual_result = ""; - get_word(actual_result, is); // Third - - // the current implementation of get_word seems inconsistent with - // skip_to_next_word. skip_to_next_word treats any character other - // than alhpa-numeric and '_' as a delimter, while get_word() - // treats only isspace() (i.e. space, form-feed('\f'), newline ('\n'), - // carriage return ('\r'), horizontal tab ('\t'), and vertical tab ('\v') - // as delimiters - actual_result = ""; - get_word(actual_result, is); // will copy Fourth-ShouldThisBePartOfFourth - - actual_result = ""; - get_word(actual_result, is); // will copy Fifth - - is.clear(); - is.str(str = " First Second \t \r \n Third Fourth_ShouldThisBePartOfFourth Fifth\n"); - skip_to_next_word(is); // should now point to First - skip_to_next_word(is); // should now point to Second - skip_to_next_word(is); // should now point to Third - skip_to_next_word(is); // should now point to Fourth - skip_to_next_word(is); // should now point to ShouldThisBePartOfFourth - expected_result = ""; - // will copy ShouldThisBePartOfFourth, the fifth word, - // while using get_word above five times result in getting "Fifth" - get_word(expected_result, is); - ensure_equals("get_word: skip_to_next_word compatibility", actual_result, expected_result); - } - - //testcases for get_word(std::string& output_string, std::istream& input_stream, int n) - template<> template<> - void streamtools_object::test<9>() - { - std::string str; - std::string expected_result; - std::string actual_result; - std::istringstream is; - bool ret; - - is.clear(); - is.str(str = " First Second \t \r \n Third Fourth-ShouldThisBePartOfFourth Fifth\n"); - actual_result = ""; - ret = get_word(actual_result, is, 255); - expected_result = "First"; - ensure_equals("get_word: 1", actual_result, expected_result); - - actual_result = ""; - ret = get_word(actual_result, is, 4); - expected_result = "Seco"; // should be cut short - ensure_equals("get_word: 2", actual_result, expected_result); - - actual_result = ""; - ret = get_word(actual_result, is, 255); - expected_result = "nd"; // get remainder of Second - ensure_equals("get_word: 3", actual_result, expected_result); - - actual_result = ""; - ret = get_word(actual_result, is, 0); // 0 size string - expected_result = ""; // get remainder of Second - ensure_equals("get_word: 0 sized output", actual_result, expected_result); - - actual_result = ""; - ret = get_word(actual_result, is, 255); - expected_result = "Third"; - ensure_equals("get_word: 4", actual_result, expected_result); - - is.clear(); - is.str(str = " \t \r \n "); - actual_result = ""; - ret = get_word(actual_result, is, 255); - ensure("get_word: empty all spaces, newline tabs", ret == false); - - is.clear(); - is.str(str = ""); - actual_result = ""; - ret = get_word(actual_result, is, 255); - ensure("get_word: empty string", ret == false); - } - - //test cases for get_line(std::string& output_string, std::istream& input_stream) - template<> template<> - void streamtools_object::test<10>() - { - std::string str; - std::string expected_result; - std::string actual_result; - std::istringstream is; - - is.clear(); - is.str(str = "First Second \t \r\n Third Fourth-ShouldThisBePartOfFourth IsThisFifth\n"); - actual_result = ""; - get_line(actual_result, is); - expected_result = "First Second \t \r\n"; - ensure_equals("get_line: 1", actual_result, expected_result); - - actual_result = ""; - get_line(actual_result, is); - expected_result = " Third Fourth-ShouldThisBePartOfFourth IsThisFifth\n"; - ensure_equals("get_line: 2", actual_result, expected_result); - - is.clear(); - is.str(str = "\nFirst Line.\n\nSecond Line.\n"); - actual_result = ""; - get_line(actual_result, is); - expected_result = "\n"; - ensure_equals("get_line: First char as newline", actual_result, expected_result); - - actual_result = ""; - get_line(actual_result, is); - expected_result = "First Line.\n"; - ensure_equals("get_line: 3", actual_result, expected_result); - - actual_result = ""; - get_line(actual_result, is); - expected_result = "\n"; - ensure_equals("get_line: 4", actual_result, expected_result); - - actual_result = ""; - get_line(actual_result, is); - expected_result = "Second Line.\n"; - ensure_equals("get_line: 5", actual_result, expected_result); - } - - //test cases for get_line(std::string& output_string, std::istream& input_stream) - template<> template<> - void streamtools_object::test<11>() - { - std::string str; - std::string expected_result; - std::string actual_result; - std::istringstream is; - bool ret; - - is.clear(); - is.str(str = "One Line only with no newline"); - actual_result = ""; - ret = get_line(actual_result, is); - expected_result = "One Line only with no newline"; - ensure_equals("get_line: No newline", actual_result, expected_result); - ensure_equals("return value is good state of stream", ret, is.good()); - } - - //test cases for get_line(std::string& output_string, std::istream& input_stream) - template<> template<> - void streamtools_object::test<12>() - { - std::string str; - std::string expected_result; - std::string actual_result; - std::istringstream is; - - // need to be check if this test case is wrong or the implementation is wrong. - is.clear(); - is.str(str = "Should not skip lone \r.\r\n"); - actual_result = ""; - get_line(actual_result, is); - expected_result = "Should not skip lone \r.\r\n"; - ensure_equals("get_line: carriage return skipped even though not followed by newline", actual_result, expected_result); - } - - //test cases for get_line(std::string& output_string, std::istream& input_stream) - template<> template<> - void streamtools_object::test<13>() - { - std::string str; - std::string expected_result; - std::string actual_result; - std::istringstream is; - - is.clear(); - is.str(str = "\n"); - actual_result = ""; - get_line(actual_result, is); - expected_result = "\n"; - ensure_equals("get_line: Just newline", actual_result, expected_result); - } - - - //testcases for get_line(std::string& output_string, std::istream& input_stream, int n) - template<> template<> - void streamtools_object::test<14>() - { - std::string str; - std::string expected_result; - std::string actual_result; - std::istringstream is; - - is.clear(); - is.str(str = "First Line.\nSecond Line.\n"); - actual_result = ""; - get_line(actual_result, is, 255); - expected_result = "First Line.\n"; - ensure_equals("get_line: Basic Operation", actual_result, expected_result); - - actual_result = ""; - get_line(actual_result, is, sizeof("Second")-1); - expected_result = "Second\n"; - ensure_equals("get_line: Insufficient length 1", actual_result, expected_result); - - actual_result = ""; - get_line(actual_result, is, 255); - expected_result = " Line.\n"; - ensure_equals("get_line: Remainder after earlier insufficient length", actual_result, expected_result); - - is.clear(); - is.str(str = "One Line only with no newline with limited length"); - actual_result = ""; - get_line(actual_result, is, sizeof("One Line only with no newline with limited length")-1); - expected_result = "One Line only with no newline with limited length\n"; - ensure_equals("get_line: No newline with limited length", actual_result, expected_result); - - is.clear(); - is.str(str = "One Line only with no newline"); - actual_result = ""; - get_line(actual_result, is, 255); - expected_result = "One Line only with no newline"; - ensure_equals("get_line: No newline", actual_result, expected_result); - } - - //testcases for get_line(std::string& output_string, std::istream& input_stream, int n) - template<> template<> - void streamtools_object::test<15>() - { - std::string str; - std::string expected_result; - std::string actual_result; - std::istringstream is; - bool ret; - - is.clear(); - is.str(str = "One Line only with no newline"); - actual_result = ""; - ret = get_line(actual_result, is, 255); - expected_result = "One Line only with no newline"; - ensure_equals("get_line: No newline", actual_result, expected_result); - ensure_equals("return value is good state of stream", ret, is.good()); - } - - //testcases for remove_last_char() - template<> template<> - void streamtools_object::test<16>() - { - std::string str; - std::string expected_result; - bool ret; - - str = "SecondLife is a 3D World"; - - ret = remove_last_char('d',str); - expected_result = "SecondLife is a 3D Worl"; - ensure_equals("remove_last_char: should remove last char", str, expected_result); - - str = "SecondLife is a 3D World"; - ret = remove_last_char('W',str); - expected_result = "SecondLife is a 3D World"; - ensure_equals("remove_last_char: should not remove as it is not last char", str, expected_result); - ensure("remove_last_char: should return false", ret == false); - - str = "SecondLife is a 3D World\n"; - ret = remove_last_char('\n',str); - expected_result = "SecondLife is a 3D World"; - ensure_equals("remove_last_char: should remove last newline", str, expected_result); - ensure("remove_last_char: should remove newline and return true", ret == true); - } - - - //testcases for unescaped_string() - template<> template<> - void streamtools_object::test<17>() - { - std::string str; - std::string expected_result; - - str = "SecondLife is a 3D world \\n"; - unescape_string(str); - expected_result = "SecondLife is a 3D world \n"; - ensure_equals("unescape_string: newline", str, expected_result); - - str = "SecondLife is a 3D world \\\\t \\n"; - unescape_string(str); - expected_result = "SecondLife is a 3D world \\t \n"; - ensure_equals("unescape_string: backslash and newline", str, expected_result); - - str = "SecondLife is a 3D world \\ "; - unescape_string(str); - expected_result = "SecondLife is a 3D world \\ "; - ensure_equals("unescape_string: insufficient to unescape", str, expected_result); - - str = "SecondLife is a 3D world \\n \\n \\n \\\\\\n"; - unescape_string(str); - expected_result = "SecondLife is a 3D world \n \n \n \\\n"; - ensure_equals("unescape_string: multipel newline and backslash", str, expected_result); - - str = "SecondLife is a 3D world \\t"; - unescape_string(str); - expected_result = "SecondLife is a 3D world \\t"; - ensure_equals("unescape_string: leaves tab as is", str, expected_result); - - str = "\\n"; - unescape_string(str); - expected_result = "\n"; - ensure_equals("unescape_string: only a newline", str, expected_result); - } - - //testcases for escape_string() - template<> template<> - void streamtools_object::test<18>() - { - std::string str; - std::string expected_result; - - str = "SecondLife is a 3D world \n"; - escape_string(str); - expected_result = "SecondLife is a 3D world \\n"; - ensure_equals("escape_string: newline", str, expected_result); - - str = "SecondLife is a 3D world \\t \n"; - escape_string(str); - expected_result = "SecondLife is a 3D world \\\\t \\n"; - ensure_equals("escape_string: backslash and newline", str, expected_result); - - str = "SecondLife is a 3D world \n \n \n \\\n"; - escape_string(str); - expected_result = "SecondLife is a 3D world \\n \\n \\n \\\\\\n"; - ensure_equals("escape_string: multipel newline and backslash", str, expected_result); - - str = "SecondLife is a 3D world \t"; - escape_string(str); - expected_result = "SecondLife is a 3D world \t"; - ensure_equals("unescape_string: leaves tab as is", str, expected_result); - - str = "\n"; - escape_string(str); - expected_result = "\\n"; - ensure_equals("unescape_string: only a newline", str, expected_result); - - // serialization/deserialization escape->unescape - str = "SecondLife is a 3D world \n \n \n \\\n"; - escape_string(str); - unescape_string(str); - expected_result = "SecondLife is a 3D world \n \n \n \\\n"; - ensure_equals("escape_string: should preserve with escape/unescape", str, expected_result); - - // serialization/deserialization unescape->escape - str = "SecondLife is a 3D world \\n \\n \\n \\\\"; - unescape_string(str); - escape_string(str); - expected_result = "SecondLife is a 3D world \\n \\n \\n \\\\"; - ensure_equals("escape_string: should preserve with unescape/escape", str, expected_result); - } - - // testcases for replace_newlines_with_whitespace() - template<> template<> - void streamtools_object::test<19>() - { - std::string str; - std::string expected_result; - - str = "SecondLife is a 3D \n\nworld\n"; - replace_newlines_with_whitespace(str); - expected_result = "SecondLife is a 3D world "; - ensure_equals("replace_newlines_with_whitespace: replace all newline", str, expected_result); - - str = "\nSecondLife is a 3D world\n"; - replace_newlines_with_whitespace(str); - expected_result = " SecondLife is a 3D world "; - ensure_equals("replace_newlines_with_whitespace: begin and newline", str, expected_result); - - str = "SecondLife is a 3D world\r\t"; - replace_newlines_with_whitespace(str); - expected_result = "SecondLife is a 3D world\r\t"; - ensure_equals("replace_newlines_with_whitespace: should only replace newline", str, expected_result); - - str = ""; - replace_newlines_with_whitespace(str); - expected_result = ""; - ensure_equals("replace_newlines_with_whitespace: empty string", str, expected_result); - } - - //testcases for remove_double_quotes() - template<> template<> - void streamtools_object::test<20>() - { - std::string str; - std::string expected_result; - - str = "SecondLife is a \"\"3D world"; - remove_double_quotes(str); - expected_result = "SecondLife is a 3D world"; - ensure_equals("remove_double_quotes: replace empty doube quotes", str, expected_result); - - str = "SecondLife is a \"3D world"; - remove_double_quotes(str); - expected_result = "SecondLife is a 3D world"; - ensure_equals("remove_double_quotes: keep as is it matching quote not found", str, expected_result); - } - - // testcases for get_brace_count() - template<> template<> - void streamtools_object::test<21>() - { - } - - //testcases for get_keyword_and_value() - template<> template<> - void streamtools_object::test<22>() - { - std::string s = "SecondLife is a 3D World"; - std::string keyword; - std::string value; - get_keyword_and_value(keyword, value, s); - ensure("get_keyword_and_value: Unable to get Keyword and Value", ((keyword == "SecondLife") && (value == "is a 3D World"))); - - s = "SecondLife"; - get_keyword_and_value(keyword, value, s); - ensure("get_keyword_and_value: value should be empty", ((keyword == "SecondLife") && (value == ""))); - - s = "SecondLife \t is cool! \n"; - get_keyword_and_value(keyword, value, s); - ensure("get_keyword_and_value: remove space before value but not after", ((keyword == "SecondLife") && (value == "is cool! "))); - } - - //testcases for get_keyword_and_value() - template<> template<> - void streamtools_object::test<23>() - { - std::string s; - std::string keyword = "SOME PRIOR KEYWORD"; - std::string value = "SOME PRIOR VALUE"; - - s = "SecondLife\n"; - get_keyword_and_value(keyword, value, s); - ensure("get_keyword_and_value: terminated with newline. value should be empty", ((keyword == "SecondLife") && (value == ""))); - } - - //testcases for get_keyword_and_value() - template<> template<> - void streamtools_object::test<24>() - { - std::string s; - std::string keyword = "SOME PRIOR KEYWORD"; - std::string value = "SOME PRIOR VALUE"; - - s = ""; - get_keyword_and_value(keyword, value, s); - ensure("get_keyword_and_value: empty string. keyword value should empty", ((keyword == "") && (value == ""))); - } - - //testcase for fullread() - template<> template<> - void streamtools_object::test<25>() - { - std::string str = "First Line.\nSecond Line\n"; - std::istringstream is(str); - char buf[255] = {0}; - - fullread(is, buf, 255); - ensure_memory_matches("fullread: read with newlines", (void*) buf, static_cast(str.size())-1, (void*) str.c_str(), static_cast(str.size())-1); - - is.clear(); - is.str(str = "First Line.\nSecond Line\n"); - memset(buf, 0, 255); - - char expected_string[] = "First Line.\nSecond"; - int len = sizeof(expected_string)-1; - fullread(is, buf, len); - ensure_memory_matches("fullread: read with newlines", (void*) buf, len, (void*) &expected_string, len); - } - - -// testcases for operator >> - - template<> template<> - void streamtools_object::test<26>() - { - char arr[255]; - std::string str; - std::string toCheck = "SecondLife" ; - std::string expected_result; - std::istringstream stream("SecondLife is a 3D World"); - stream >> toCheck.c_str(); - stream.get(arr, 255, '\0'); - expected_result = " is a 3D World"; - ensure_equals("istream << operator", arr, expected_result); - - stream.clear(); - stream.str(str = "SecondLife is a 3D World"); - toCheck = "is"; - stream >> toCheck.c_str(); - ensure("istream << operator should have failed", stream.good() == false); - } -} diff --git a/indra/test/lltemplatemessagebuilder_tut.cpp b/indra/test/lltemplatemessagebuilder_tut.cpp deleted file mode 100644 index ddf1c3dbcc..0000000000 --- a/indra/test/lltemplatemessagebuilder_tut.cpp +++ /dev/null @@ -1,971 +0,0 @@ -/** - * @file lltemplatemessagebuilder_tut.cpp - * @date 2007-04 - * @brief Tests for building messages. - * - * $LicenseInfo:firstyear=2007&license=viewerlgpl$ - * Second Life Viewer Source Code - * Copyright (C) 2010, Linden Research, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; - * version 2.1 of the License only. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA - * $/LicenseInfo$ - */ - -#include -#include "linden_common.h" -#include "lltut.h" - -#include "llapr.h" -#include "llmessagetemplate.h" -#include "llmath.h" -#include "llquaternion.h" -#include "lltemplatemessagebuilder.h" -#include "lltemplatemessagereader.h" -#include "message_prehash.h" -#include "u64.h" -#include "v3dmath.h" -#include "v3math.h" -#include "v4math.h" - -namespace tut -{ - static LLTemplateMessageBuilder::message_template_name_map_t nameMap; - static LLTemplateMessageReader::message_template_number_map_t numberMap; - - struct LLTemplateMessageBuilderTestData - { - static LLMessageTemplate defaultTemplate() - { - static bool init = false; - if(! init) - { - ll_init_apr(); - const F32 circuit_heartbeat_interval=5; - const F32 circuit_timeout=100; - - start_messaging_system("notafile", 13035, - 1, - 0, - 0, - false, - "notasharedsecret", - NULL, - false, - circuit_heartbeat_interval, - circuit_timeout); - //init_prehash_data(); - init = true; - } - return LLMessageTemplate(_PREHASH_TestMessage, 1, MFT_HIGH); - } - - static LLMessageBlock* defaultBlock(const EMsgVariableType type = MVT_NULL, const S32 size = 0, EMsgBlockType block = MBT_VARIABLE) - { - return createBlock(const_cast(_PREHASH_Test0), type, size, block); - } - - static LLMessageBlock* createBlock(char* name, const EMsgVariableType type = MVT_NULL, const S32 size = 0, EMsgBlockType block = MBT_VARIABLE) - { - LLMessageBlock* result = new LLMessageBlock(name, block); - if(type != MVT_NULL) - { - result->addVariable(const_cast(_PREHASH_Test0), type, size); - } - return result; - } - - static LLTemplateMessageBuilder* defaultBuilder(LLMessageTemplate& messageTemplate, char* name = const_cast(_PREHASH_Test0)) - { - nameMap[_PREHASH_TestMessage] = &messageTemplate; - LLTemplateMessageBuilder* builder = new LLTemplateMessageBuilder(nameMap); - builder->newMessage(_PREHASH_TestMessage); - builder->nextBlock(name); - return builder; - } - - /** Takes ownership of builder */ - static LLTemplateMessageReader* setReader( - LLMessageTemplate& messageTemplate, - LLTemplateMessageBuilder* builder, - U8 offset = 0) - { - numberMap[1] = &messageTemplate; - const U32 bufferSize = 1024; - U8 buffer[bufferSize]; - // zero out the packet ID field - memset(buffer, 0, LL_PACKET_ID_SIZE); - U32 builtSize = builder->buildMessage(buffer, bufferSize, offset); - delete builder; - LLTemplateMessageReader* reader = new LLTemplateMessageReader(numberMap); - reader->validateMessage(buffer, builtSize, LLHost()); - reader->readMessage(buffer, LLHost()); - return reader; - } - - }; - - typedef test_group LLTemplateMessageBuilderTestGroup; - typedef LLTemplateMessageBuilderTestGroup::object LLTemplateMessageBuilderTestObject; - LLTemplateMessageBuilderTestGroup templateMessageBuilderTestGroup("LLTemplateMessageBuilder"); - - template<> template<> - void LLTemplateMessageBuilderTestObject::test<1>() - // construction and test of undefined - { - LLMessageTemplate messageTemplate = defaultTemplate(); - messageTemplate.addBlock(defaultBlock()); - LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); - LLTemplateMessageReader* reader = setReader(messageTemplate, builder); - delete reader; - } - - template<> template<> - void LLTemplateMessageBuilderTestObject::test<2>() - // bool - { - LLMessageTemplate messageTemplate = defaultTemplate(); - messageTemplate.addBlock(defaultBlock(MVT_BOOL, 1)); - bool outValue, inValue = true; - LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); - builder->addBOOL(_PREHASH_Test0, inValue); - LLTemplateMessageReader* reader = setReader(messageTemplate, builder); - reader->getBOOL(_PREHASH_Test0, _PREHASH_Test0, outValue); - ensure_equals("Ensure bool", inValue, outValue); - delete reader; - } - - template<> template<> - void LLTemplateMessageBuilderTestObject::test<3>() - // U8 - { - LLMessageTemplate messageTemplate = defaultTemplate(); - messageTemplate.addBlock(defaultBlock(MVT_U8, 1)); - U8 outValue, inValue = 2; - LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); - builder->addU8(_PREHASH_Test0, inValue); - LLTemplateMessageReader* reader = setReader(messageTemplate, builder); - reader->getU8(_PREHASH_Test0, _PREHASH_Test0, outValue); - ensure_equals("Ensure U8", inValue, outValue); - delete reader; - } - - template<> template<> - void LLTemplateMessageBuilderTestObject::test<4>() - // S16 - { - LLMessageTemplate messageTemplate = defaultTemplate(); - messageTemplate.addBlock(defaultBlock(MVT_S16, 2)); - S16 outValue, inValue = 90; - LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); - builder->addS16(_PREHASH_Test0, inValue); - LLTemplateMessageReader* reader = setReader(messageTemplate, builder); - reader->getS16(_PREHASH_Test0, _PREHASH_Test0, outValue); - ensure_equals("Ensure S16", inValue, outValue); - delete reader; - } - - template<> template<> - void LLTemplateMessageBuilderTestObject::test<5>() - // U16 - { - LLMessageTemplate messageTemplate = defaultTemplate(); - messageTemplate.addBlock(defaultBlock(MVT_U16, 2)); - U16 outValue, inValue = 3; - LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); - builder->addU16(_PREHASH_Test0, inValue); - LLTemplateMessageReader* reader = setReader(messageTemplate, builder); - reader->getU16(_PREHASH_Test0, _PREHASH_Test0, outValue); - ensure_equals("Ensure U16", inValue, outValue); - delete reader; - } - - template<> template<> - void LLTemplateMessageBuilderTestObject::test<6>() - // S32 - { - LLMessageTemplate messageTemplate = defaultTemplate(); - messageTemplate.addBlock(defaultBlock(MVT_S32, 4)); - S32 outValue, inValue = 44; - LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); - builder->addS32(_PREHASH_Test0, inValue); - LLTemplateMessageReader* reader = setReader(messageTemplate, builder); - reader->getS32(_PREHASH_Test0, _PREHASH_Test0, outValue); - ensure_equals("Ensure S32", inValue, outValue); - delete reader; - } - - template<> template<> - void LLTemplateMessageBuilderTestObject::test<7>() - // F32 - { - LLMessageTemplate messageTemplate = defaultTemplate(); - messageTemplate.addBlock(defaultBlock(MVT_F32, 4)); - F32 outValue, inValue = 121.44f; - LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); - builder->addF32(_PREHASH_Test0, inValue); - LLTemplateMessageReader* reader = setReader(messageTemplate, builder); - reader->getF32(_PREHASH_Test0, _PREHASH_Test0, outValue); - ensure_equals("Ensure F32", inValue, outValue); - delete reader; - } - - template<> template<> - void LLTemplateMessageBuilderTestObject::test<8>() - // U32 - { - LLMessageTemplate messageTemplate = defaultTemplate(); - messageTemplate.addBlock(defaultBlock(MVT_U32, 4)); - U32 outValue, inValue = 88; - LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); - builder->addU32(_PREHASH_Test0, inValue); - LLTemplateMessageReader* reader = setReader(messageTemplate, builder); - reader->getU32(_PREHASH_Test0, _PREHASH_Test0, outValue); - ensure_equals("Ensure U32", inValue, outValue); - delete reader; - } - - template<> template<> - void LLTemplateMessageBuilderTestObject::test<9>() - // U64 - { - LLMessageTemplate messageTemplate = defaultTemplate(); - messageTemplate.addBlock(defaultBlock(MVT_U64, 8)); - U64 outValue, inValue = 121; - LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); - builder->addU64(_PREHASH_Test0, inValue); - LLTemplateMessageReader* reader = setReader(messageTemplate, builder); - reader->getU64(_PREHASH_Test0, _PREHASH_Test0, outValue); - ensure_equals("Ensure U64", inValue, outValue); - delete reader; - } - - template<> template<> - void LLTemplateMessageBuilderTestObject::test<10>() - // F64 - { - LLMessageTemplate messageTemplate = defaultTemplate(); - messageTemplate.addBlock(defaultBlock(MVT_F64, 8)); - F64 outValue, inValue = 3232143.33; - LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); - builder->addF64(_PREHASH_Test0, inValue); - LLTemplateMessageReader* reader = setReader(messageTemplate, builder); - reader->getF64(_PREHASH_Test0, _PREHASH_Test0, outValue); - ensure_equals("Ensure F64", inValue, outValue); - delete reader; - } - - template<> template<> - void LLTemplateMessageBuilderTestObject::test<11>() - // Vector3 - { - LLMessageTemplate messageTemplate = defaultTemplate(); - messageTemplate.addBlock(defaultBlock(MVT_LLVector3, 12)); - LLVector3 outValue, inValue = LLVector3(1,2,3); - LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); - builder->addVector3(_PREHASH_Test0, inValue); - LLTemplateMessageReader* reader = setReader(messageTemplate, builder); - reader->getVector3(_PREHASH_Test0, _PREHASH_Test0, outValue); - ensure_equals("Ensure LLVector3", inValue, outValue); - delete reader; - } - - template<> template<> - void LLTemplateMessageBuilderTestObject::test<12>() - // Vector4 - { - LLMessageTemplate messageTemplate = defaultTemplate(); - messageTemplate.addBlock(defaultBlock(MVT_LLVector4, 16)); - LLVector4 outValue, inValue = LLVector4(1,2,3,4); - LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); - builder->addVector4(_PREHASH_Test0, inValue); - LLTemplateMessageReader* reader = setReader(messageTemplate, builder); - reader->getVector4(_PREHASH_Test0, _PREHASH_Test0, outValue); - ensure_equals("Ensure LLVector4", inValue, outValue); - delete reader; - } - - template<> template<> - void LLTemplateMessageBuilderTestObject::test<13>() - // Vector3d - { - LLMessageTemplate messageTemplate = defaultTemplate(); - messageTemplate.addBlock(defaultBlock(MVT_LLVector3d, 24)); - LLVector3d outValue, inValue = LLVector3d(1,2,3); - LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); - builder->addVector3d(_PREHASH_Test0, inValue); - LLTemplateMessageReader* reader = setReader(messageTemplate, builder); - reader->getVector3d(_PREHASH_Test0, _PREHASH_Test0, outValue); - ensure_equals("Ensure LLVector3d", inValue, outValue); - delete reader; - } - - template<> template<> - void LLTemplateMessageBuilderTestObject::test<14>() - // Quaternion - { - LLMessageTemplate messageTemplate = defaultTemplate(); - messageTemplate.addBlock(defaultBlock(MVT_LLQuaternion, 12)); - LLQuaternion outValue, inValue = LLQuaternion(0.0f, LLVector3(0.3713907f, 0.5570861f, 0.7427813f)); - - LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); - builder->addQuat(_PREHASH_Test0, inValue); - LLTemplateMessageReader* reader = setReader(messageTemplate, builder); - reader->getQuat(_PREHASH_Test0, _PREHASH_Test0, outValue); - ensure_equals("Ensure LLQuaternion", inValue, outValue); - delete reader; - } - - template<> template<> - void LLTemplateMessageBuilderTestObject::test<15>() - // UUID - { - LLMessageTemplate messageTemplate = defaultTemplate(); - messageTemplate.addBlock(defaultBlock(MVT_LLUUID, 16)); - LLUUID outValue, inValue; - inValue.generate(); - LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); - builder->addUUID(_PREHASH_Test0, inValue); - LLTemplateMessageReader* reader = setReader(messageTemplate, builder); - reader->getUUID(_PREHASH_Test0, _PREHASH_Test0, outValue); - ensure_equals("Ensure UUID", inValue, outValue); - delete reader; - } - - template<> template<> - void LLTemplateMessageBuilderTestObject::test<16>() - // IPAddr - { - LLMessageTemplate messageTemplate = defaultTemplate(); - messageTemplate.addBlock(defaultBlock(MVT_IP_ADDR, 4)); - U32 outValue, inValue = 12344556; - LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); - builder->addIPAddr(_PREHASH_Test0, inValue); - LLTemplateMessageReader* reader = setReader(messageTemplate, builder); - reader->getIPAddr(_PREHASH_Test0, _PREHASH_Test0, outValue); - ensure_equals("Ensure IPAddr", inValue, outValue); - delete reader; - } - - template<> template<> - void LLTemplateMessageBuilderTestObject::test<17>() - // IPPort - { - LLMessageTemplate messageTemplate = defaultTemplate(); - messageTemplate.addBlock(defaultBlock(MVT_IP_PORT, 2)); - U16 outValue, inValue = 80; - LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); - builder->addIPPort(_PREHASH_Test0, inValue); - LLTemplateMessageReader* reader = setReader(messageTemplate, builder); - reader->getIPPort(_PREHASH_Test0, _PREHASH_Test0, outValue); - ensure_equals("Ensure IPPort", inValue, outValue); - delete reader; - } - - template<> template<> - void LLTemplateMessageBuilderTestObject::test<18>() - // String - { - LLMessageTemplate messageTemplate = defaultTemplate(); - messageTemplate.addBlock(defaultBlock(MVT_VARIABLE, 1)); - std::string outValue, inValue = "testing"; - LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); - builder->addString(_PREHASH_Test0, inValue.c_str()); - LLTemplateMessageReader* reader = setReader(messageTemplate, builder); - char buffer[MAX_STRING]; - reader->getString(_PREHASH_Test0, _PREHASH_Test0, MAX_STRING, buffer); - outValue = buffer; - ensure_equals("Ensure String", inValue, outValue); - delete reader; - } - - template<> template<> - void LLTemplateMessageBuilderTestObject::test<19>() - // block name !-> binary order - { - U8 buffer1[MAX_BUFFER_SIZE]; - memset(buffer1, 0, MAX_BUFFER_SIZE); - U8 buffer2[MAX_BUFFER_SIZE]; - memset(buffer2, 0, MAX_BUFFER_SIZE); - U32 bufferSize1, bufferSize2; - - // build template: Test0 before Test1 - LLMessageTemplate messageTemplate = defaultTemplate(); - messageTemplate.addBlock(createBlock(const_cast(_PREHASH_Test0), MVT_U32, 4, MBT_SINGLE)); - messageTemplate.addBlock(createBlock(const_cast(_PREHASH_Test1), MVT_U32, 4, MBT_SINGLE)); - - // build message: 1st declared block var == 0xaaaa, 2nd declared block var == 0xbbbb - LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate, const_cast(_PREHASH_Test0)); - builder->addU32(_PREHASH_Test0, 0xaaaa); - builder->nextBlock(_PREHASH_Test1); - builder->addU32(_PREHASH_Test0, 0xbbbb); - bufferSize1 = builder->buildMessage(buffer1, MAX_BUFFER_SIZE, 0); - delete builder; - - // build template: Test1 before Test0 - messageTemplate = defaultTemplate(); - messageTemplate.addBlock(createBlock(const_cast(_PREHASH_Test1), MVT_U32, 4, MBT_SINGLE)); - messageTemplate.addBlock(createBlock(const_cast(_PREHASH_Test0), MVT_U32, 4, MBT_SINGLE)); - - // build message: 1st declared block var == 0xaaaa, 2nd declared block var == 0xbbbb - builder = defaultBuilder(messageTemplate, const_cast(_PREHASH_Test1)); - builder->addU32(_PREHASH_Test0, 0xaaaa); - builder->nextBlock(_PREHASH_Test0); - builder->addU32(_PREHASH_Test0, 0xbbbb); - bufferSize2 = builder->buildMessage(buffer2, MAX_BUFFER_SIZE, 0); - delete builder; - - ensure_equals("Ensure Buffer Sizes Equal", bufferSize1, bufferSize2); - ensure_equals("Ensure Buffer Contents Equal", memcmp(buffer1, buffer2, bufferSize1), 0); - } - - template<> template<> - void LLTemplateMessageBuilderTestObject::test<20>() - // block build order !-> binary order - { - U8 buffer1[MAX_BUFFER_SIZE]; - memset(buffer1, 0, MAX_BUFFER_SIZE); - U8 buffer2[MAX_BUFFER_SIZE]; - memset(buffer2, 0, MAX_BUFFER_SIZE); - U32 bufferSize1, bufferSize2; - - // build template: Test0 before Test1 - LLMessageTemplate messageTemplate = defaultTemplate(); - messageTemplate.addBlock(createBlock(const_cast(_PREHASH_Test0), MVT_U32, 4, MBT_SINGLE)); - messageTemplate.addBlock(createBlock(const_cast(_PREHASH_Test1), MVT_U32, 4, MBT_SINGLE)); - - // build message: 1st declared block var == 0xaaaa, 2nd declared block var == 0xbbbb - LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate, const_cast(_PREHASH_Test0)); - builder->addU32(_PREHASH_Test0, 0xaaaa); - builder->nextBlock(_PREHASH_Test1); - builder->addU32(_PREHASH_Test0, 0xbbbb); - bufferSize1 = builder->buildMessage(buffer1, MAX_BUFFER_SIZE, 0); - delete builder; - - // build message: 1st declared block var == 0xaaaa, 2nd declared block var == 0xbbbb - builder = defaultBuilder(messageTemplate, const_cast(_PREHASH_Test1)); - builder->addU32(_PREHASH_Test0, 0xbbbb); - builder->nextBlock(_PREHASH_Test0); - builder->addU32(_PREHASH_Test0, 0xaaaa); - bufferSize2 = builder->buildMessage(buffer2, MAX_BUFFER_SIZE, 0); - delete builder; - - ensure_equals("Ensure Buffer Sizes Equal", bufferSize1, bufferSize2); - ensure_equals("Ensure Buffer Contents Equal", memcmp(buffer1, buffer2, bufferSize1), 0); - } - - template<> template<> - void LLTemplateMessageBuilderTestObject::test<21>() - // block appended in declaration -> data appended in binary - { - U8 buffer1[MAX_BUFFER_SIZE]; - memset(buffer1, 0, MAX_BUFFER_SIZE); - U8 buffer2[MAX_BUFFER_SIZE]; - memset(buffer2, 0, MAX_BUFFER_SIZE); - U32 bufferSize1, bufferSize2; - - // Build template: Test0 only - LLMessageTemplate messageTemplate = defaultTemplate(); - messageTemplate.addBlock(createBlock(const_cast(_PREHASH_Test0), MVT_U32, 4, MBT_SINGLE)); - - // Build message - LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate, const_cast(_PREHASH_Test0)); - builder->addU32(_PREHASH_Test0, 0xaaaa); - bufferSize1 = builder->buildMessage(buffer1, MAX_BUFFER_SIZE, 0); - delete builder; - - // Build template: Test0 before Test1 - messageTemplate = defaultTemplate(); - messageTemplate.addBlock(createBlock(const_cast(_PREHASH_Test0), MVT_U32, 4, MBT_SINGLE)); - messageTemplate.addBlock(createBlock(const_cast(_PREHASH_Test1), MVT_U32, 4, MBT_SINGLE)); - - // Build message - builder = defaultBuilder(messageTemplate, const_cast(_PREHASH_Test0)); - builder->addU32(_PREHASH_Test0, 0xaaaa); - builder->nextBlock(_PREHASH_Test1); - builder->addU32(_PREHASH_Test0, 0xbbbb); - bufferSize2 = builder->buildMessage(buffer2, MAX_BUFFER_SIZE, 0); - delete builder; - - ensure_not_equals("Ensure Buffer Sizes Not Equal", bufferSize1, bufferSize2); - ensure_equals("Ensure Buffer Prefix Equal", memcmp(buffer1, buffer2, bufferSize1), 0); - ensure_not_equals("Ensure Buffer Contents Not Equal", memcmp(buffer1, buffer2, bufferSize2), 0); - } - - template<> template<> - void LLTemplateMessageBuilderTestObject::test<22>() - // repeated penultimate block (crashes when data in LLDynamicArrayIndexed) - { - U32 inTest00 = 0, inTest01 = 1, inTest1 = 2; - U32 outTest00, outTest01, outTest1; - LLMessageTemplate messageTemplate = defaultTemplate(); - messageTemplate.addBlock(createBlock(const_cast(_PREHASH_Test0), MVT_U32, 4)); - messageTemplate.addBlock(createBlock(const_cast(_PREHASH_Test1), MVT_U32, 4)); - LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); - builder->addU32(_PREHASH_Test0, inTest00); - builder->nextBlock(_PREHASH_Test0); - builder->addU32(_PREHASH_Test0, inTest01); - builder->nextBlock(_PREHASH_Test1); - builder->addU32(_PREHASH_Test0, inTest1); - LLTemplateMessageReader* reader = setReader(messageTemplate, builder); - reader->getU32(_PREHASH_Test0, _PREHASH_Test0, outTest00, 0); - reader->getU32(_PREHASH_Test0, _PREHASH_Test0, outTest01, 1); - reader->getU32(_PREHASH_Test1, _PREHASH_Test0, outTest1); - ensure_equals("Ensure Test0[0]", inTest00, outTest00); - ensure_equals("Ensure Test0[1]", inTest01, outTest01); - ensure_equals("Ensure Test1", inTest1, outTest1); - delete reader; - } - - template<> template<> - void LLTemplateMessageBuilderTestObject::test<23>() - // variable repeated block name never accessed - { - U32 inTest = 1, outTest; - LLMessageTemplate messageTemplate = defaultTemplate(); - messageTemplate.addBlock( - createBlock(const_cast(_PREHASH_Test0), MVT_U32, 4, MBT_SINGLE)); - messageTemplate.addBlock(createBlock(const_cast(_PREHASH_Test1), MVT_U32, 4)); - - LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); - builder->addU32(_PREHASH_Test0, inTest); - - LLTemplateMessageReader* reader = setReader(messageTemplate, builder); - reader->getU32(_PREHASH_Test0, _PREHASH_Test0, outTest); - S32 blockCount = reader->getNumberOfBlocks(const_cast(_PREHASH_Test1)); - ensure_equals("Ensure block count", blockCount, 0); - ensure_equals("Ensure Test0", inTest, outTest); - delete reader; - } - - template<> template<> - void LLTemplateMessageBuilderTestObject::test<24>() - // forwarding message - { - // build template - LLMessageTemplate messageTemplate = defaultTemplate(); - messageTemplate.addBlock(createBlock(const_cast(_PREHASH_Test0), MVT_U32, 4)); - - // build message - LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); - builder->addU32(_PREHASH_Test0, 42); - - // read message - LLTemplateMessageReader* reader = setReader(messageTemplate, builder); - - // forward message - builder = defaultBuilder(messageTemplate); - builder->newMessage(_PREHASH_TestMessage); - reader->copyToBuilder(*builder); - U8 buffer[MAX_BUFFER_SIZE]; - builder->buildMessage(buffer, MAX_BUFFER_SIZE, 0); - - delete builder; - delete reader; - } - - template<> template<> - void LLTemplateMessageBuilderTestObject::test<25>() - // non-zero offset with undefined - { - LLMessageTemplate messageTemplate = defaultTemplate(); - messageTemplate.addBlock(defaultBlock()); - LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); - LLTemplateMessageReader* reader = setReader( - messageTemplate, builder, 10); - delete reader; - } - - template<> template<> - void LLTemplateMessageBuilderTestObject::test<26>() - // non-zero offset with bool - { - LLMessageTemplate messageTemplate = defaultTemplate(); - messageTemplate.addBlock(defaultBlock(MVT_BOOL, 1)); - bool outValue, inValue = true; - LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); - builder->addBOOL(_PREHASH_Test0, inValue); - LLTemplateMessageReader* reader = setReader( - messageTemplate, builder, 1); - reader->getBOOL(_PREHASH_Test0, _PREHASH_Test0, outValue); - ensure_equals("Ensure bool", inValue, outValue); - delete reader; - } - - template<> template<> - void LLTemplateMessageBuilderTestObject::test<27>() - // non-zero offset with U8 - { - LLMessageTemplate messageTemplate = defaultTemplate(); - messageTemplate.addBlock(defaultBlock(MVT_U8, 1)); - U8 outValue, inValue = 2; - LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); - builder->addU8(_PREHASH_Test0, inValue); - LLTemplateMessageReader* reader = setReader( - messageTemplate, builder, 255); - reader->getU8(_PREHASH_Test0, _PREHASH_Test0, outValue); - ensure_equals("Ensure U8", inValue, outValue); - delete reader; - } - - template<> template<> - void LLTemplateMessageBuilderTestObject::test<28>() - // non-zero offset with S16 - { - LLMessageTemplate messageTemplate = defaultTemplate(); - messageTemplate.addBlock(defaultBlock(MVT_S16, 2)); - S16 outValue, inValue = 90; - LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); - builder->addS16(_PREHASH_Test0, inValue); - LLTemplateMessageReader* reader = setReader( - messageTemplate, builder, 2); - reader->getS16(_PREHASH_Test0, _PREHASH_Test0, outValue); - ensure_equals("Ensure S16", inValue, outValue); - delete reader; - } - - template<> template<> - void LLTemplateMessageBuilderTestObject::test<29>() - // non-zero offset with U16 - { - LLMessageTemplate messageTemplate = defaultTemplate(); - messageTemplate.addBlock(defaultBlock(MVT_U16, 2)); - U16 outValue, inValue = 3; - LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); - builder->addU16(_PREHASH_Test0, inValue); - LLTemplateMessageReader* reader = setReader( - messageTemplate, builder, 4); - reader->getU16(_PREHASH_Test0, _PREHASH_Test0, outValue); - ensure_equals("Ensure U16", inValue, outValue); - delete reader; - } - - template<> template<> - void LLTemplateMessageBuilderTestObject::test<30>() - // non-zero offset with S32 - { - LLMessageTemplate messageTemplate = defaultTemplate(); - messageTemplate.addBlock(defaultBlock(MVT_S32, 4)); - S32 outValue, inValue = 44; - LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); - builder->addS32(_PREHASH_Test0, inValue); - LLTemplateMessageReader* reader = setReader( - messageTemplate, builder, 4); - reader->getS32(_PREHASH_Test0, _PREHASH_Test0, outValue); - ensure_equals("Ensure S32", inValue, outValue); - delete reader; - } - - template<> template<> - void LLTemplateMessageBuilderTestObject::test<31>() - // non-zero offset with F32 - { - LLMessageTemplate messageTemplate = defaultTemplate(); - messageTemplate.addBlock(defaultBlock(MVT_F32, 4)); - F32 outValue, inValue = 121.44f; - LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); - builder->addF32(_PREHASH_Test0, inValue); - LLTemplateMessageReader* reader = setReader( - messageTemplate, builder, 16); - reader->getF32(_PREHASH_Test0, _PREHASH_Test0, outValue); - ensure_equals("Ensure F32", inValue, outValue); - delete reader; - } - - template<> template<> - void LLTemplateMessageBuilderTestObject::test<32>() - // non-zero offset with U32 - { - LLMessageTemplate messageTemplate = defaultTemplate(); - messageTemplate.addBlock(defaultBlock(MVT_U32, 4)); - U32 outValue, inValue = 88; - LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); - builder->addU32(_PREHASH_Test0, inValue); - LLTemplateMessageReader* reader = setReader( - messageTemplate, builder, 127); - reader->getU32(_PREHASH_Test0, _PREHASH_Test0, outValue); - ensure_equals("Ensure U32", inValue, outValue); - delete reader; - } - - template<> template<> - void LLTemplateMessageBuilderTestObject::test<33>() - // non-zero offset with U64 - { - LLMessageTemplate messageTemplate = defaultTemplate(); - messageTemplate.addBlock(defaultBlock(MVT_U64, 8)); - U64 outValue, inValue = 121; - LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); - builder->addU64(_PREHASH_Test0, inValue); - LLTemplateMessageReader* reader = setReader( - messageTemplate, builder, 32); - reader->getU64(_PREHASH_Test0, _PREHASH_Test0, outValue); - ensure_equals("Ensure U64", inValue, outValue); - delete reader; - } - - template<> template<> - void LLTemplateMessageBuilderTestObject::test<34>() - // non-zero offset with F64 - { - LLMessageTemplate messageTemplate = defaultTemplate(); - messageTemplate.addBlock(defaultBlock(MVT_F64, 8)); - F64 outValue, inValue = 3232143.33; - LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); - builder->addF64(_PREHASH_Test0, inValue); - LLTemplateMessageReader* reader = setReader( - messageTemplate, builder, 128); - reader->getF64(_PREHASH_Test0, _PREHASH_Test0, outValue); - ensure_equals("Ensure F64", inValue, outValue); - delete reader; - } - - template<> template<> - void LLTemplateMessageBuilderTestObject::test<35>() - // non-zero offset with Vector3 - { - LLMessageTemplate messageTemplate = defaultTemplate(); - messageTemplate.addBlock(defaultBlock(MVT_LLVector3, 12)); - LLVector3 outValue, inValue = LLVector3(1,2,3); - LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); - builder->addVector3(_PREHASH_Test0, inValue); - LLTemplateMessageReader* reader = setReader( - messageTemplate, builder, 63); - reader->getVector3(_PREHASH_Test0, _PREHASH_Test0, outValue); - ensure_equals("Ensure LLVector3", inValue, outValue); - delete reader; - } - - template<> template<> - void LLTemplateMessageBuilderTestObject::test<36>() - // non-zero offset with Vector4 - { - LLMessageTemplate messageTemplate = defaultTemplate(); - messageTemplate.addBlock(defaultBlock(MVT_LLVector4, 16)); - LLVector4 outValue, inValue = LLVector4(1,2,3,4); - LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); - builder->addVector4(_PREHASH_Test0, inValue); - LLTemplateMessageReader* reader = setReader( - messageTemplate, builder, 64); - reader->getVector4(_PREHASH_Test0, _PREHASH_Test0, outValue); - ensure_equals("Ensure LLVector4", inValue, outValue); - delete reader; - } - - template<> template<> - void LLTemplateMessageBuilderTestObject::test<37>() - // non-zero offset with Vector3d - { - LLMessageTemplate messageTemplate = defaultTemplate(); - messageTemplate.addBlock(defaultBlock(MVT_LLVector3d, 24)); - LLVector3d outValue, inValue = LLVector3d(1,2,3); - LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); - builder->addVector3d(_PREHASH_Test0, inValue); - LLTemplateMessageReader* reader = setReader( - messageTemplate, builder, 64); - reader->getVector3d(_PREHASH_Test0, _PREHASH_Test0, outValue); - ensure_equals("Ensure LLVector3d", inValue, outValue); - delete reader; - } - - template<> template<> - void LLTemplateMessageBuilderTestObject::test<38>() - // non-zero offset with Quaternion - { - LLMessageTemplate messageTemplate = defaultTemplate(); - messageTemplate.addBlock(defaultBlock(MVT_LLQuaternion, 12)); - LLQuaternion outValue, inValue = LLQuaternion(0.0f, LLVector3(0.3713907f, 0.5570861f, 0.7427813f)); - LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); - builder->addQuat(_PREHASH_Test0, inValue); - LLTemplateMessageReader* reader = setReader( - messageTemplate, builder, 12); - reader->getQuat(_PREHASH_Test0, _PREHASH_Test0, outValue); - ensure_equals("Ensure LLQuaternion", inValue, outValue); - delete reader; - } - - template<> template<> - void LLTemplateMessageBuilderTestObject::test<39>() - // non-zero offset with UUID - { - LLMessageTemplate messageTemplate = defaultTemplate(); - messageTemplate.addBlock(defaultBlock(MVT_LLUUID, 16)); - LLUUID outValue, inValue; - inValue.generate(); - LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); - builder->addUUID(_PREHASH_Test0, inValue); - LLTemplateMessageReader* reader = setReader( - messageTemplate, builder, 31); - reader->getUUID(_PREHASH_Test0, _PREHASH_Test0, outValue); - ensure_equals("Ensure UUID", inValue, outValue); - delete reader; - } - - template<> template<> - void LLTemplateMessageBuilderTestObject::test<40>() - // non-zero offset with IPAddr - { - LLMessageTemplate messageTemplate = defaultTemplate(); - messageTemplate.addBlock(defaultBlock(MVT_IP_ADDR, 4)); - U32 outValue, inValue = 12344556; - LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); - builder->addIPAddr(_PREHASH_Test0, inValue); - LLTemplateMessageReader* reader = setReader( - messageTemplate, builder, 32); - reader->getIPAddr(_PREHASH_Test0, _PREHASH_Test0, outValue); - ensure_equals("Ensure IPAddr", inValue, outValue); - delete reader; - } - - template<> template<> - void LLTemplateMessageBuilderTestObject::test<41>() - // non-zero offset with IPPort - { - LLMessageTemplate messageTemplate = defaultTemplate(); - messageTemplate.addBlock(defaultBlock(MVT_IP_PORT, 2)); - U16 outValue, inValue = 80; - LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); - builder->addIPPort(_PREHASH_Test0, inValue); - LLTemplateMessageReader* reader = setReader( - messageTemplate, builder, 6); - reader->getIPPort(_PREHASH_Test0, _PREHASH_Test0, outValue); - ensure_equals("Ensure IPPort", inValue, outValue); - delete reader; - } - - template<> template<> - void LLTemplateMessageBuilderTestObject::test<42>() - // non-zero offset with String - { - LLMessageTemplate messageTemplate = defaultTemplate(); - messageTemplate.addBlock(defaultBlock(MVT_VARIABLE, 1)); - std::string outValue, inValue = "testing"; - LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); - builder->addString(_PREHASH_Test0, inValue.c_str()); - LLTemplateMessageReader* reader = setReader( - messageTemplate, builder, 255); - char buffer[MAX_STRING]; - reader->getString(_PREHASH_Test0, _PREHASH_Test0, MAX_STRING, buffer); - outValue = buffer; - ensure_equals("Ensure String", inValue, outValue); - delete reader; - } - - template<> template<> - void LLTemplateMessageBuilderTestObject::test<43>() - // read past end of message -> default values (forward compatibility) - { - // build message with single block - LLMessageTemplate messageTemplate = defaultTemplate(); - messageTemplate.addBlock(defaultBlock(MVT_U32, 4, MBT_SINGLE)); - U32 outValue, outValue2, inValue = 0xbbbbbbbb; - LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); - builder->addU32(_PREHASH_Test0, inValue); - const U32 bufferSize = 1024; - U8 buffer[bufferSize]; - memset(buffer, 0xaa, bufferSize); - memset(buffer, 0, LL_PACKET_ID_SIZE); - U32 builtSize = builder->buildMessage(buffer, bufferSize, 0); - delete builder; - - // add block to reader template - messageTemplate.addBlock(createBlock(const_cast(_PREHASH_Test1), MVT_U32, 4, MBT_SINGLE)); - - // read message value and default value - numberMap[1] = &messageTemplate; - LLTemplateMessageReader* reader = - new LLTemplateMessageReader(numberMap); - reader->validateMessage(buffer, builtSize, LLHost()); - reader->readMessage(buffer, LLHost()); - reader->getU32(_PREHASH_Test0, _PREHASH_Test0, outValue); - reader->getU32(_PREHASH_Test1, _PREHASH_Test0, outValue2); - ensure_equals("Ensure present value ", outValue, inValue); - ensure_equals("Ensure default value ", outValue2, 0); - delete reader; - } - - template<> template<> - void LLTemplateMessageBuilderTestObject::test<44>() - // read variable block past end of message -> 0 repeats - { - // build message with single block - LLMessageTemplate messageTemplate = defaultTemplate(); - messageTemplate.addBlock(defaultBlock(MVT_U32, 4, MBT_SINGLE)); - U32 outValue, outValue2, inValue = 0xbbbbbbbb; - LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); - builder->addU32(_PREHASH_Test0, inValue); - const U32 bufferSize = 1024; - U8 buffer[bufferSize]; - memset(buffer, 0xaa, bufferSize); - memset(buffer, 0, LL_PACKET_ID_SIZE); - U32 builtSize = builder->buildMessage(buffer, bufferSize, 0); - delete builder; - - // add variable block to reader template - messageTemplate.addBlock(createBlock(const_cast(_PREHASH_Test1), MVT_U32, 4)); - - // read message value and check block repeat count - numberMap[1] = &messageTemplate; - LLTemplateMessageReader* reader = - new LLTemplateMessageReader(numberMap); - reader->validateMessage(buffer, builtSize, LLHost()); - reader->readMessage(buffer, LLHost()); - reader->getU32(_PREHASH_Test0, _PREHASH_Test0, outValue); - outValue2 = reader->getNumberOfBlocks(_PREHASH_Test1); - ensure_equals("Ensure present value ", outValue, inValue); - ensure_equals("Ensure 0 repeats ", outValue2, 0); - delete reader; - } - - template<> template<> - void LLTemplateMessageBuilderTestObject::test<45>() - // read variable length data past end of message -> 0 length - { - // build message with single block - LLMessageTemplate messageTemplate = defaultTemplate(); - messageTemplate.addBlock(defaultBlock(MVT_U32, 4, MBT_SINGLE)); - U32 outValue, inValue = 0xbbbbbbbb; - LLTemplateMessageBuilder* builder = defaultBuilder(messageTemplate); - builder->addU32(_PREHASH_Test0, inValue); - const U32 bufferSize = 1024; - U8 buffer[bufferSize]; - memset(buffer, 0xaa, bufferSize); - memset(buffer, 0, LL_PACKET_ID_SIZE); - U32 builtSize = builder->buildMessage(buffer, bufferSize, 0); - delete builder; - - // add variable block to reader template - messageTemplate.addBlock(createBlock(const_cast(_PREHASH_Test1), MVT_VARIABLE, 4, - MBT_SINGLE)); - - // read message value and default string - numberMap[1] = &messageTemplate; - LLTemplateMessageReader* reader = - new LLTemplateMessageReader(numberMap); - reader->validateMessage(buffer, builtSize, LLHost()); - reader->readMessage(buffer, LLHost()); - reader->getU32(_PREHASH_Test0, _PREHASH_Test0, outValue); - (void)outValue; - char outBuffer[bufferSize]; - memset(buffer, 0xcc, bufferSize); - reader->getString(_PREHASH_Test1, _PREHASH_Test0, bufferSize, - outBuffer); - ensure_equals("Ensure present value ", outValue, inValue); - ensure_equals("Ensure unchanged buffer ", strlen(outBuffer), 0); - delete reader; - } -} - diff --git a/indra/test/lltimestampcache_tut.cpp b/indra/test/lltimestampcache_tut.cpp deleted file mode 100644 index 857dfe6e6e..0000000000 --- a/indra/test/lltimestampcache_tut.cpp +++ /dev/null @@ -1,124 +0,0 @@ -/** - * @file lltimestampcache_tut.cpp - * @author James Tess - * @date 2008-12-03 - * - * $LicenseInfo:firstyear=2008&license=viewerlgpl$ - * Second Life Viewer Source Code - * Copyright (C) 2010, Linden Research, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; - * version 2.1 of the License only. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA - * $/LicenseInfo$ - */ - -#include - -#include "linden_common.h" -#include "../mapserver/lltimestampcache.h" -#include "lltut.h" - - -namespace tut -{ - struct LLTimestampCacheTestData - { - }; - - typedef test_group LLTimestampCacheTestGroup; - typedef LLTimestampCacheTestGroup::object LLTimestampCacheTestObject; - - LLTimestampCacheTestGroup timestampCacheTestGroup("LLTimestampCache"); - - // Most common usage - template<> template<> - void LLTimestampCacheTestObject::test<1>() - { - LLTimestampCache cache; - // put in some data - cache.insert("key1", "val1", 1); - cache.insert("key2", "val2", 2); - cache.insert("key3", "val3", 3); - ensure_equals("size is 3", cache.size(), 3); - // check some items - ensure("has key1", cache.has("key1")); - ensure("no invalid key", !cache.has("invalid key")); - // get some items - ensure_equals("get key1", cache.get("key1", 4), "val1"); - ensure_equals("get invalid key", - cache.get("invalid key", 4), std::string() ); - // timestamps - ensure_equals("key1 timestamp updated", cache.getTimestamp("key1"), 4); - ensure_equals("invalid key timestamp", - cache.getTimestamp("invalid key"), 0); - } - - // New empty cache shouldn't have any entries - template<> template<> - void LLTimestampCacheTestObject::test<2>() - { - LLTimestampCache cache; - ensure_equals("starts empty", cache.size(), 0); - ensure_equals("has nothing", cache.has("foo"), false); - ensure_equals("gets nothing", cache.get("foo", 0), std::string() ); - U32 max_time = 0xFFFFFFFF; - ensure_equals("erases nothing", cache.eraseBefore(max_time), 0); - } - - // Non empty cache - template<> template<> - void LLTimestampCacheTestObject::test<3>() - { - LLTimestampCache cache; - cache.insert("foo", "bar", 123); - ensure_equals("size one", cache.size(), 1); - ensure_equals("has it", cache.has("foo"), true); - ensure_equals("timestamp correct", cache.getTimestamp("foo"), 123); - std::string value = cache.get("foo", 456); - ensure_equals("get value", value, "bar"); - ensure_equals("timestamp updated", cache.getTimestamp("foo"), 456); - ensure_equals("erase nothing", cache.eraseBefore(0), 0); - ensure_equals("erase one", cache.eraseBefore(789), 1); - ensure_equals("empty after erase", cache.size(), 0); - } - - // Recache of item should update timestamp - template<> template<> - void LLTimestampCacheTestObject::test<4>() - { - LLTimestampCache cache; - cache.insert("foo", "bar", 123); - cache.insert("foo", "bar", 456); - ensure_equals("duplicate suppressed", cache.size(), 1); - ensure_equals("timestamp replaced", cache.getTimestamp("foo"), 456); - } - - // Erasing some items - template<> template<> - void LLTimestampCacheTestObject::test<5>() - { - LLTimestampCache cache; - cache.insert("key1", "val1", 1); - cache.insert("key2", "val2", 2); - cache.insert("key3", "val3", 3); - cache.insert("key4", "val4", 4); - size_t erased = cache.eraseBefore(3); - ensure_equals("erase range", erased, 2); - ensure_equals("cache post erase", cache.size(), 2); - ensure_equals("has key3", cache.has("key3"), true); - ensure_equals("not has key2", cache.has("key2"), false); - } -} diff --git a/indra/test/lltranscode_tut.cpp b/indra/test/lltranscode_tut.cpp deleted file mode 100644 index 23d554d46d..0000000000 --- a/indra/test/lltranscode_tut.cpp +++ /dev/null @@ -1,86 +0,0 @@ -/** - * @file llscriptresource_tut.cpp - * @brief Test LLScriptResource - * - * $LicenseInfo:firstyear=2008&license=viewerlgpl$ - * Second Life Viewer Source Code - * Copyright (C) 2010, Linden Research, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; - * version 2.1 of the License only. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA - * $/LicenseInfo$ - */ - -//#include -#include "linden_common.h" - -#include "lltut.h" - -#include "../newsim/lltranscode.cpp" // include TU to pull in newsim implementation. - -static const char test_utf8[] = "Edelwei\xc3\x9f"; -static const char test_utf7[] = "Edelwei+AN8-"; -static const char test_latin1[] = "Edelwei\xdf"; -static const char test_latin2[] = "Edelwei\xdf"; - -namespace tut -{ - class LLTranscodeTestData - { - }; - - typedef test_group LLTranscodeTestGroup; - typedef LLTranscodeTestGroup::object LLTranscodeTestObject; - LLTranscodeTestGroup transcodeTestGroup("transcode"); - - template<> template<> - void LLTranscodeTestObject::test<1>() - { - // Test utf8 - std::stringstream input; - std::stringstream output; - - input.str(test_utf7); - output.clear(); - LLTranscode::transcode("charset=UTF-7", input, output); - ensure_equals("UTF-7 to UTF-8 transcoding", output.str(), - std::string(test_utf8)); - - input.str(test_latin1); - output.clear(); - LLTranscode::transcode("", input, output); - ensure_equals("Default (latin_1) to UTF8 transcoding", output.str(), - std::string(test_utf8)); - - input.str(test_latin1); - output.clear(); - LLTranscode::transcode("charset=iso-8859-1", input, output); - ensure_equals("latin_1 (ISO-8859-1) to UTF8 transcoding", output.str(), - std::string(test_utf8)); - - input.str(test_latin2); - output.clear(); - LLTranscode::transcode("charset=iso-8859-2", input, output); - ensure_equals("latin_2 (ISO-8859-2) to UTF8 transcoding", output.str(), - std::string(test_utf8)); - - input.str(test_utf8); - output.clear(); - LLTranscode::transcode("charset=utf-8", input, output); - ensure_equals("UTF8 to UTF8 transcoding", output.str(), - std::string(test_utf8)); - } -} diff --git a/indra/test/lluserrelations_tut.cpp b/indra/test/lluserrelations_tut.cpp deleted file mode 100644 index 80a659da65..0000000000 --- a/indra/test/lluserrelations_tut.cpp +++ /dev/null @@ -1,156 +0,0 @@ -/** - * @file lluserrelations_tut.cpp - * @author Phoenix - * @date 2006-10-12 - * @brief Unit tests for the LLRelationship class. - * - * $LicenseInfo:firstyear=2006&license=viewerlgpl$ - * Second Life Viewer Source Code - * Copyright (C) 2010, Linden Research, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; - * version 2.1 of the License only. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA - * $/LicenseInfo$ - */ - -#include - -#include "linden_common.h" -#include "lluserrelations.h" - -namespace tut -{ - struct user_relationship - { - LLRelationship mRelationship; - }; - typedef test_group user_relationship_t; - typedef user_relationship_t::object user_relationship_object_t; - tut::user_relationship_t tut_user_relationship("relationships"); - - template<> template<> - void user_relationship_object_t::test<1>() - { - // Test the default construction - ensure( - "No granted rights to", - !mRelationship.isRightGrantedTo( - LLRelationship::GRANT_ONLINE_STATUS)); - ensure( - "No granted rights from", - !mRelationship.isRightGrantedFrom( - LLRelationship::GRANT_ONLINE_STATUS)); - ensure("No online status",!mRelationship.isOnline()); - } - - template<> template<> - void user_relationship_object_t::test<2>() - { - // Test some granting - mRelationship.grantRights( - LLRelationship::GRANT_ONLINE_STATUS, - LLRelationship::GRANT_MODIFY_OBJECTS); - ensure( - "Granted rights to has online", - mRelationship.isRightGrantedTo( - LLRelationship::GRANT_ONLINE_STATUS)); - ensure( - "Granted rights from does not have online", - !mRelationship.isRightGrantedFrom( - LLRelationship::GRANT_ONLINE_STATUS)); - ensure( - "Granted rights to does not have modify", - !mRelationship.isRightGrantedTo( - LLRelationship::GRANT_MODIFY_OBJECTS)); - ensure( - "Granted rights from has modify", - mRelationship.isRightGrantedFrom( - LLRelationship::GRANT_MODIFY_OBJECTS)); - } - - template<> template<> - void user_relationship_object_t::test<3>() - { - // Test revoking - mRelationship.grantRights( - LLRelationship::GRANT_ONLINE_STATUS - | LLRelationship::GRANT_MAP_LOCATION, - LLRelationship::GRANT_ONLINE_STATUS); - ensure( - "Granted rights to has online and map", - mRelationship.isRightGrantedTo( - LLRelationship::GRANT_ONLINE_STATUS - | LLRelationship::GRANT_MAP_LOCATION)); - ensure( - "Granted rights from has online", - mRelationship.isRightGrantedFrom( - LLRelationship::GRANT_ONLINE_STATUS)); - - mRelationship.revokeRights( - LLRelationship::GRANT_MAP_LOCATION, - LLRelationship::GRANT_NONE); - ensure( - "Granted rights revoked map", - !mRelationship.isRightGrantedTo( - LLRelationship::GRANT_ONLINE_STATUS - | LLRelationship::GRANT_MAP_LOCATION)); - ensure( - "Granted rights revoked still has online", - mRelationship.isRightGrantedTo( - LLRelationship::GRANT_ONLINE_STATUS)); - - mRelationship.grantRights( - LLRelationship::GRANT_NONE, - LLRelationship::GRANT_MODIFY_OBJECTS); - ensure( - "Granted rights from still has online", - mRelationship.isRightGrantedFrom( - LLRelationship::GRANT_ONLINE_STATUS)); - ensure( - "Granted rights from has full grant", - mRelationship.isRightGrantedFrom( - LLRelationship::GRANT_ONLINE_STATUS - | LLRelationship::GRANT_MODIFY_OBJECTS)); - mRelationship.revokeRights( - LLRelationship::GRANT_NONE, - LLRelationship::GRANT_MODIFY_OBJECTS); - ensure( - "Granted rights from still has online", - mRelationship.isRightGrantedFrom( - LLRelationship::GRANT_ONLINE_STATUS)); - ensure( - "Granted rights from no longer modify", - !mRelationship.isRightGrantedFrom( - LLRelationship::GRANT_MODIFY_OBJECTS)); - } - - template<> template<> - void user_relationship_object_t::test<4>() - { - ensure("No online status", !mRelationship.isOnline()); - mRelationship.online(true); - ensure("Online status", mRelationship.isOnline()); - mRelationship.online(false); - ensure("No online status", !mRelationship.isOnline()); - } - -/* - template<> template<> - void user_relationship_object_t::test<>() - { - } -*/ -} diff --git a/indra/test/llxorcipher_tut.cpp b/indra/test/llxorcipher_tut.cpp deleted file mode 100644 index 9acac53604..0000000000 --- a/indra/test/llxorcipher_tut.cpp +++ /dev/null @@ -1,131 +0,0 @@ -/** - * @file llxorcipher_tut.cpp - * @author Adroit - * @date 2007-03 - * @brief llxorcipher, llnullcipher test cases. - * - * $LicenseInfo:firstyear=2007&license=viewerlgpl$ - * Second Life Viewer Source Code - * Copyright (C) 2010, Linden Research, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; - * version 2.1 of the License only. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA - * $/LicenseInfo$ - */ - -#include "linden_common.h" -#include "lltut.h" -#include "llxorcipher.h" -#include "llnullcipher.h" - -namespace tut -{ - struct cipher - { - }; - typedef test_group cipher_t; - typedef cipher_t::object cipher_object_t; - tut::cipher_t tut_cipher("cipher"); - - //encrypt->decrypt - template<> template<> - void cipher_object_t::test<1>() - { - const U32 len = 3; - const U8 pad[] = "abc"; - const char str[] = "SecondLife"; - const S32 str_len = sizeof(str); - U8 encrypted[str_len]; - U8 decrypted[str_len]; - LLXORCipher xorCipher(pad, len); - LLXORCipher xorCipher1(pad, len); - - U32 length = xorCipher.requiredEncryptionSpace(50); - ensure("requiredEncryptionSpace() function failed", (length == 50)); - - U32 lenEncrypted = xorCipher.encrypt((U8 *) str, str_len, encrypted, str_len); - ensure("Encryption failed", (lenEncrypted == str_len)); - U32 lenDecrypted = xorCipher1.decrypt(encrypted, str_len, decrypted, str_len); - ensure("Decryption failed", (lenDecrypted == str_len)); - ensure_memory_matches("LLXORCipher Encrypt/Decrypt failed", str, str_len, decrypted, lenDecrypted); - } - - // operator= - template<> template<> - void cipher_object_t::test<2>() - { - const U8 pad[] = "ABCDEFGHIJKLMNOPQ"; // pad len longer than data to be ciphered - const U32 pad_len = sizeof(pad); - const U8 pad1[] = "SecondLife"; - const U32 pad_len1 = sizeof(pad1); - const char str[] = "To Be Ciphered"; - const S32 str_len = sizeof(str); - U8 encrypted[str_len]; - U8 decrypted[str_len]; - - LLXORCipher xorCipher(pad, pad_len); - LLXORCipher xorCipher1(pad1, pad_len1); - - xorCipher.encrypt((U8 *) str, str_len, encrypted, str_len); - // make xorCipher1 same as xorCipher..so that xorCipher1 can decrypt what was - // encrypted using xorCipher - xorCipher1 = xorCipher; - U32 lenDecrypted = xorCipher1.decrypt(encrypted, str_len, decrypted, str_len); - ensure_memory_matches("LLXORCipher operator= failed", str, str_len, decrypted, lenDecrypted); - } - - //in place encrypt->decrypt - template<> template<> - void cipher_object_t::test<3>() - { - U32 padNum = 0x12349087; - const U8* pad = (U8*) &padNum; - const U32 pad_len = sizeof(U32); - char str[] = "To Be Ciphered a long string.........!!!."; - char str1[] = "To Be Ciphered a long string.........!!!."; // same as str - const S32 str_len = sizeof(str); - - LLXORCipher xorCipher(pad, pad_len); - LLXORCipher xorCipher1(pad, pad_len); - xorCipher.encrypt((U8 *) str, str_len); - // it should not be the same as original data! - ensure("LLXORCipher: In Place encrypt failed", memcmp(str, str1, str_len) != 0); - xorCipher1.decrypt((U8 *) str, str_len); - // it should not be the same as original data! - ensure_memory_matches("LLXORCipher: In Place decrypt failed", str, str_len, str1, str_len); - } - - //LLNullCipher encrypt->decrypt - template<> template<> - void cipher_object_t::test<4>() - { - const char str[] = "SecondLife"; - const S32 str_len = sizeof(str); - U8 encrypted[str_len]; - U8 decrypted[str_len]; - LLNullCipher nullCipher; - LLNullCipher nullCipher1; - - U32 length = nullCipher.requiredEncryptionSpace(50); - ensure("LLNullCipher::requiredEncryptionSpace() function failed", (length == 50)); - - U32 len1 = nullCipher.encrypt((U8 *) str, str_len, encrypted, str_len); - ensure_memory_matches("LLNullCipher - Source transformed during encryption.", encrypted, len1, str, str_len); - - U32 len2 = nullCipher1.decrypt(encrypted, str_len, decrypted, str_len); - ensure_memory_matches("LLNullCipher - Decryption failed", decrypted, len2, str, str_len); - } -} diff --git a/indra/test/message_tut.cpp b/indra/test/message_tut.cpp deleted file mode 100644 index 11cd710ef6..0000000000 --- a/indra/test/message_tut.cpp +++ /dev/null @@ -1,147 +0,0 @@ -/** - * @file lldatapacker_tut.cpp - * @date 2007-04 - * @brief LLDataPacker test cases. - * - * $LicenseInfo:firstyear=2007&license=viewerlgpl$ - * Second Life Viewer Source Code - * Copyright (C) 2010, Linden Research, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; - * version 2.1 of the License only. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA - * $/LicenseInfo$ - */ - -#include -#include "linden_common.h" -#include "lltut.h" -#include "llhttpconstants.h" -#include "llapr.h" -#include "llmessageconfig.h" -#include "llsdserialize.h" -#include "message.h" -#include "message_prehash.h" - -namespace -{ - struct Response : public LLHTTPNode::Response - { - virtual void result(const LLSD&) {} - virtual void status(S32 code, const std::string& message) - { - mStatus = code; - } - virtual void extendedResult(S32 code, const std::string& message, const LLSD& headers) { } - virtual void extendedResult(S32 code, const LLSD& result, const LLSD& headers) { } - S32 mStatus; - }; -} - -namespace tut -{ - struct LLMessageSystemTestData - { - std::string mTestConfigDir; - std::string mSep; - - LLMessageSystemTestData() - { - static bool init = false; - if(!init) - { - ll_init_apr(); - //init_prehash_data(); - init = true; - } - const F32 circuit_heartbeat_interval=5; - const F32 circuit_timeout=100; - - - // currently test disconnected message system - start_messaging_system("notafile", 13035, - 1, - 0, - 0, - false, - "notasharedsecret", - NULL, - false, - circuit_heartbeat_interval, - circuit_timeout - ); - // generate temp dir - std::ostringstream ostr; -#if LL_WINDOWS - mSep = "\\"; - ostr << "C:" << mSep; -#else - mSep = "/"; - ostr << mSep << "tmp" << mSep; -#endif - LLUUID random; - random.generate(); - ostr << "message-test-" << random; - mTestConfigDir = ostr.str(); - LLFile::mkdir(mTestConfigDir); - writeConfigFile(LLSD()); - LLMessageConfig::initClass("simulator", ostr.str()); - } - - ~LLMessageSystemTestData() - { - // not end_messaging_system() - delete static_cast(gMessageSystem); - gMessageSystem = NULL; - - // rm contents of temp dir - std::ostringstream ostr; - ostr << mTestConfigDir << mSep << "message.xml"; - int rmfile = LLFile::remove(ostr.str()); - ensure_equals("rmfile value", rmfile, 0); - - // rm temp dir - int rmdir = LLFile::rmdir(mTestConfigDir); - ensure_equals("rmdir value", rmdir, 0); - } - - void writeConfigFile(const LLSD& config) - { - std::string ostr(mTestConfigDir + mSep + "message.xml"); - llofstream file(ostr.c_str()); - if (file.is_open()) - { - LLSDSerialize::toPrettyXML(config, file); - } - file.close(); - } - }; - - typedef test_group LLMessageSystemTestGroup; - typedef LLMessageSystemTestGroup::object LLMessageSystemTestObject; - LLMessageSystemTestGroup messageTestGroup("LLMessageSystem"); - - template<> template<> - void LLMessageSystemTestObject::test<1>() - // dispatch unknown message - { - const char* name = "notamessasge"; - const LLSD message; - const LLPointer response = new Response(); - gMessageSystem->dispatch(name, message, response); - ensure_equals(response->mStatus, HTTP_NOT_FOUND); - } -} - diff --git a/indra/test/mock_http_client.cpp b/indra/test/mock_http_client.cpp deleted file mode 100644 index a97d31c7f4..0000000000 --- a/indra/test/mock_http_client.cpp +++ /dev/null @@ -1,82 +0,0 @@ -/** - * @file mock_http_client.cpp - * @brief Framework for testing HTTP requests - * - * $LicenseInfo:firstyear=2007&license=viewerlgpl$ - * Second Life Viewer Source Code - * Copyright (C) 2010, Linden Research, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; - * version 2.1 of the License only. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA - * $/LicenseInfo$ - */ - -#include "linden_common.h" -#include "llhttpnode.h" - -namespace tut -{ - class SuccessNode : public LLHTTPNode - { - public: - void get(ResponsePtr r, const LLSD& context) const - { - LLSD result; - result["state"] = "complete"; - result["test"] = "test"; - r->result(result); - } - void post(ResponsePtr r, const LLSD& context, const LLSD& input) const - { - LLSD result; - result["state"] = "complete"; - result["test"] = "test"; - r->result(result); - } - }; - - class ErrorNode : public LLHTTPNode - { - public: - void get(ResponsePtr r, const LLSD& context) const - { r->status(599, "Intentional error"); } - void post(ResponsePtr r, const LLSD& context, const LLSD& input) const - { r->status(input["status"], input["reason"]); } - }; - - class TimeOutNode : public LLHTTPNode - { - public: - void get(ResponsePtr r, const LLSD& context) const - { - /* do nothing, the request will eventually time out */ - } - }; - - LLSD storage; - - class LLSDStorageNode : public LLHTTPNode - { - public: - LLSD get() const{ return storage; } - LLSD put(const LLSD& value) const{ storage = value; return LLSD(); } - }; - - LLHTTPRegistration gStorageNode("/test/storage"); - LLHTTPRegistration gSuccessNode("/test/success"); - LLHTTPRegistration gErrorNode("/test/error"); - LLHTTPRegistration gTimeOutNode("/test/timeout"); -} diff --git a/indra/test/mock_http_client.h b/indra/test/mock_http_client.h deleted file mode 100644 index ef268abc6e..0000000000 --- a/indra/test/mock_http_client.h +++ /dev/null @@ -1,190 +0,0 @@ -/** - * @file mock_http_client.cpp - * @brief Framework for testing HTTP requests - * - * $LicenseInfo:firstyear=2007&license=viewerlgpl$ - * Second Life Viewer Source Code - * Copyright (C) 2010, Linden Research, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; - * version 2.1 of the License only. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA - * $/LicenseInfo$ - */ - -#include "llsdhttpserver.h" -#include "lliohttpserver.h" -#include "llhttpclient.h" -#include "llformat.h" -#include "llpipeutil.h" -#include "llpumpio.h" - -namespace tut -{ - struct MockHttpClient - { - public: - MockHttpClient() - { - apr_pool_create(&mPool, NULL); - mServerPump = new LLPumpIO(mPool); - mClientPump = new LLPumpIO(mPool); - - LLHTTPClient::setPump(*mClientPump); - } - - ~MockHttpClient() - { - delete mServerPump; - delete mClientPump; - apr_pool_destroy(mPool); - } - - void setupTheServer() - { - LLHTTPNode& root = LLIOHTTPServer::create(mPool, *mServerPump, 8888); - - LLHTTPStandardServices::useServices(); - LLHTTPRegistrar::buildAllServices(root); - } - - void runThePump(float timeout = 100.0f) - { - LLTimer timer; - timer.setTimerExpirySec(timeout); - - while(!mSawCompleted && !timer.hasExpired()) - { - if (mServerPump) - { - mServerPump->pump(); - mServerPump->callback(); - } - if (mClientPump) - { - mClientPump->pump(); - mClientPump->callback(); - } - } - } - - void killServer() - { - delete mServerPump; - mServerPump = NULL; - } - - private: - apr_pool_t* mPool; - LLPumpIO* mServerPump; - LLPumpIO* mClientPump; - - - protected: - void ensureStatusOK() - { - if (mSawError) - { - std::string msg = - llformat("httpFailure() called when not expected, status %d", - mStatus); - fail(msg); - } - } - - void ensureStatusError() - { - if (!mSawError) - { - fail("httpFailure() wasn't called"); - } - } - - LLSD getResult() - { - return mResult; - } - - protected: - bool mSawError; - S32 mStatus; - std::string mReason; - bool mSawCompleted; - LLSD mResult; - bool mResultDeleted; - - class Result : public LLHTTPClient::Responder - { - protected: - Result(MockHttpClient& client) - : mClient(client) - { - } - - public: - static boost::intrusive_ptr build(MockHttpClient& client) - { - return boost::intrusive_ptr(new Result(client)); - } - - ~Result() - { - mClient.mResultDeleted = true; - } - - protected: - virtual void httpFailure() - { - mClient.mSawError = true; - mClient.mStatus = getStatus(); - mClient.mReason = getReason(); - } - - virtual void httpSuccess() - { - mClient.mResult = getContent(); - } - - virtual void httpCompleted() - { - LLHTTPClient::Responder::httpCompleted(); - - mClient.mSawCompleted = true; - } - - private: - MockHttpClient& mClient; - }; - - friend class Result; - - protected: - - void reset() - { - mSawError = false; - mStatus = 0; - mSawCompleted = false; - mResult.clear(); - mResultDeleted = false; - } - - LLHTTPClient::ResponderPtr newResult() - { - reset(); - return Result::build(*this); - } - }; -} diff --git a/indra/test/prim_linkability_tut.cpp b/indra/test/prim_linkability_tut.cpp deleted file mode 100644 index 3603b25f18..0000000000 --- a/indra/test/prim_linkability_tut.cpp +++ /dev/null @@ -1,495 +0,0 @@ -/** - * @file linkability.cpp - * @author andrew@lindenlab.com - * @date 2007-04-23 - * @brief Tests for the LLPrimLinkInfo template which computes the linkability of prims - * - * $LicenseInfo:firstyear=2007&license=viewerlgpl$ - * Second Life Viewer Source Code - * Copyright (C) 2010, Linden Research, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; - * version 2.1 of the License only. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA - * $/LicenseInfo$ - */ - -#include "linden_common.h" -#include "lltut.h" -#include "llprimlinkinfo.h" -#include "llrand.h" - - -// helper function -void randomize_sphere(LLSphere& sphere, F32 center_range, F32 radius_range) -{ - F32 radius = ll_frand(2.f * radius_range) - radius_range; - LLVector3 center; - for (S32 i=0; i<3; ++i) - { - center.mV[i] = ll_frand(2.f * center_range) - center_range; - } - sphere.setRadius(radius); - sphere.setCenter(center); -} - -// helper function. Same as above with a min and max radius. -void randomize_sphere(LLSphere& sphere, F32 center_range, F32 minimum_radius, F32 maximum_radius) -{ - F32 radius = ll_frand(maximum_radius - minimum_radius) + minimum_radius; - LLVector3 center; - for (S32 i=0; i<3; ++i) - { - center.mV[i] = ll_frand(2.f * center_range) - center_range; - } - sphere.setRadius(radius); - sphere.setCenter(center); -} - -// helper function -bool random_sort( const LLPrimLinkInfo< S32 >&, const LLPrimLinkInfo< S32 >& b) -{ - return (ll_rand(64) < 32); -} - -namespace tut -{ - struct linkable_data - { - LLPrimLinkInfo info; - }; - - typedef test_group linkable_test; - typedef linkable_test::object linkable_object; - tut::linkable_test wtf("prim linkability"); - - template<> template<> - void linkable_object::test<1>() - { - // Here we test the boundary of the LLPrimLinkInfo::canLink() method - // between semi-random middle-sized objects. - - S32 number_of_tests = 100; - for (S32 test = 0; test < number_of_tests; ++test) - { - // compute the radii that would provide the above max link distance - F32 first_radius = 0.f; - F32 second_radius = 0.f; - - // compute a random center for the first sphere - // compute some random max link distance - F32 max_link_span = ll_frand(MAX_OBJECT_SPAN); - if (max_link_span < OBJECT_SPAN_BONUS) - { - max_link_span += OBJECT_SPAN_BONUS; - } - LLVector3 first_center( - ll_frand(2.f * max_link_span) - max_link_span, - ll_frand(2.f * max_link_span) - max_link_span, - ll_frand(2.f * max_link_span) - max_link_span); - - // put the second sphere at the right distance from the origin - // such that it is within the max_link_distance of the first - LLVector3 direction(ll_frand(2.f) - 1.f, ll_frand(2.f) - 1.f, ll_frand(2.f) - 1.f); - direction.normalize(); - F32 half_milimeter = 0.0005f; - LLVector3 second_center; - - // max_span = 3 * (first_radius + second_radius) + OBJECT_SPAN_BONUS - // make sure they link at short distances - { - second_center = first_center + (OBJECT_SPAN_BONUS - half_milimeter) * direction; - LLPrimLinkInfo first_info(0, LLSphere(first_center, first_radius) ); - LLPrimLinkInfo second_info(1, LLSphere(second_center, second_radius) ); - ensure("these nearby objects should link", first_info.canLink(second_info) ); - } - - // make sure they fail to link if we move them apart just a little bit - { - second_center = first_center + (OBJECT_SPAN_BONUS + half_milimeter) * direction; - LLPrimLinkInfo first_info(0, LLSphere(first_center, first_radius) ); - LLPrimLinkInfo second_info(1, LLSphere(second_center, second_radius) ); - ensure("these nearby objects should NOT link", !first_info.canLink(second_info) ); - } - - // make sure the objects link or not at medium distances - { - first_radius = 0.3f * ll_frand(max_link_span - OBJECT_SPAN_BONUS); - - // This is the exact second radius that will link at exactly our random max_link_distance - second_radius = ((max_link_span - OBJECT_SPAN_BONUS) / 3.f) - first_radius; - second_center = first_center + (max_link_span - first_radius - second_radius - half_milimeter) * direction; - - LLPrimLinkInfo first_info(0, LLSphere(first_center, first_radius) ); - LLPrimLinkInfo second_info(1, LLSphere(second_center, second_radius) ); - - ensure("these objects should link", first_info.canLink(second_info) ); - } - - // make sure they fail to link if we move them apart just a little bit - { - // move the second sphere such that it is a little too far from the first - second_center += (2.f * half_milimeter) * direction; - LLPrimLinkInfo first_info(0, LLSphere(first_center, first_radius) ); - LLPrimLinkInfo second_info(1, LLSphere(second_center, second_radius) ); - - ensure("these objects should NOT link", !first_info.canLink(second_info) ); - } - - // make sure things don't link at far distances - { - second_center = first_center + (MAX_OBJECT_SPAN + 2.f * half_milimeter) * direction; - second_radius = 0.3f * MAX_OBJECT_SPAN; - LLPrimLinkInfo first_info(0, LLSphere(first_center, first_radius) ); - LLPrimLinkInfo second_info(1, LLSphere(second_center, second_radius) ); - ensure("these objects should NOT link", !first_info.canLink(second_info) ); - } - - } - } - - template<> template<> - void linkable_object::test<2>() - { - - // Consider a row of eight spheres in a row, each 10m in diameter and centered - // at 10m intervals: 01234567. - - F32 radius = 5.f; - F32 spacing = 10.f; - - LLVector3 line_direction(ll_frand(2.f) - 1.f, ll_frand(2.f) - 1.f, ll_frand(2.f) - 1.f); - line_direction.normalize(); - - LLVector3 first_center(ll_frand(2.f * spacing) -spacing, ll_frand(2.f * spacing) - spacing, ll_frand(2.f * spacing) - spacing); - - LLPrimLinkInfo infos[8]; - - for (S32 index = 0; index < 8; ++index) - { - LLVector3 center = first_center + ((F32)(index) * spacing) * line_direction; - infos[index].set(index, LLSphere(center, radius)); - } - - // Max span for 2 spheres of 5m radius is 3 * (5 + 5) + 1 = 31m - // spheres 0&2 have a 30m span (from outside edge to outside edge) and should link - { - LLPrimLinkInfo root_info = infos[0]; - std::list< LLPrimLinkInfo > info_list; - info_list.push_back(infos[2]); - root_info.mergeLinkableSet(info_list); - S32 prim_count = root_info.getPrimCount(); - ensure_equals("0&2 prim count should be 2", prim_count, 2); - ensure_equals("0&2 unlinkable list should have length 0", (S32) info_list.size(), 0); - } - - - // spheres 0&3 have a 40 meter span and should NOT link outright - { - LLPrimLinkInfo root_info = infos[0]; - std::list< LLPrimLinkInfo > info_list; - info_list.push_back(infos[3]); - root_info.mergeLinkableSet(info_list); - S32 prim_count = root_info.getPrimCount(); - ensure_equals("0&4 prim count should be 1", prim_count, 1); - ensure_equals("0&4 unlinkable list should have length 1", (S32) info_list.size(), 1); - } - - - // spheres 0-4 should link no matter what order : 01234 - // Total span = 50m, 012 link with a r=15.5 giving max span of 3 * (15.5 + 5) + 1 = 62.5, but the cap is 54m - { - LLPrimLinkInfo root_info = infos[0]; - std::list< LLPrimLinkInfo > info_list; - for (S32 index = 1; index < 5; ++index) - { - info_list.push_back(infos[index]); - } - root_info.mergeLinkableSet(info_list); - S32 prim_count = root_info.getPrimCount(); - ensure_equals("01234 prim count should be 5", prim_count, 5); - ensure_equals("01234 unlinkable list should have length 0", (S32) info_list.size(), 0); - } - - - // spheres 0-5 should link no matter what order : 04321 - { - LLPrimLinkInfo root_info = infos[0]; - std::list< LLPrimLinkInfo > info_list; - for (S32 index = 4; index > 0; --index) - { - info_list.push_back(infos[index]); - } - root_info.mergeLinkableSet(info_list); - S32 prim_count = root_info.getPrimCount(); - ensure_equals("04321 prim count should be 5", prim_count, 5); - ensure_equals("04321 unlinkable list should have length 0", (S32) info_list.size(), 0); - } - - // spheres 0-4 should link no matter what order : 01423 - { - LLPrimLinkInfo root_info = infos[0]; - std::list< LLPrimLinkInfo > info_list; - info_list.push_back(infos[1]); - info_list.push_back(infos[4]); - info_list.push_back(infos[2]); - info_list.push_back(infos[3]); - root_info.mergeLinkableSet(info_list); - S32 prim_count = root_info.getPrimCount(); - ensure_equals("01423 prim count should be 5", prim_count, 5); - ensure_equals("01423 unlinkable list should have length 0", (S32) info_list.size(), 0); - } - - // spheres 0-5 should NOT fully link, only 0-4 - { - LLPrimLinkInfo root_info = infos[0]; - std::list< LLPrimLinkInfo > info_list; - for (S32 index = 1; index < 6; ++index) - { - info_list.push_back(infos[index]); - } - root_info.mergeLinkableSet(info_list); - S32 prim_count = root_info.getPrimCount(); - ensure_equals("012345 prim count should be 5", prim_count, 5); - ensure_equals("012345 unlinkable list should have length 1", (S32) info_list.size(), 1); - std::list< LLPrimLinkInfo >::iterator info_itr = info_list.begin(); - if (info_itr != info_list.end()) - { - // examine the contents of the unlinked info - std::list unlinked_indecies; - info_itr->getData(unlinked_indecies); - // make sure there is only one index in the unlinked_info - ensure_equals("012345 unlinkable index count should be 1", (S32) unlinked_indecies.size(), 1); - // make sure its value is 6 - std::list::iterator unlinked_index_itr = unlinked_indecies.begin(); - S32 unlinkable_index = *unlinked_index_itr; - ensure_equals("012345 unlinkable index should be 5", (S32) unlinkable_index, 5); - } - } - - // spheres 0-7 should NOT fully link, only 0-5 - { - LLPrimLinkInfo root_info = infos[0]; - std::list< LLPrimLinkInfo > info_list; - for (S32 index = 1; index < 8; ++index) - { - info_list.push_back(infos[index]); - } - root_info.mergeLinkableSet(info_list); - S32 prim_count = root_info.getPrimCount(); - ensure_equals("01234567 prim count should be 5", prim_count, 5); - // Should be 1 linkinfo on unlinkable that has 2 prims - ensure_equals("01234567 unlinkable list should have length 1", (S32) info_list.size(), 1); - std::list< LLPrimLinkInfo >::iterator info_itr = info_list.begin(); - if (info_itr != info_list.end()) - { - // make sure there is only one index in the unlinked_info - std::list unlinked_indecies; - info_itr->getData(unlinked_indecies); - ensure_equals("0123456 unlinkable index count should be 3", (S32) unlinked_indecies.size(), 3); - - // make sure its values are 6 and 7 - std::list::iterator unlinked_index_itr = unlinked_indecies.begin(); - S32 unlinkable_index = *unlinked_index_itr; - ensure_equals("0123456 first unlinkable index should be 5", (S32) unlinkable_index, 5); - ++unlinked_index_itr; - unlinkable_index = *unlinked_index_itr; - ensure_equals("0123456 second unlinkable index should be 6", (S32) unlinkable_index, 6); - ++unlinked_index_itr; - unlinkable_index = *unlinked_index_itr; - ensure_equals("0123456 third unlinkable index should be 7", (S32) unlinkable_index, 7); - - } - } - } - - template<> template<> - void linkable_object::test<3>() - { - // Here we test the link results between an LLPrimLinkInfo and a set of - // randomized LLPrimLinkInfos where the expected results are known. - S32 number_of_tests = 5; - for (S32 test = 0; test < number_of_tests; ++test) - { - // the radii are known - F32 first_radius = 1.f; - F32 second_radius = 2.f; - F32 third_radius = 3.f; - - // compute the distances - F32 half_milimeter = 0.0005f; - F32 max_first_second_span = 3.f * (first_radius + second_radius) + OBJECT_SPAN_BONUS; - F32 linkable_distance = max_first_second_span - first_radius - second_radius - half_milimeter; - - F32 max_full_span = 3.f * (0.5f * max_first_second_span + third_radius) + OBJECT_SPAN_BONUS; - F32 unlinkable_distance = max_full_span - 0.5f * linkable_distance - third_radius + half_milimeter; - - // compute some random directions - LLVector3 first_direction(ll_frand(2.f) - 1.f, ll_frand(2.f) - 1.f, ll_frand(2.f) - 1.f); - first_direction.normalize(); - LLVector3 second_direction(ll_frand(2.f) - 1.f, ll_frand(2.f) - 1.f, ll_frand(2.f) - 1.f); - second_direction.normalize(); - LLVector3 third_direction(ll_frand(2.f) - 1.f, ll_frand(2.f) - 1.f, ll_frand(2.f) - 1.f); - third_direction.normalize(); - - // compute the centers - LLVector3 first_center = ll_frand(10.f) * first_direction; - LLVector3 second_center = first_center + ll_frand(linkable_distance) * second_direction; - LLVector3 first_join_center = 0.5f * (first_center + second_center); - LLVector3 third_center = first_join_center + unlinkable_distance * third_direction; - - // make sure the second info links and the third does not - { - // initialize the infos - S32 index = 0; - LLPrimLinkInfo first_info(index++, LLSphere(first_center, first_radius)); - LLPrimLinkInfo second_info(index++, LLSphere(second_center, second_radius)); - LLPrimLinkInfo third_info(index++, LLSphere(third_center, third_radius)); - - // put the second and third infos in a list - std::list< LLPrimLinkInfo > info_list; - info_list.push_back(second_info); - info_list.push_back(third_info); - - // merge the list with the first_info - first_info.mergeLinkableSet(info_list); - S32 prim_count = first_info.getPrimCount(); - - ensure_equals("prim count should be 2", prim_count, 2); - ensure_equals("unlinkable list should have length 1", (S32) info_list.size(), 1); - } - - // reverse the order and make sure we get the same results - { - // initialize the infos - S32 index = 0; - LLPrimLinkInfo first_info(index++, LLSphere(first_center, first_radius)); - LLPrimLinkInfo second_info(index++, LLSphere(second_center, second_radius)); - LLPrimLinkInfo third_info(index++, LLSphere(third_center, third_radius)); - - // build the list in the reverse order - std::list< LLPrimLinkInfo > info_list; - info_list.push_back(third_info); - info_list.push_back(second_info); - - // merge the list with the first_info - first_info.mergeLinkableSet(info_list); - S32 prim_count = first_info.getPrimCount(); - - ensure_equals("prim count should be 2", prim_count, 2); - ensure_equals("unlinkable list should have length 1", (S32) info_list.size(), 1); - } - } - } - - template<> template<> - void linkable_object::test<4>() - { - // Here we test whether linkability is invarient under permutations - // of link order. To do this we generate a bunch of random spheres - // and then try to link them in different ways. - // - // NOTE: the linkability will only be invarient if there is only one - // linkable solution. Multiple solutions will exist if the set of - // candidates are larger than the maximum linkable distance, or more - // numerous than a single linked object can contain. This is easily - // understood by considering a very large set of link candidates, - // and first linking preferentially to the left until linking fails, - // then doing the same to the right -- the final solutions will differ. - // Hence for this test we must generate candidate sets that lie within - // the linkability envelope of a single object. - // - // NOTE: a random set of objects will tend to either be totally linkable - // or totally not. That is, the random orientations that - - F32 root_center_range = 0.f; - F32 min_prim_radius = 0.1f; - F32 max_prim_radius = 2.f; - - // Linkability is min(MAX_OBJECT_SPAN,3 *( R1 + R2 ) + BONUS) - // 3 * (min_prim_radius + min_prim_radius) + OBJECT_SPAN_BONUS = 6 * min_prim_radius + OBJECT_SPAN_BONUS; - // Use .45 instead of .5 to gaurantee objects are within the minimum span. - F32 child_center_range = 0.45f * ( (6*min_prim_radius) + OBJECT_SPAN_BONUS ); - - S32 number_of_tests = 100; - S32 number_of_spheres = 10; - S32 number_of_scrambles = 10; - S32 number_of_random_bubble_sorts = 10; - - for (S32 test = 0; test < number_of_tests; ++test) - { - LLSphere sphere; - S32 sphere_index = 0; - - // build the root piece - randomize_sphere(sphere, root_center_range, min_prim_radius, max_prim_radius); - info.set( sphere_index++, sphere ); - - // build the unlinked pieces - std::list< LLPrimLinkInfo > info_list; - for (; sphere_index < number_of_spheres; ++sphere_index) - { - randomize_sphere(sphere, child_center_range, min_prim_radius, max_prim_radius); - LLPrimLinkInfo child_info( sphere_index, sphere ); - info_list.push_back(child_info); - } - - // declare the variables used to store the results - std::list first_linked_list; - - { - // the link attempt will modify our original info's, so we - // have to make copies of the originals for testing - LLPrimLinkInfo test_info( 0, LLSphere(info.getCenter(), 0.5f * info.getDiameter()) ); - std::list< LLPrimLinkInfo > test_list; - test_list.assign(info_list.begin(), info_list.end()); - - // try to link - test_info.mergeLinkableSet(test_list); - - ensure("All prims should link, but did not.",test_list.empty()); - - // store the results - test_info.getData(first_linked_list); - first_linked_list.sort(); - } - - // try to link the spheres in various random orders - for (S32 scramble = 0; scramble < number_of_scrambles; ++scramble) - { - LLPrimLinkInfo test_info(0, LLSphere(info.getCenter(), 0.5f * info.getDiameter()) ); - - // scramble the order of the info_list - std::list< LLPrimLinkInfo > test_list; - test_list.assign(info_list.begin(), info_list.end()); - for (S32 i = 0; i < number_of_random_bubble_sorts; i++) - { - test_list.sort(random_sort); - } - - // try to link - test_info.mergeLinkableSet(test_list); - - // get the results - std::list linked_list; - test_info.getData(linked_list); - linked_list.sort(); - - ensure_equals("linked set size should be order independent",linked_list.size(),first_linked_list.size()); - } - } - } -} - -- cgit v1.3 From 76dd2826f69f783103591be6fae3dc7582b2f6ed Mon Sep 17 00:00:00 2001 From: Rye Date: Mon, 15 Dec 2025 14:07:15 -0500 Subject: Clean up dead partsyspacket code Signed-off-by: Rye --- indra/llmessage/CMakeLists.txt | 2 - indra/llmessage/partsyspacket.cpp | 1297 ------------------------------------- indra/llmessage/partsyspacket.h | 261 -------- 3 files changed, 1560 deletions(-) delete mode 100644 indra/llmessage/partsyspacket.cpp delete mode 100644 indra/llmessage/partsyspacket.h (limited to 'indra/llmessage') diff --git a/indra/llmessage/CMakeLists.txt b/indra/llmessage/CMakeLists.txt index 2e51e1b5d4..f143ee18cf 100644 --- a/indra/llmessage/CMakeLists.txt +++ b/indra/llmessage/CMakeLists.txt @@ -79,7 +79,6 @@ set(llmessage_SOURCE_FILES message_prehash.cpp message_string_table.cpp net.cpp - partsyspacket.cpp patch_code.cpp patch_dct.cpp patch_idct.cpp @@ -171,7 +170,6 @@ set(llmessage_HEADER_FILES message.h message_prehash.h net.h - partsyspacket.h patch_code.h patch_dct.h sound_ids.h diff --git a/indra/llmessage/partsyspacket.cpp b/indra/llmessage/partsyspacket.cpp deleted file mode 100644 index 6113adbfcf..0000000000 --- a/indra/llmessage/partsyspacket.cpp +++ /dev/null @@ -1,1297 +0,0 @@ -/** - * @file partsyspacket.cpp - * @brief Object for packing particle system initialization parameters - * before sending them over the network. - * - * $LicenseInfo:firstyear=2000&license=viewerlgpl$ - * Second Life Viewer Source Code - * Copyright (C) 2010, Linden Research, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; - * version 2.1 of the License only. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA - * $/LicenseInfo$ - */ - -#include "linden_common.h" - -#include "partsyspacket.h" -#include "indra_constants.h" - -// this function is global -void gSetInitDataDefaults(LLPartInitData *setMe) -{ - U32 i; - - //for(i = 0; i < 18; i++) - //{ - // setMe->k[i] = 0.0f; - //} - - //setMe->kill_p[0] = setMe->kill_p[1] = setMe->kill_p[2] = 0.0f; - //setMe->kill_p[3] = -0.2f; // time parameter, die when t= 5.0f - //setMe->kill_p[4] = 1.0f; - //setMe->kill_p[5] = -0.5f; // or radius == 2 (contracting) - - //setMe->bounce_p[0] = setMe->bounce_p[1] = - // setMe->bounce_p[2] = setMe->bounce_p[3] = 0.0f; - //setMe->bounce_p[4] = 1.0f; - - setMe->bounce_b = 1.0f; - // i just changed the meaning of bounce_b - // its now the attenuation from revlecting your velocity across the normal - // set by bounce_p - - //setMe->pos_ranges[0] = setMe->pos_ranges[2] = setMe->pos_ranges[4] = -1.0f; - //setMe->pos_ranges[1] = setMe->pos_ranges[3] = setMe->pos_ranges[5] = 1.0f; - - //setMe->vel_ranges[0] = setMe->vel_ranges[2] = setMe->vel_ranges[4] = -1.0f; - //setMe->vel_ranges[1] = setMe->vel_ranges[3] = setMe->vel_ranges[5] = 1.0f; - - for(i = 0; i < 3; i++) - { - setMe->diffEqAlpha[i] = 0.0f; - setMe->diffEqScale[i] = 0.0f; - } - - setMe->scale_range[0] = 1.00f; - setMe->scale_range[1] = 5.00f; - setMe->scale_range[2] = setMe->scale_range[3] = 0.0f; - - setMe->alpha_range[0] = setMe->alpha_range[1] = 1.0f; - setMe->alpha_range[2] = setMe->alpha_range[3] = 0.0f; - - setMe->vel_offset[0] = 0.0f; - setMe->vel_offset[1] = 0.0f; - setMe->vel_offset[2] = 0.0f; - - // start dropping particles when I'm more then one sim away - setMe->mDistBeginFadeout = 256.0f; - setMe->mDistEndFadeout = 1.414f * 512.0f; - // stop displaying particles when I'm more then two sim diagonals away - - setMe->mImageUuid = IMG_SHOT; - - for(i = 0; i < 8; i++) - { - setMe->mFlags[i] = 0x00; - } - - setMe->createMe = true; - - setMe->maxParticles = 25; - setMe->initialParticles = 25; - - //These defaults are for an explosion - a short lived set of debris affected by gravity. - //Action flags default to PART_SYS_AFFECTED_BY_WIND + PART_SYS_AFFECTED_BY_GRAVITY + PART_SYS_DISTANCE_DEATH - setMe->mFlags[PART_SYS_ACTION_BYTE] = PART_SYS_AFFECTED_BY_WIND | PART_SYS_AFFECTED_BY_GRAVITY | PART_SYS_DISTANCE_DEATH; - setMe->mFlags[PART_SYS_KILL_BYTE] = PART_SYS_DISTANCE_DEATH + PART_SYS_TIME_DEATH; - - setMe->killPlaneNormal[0] = 0.0f;setMe->killPlaneNormal[1] = 0.0f;setMe->killPlaneNormal[2] = 1.0f; //Straight up - setMe->killPlaneZ = 0.0f; //get local ground z as an approximation if turn on PART_SYS_KILL_PLANE - setMe->bouncePlaneNormal[0] = 0.0f;setMe->bouncePlaneNormal[1] = 0.0f;setMe->bouncePlaneNormal[2] = 1.0f; //Straight up - setMe->bouncePlaneZ = 0.0f; //get local ground z as an approximation if turn on PART_SYS_BOUNCE - setMe->spawnRange = 1.0f; - setMe->spawnFrequency = 0.0f; //Create the instant one dies - setMe->spawnFreqencyRange = 0.0f; - setMe->spawnDirection[0] = 0.0f;setMe->spawnDirection[1] = 0.0f;setMe->spawnDirection[2] = 1.0f; //Straight up - setMe->spawnDirectionRange = 1.0f; //global scattering - setMe->spawnVelocity = 0.75f; - setMe->spawnVelocityRange = 0.25f; //velocity +/- 0.25 - setMe->speedLimit = 1.0f; - - setMe->windWeight = 0.5f; //0.0f means looks like a heavy object (if gravity is on), 1.0f means light and fluffy - setMe->currentGravity[0] = 0.0f;setMe->currentGravity[1] = 0.0f;setMe->currentGravity[2] = -9.81f; - //This has to be constant to allow for compression - - setMe->gravityWeight = 0.5f; //0.0f means boyed by air, 1.0f means it's a lead weight - setMe->globalLifetime = 0.0f; //Arbitrary, but default is no global die, so doesn't matter - setMe->individualLifetime = 5.0f; - setMe->individualLifetimeRange = 1.0f; //Particles last 5 secs +/- 1 - setMe->alphaDecay = 1.0f; //normal alpha fadeout - setMe->scaleDecay = 0.0f; //no scale decay - setMe->distanceDeath = 10.0f; //die if hit unit radius - setMe->dampMotionFactor = 0.0f; - - setMe->windDiffusionFactor[0] = 0.0f; - setMe->windDiffusionFactor[1] = 0.0f; - setMe->windDiffusionFactor[2] = 0.0f; -} - -LLPartSysCompressedPacket::LLPartSysCompressedPacket() -{ - // default constructor for mDefaults called implicitly/automatically here - for(int i = 0; i < MAX_PART_SYS_PACKET_SIZE; i++) - { - mData[i] = '\0'; - } - - mNumBytes = 0; - - gSetInitDataDefaults(&mDefaults); -} - -LLPartSysCompressedPacket::~LLPartSysCompressedPacket() -{ - // no dynamic data is stored by this class, do nothing. -} - -void LLPartSysCompressedPacket::writeFlagByte(LLPartInitData *in) -{ - mData[0] = mData[1] = mData[2] = '\0'; - - U32 i; - //for(i = 1; i < 18; i++) { - // if(in->k[i] != mDefaults.k[i]) - // { - // mData[0] |= PART_SYS_K_MASK; - // break; - // } - //} - - if(in->killPlaneZ != mDefaults.killPlaneZ || - in->killPlaneNormal[0] != mDefaults.killPlaneNormal[0] || - in->killPlaneNormal[1] != mDefaults.killPlaneNormal[1] || - in->killPlaneNormal[2] != mDefaults.killPlaneNormal[2] || - in->distanceDeath != mDefaults.distanceDeath) - { - mData[0] |= PART_SYS_KILL_P_MASK; - } - - - - if(in->bouncePlaneZ != mDefaults.bouncePlaneZ || - in->bouncePlaneNormal[0] != mDefaults.bouncePlaneNormal[0] || - in->bouncePlaneNormal[1] != mDefaults.bouncePlaneNormal[1] || - in->bouncePlaneNormal[2] != mDefaults.bouncePlaneNormal[2]) - { - mData[0] |= PART_SYS_BOUNCE_P_MASK; - } - - if(in->bounce_b != mDefaults.bounce_b) - { - mData[0] |= PART_SYS_BOUNCE_B_MASK; - } - - - //if(in->pos_ranges[0] != mDefaults.pos_ranges[0] || in->pos_ranges[1] != mDefaults.pos_ranges[1] || - // in->pos_ranges[2] != mDefaults.pos_ranges[2] || in->pos_ranges[3] != mDefaults.pos_ranges[3] || - // in->pos_ranges[4] != mDefaults.pos_ranges[4] || in->pos_ranges[5] != mDefaults.pos_ranges[5]) - //{ - // mData[0] |= PART_SYS_POS_RANGES_MASK; - //} - - //if(in->vel_ranges[0] != mDefaults.vel_ranges[0] || in->vel_ranges[1] != mDefaults.vel_ranges[1] || - // in->vel_ranges[2] != mDefaults.vel_ranges[2] || in->vel_ranges[3] != mDefaults.vel_ranges[3] || - // in->vel_ranges[4] != mDefaults.vel_ranges[4] || in->vel_ranges[5] != mDefaults.vel_ranges[5]) - //{ -// mData[0] |= PART_SYS_VEL_RANGES_MASK; - //} - - - if(in->diffEqAlpha[0] != mDefaults.diffEqAlpha[0] || - in->diffEqAlpha[1] != mDefaults.diffEqAlpha[1] || - in->diffEqAlpha[2] != mDefaults.diffEqAlpha[2] || - in->diffEqScale[0] != mDefaults.diffEqScale[0] || - in->diffEqScale[1] != mDefaults.diffEqScale[1] || - in->diffEqScale[2] != mDefaults.diffEqScale[2]) - { - mData[0] |= PART_SYS_ALPHA_SCALE_DIFF_MASK; - } - - - if(in->scale_range[0] != mDefaults.scale_range[0] || - in->scale_range[1] != mDefaults.scale_range[1] || - in->scale_range[2] != mDefaults.scale_range[2] || - in->scale_range[3] != mDefaults.scale_range[3]) - { - mData[0] |= PART_SYS_SCALE_RANGE_MASK; - } - - - if(in->alpha_range[0] != mDefaults.alpha_range[0] || - in->alpha_range[1] != mDefaults.alpha_range[1] || - in->alpha_range[2] != mDefaults.alpha_range[2] || - in->alpha_range[3] != mDefaults.alpha_range[3]) - { - mData[2] |= PART_SYS_BYTE_3_ALPHA_MASK; - } - - if(in->vel_offset[0] != mDefaults.vel_offset[0] || - in->vel_offset[1] != mDefaults.vel_offset[1] || - in->vel_offset[2] != mDefaults.vel_offset[2]) - { - mData[0] |= PART_SYS_VEL_OFFSET_MASK; - } - - - if(in->mImageUuid != mDefaults.mImageUuid) - { - mData[0] |= PART_SYS_M_IMAGE_UUID_MASK; - } - - for( i = 0; i < 8; i++) - { - if(in->mFlags[i]) - { - mData[1] |= 1<mFlags[i]); - } - } - - - if(in->spawnRange != mDefaults.spawnRange || - in->spawnFrequency != mDefaults.spawnFrequency || - in->spawnFreqencyRange != mDefaults.spawnFreqencyRange || - in->spawnDirection[0] != mDefaults.spawnDirection[0] || - in->spawnDirection[1] != mDefaults.spawnDirection[1] || - in->spawnDirection[2] != mDefaults.spawnDirection[2] || - in->spawnDirectionRange != mDefaults.spawnDirectionRange || - in->spawnVelocity != mDefaults.spawnVelocity || - in->spawnVelocityRange != mDefaults.spawnVelocityRange) - { - mData[3] |= PART_SYS_BYTE_SPAWN_MASK; - } - - - if(in->windWeight != mDefaults.windWeight || - in->currentGravity[0] != mDefaults.currentGravity[0] || - in->currentGravity[1] != mDefaults.currentGravity[1] || - in->currentGravity[2] != mDefaults.currentGravity[2] || - in->gravityWeight != mDefaults.gravityWeight) - { - mData[3] |= PART_SYS_BYTE_ENVIRONMENT_MASK; - } - - - if(in->globalLifetime != mDefaults.globalLifetime || - in->individualLifetime != mDefaults.individualLifetime || - in->individualLifetimeRange != mDefaults.individualLifetimeRange) - { - mData[3] |= PART_SYS_BYTE_LIFESPAN_MASK; - } - - - if(in->speedLimit != mDefaults.speedLimit || - in->alphaDecay != mDefaults.alphaDecay || - in->scaleDecay != mDefaults.scaleDecay || - in->dampMotionFactor != mDefaults.dampMotionFactor) - { - mData[3] |= PART_SYS_BYTE_DECAY_DAMP_MASK; - } - - if(in->windDiffusionFactor[0] != mDefaults.windDiffusionFactor[0] || - in->windDiffusionFactor[1] != mDefaults.windDiffusionFactor[1] || - in->windDiffusionFactor[2] != mDefaults.windDiffusionFactor[2]) - { - mData[3] |= PART_SYS_BYTE_WIND_DIFF_MASK; - } -} - -F32 floatFromTwoBytes(S8 bMant, S8 bExp) -{ - F32 result = bMant; - while(bExp > 0) - { - result *= 2.0f; - bExp--; - } - while(bExp < 0) - { - result *= 0.5f; - bExp++; - } - return result; -} - -void twoBytesFromFloat(F32 fIn, S8 &bMant, S8 &bExp) -{ - bExp = 0; - if(fIn > 127.0f) - { - fIn = 127.0f; - } - if(fIn < -127.0f) - { - fIn = -127.0f; - } - while(fIn < 64 && fIn > -64 && bExp > -127) - { - fIn *= 2.0f; - bExp--; - } - while((fIn > 128 || fIn < -128) && bExp < 127) - { - fIn *= 0.5f; - bExp++; - } - bMant = (S8)fIn; -} - - - -/* -U32 LLPartSysCompressedPacket::writeK(LLPartInitData *in, U32 startByte) -{ - U32 i, kFlag, i_mod_eight; - S8 bMant, bExp; - - kFlag = startByte; - - startByte += 3; // 3 bytes contain enough room for 18 flag bits - mData[kFlag] = 0x00; -// llprintline("In the writeK\n"); - - i_mod_eight = 0; - for(i = 0; i < 18; i++) - { - if(in->k[i] != mDefaults.k[i]) - { - - mData[kFlag] |= 1<k[i], bMant, bExp); - - mData[startByte++] = bMant; - mData[startByte++] = bExp; - } - i_mod_eight++; - while(i_mod_eight >= 8) - { - kFlag++; - i_mod_eight -= 8; - } - } - - return startByte; -}*/ - -U32 LLPartSysCompressedPacket::writeKill_p(LLPartInitData *in, U32 startByte) -{ - S8 bMant, bExp; - - twoBytesFromFloat(in->killPlaneNormal[0], bMant, bExp); - mData[startByte++] = bMant; - mData[startByte++] = bExp; - twoBytesFromFloat(in->killPlaneNormal[1], bMant, bExp); - mData[startByte++] = bMant; - mData[startByte++] = bExp; - twoBytesFromFloat(in->killPlaneNormal[2], bMant, bExp); - mData[startByte++] = bMant; - mData[startByte++] = bExp; - - twoBytesFromFloat(in->killPlaneZ, bMant, bExp); - mData[startByte++] = bMant; - mData[startByte++] = bExp; - twoBytesFromFloat(in->distanceDeath, bMant, bExp); - mData[startByte++] = bMant; - mData[startByte++] = bExp; - - return startByte; -} - -U32 LLPartSysCompressedPacket::writeBounce_p(LLPartInitData *in, U32 startByte) -{ - S8 bMant, bExp; - - twoBytesFromFloat(in->bouncePlaneNormal[0], bMant, bExp); - mData[startByte++] = bMant; - mData[startByte++] = bExp; - twoBytesFromFloat(in->bouncePlaneNormal[1], bMant, bExp); - mData[startByte++] = bMant; - mData[startByte++] = bExp; - twoBytesFromFloat(in->bouncePlaneNormal[2], bMant, bExp); - mData[startByte++] = bMant; - mData[startByte++] = bExp; - - - twoBytesFromFloat(in->bouncePlaneZ, bMant, bExp); - mData[startByte++] = bMant; - mData[startByte++] = bExp; - - return startByte; -} - -U32 LLPartSysCompressedPacket::writeBounce_b(LLPartInitData *in, U32 startByte) -{ - S8 bMant, bExp; - twoBytesFromFloat(in->bounce_b, bMant, bExp); - mData[startByte++] = bMant; - mData[startByte++] = bExp; - return startByte; -} - -//U32 LLPartSysCompressedPacket::writePos_ranges(LLPartInitData *in, U32 startByte) -//{ -// S8 tmp; -// int i; -// for(i = 0; i < 6; i++) -// { -// tmp = (S8) in->pos_ranges[i]; // float to int conversion (keep the sign) -// mData[startByte++] = (U8)tmp; // signed to unsigned typecast -// } -// return startByte; -//} - -//U32 LLPartSysCompressedPacket::writeVel_ranges(LLPartInitData *in, U32 startByte) -//{ -// S8 tmp; -// int i; -// for(i = 0; i < 6; i++) -// { -// tmp = (S8) in->vel_ranges[i]; // float to int conversion (keep the sign) -// mData[startByte++] = (U8)tmp; // signed to unsigned typecast -// } -// return startByte; -//} - -U32 LLPartSysCompressedPacket::writeAlphaScaleDiffEqn_range(LLPartInitData *in, U32 startByte) -{ - S8 bExp, bMant; - int i; - for(i = 0; i < 3; i++) - { - twoBytesFromFloat(in->diffEqAlpha[i], bMant, bExp); - mData[startByte++] = bMant; - mData[startByte++] = bExp; - } - for(i = 0; i < 3; i++) - { - twoBytesFromFloat(in->diffEqScale[i], bMant, bExp); - mData[startByte++] = bMant; - mData[startByte++] = bExp; - } - return startByte; -} - -U32 LLPartSysCompressedPacket::writeScale_range(LLPartInitData *in, U32 startByte) -{ - S8 bExp, bMant; - int i; - for(i = 0; i < 4; i++) - { - twoBytesFromFloat(in->scale_range[i], bMant, bExp); - mData[startByte++] = bMant; - mData[startByte++] = bExp; - } - return startByte; -} - - -U32 LLPartSysCompressedPacket::writeAlpha_range(LLPartInitData *in, U32 startByte) -{ - S8 bExp, bMant; - int i; - for(i = 0; i < 4; i++) - { - twoBytesFromFloat(in->alpha_range[i], bMant, bExp); - mData[startByte++] = bMant; - mData[startByte++] = bExp; - } - return startByte; -} - -U32 LLPartSysCompressedPacket::writeVelocityOffset(LLPartInitData *in, U32 startByte) -{ - S8 bExp, bMant; - int i; - for(i = 0; i < 3; i++) - { - twoBytesFromFloat(in->vel_offset[i], bMant, bExp); - mData[startByte++] = bMant; - mData[startByte++] = bExp; - } - return startByte; -} - -U32 LLPartSysCompressedPacket::writeUUID(LLPartInitData *in, U32 startByte) -{ - U8 * bufPtr = mData + startByte; - if(in->mImageUuid == IMG_SHOT) { - mData[startByte++] = 0x01; - return startByte; - } - - if(in->mImageUuid == IMG_SPARK) { - mData[startByte++] = 0x02; - return startByte; - } - - - if(in->mImageUuid == IMG_BIG_EXPLOSION_1) { - mData[startByte++] = 0x03; - return startByte; - } - - if(in->mImageUuid == IMG_BIG_EXPLOSION_2) { - mData[startByte++] = 0x04; - return startByte; - } - - - if(in->mImageUuid == IMG_SMOKE_POOF) { - mData[startByte++] = 0x05; - return startByte; - } - - if(in->mImageUuid == IMG_FIRE) { - mData[startByte++] = 0x06; - return startByte; - } - - - if(in->mImageUuid == IMG_EXPLOSION) { - mData[startByte++] = 0x07; - return startByte; - } - - if(in->mImageUuid == IMG_EXPLOSION_2) { - mData[startByte++] = 0x08; - return startByte; - } - - - if(in->mImageUuid == IMG_EXPLOSION_3) { - mData[startByte++] = 0x09; - return startByte; - } - - if(in->mImageUuid == IMG_EXPLOSION_4) { - mData[startByte++] = 0x0A; - return startByte; - } - - mData[startByte++] = 0x00; // flag for "read whole UUID" - - memcpy(bufPtr, in->mImageUuid.mData, 16); /* Flawfinder: ignore */ - return (startByte+16); -} - -U32 LLPartSysCompressedPacket::writeSpawn(LLPartInitData *in, U32 startByte) -{ - S8 bExp, bMant; - int i; - - twoBytesFromFloat(in->spawnRange, bMant, bExp); - mData[startByte++] = bMant; - mData[startByte++] = bExp; - twoBytesFromFloat(in->spawnFrequency, bMant, bExp); - mData[startByte++] = bMant; - mData[startByte++] = bExp; - twoBytesFromFloat(in->spawnFreqencyRange, bMant, bExp); - mData[startByte++] = bMant; - mData[startByte++] = bExp; - - - - for(i = 0; i < 3; i++) - { - twoBytesFromFloat(in->spawnDirection[i], bMant, bExp); - mData[startByte++] = bMant; - mData[startByte++] = bExp; - } - - twoBytesFromFloat(in->spawnDirectionRange, bMant, bExp); - mData[startByte++] = bMant; - mData[startByte++] = bExp; - twoBytesFromFloat(in->spawnVelocity, bMant, bExp); - mData[startByte++] = bMant; - mData[startByte++] = bExp; - twoBytesFromFloat(in->spawnVelocityRange, bMant, bExp); - mData[startByte++] = bMant; - mData[startByte++] = bExp; - - return startByte; -} - -U32 LLPartSysCompressedPacket::writeEnvironment(LLPartInitData *in, U32 startByte) -{ - S8 bExp, bMant; - int i; - - twoBytesFromFloat(in->windWeight, bMant, bExp); - mData[startByte++] = bMant; - mData[startByte++] = bExp; - - for(i = 0; i < 3; i++) - { - twoBytesFromFloat(in->currentGravity[i], bMant, bExp); - mData[startByte++] = bMant; - mData[startByte++] = bExp; - } - - twoBytesFromFloat(in->gravityWeight, bMant, bExp); - mData[startByte++] = bMant; - mData[startByte++] = bExp; - return startByte; -} - -U32 LLPartSysCompressedPacket::writeLifespan(LLPartInitData *in, U32 startByte) -{ - S8 bExp, bMant; - - twoBytesFromFloat(in->globalLifetime, bMant, bExp); - mData[startByte++] = bMant; - mData[startByte++] = bExp; - - twoBytesFromFloat(in->individualLifetime, bMant, bExp); - mData[startByte++] = bMant; - mData[startByte++] = bExp; - - twoBytesFromFloat(in->individualLifetimeRange, bMant, bExp); - mData[startByte++] = bMant; - mData[startByte++] = bExp; - - return startByte; -} - - -U32 LLPartSysCompressedPacket::writeDecayDamp(LLPartInitData *in, U32 startByte) -{ - S8 bExp, bMant; - - twoBytesFromFloat(in->speedLimit, bMant, bExp); - mData[startByte++] = bMant; - mData[startByte++] = bExp; - - twoBytesFromFloat(in->alphaDecay, bMant, bExp); - mData[startByte++] = bMant; - mData[startByte++] = bExp; - - twoBytesFromFloat(in->scaleDecay, bMant, bExp); - mData[startByte++] = bMant; - mData[startByte++] = bExp; - - twoBytesFromFloat(in->dampMotionFactor, bMant, bExp); - mData[startByte++] = bMant; - mData[startByte++] = bExp; - - return startByte; -} - -U32 LLPartSysCompressedPacket::writeWindDiffusionFactor(LLPartInitData *in, U32 startByte) -{ - S8 bExp, bMant; - - twoBytesFromFloat(in->windDiffusionFactor[0], bMant, bExp); - mData[startByte++] = bMant; - mData[startByte++] = bExp; - - twoBytesFromFloat(in->windDiffusionFactor[1], bMant, bExp); - mData[startByte++] = bMant; - mData[startByte++] = bExp; - - twoBytesFromFloat(in->windDiffusionFactor[2], bMant, bExp); - mData[startByte++] = bMant; - mData[startByte++] = bExp; - - return startByte; -} - - - - - - -/* -U32 LLPartSysCompressedPacket::readK(LLPartInitData *in, U32 startByte) -{ - U32 i, i_mod_eight, kFlag; - S8 bMant, bExp; // 1 bytes mantissa and exponent for a float - kFlag = startByte; - startByte += 3; // 3 bytes has enough room for 18 bits - - i_mod_eight = 0; - for(i = 0; i < 18; i++) - { - if(mData[kFlag]&(1<k[i] = floatFromTwoBytes(bMant, bExp); // much tighter platform-independent - // way to ship floats - - } - i_mod_eight++; - if(i_mod_eight >= 8) - { - i_mod_eight -= 8; - kFlag++; - } - } - - return startByte; -} -*/ - -U32 LLPartSysCompressedPacket::readKill_p(LLPartInitData *in, U32 startByte) -{ - S8 bMant, bExp; - - bMant = mData[startByte++]; - bExp = mData[startByte++]; - in->killPlaneNormal[0] = floatFromTwoBytes(bMant, bExp); - bMant = mData[startByte++]; - bExp = mData[startByte++]; - in->killPlaneNormal[1] = floatFromTwoBytes(bMant, bExp); - bMant = mData[startByte++]; - bExp = mData[startByte++]; - in->killPlaneNormal[2] = floatFromTwoBytes(bMant, bExp); - - bMant = mData[startByte++]; - bExp = mData[startByte++]; - in->killPlaneZ = floatFromTwoBytes(bMant, bExp); - bMant = mData[startByte++]; - bExp = mData[startByte++]; - in->distanceDeath = floatFromTwoBytes(bMant, bExp); - - return startByte; -} - -U32 LLPartSysCompressedPacket::readBounce_p(LLPartInitData *in, U32 startByte) -{ - - S8 bMant, bExp; - - bMant = mData[startByte++]; - bExp = mData[startByte++]; - in->bouncePlaneNormal[0] = floatFromTwoBytes(bMant, bExp); - bMant = mData[startByte++]; - bExp = mData[startByte++]; - in->bouncePlaneNormal[1] = floatFromTwoBytes(bMant, bExp); - bMant = mData[startByte++]; - bExp = mData[startByte++]; - in->bouncePlaneNormal[2] = floatFromTwoBytes(bMant, bExp); - - bMant = mData[startByte++]; - bExp = mData[startByte++]; - in->bouncePlaneZ = floatFromTwoBytes(bMant, bExp); - - return startByte; -} - -U32 LLPartSysCompressedPacket::readBounce_b(LLPartInitData *in, U32 startByte) -{ - S8 bMant, bExp; - bMant = mData[startByte++]; - bExp = mData[startByte++]; - in->bounce_b = floatFromTwoBytes(bMant, bExp); - return startByte; -} - - -//U32 LLPartSysCompressedPacket::readPos_ranges(LLPartInitData *in, U32 startByte) -//{ -// S8 tmp; -// int i; -// for(i = 0; i < 6; i++) -// { -// tmp = (S8)mData[startByte++]; -// in->pos_ranges[i] = tmp; -// } -// return startByte; -//} - -//U32 LLPartSysCompressedPacket::readVel_ranges(LLPartInitData *in, U32 startByte) -//{ -// S8 tmp; -// int i; -// for(i = 0; i < 6; i++) -// { -// tmp = (S8)mData[startByte++]; -// in->vel_ranges[i] = tmp; -// } -// return startByte; -//} - - - -U32 LLPartSysCompressedPacket::readAlphaScaleDiffEqn_range(LLPartInitData *in, U32 startByte) -{ - int i; - S8 bMant, bExp; - for(i = 0; i < 3; i++) - { - bMant = mData[startByte++]; - bExp = mData[startByte++]; - in->diffEqAlpha[i] = floatFromTwoBytes(bMant, bExp); - } - for(i = 0; i < 3; i++) - { - bMant = mData[startByte++]; - bExp = mData[startByte++]; - in->diffEqScale[i] = floatFromTwoBytes(bMant, bExp); - } - return startByte; -} - -U32 LLPartSysCompressedPacket::readAlpha_range(LLPartInitData *in, U32 startByte) -{ - int i; - S8 bMant, bExp; - for(i = 0; i < 4; i++) - { - bMant = mData[startByte++]; - bExp = mData[startByte++]; - in->alpha_range[i] = floatFromTwoBytes(bMant, bExp); - } - return startByte; -} - -U32 LLPartSysCompressedPacket::readScale_range(LLPartInitData *in, U32 startByte) -{ - int i; - S8 bMant, bExp; - for(i = 0; i < 4; i++) - { - bMant = mData[startByte++]; - bExp = mData[startByte++]; - in->scale_range[i] = floatFromTwoBytes(bMant, bExp); - } - return startByte; -} - -U32 LLPartSysCompressedPacket::readVelocityOffset(LLPartInitData *in, U32 startByte) -{ - int i; - S8 bMant, bExp; - for(i = 0; i < 3; i++) - { - bMant = mData[startByte++]; - bExp = mData[startByte++]; - in->vel_offset[i] = floatFromTwoBytes(bMant, bExp); - } - return startByte; -} - -U32 LLPartSysCompressedPacket::readUUID(LLPartInitData *in, U32 startByte) -{ - U8 * bufPtr = mData + startByte; - - if(mData[startByte] == 0x01) - { - in->mImageUuid = IMG_SHOT; - return startByte+1; - } - if(mData[startByte] == 0x02) - { - in->mImageUuid = IMG_SPARK; - return startByte+1; - } - if(mData[startByte] == 0x03) - { - in->mImageUuid = IMG_BIG_EXPLOSION_1; - return startByte+1; - } - if(mData[startByte] == 0x04) - { - in->mImageUuid = IMG_BIG_EXPLOSION_2; - return startByte+1; - } - if(mData[startByte] == 0x05) - { - in->mImageUuid = IMG_SMOKE_POOF; - return startByte+1; - } - if(mData[startByte] == 0x06) - { - in->mImageUuid = IMG_FIRE; - return startByte+1; - } - if(mData[startByte] == 0x07) - { - in->mImageUuid = IMG_EXPLOSION; - return startByte+1; - } - if(mData[startByte] == 0x08) - { - in->mImageUuid = IMG_EXPLOSION_2; - return startByte+1; - } - if(mData[startByte] == 0x09) - { - in->mImageUuid = IMG_EXPLOSION_3; - return startByte+1; - } - if(mData[startByte] == 0x0A) - { - in->mImageUuid = IMG_EXPLOSION_4; - return startByte+1; - } - - startByte++; // cause we actually have to read the UUID now. - memcpy(in->mImageUuid.mData, bufPtr, 16); /* Flawfinder: ignore */ - return (startByte+16); -} - - - - -U32 LLPartSysCompressedPacket::readSpawn(LLPartInitData *in, U32 startByte) -{ - S8 bMant, bExp; - U32 i; - - bMant = mData[startByte++]; - bExp = mData[startByte++]; - in->spawnRange = floatFromTwoBytes(bMant, bExp); - bMant = mData[startByte++]; - bExp = mData[startByte++]; - in->spawnFrequency = floatFromTwoBytes(bMant, bExp); - bMant = mData[startByte++]; - bExp = mData[startByte++]; - in->spawnFreqencyRange = floatFromTwoBytes(bMant, bExp); - - for(i = 0; i < 3; i++) - { - bMant = mData[startByte++]; - bExp = mData[startByte++]; - in->spawnDirection[i] = floatFromTwoBytes(bMant, bExp); - } - - bMant = mData[startByte++]; - bExp = mData[startByte++]; - in->spawnDirectionRange = floatFromTwoBytes(bMant, bExp); - bMant = mData[startByte++]; - bExp = mData[startByte++]; - in->spawnVelocity = floatFromTwoBytes(bMant, bExp); - bMant = mData[startByte++]; - bExp = mData[startByte++]; - in->spawnVelocityRange = floatFromTwoBytes(bMant, bExp); - - return startByte; -} - -U32 LLPartSysCompressedPacket::readEnvironment(LLPartInitData *in, U32 startByte) -{ - S8 bMant, bExp; - U32 i; - - - bMant = mData[startByte++]; - bExp = mData[startByte++]; - in->windWeight = floatFromTwoBytes(bMant, bExp); - - for(i = 0; i < 3; i++) - { - bMant = mData[startByte++]; - bExp = mData[startByte++]; - in->currentGravity[i] = floatFromTwoBytes(bMant, bExp); - } - - bMant = mData[startByte++]; - bExp = mData[startByte++]; - in->gravityWeight = floatFromTwoBytes(bMant, bExp); - - return startByte; -} - -U32 LLPartSysCompressedPacket::readLifespan(LLPartInitData *in, U32 startByte) -{ - S8 bMant, bExp; - - bMant = mData[startByte++]; - bExp = mData[startByte++]; - in->globalLifetime = floatFromTwoBytes(bMant, bExp); - bMant = mData[startByte++]; - bExp = mData[startByte++]; - in->individualLifetime = floatFromTwoBytes(bMant, bExp); - bMant = mData[startByte++]; - bExp = mData[startByte++]; - in->individualLifetimeRange = floatFromTwoBytes(bMant, bExp); - - return startByte; -} - -U32 LLPartSysCompressedPacket::readDecayDamp(LLPartInitData *in, U32 startByte) -{ - S8 bMant, bExp; - - bMant = mData[startByte++]; - bExp = mData[startByte++]; - in->speedLimit = floatFromTwoBytes(bMant, bExp); - bMant = mData[startByte++]; - bExp = mData[startByte++]; - in->alphaDecay = floatFromTwoBytes(bMant, bExp); - bMant = mData[startByte++]; - bExp = mData[startByte++]; - in->scaleDecay = floatFromTwoBytes(bMant, bExp); - bMant = mData[startByte++]; - bExp = mData[startByte++]; - in->dampMotionFactor = floatFromTwoBytes(bMant, bExp); - - return startByte; -} - -U32 LLPartSysCompressedPacket::readWindDiffusionFactor(LLPartInitData *in, U32 startByte) -{ - int i; - S8 bMant, bExp; - for(i = 0; i < 3; i++) - { - bMant = mData[startByte++]; - bExp = mData[startByte++]; - in->windDiffusionFactor[i] = floatFromTwoBytes(bMant, bExp); - } - return startByte; -} - -bool LLPartSysCompressedPacket::fromLLPartInitData(LLPartInitData *in, U32 &bytesUsed) -{ - - writeFlagByte(in); - U32 currByte = 4; - -// llprintline("calling \"fromLLPartInitData\"\n"); - - //if(mData[0] & PART_SYS_K_MASK) - //{ - // currByte = writeK(in, 3); // first 3 bytes are reserved for header data - //} - - - - if(mData[0] & PART_SYS_KILL_P_MASK) - { - currByte = writeKill_p(in, currByte); - } - - if(mData[0] & PART_SYS_BOUNCE_P_MASK) - { - currByte = writeBounce_p(in, currByte); - } - - if(mData[0] & PART_SYS_BOUNCE_B_MASK) - { - currByte = writeBounce_b(in, currByte); - } - - //if(mData[0] & PART_SYS_POS_RANGES_MASK) - //{ - // currByte = writePos_ranges(in, currByte); - //} - - //if(mData[0] & PART_SYS_VEL_RANGES_MASK) - //{ - // currByte = writeVel_ranges(in, currByte); - //} - - if(mData[0] & PART_SYS_ALPHA_SCALE_DIFF_MASK) - { - currByte = writeAlphaScaleDiffEqn_range(in, currByte); - } - - if(mData[0] & PART_SYS_SCALE_RANGE_MASK) - { - currByte = writeScale_range(in, currByte); - } - - if(mData[0] & PART_SYS_VEL_OFFSET_MASK) - { - currByte = writeVelocityOffset(in, currByte); - } - - if(mData[0] & PART_SYS_M_IMAGE_UUID_MASK) - { - currByte = writeUUID(in, currByte); - } - - - if(mData[3] & PART_SYS_BYTE_SPAWN_MASK) - { - currByte = writeSpawn(in, currByte); - } - - if(mData[3] & PART_SYS_BYTE_ENVIRONMENT_MASK) - { - currByte = writeEnvironment(in, currByte); - } - - if(mData[3] & PART_SYS_BYTE_LIFESPAN_MASK) - { - currByte = writeLifespan(in, currByte); - } - - if(mData[3] & PART_SYS_BYTE_DECAY_DAMP_MASK) - { - currByte = writeDecayDamp(in, currByte); - } - - if(mData[3] & PART_SYS_BYTE_WIND_DIFF_MASK) - { - currByte = writeWindDiffusionFactor(in, currByte); - } - - - if(mData[2] & PART_SYS_BYTE_3_ALPHA_MASK) - { - currByte = writeAlpha_range(in, currByte); - } - - mData[currByte++] = (U8)in->maxParticles; - mData[currByte++] = (U8)in->initialParticles; - - - U32 flagFlag = 1; // flag indicating which flag bytes are non-zero - // yeah, I know, the name sounds funny - for(U32 i = 0; i < 8; i++) - { - -// llprintline("Flag \"%x\" gets byte \"%x\"\n", flagFlag, in->mFlags[i]); - if(mData[1] & flagFlag) - { - mData[currByte++] = in->mFlags[i]; -// llprintline("and is valid...\n"); - } - flagFlag <<= 1; - } - - bytesUsed = mNumBytes = currByte; - - - -// llprintline("returning from \"fromLLPartInitData\" with %d bytes\n", bytesUsed); - - return true; -} - -bool LLPartSysCompressedPacket::toLLPartInitData(LLPartInitData *out, U32 *bytesUsed) -{ - U32 currByte = 4; - - gSetInitDataDefaults(out); - - if(mData[0] & PART_SYS_KILL_P_MASK) - { - currByte = readKill_p(out, currByte); - } - - if(mData[0] & PART_SYS_BOUNCE_P_MASK) - { - currByte = readBounce_p(out, currByte); - } - - if(mData[0] & PART_SYS_BOUNCE_B_MASK) - { - currByte = readBounce_b(out, currByte); - } - - if(mData[0] & PART_SYS_ALPHA_SCALE_DIFF_MASK) - { - currByte = readAlphaScaleDiffEqn_range(out, currByte); - } - - if(mData[0] & PART_SYS_SCALE_RANGE_MASK) - { - currByte = readScale_range(out, currByte); - } - - if(mData[0] & PART_SYS_VEL_OFFSET_MASK) - { - currByte = readVelocityOffset(out, currByte); - } - - if(mData[0] & PART_SYS_M_IMAGE_UUID_MASK) - { - currByte = readUUID(out, currByte); - } - - - if(mData[3] & PART_SYS_BYTE_SPAWN_MASK) - { - currByte = readSpawn(out, currByte); - } - - if(mData[3] & PART_SYS_BYTE_ENVIRONMENT_MASK) - { - currByte = readEnvironment(out, currByte); - } - - if(mData[3] & PART_SYS_BYTE_LIFESPAN_MASK) - { - currByte = readLifespan(out, currByte); - } - - if(mData[3] & PART_SYS_BYTE_DECAY_DAMP_MASK) - { - currByte = readDecayDamp(out, currByte); - } - - if(mData[3] & PART_SYS_BYTE_WIND_DIFF_MASK) - { - currByte = readWindDiffusionFactor(out, currByte); - } - - if(mData[2] & PART_SYS_BYTE_3_ALPHA_MASK) - { - currByte = readAlpha_range(out, currByte); - } - - out->maxParticles = mData[currByte++]; - out->initialParticles = mData[currByte++]; - - U32 flagFlag = 1; // flag indicating which flag bytes are non-zero - // yeah, I know, the name sounds funny - for(U32 i = 0; i < 8; i++) - { - flagFlag = 1<mFlags[i] = mData[currByte++]; - } - } - - *bytesUsed = currByte; - return true; -} - -bool LLPartSysCompressedPacket::fromUnsignedBytes(U8 *in, U32 bytesUsed) -{ - if ((in != NULL) && (bytesUsed <= sizeof(mData))) - { - memcpy(mData, in, bytesUsed); /* Flawfinder: ignore */ - mNumBytes = bytesUsed; - return true; - } - else - { - LL_ERRS() << "NULL input data or number of bytes exceed mData size" << LL_ENDL; - return false; - } -} - - -U32 LLPartSysCompressedPacket::bufferSize() -{ - return mNumBytes; -} - -bool LLPartSysCompressedPacket::toUnsignedBytes(U8 *out) -{ - memcpy(out, mData, mNumBytes); /* Flawfinder: ignore */ - return true; -} - -U8 * LLPartSysCompressedPacket::getBytePtr() -{ - return mData; -} - - diff --git a/indra/llmessage/partsyspacket.h b/indra/llmessage/partsyspacket.h deleted file mode 100644 index 23307f3409..0000000000 --- a/indra/llmessage/partsyspacket.h +++ /dev/null @@ -1,261 +0,0 @@ -/** - * @file partsyspacket.h - * @brief Object for packing particle system initialization parameters - * before sending them over the network - * - * $LicenseInfo:firstyear=2000&license=viewerlgpl$ - * Second Life Viewer Source Code - * Copyright (C) 2010, Linden Research, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; - * version 2.1 of the License only. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA - * $/LicenseInfo$ - */ - -#ifndef LL_PARTSYSPACKET_H -#define LL_PARTSYSPACKET_H - -#include "lluuid.h" - -// Particle system stuff - -const U64 PART_SYS_MAX_TIME_IN_USEC = 1000000; // 1 second, die not quite near instantaneously - - -// this struct is for particle system initialization parameters -// I'm breaking some rules here, but I need a storage structure to hold initialization data -// for these things. Sorry guys, they're not simple enough (yet) to avoid this cleanly -struct LLPartInitData { - // please do not add functions to this class -- data only! - //F32 k[18]; // first 9 --> x,y,z last 9 --> scale, alpha, rot - //F32 kill_p[6]; // last one is for particles that die when they reach a spherical bounding radius - //F32 kill_plane[3]; - //F32 bounce_p[5]; - F32 bounce_b; // recently changed - // no need to store orientation and position here, as they're sent over seperately - //F32 pos_ranges[6]; - //F32 vel_ranges[6]; - F32 scale_range[4]; - F32 alpha_range[4]; - F32 vel_offset[3]; //new - more understandable! - - F32 mDistBeginFadeout; // for fadeout LOD optimization - F32 mDistEndFadeout; - - LLUUID mImageUuid; - //U8 n; // number of particles - U8 mFlags[8]; // for miscellaneous data --> its interpretation can change at my whim! - U8 createMe; // do I need to be created? or has the work allready been done? - //ActionFlag is now mFlags[PART_SYS_ACTION_BYTE] - //Spawn point is initially object creation center - - F32 diffEqAlpha[3]; - F32 diffEqScale[3]; - - U8 maxParticles; - //How many particles exist at any time within the system? - U8 initialParticles; - //How many particles exist when the system is created? - F32 killPlaneZ; - //For simplicity assume the XY plane, so this sets an altitude at which to die - F32 killPlaneNormal[3]; - //Normal if not planar XY - F32 bouncePlaneZ; - //For simplicity assume the XY plane, so this sets an altitude at which to bounce - F32 bouncePlaneNormal[3]; - //Normal if not planar XY - F32 spawnRange; - //Range of emission points about the mSpawnPoint - F32 spawnFrequency; - //Required if the system is to spawn new particles. - //This variable determines the time after a particle dies when it is respawned. - F32 spawnFreqencyRange; - //Determines the random range of time until a new particle is spawned. - F32 spawnDirection[3]; - //Direction vector giving the mean direction in which particles are spawned - F32 spawnDirectionRange; - //Direction limiting the angular range of emissions about the mean direction. 1.0f means everywhere, 0.0f means uni-directional - F32 spawnVelocity; - //The mean speed at which particles are emitted - F32 spawnVelocityRange; - //The range of speeds about the mean at which particles are emitted. - F32 speedLimit; - //Used to constrain particle maximum velocity - F32 windWeight; - //How much of an effect does wind have - F32 currentGravity[3]; - //Gravity direction used in update calculations - F32 gravityWeight; - //How much of an effect does gravity have - F32 globalLifetime; - //If particles re-spawn, a system can exist forever. - //If (ActionFlags & PART_SYS_GLOBAL_DIE) is true this variable is used to determine how long the system lasts. - F32 individualLifetime; - //How long does each particle last if nothing else happens to it - F32 individualLifetimeRange; - //Range of variation in individual lifetimes - F32 alphaDecay; - //By what factor does alpha decrease as the lifetime of a particle is approached. - F32 scaleDecay; - //By what factor does scale decrease as the lifetime of a particle is approached. - F32 distanceDeath; - //With the increased functionality, particle systems can expand to indefinite size - //(e.g. wind can chaotically move particles into a wide spread). - //To avoid particles exceeding normal object size constraints, - //set the PART_SYS_DISTANCE_DEATH flag, and set a distance value here, representing a radius around the spawn point. - F32 dampMotionFactor; - //How much to damp motion - F32 windDiffusionFactor[3]; - //Change the size and alpha of particles as wind speed increases (scale gets bigger, alpha smaller) -}; - -// constants for setting flag values -// BYTES are in range 0-8, bits are in range 2^0 - 2^8 and can only be powers of two -const int PART_SYS_NO_Z_BUFFER_BYTE = 0; // option to turn off z-buffer when rendering -const int PART_SYS_NO_Z_BUFFER_BIT = 2; // particle systems -- -// I advise against using this, as it looks bad in every case I've tried - -const int PART_SYS_SLOW_ANIM_BYTE = 0; // slow animation down by a factor of 10 -const int PART_SYS_SLOW_ANIM_BIT = 1; // useful for tweaking anims during debugging - -const int PART_SYS_FOLLOW_VEL_BYTE = 0; // indicates whether to orient sprites towards -const int PART_SYS_FOLLOW_VEL_BIT = 4; // their velocity vector -- default is false - -const int PART_SYS_IS_LIGHT_BYTE = 0; // indicates whether a particular particle system -const int PART_SYS_IS_LIGHT_BIT = 8; // is also a light object -- for andrew -// should deprecate this once there is a general method for setting light properties of objects - -const int PART_SYS_SPAWN_COPY_BYTE = 0; // indicates whether to spawn baby particle systems on -const int PART_SYS_SPAWN_COPY_BIT = 0x10; // particle death -- intended for smoke trails - -const int PART_SYS_COPY_VEL_BYTE = 0; // indicates whether baby particle systems inherit parents vel -const int PART_SYS_COPY_VEL_BIT = 0x20; // (by default they don't) - -const int PART_SYS_INVISIBLE_BYTE = 0; // optional -- turn off display, just simulate -const int PART_SYS_INVISIBLE_BIT = 0x40; // useful for smoke trails - -const int PART_SYS_ADAPT_TO_FRAMERATE_BYTE = 0; // drop sprites from render call proportionally -const int PART_SYS_ADAPT_TO_FRAMERATE_BIT = 0x80; // to how far we are below 60 fps - - -// 26 September 2001 - not even big enough to hold all changes, so should enlarge anyway -//const U16 MAX_PART_SYS_PACKET_SIZE = 180; -const U16 MAX_PART_SYS_PACKET_SIZE = 256; - -//const U8 PART_SYS_K_MASK = 0x01; -const U8 PART_SYS_KILL_P_MASK = 0x02; -const U8 PART_SYS_BOUNCE_P_MASK = 0x04; -const U8 PART_SYS_BOUNCE_B_MASK = 0x08; -//const U8 PART_SYS_POS_RANGES_MASK = 0x10; -//const U8 PART_SYS_VEL_RANGES_MASK = 0x20; -const U8 PART_SYS_VEL_OFFSET_MASK = 0x10; //re-use one of the original slots now commented out -const U8 PART_SYS_ALPHA_SCALE_DIFF_MASK = 0x20; //re-use one of the original slots now commented out -const U8 PART_SYS_SCALE_RANGE_MASK = 0x40; -const U8 PART_SYS_M_IMAGE_UUID_MASK = 0x80; -const U8 PART_SYS_BYTE_3_ALPHA_MASK = 0x01; // wrapped around, didn't we? - -const U8 PART_SYS_BYTE_SPAWN_MASK = 0x01; -const U8 PART_SYS_BYTE_ENVIRONMENT_MASK = 0x02; -const U8 PART_SYS_BYTE_LIFESPAN_MASK = 0x04; -const U8 PART_SYS_BYTE_DECAY_DAMP_MASK = 0x08; -const U8 PART_SYS_BYTE_WIND_DIFF_MASK = 0x10; - - -// 26 September 2001 - new constants for mActionFlags -const int PART_SYS_ACTION_BYTE = 1; -const U8 PART_SYS_SPAWN = 0x01; -const U8 PART_SYS_BOUNCE = 0x02; -const U8 PART_SYS_AFFECTED_BY_WIND = 0x04; -const U8 PART_SYS_AFFECTED_BY_GRAVITY = 0x08; -const U8 PART_SYS_EVALUATE_WIND_PER_PARTICLE = 0x10; -const U8 PART_SYS_DAMP_MOTION = 0x20; -const U8 PART_SYS_WIND_DIFFUSION = 0x40; - -// 26 September 2001 - new constants for mKillFlags -const int PART_SYS_KILL_BYTE = 2; -const U8 PART_SYS_KILL_PLANE = 0x01; -const U8 PART_SYS_GLOBAL_DIE = 0x02; -const U8 PART_SYS_DISTANCE_DEATH = 0x04; -const U8 PART_SYS_TIME_DEATH = 0x08; - - -// global, because the sim-side also calls it in the LLPartInitDataFactory - - -void gSetInitDataDefaults(LLPartInitData *setMe); - -class LLPartSysCompressedPacket -{ -public: - LLPartSysCompressedPacket(); - ~LLPartSysCompressedPacket(); - bool fromLLPartInitData(LLPartInitData *in, U32 &bytesUsed); - bool toLLPartInitData(LLPartInitData *out, U32 *bytesUsed); - bool fromUnsignedBytes(U8 *in, U32 bytesUsed); - bool toUnsignedBytes(U8 *out); - U32 bufferSize(); - U8 *getBytePtr(); - -protected: - U8 mData[MAX_PART_SYS_PACKET_SIZE]; - U32 mNumBytes; - LLPartInitData mDefaults; // this is intended to hold default LLPartInitData values - // please do not modify it - LLPartInitData mWorkingCopy; // uncompressed data I'm working with - -protected: - // private functions (used only to break up code) - void writeFlagByte(LLPartInitData *in); - //U32 writeK(LLPartInitData *in, U32 startByte); - U32 writeKill_p(LLPartInitData *in, U32 startByte); - U32 writeBounce_p(LLPartInitData *in, U32 startByte); - U32 writeBounce_b(LLPartInitData *in, U32 startByte); - //U32 writePos_ranges(LLPartInitData *in, U32 startByte); - //U32 writeVel_ranges(LLPartInitData *in, U32 startByte); - U32 writeAlphaScaleDiffEqn_range(LLPartInitData *in, U32 startByte); - U32 writeScale_range(LLPartInitData *in, U32 startByte); - U32 writeAlpha_range(LLPartInitData *in, U32 startByte); - U32 writeUUID(LLPartInitData *in, U32 startByte); - - U32 writeVelocityOffset(LLPartInitData *in, U32 startByte); - U32 writeSpawn(LLPartInitData *in, U32 startByte); //all spawn data - U32 writeEnvironment(LLPartInitData *in, U32 startByte); //wind and gravity - U32 writeLifespan(LLPartInitData *in, U32 startByte); //lifespan data - individual and global - U32 writeDecayDamp(LLPartInitData *in, U32 startByte); //alpha and scale, and motion damp - U32 writeWindDiffusionFactor(LLPartInitData *in, U32 startByte); - - - //U32 readK(LLPartInitData *in, U32 startByte); - U32 readKill_p(LLPartInitData *in, U32 startByte); - U32 readBounce_p(LLPartInitData *in, U32 startByte); - U32 readBounce_b(LLPartInitData *in, U32 startByte); - //U32 readPos_ranges(LLPartInitData *in, U32 startByte); - //U32 readVel_ranges(LLPartInitData *in, U32 startByte); - U32 readAlphaScaleDiffEqn_range(LLPartInitData *in, U32 startByte); - U32 readScale_range(LLPartInitData *in, U32 startByte); - U32 readAlpha_range(LLPartInitData *in, U32 startByte); - U32 readUUID(LLPartInitData *in, U32 startByte); - - U32 readVelocityOffset(LLPartInitData *in, U32 startByte); - U32 readSpawn(LLPartInitData *in, U32 startByte); //all spawn data - U32 readEnvironment(LLPartInitData *in, U32 startByte); //wind and gravity - U32 readLifespan(LLPartInitData *in, U32 startByte); //lifespan data - individual and global - U32 readDecayDamp(LLPartInitData *in, U32 startByte); //alpha and scale, and motion damp - U32 readWindDiffusionFactor(LLPartInitData *in, U32 startByte); -}; - -#endif - -- cgit v1.3 From 9440f969033b73e2e2a037c291bcb45619b1dfd1 Mon Sep 17 00:00:00 2001 From: Andrey Kleshchev <117672381+akleshchev@users.noreply.github.com> Date: Thu, 11 Dec 2025 01:43:58 +0200 Subject: Reapply "Add more functionality to LLFile and cleanup LLAPRFile"" # Conflicts: # indra/llcrashlogger/llcrashlock.cpp # indra/llrender/llshadermgr.cpp # indra/test/CMakeLists.txt --- .../llappearanceutility/llappappearanceutility.cpp | 2 + indra/llaudio/llaudiodecodemgr.cpp | 2 +- indra/llcommon/CMakeLists.txt | 1 + indra/llcommon/llapp.cpp | 4 +- indra/llcommon/llapr.cpp | 220 ---- indra/llcommon/llapr.h | 17 - indra/llcommon/llerror.cpp | 10 +- indra/llcommon/llfile.cpp | 1155 +++++++++++++++----- indra/llcommon/llfile.h | 488 ++++++--- indra/llcommon/tests/llfile_test.cpp | 253 +++++ indra/llfilesystem/lldir.cpp | 56 +- indra/llfilesystem/lldir_win32.cpp | 13 +- indra/llfilesystem/llfilesystem.cpp | 29 +- indra/llfilesystem/llfilesystem.h | 4 +- indra/llfilesystem/tests/lldir_test.cpp | 4 +- indra/llmessage/llassetstorage.cpp | 2 +- indra/llmessage/tests/llmessageconfig_test.cpp | 2 +- indra/llmessage/tests/message_test.cpp | 2 +- indra/llrender/llshadermgr.cpp | 20 +- indra/llxml/tests/llcontrol_test.cpp | 2 +- indra/newview/llappviewer.cpp | 28 +- indra/newview/llfloaterpreference.cpp | 12 +- indra/newview/llfloateruipreview.cpp | 37 +- indra/newview/llpreviewnotecard.cpp | 3 +- indra/newview/llpreviewscript.cpp | 3 +- indra/newview/lltexturecache.cpp | 87 +- indra/newview/llviewerassetstorage.cpp | 2 +- indra/newview/llviewerassetupload.cpp | 39 +- indra/newview/llviewerdisplay.cpp | 5 +- indra/newview/llviewermedia.cpp | 5 +- indra/newview/llvocache.cpp | 6 +- indra/newview/llvoicevivox.cpp | 3 +- 32 files changed, 1624 insertions(+), 892 deletions(-) mode change 100644 => 100755 indra/llcommon/llerror.cpp mode change 100644 => 100755 indra/llcommon/llfile.cpp mode change 100644 => 100755 indra/llcommon/llfile.h create mode 100644 indra/llcommon/tests/llfile_test.cpp mode change 100644 => 100755 indra/llfilesystem/lldir.cpp mode change 100644 => 100755 indra/llfilesystem/lldir_win32.cpp mode change 100644 => 100755 indra/llfilesystem/llfilesystem.cpp mode change 100644 => 100755 indra/llfilesystem/tests/lldir_test.cpp mode change 100644 => 100755 indra/llmessage/tests/llmessageconfig_test.cpp mode change 100644 => 100755 indra/llmessage/tests/message_test.cpp mode change 100644 => 100755 indra/llxml/tests/llcontrol_test.cpp mode change 100644 => 100755 indra/newview/llappviewer.cpp mode change 100644 => 100755 indra/newview/llfloaterpreference.cpp mode change 100644 => 100755 indra/newview/llfloateruipreview.cpp mode change 100644 => 100755 indra/newview/llpreviewnotecard.cpp mode change 100644 => 100755 indra/newview/llpreviewscript.cpp mode change 100644 => 100755 indra/newview/lltexturecache.cpp mode change 100644 => 100755 indra/newview/llviewerdisplay.cpp mode change 100644 => 100755 indra/newview/llviewermedia.cpp mode change 100644 => 100755 indra/newview/llvocache.cpp mode change 100644 => 100755 indra/newview/llvoicevivox.cpp (limited to 'indra/llmessage') diff --git a/indra/llappearanceutility/llappappearanceutility.cpp b/indra/llappearanceutility/llappappearanceutility.cpp index d223c859ab..cdc9cfdf40 100644 --- a/indra/llappearanceutility/llappappearanceutility.cpp +++ b/indra/llappearanceutility/llappappearanceutility.cpp @@ -57,6 +57,8 @@ #include "llprocesstexture.h" #include "llprocessskin.h" +#include "apr_getopt.h" + const std::string NOTHING_EXTRA(""); //////////////////////////////////////////// diff --git a/indra/llaudio/llaudiodecodemgr.cpp b/indra/llaudio/llaudiodecodemgr.cpp index d8a6fffea6..232b429130 100755 --- a/indra/llaudio/llaudiodecodemgr.cpp +++ b/indra/llaudio/llaudiodecodemgr.cpp @@ -199,7 +199,7 @@ bool LLVorbisDecodeState::initDecode() LL_DEBUGS("AudioEngine") << "Initing decode from vfile: " << mUUID << LL_ENDL; mInFilep = new LLFileSystem(mUUID, LLAssetType::AT_SOUND); - if (!mInFilep || !mInFilep->getSize()) + if (!mInFilep || mInFilep->getSize() <= 0) { LL_WARNS("AudioEngine") << "unable to open vorbis source vfile for reading" << LL_ENDL; delete mInFilep; diff --git a/indra/llcommon/CMakeLists.txt b/indra/llcommon/CMakeLists.txt index 597a222b32..cb3f0d7842 100644 --- a/indra/llcommon/CMakeLists.txt +++ b/indra/llcommon/CMakeLists.txt @@ -322,6 +322,7 @@ if (LL_TESTS) LL_ADD_INTEGRATION_TEST(lleventdispatcher "" "${test_libs}") LL_ADD_INTEGRATION_TEST(lleventfilter "" "${test_libs}") LL_ADD_INTEGRATION_TEST(llevents "" "${test_libs}") + LL_ADD_INTEGRATION_TEST(llfile "" "${test_libs}") LL_ADD_INTEGRATION_TEST(llframetimer "" "${test_libs}") LL_ADD_INTEGRATION_TEST(llhttpdate "" "${test_libs}") LL_ADD_INTEGRATION_TEST(llheteromap "" "${test_libs}") diff --git a/indra/llcommon/llapp.cpp b/indra/llcommon/llapp.cpp index 73b50d0a50..aa84895fb8 100644 --- a/indra/llcommon/llapp.cpp +++ b/indra/llcommon/llapp.cpp @@ -37,7 +37,7 @@ #endif #include "llcommon.h" -#include "llapr.h" + #include "llerrorcontrol.h" #include "llframetimer.h" #include "lllivefile.h" @@ -53,6 +53,8 @@ // // Signal handling #ifndef LL_WINDOWS +#include "apr_signal.h" + # include # include // for fork() void setup_signals(); diff --git a/indra/llcommon/llapr.cpp b/indra/llcommon/llapr.cpp index 65ee383c6b..9ea7a34bac 100644 --- a/indra/llcommon/llapr.cpp +++ b/indra/llcommon/llapr.cpp @@ -526,226 +526,6 @@ S32 LLAPRFile::seek(apr_file_t* file_handle, apr_seek_where_t where, S32 offset) } } -//static -S32 LLAPRFile::readEx(const std::string& filename, void *buf, S32 offset, S32 nbytes, LLVolatileAPRPool* pool) -{ - LL_PROFILE_ZONE_SCOPED; - //***************************************** - LLAPRFilePoolScope scope(pool); - apr_file_t* file_handle = open(filename, scope.getVolatileAPRPool(), APR_READ|APR_BINARY); - //***************************************** - if (!file_handle) - { - return 0; - } - - llassert(offset >= 0); - - if (offset > 0) - offset = LLAPRFile::seek(file_handle, APR_SET, offset); - - apr_size_t bytes_read; - if (offset < 0) - { - bytes_read = 0; - } - else - { - bytes_read = nbytes ; - apr_status_t s = apr_file_read(file_handle, buf, &bytes_read); - if (s != APR_SUCCESS) - { - LL_WARNS("APR") << " Attempting to read filename: " << filename << LL_ENDL; - ll_apr_warn_status(s); - bytes_read = 0; - } - else - { - llassert_always(bytes_read <= 0x7fffffff); - } - } - - //***************************************** - close(file_handle) ; - //***************************************** - return (S32)bytes_read; -} - -//static -S32 LLAPRFile::writeEx(const std::string& filename, const void *buf, S32 offset, S32 nbytes, LLVolatileAPRPool* pool) -{ - LL_PROFILE_ZONE_SCOPED; - apr_int32_t flags = APR_CREATE|APR_WRITE|APR_BINARY; - if (offset < 0) - { - flags |= APR_APPEND; - offset = 0; - } - - //***************************************** - LLAPRFilePoolScope scope(pool); - apr_file_t* file_handle = open(filename, scope.getVolatileAPRPool(), flags); - //***************************************** - if (!file_handle) - { - return 0; - } - - if (offset > 0) - { - offset = LLAPRFile::seek(file_handle, APR_SET, offset); - } - - apr_size_t bytes_written; - if (offset < 0) - { - bytes_written = 0; - } - else - { - bytes_written = nbytes ; - apr_status_t s = apr_file_write(file_handle, buf, &bytes_written); - if (s != APR_SUCCESS) - { - LL_WARNS("APR") << "Attempting to write filename: " << filename << LL_ENDL; - if (APR_STATUS_IS_ENOSPC(s)) - { - LLApp::notifyOutOfDiskSpace(); - } - ll_apr_warn_status(s); - bytes_written = 0; - } - else - { - llassert_always(bytes_written <= 0x7fffffff); - } - } - - //***************************************** - LLAPRFile::close(file_handle); - //***************************************** - - return (S32)bytes_written; -} - -//static -bool LLAPRFile::remove(const std::string& filename, LLVolatileAPRPool* pool) -{ - apr_status_t s; - - LLAPRFilePoolScope scope(pool); - s = apr_file_remove(filename.c_str(), scope.getVolatileAPRPool()); - - if (s != APR_SUCCESS) - { - ll_apr_warn_status(s); - LL_WARNS("APR") << " Attempting to remove filename: " << filename << LL_ENDL; - return false; - } - return true; -} - -//static -bool LLAPRFile::rename(const std::string& filename, const std::string& newname, LLVolatileAPRPool* pool) -{ - apr_status_t s; - - LLAPRFilePoolScope scope(pool); - s = apr_file_rename(filename.c_str(), newname.c_str(), scope.getVolatileAPRPool()); - - if (s != APR_SUCCESS) - { - ll_apr_warn_status(s); - LL_WARNS("APR") << " Attempting to rename filename: " << filename << LL_ENDL; - return false; - } - return true; -} - -//static -bool LLAPRFile::isExist(const std::string& filename, LLVolatileAPRPool* pool, apr_int32_t flags) -{ - apr_file_t* apr_file; - apr_status_t s; - - LLAPRFilePoolScope scope(pool); - s = apr_file_open(&apr_file, filename.c_str(), flags, APR_OS_DEFAULT, scope.getVolatileAPRPool()); - - if (s != APR_SUCCESS || !apr_file) - { - return false; - } - else - { - apr_file_close(apr_file) ; - return true; - } -} - -//static -S32 LLAPRFile::size(const std::string& filename, LLVolatileAPRPool* pool) -{ - apr_file_t* apr_file; - apr_finfo_t info; - apr_status_t s; - - LLAPRFilePoolScope scope(pool); - s = apr_file_open(&apr_file, filename.c_str(), APR_READ, APR_OS_DEFAULT, scope.getVolatileAPRPool()); - - if (s != APR_SUCCESS || !apr_file) - { - return 0; - } - else - { - apr_status_t s = apr_file_info_get(&info, APR_FINFO_SIZE, apr_file); - - apr_file_close(apr_file) ; - - if (s == APR_SUCCESS) - { - return (S32)info.size; - } - else - { - return 0; - } - } -} - -//static -bool LLAPRFile::makeDir(const std::string& dirname, LLVolatileAPRPool* pool) -{ - apr_status_t s; - - LLAPRFilePoolScope scope(pool); - s = apr_dir_make(dirname.c_str(), APR_FPROT_OS_DEFAULT, scope.getVolatileAPRPool()); - - if (s != APR_SUCCESS) - { - ll_apr_warn_status(s); - LL_WARNS("APR") << " Attempting to make directory: " << dirname << LL_ENDL; - return false; - } - return true; -} - -//static -bool LLAPRFile::removeDir(const std::string& dirname, LLVolatileAPRPool* pool) -{ - apr_status_t s; - - LLAPRFilePoolScope scope(pool); - s = apr_file_remove(dirname.c_str(), scope.getVolatileAPRPool()); - - if (s != APR_SUCCESS) - { - ll_apr_warn_status(s); - LL_WARNS("APR") << " Attempting to remove directory: " << dirname << LL_ENDL; - return false; - } - return true; -} // //end of static components of LLAPRFile //******************************************************************************************************************************* diff --git a/indra/llcommon/llapr.h b/indra/llcommon/llapr.h index 0e1e4277e7..8795a0f2c4 100644 --- a/indra/llcommon/llapr.h +++ b/indra/llcommon/llapr.h @@ -35,10 +35,6 @@ #include "llwin32headers.h" #include "apr_thread_proc.h" -#include "apr_getopt.h" -#include "apr_signal.h" - -#include "llstring.h" #include @@ -184,20 +180,7 @@ private: static apr_file_t* open(const std::string& filename, apr_pool_t* apr_pool, apr_int32_t flags); static apr_status_t close(apr_file_t* file) ; static S32 seek(apr_file_t* file, apr_seek_where_t where, S32 offset); -public: - // returns false if failure: - static bool remove(const std::string& filename, LLVolatileAPRPool* pool = NULL); - static bool rename(const std::string& filename, const std::string& newname, LLVolatileAPRPool* pool = NULL); - static bool isExist(const std::string& filename, LLVolatileAPRPool* pool = NULL, apr_int32_t flags = APR_READ); - static S32 size(const std::string& filename, LLVolatileAPRPool* pool = NULL); - static bool makeDir(const std::string& dirname, LLVolatileAPRPool* pool = NULL); - static bool removeDir(const std::string& dirname, LLVolatileAPRPool* pool = NULL); - - // Returns bytes read/written, 0 if read/write fails: - static S32 readEx(const std::string& filename, void *buf, S32 offset, S32 nbytes, LLVolatileAPRPool* pool = NULL); - static S32 writeEx(const std::string& filename, const void *buf, S32 offset, S32 nbytes, LLVolatileAPRPool* pool = NULL); // offset<0 means append //******************************************************************************************************************************* }; - #endif // LL_LLAPR_H diff --git a/indra/llcommon/llerror.cpp b/indra/llcommon/llerror.cpp old mode 100644 new mode 100755 index 8ae0fabcc6..5b42c83a14 --- a/indra/llcommon/llerror.cpp +++ b/indra/llcommon/llerror.cpp @@ -481,13 +481,9 @@ namespace std::string file = user_dir + "/logcontrol-dev.xml"; - llstat stat_info; - if (LLFile::stat(file, &stat_info)) { - // NB: stat returns non-zero if it can't read the file, for example - // if it doesn't exist. LLFile has no better abstraction for - // testing for file existence. - - file = app_dir + "/logcontrol.xml"; + if (!LLFile::isfile(file)) + { + file = app_dir + "/logcontrol.xml"; } return * new LogControlFile(file); // NB: This instance is never freed diff --git a/indra/llcommon/llfile.cpp b/indra/llcommon/llfile.cpp old mode 100644 new mode 100755 index a539e4fe28..ff87d8ce10 --- a/indra/llcommon/llfile.cpp +++ b/indra/llcommon/llfile.cpp @@ -29,22 +29,17 @@ #include "linden_common.h" #include "llfile.h" -#include "llstring.h" #include "llerror.h" #include "stringize.h" #if LL_WINDOWS -#include "llwin32headers.h" -#include +#include #else #include +#include #endif -using namespace std; - -static std::string empty; - -// Many of the methods below use OS-level functions that mess with errno. Wrap +// Some of the methods below use OS-level functions that mess with errno. Wrap // variants of strerror() to report errors. #if LL_WINDOWS @@ -79,6 +74,7 @@ static errentry const errtable[] { ERROR_CURRENT_DIRECTORY, EACCES }, // 16 { ERROR_NOT_SAME_DEVICE, EXDEV }, // 17 { ERROR_NO_MORE_FILES, ENOENT }, // 18 + { ERROR_SHARING_VIOLATION, EACCES }, // 32 { ERROR_LOCK_VIOLATION, EACCES }, // 33 { ERROR_BAD_NETPATH, ENOENT }, // 53 { ERROR_NETWORK_ACCESS_DENIED, EACCES }, // 65 @@ -109,22 +105,25 @@ static errentry const errtable[] { ERROR_NOT_ENOUGH_QUOTA, ENOMEM } // 1816 }; -static int set_errno_from_oserror(unsigned long oserr) +static int get_errno_from_oserror(int oserr) { if (!oserr) return 0; // Check the table for the Windows OS error code - for (const struct errentry &entry : errtable) + for (const struct errentry& entry : errtable) { if (oserr == entry.oserr) { - _set_errno(entry.errcode); - return -1; + return entry.errcode; } } + return EINVAL; +} - _set_errno(EINVAL); +static int set_errno_from_oserror(unsigned long oserr) +{ + _set_errno(get_errno_from_oserror(oserr)); return -1; } @@ -136,69 +135,8 @@ std::string strerr(int errn) return buffer; } -inline bool is_slash(wchar_t const c) -{ - return c == L'\\' || c == L'/'; -} - -static std::wstring utf8path_to_wstring(const std::string& utf8path) -{ - if (utf8path.size() >= MAX_PATH) - { - // By prepending "\\?\" to a path, Windows widechar file APIs will not fail on long path names - std::wstring utf16path = L"\\\\?\\" + ll_convert(utf8path); - // We need to make sure that the path does not contain forward slashes as above - // prefix does bypass the path normalization that replaces slashes with backslashes - // before passing the path to kernel mode APIs - std::replace(utf16path.begin(), utf16path.end(), L'/', L'\\'); - return utf16path; - } - return ll_convert(utf8path); -} - -static unsigned short get_fileattr(const std::wstring& utf16path, bool dontFollowSymLink = false) -{ - unsigned long flags = FILE_FLAG_BACKUP_SEMANTICS; - if (dontFollowSymLink) - { - flags |= FILE_FLAG_OPEN_REPARSE_POINT; - } - HANDLE file_handle = CreateFileW(utf16path.c_str(), FILE_READ_ATTRIBUTES, - FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE, - nullptr, OPEN_EXISTING, flags, nullptr); - if (file_handle != INVALID_HANDLE_VALUE) - { - FILE_ATTRIBUTE_TAG_INFO attribute_info; - if (GetFileInformationByHandleEx(file_handle, FileAttributeTagInfo, &attribute_info, sizeof(attribute_info))) - { - // A volume path alone (only drive letter) is not recognized as directory while it technically is - bool is_directory = (attribute_info.FileAttributes & FILE_ATTRIBUTE_DIRECTORY) || - (iswalpha(utf16path[0]) && utf16path[1] == ':' && - (!utf16path[2] || (is_slash(utf16path[2]) && !utf16path[3]))); - unsigned short st_mode = is_directory ? S_IFDIR : - (attribute_info.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT ? S_IFLNK : S_IFREG); - st_mode |= (attribute_info.FileAttributes & FILE_ATTRIBUTE_READONLY) ? S_IREAD : S_IREAD | S_IWRITE; - // we do not try to guess executable flag - - // propagate user bits to group/other fields: - st_mode |= (st_mode & 0700) >> 3; - st_mode |= (st_mode & 0700) >> 6; - - CloseHandle(file_handle); - return st_mode; - } - } - // Retrieve last error and set errno before calling CloseHandle() - set_errno_from_oserror(GetLastError()); - - if (file_handle != INVALID_HANDLE_VALUE) - { - CloseHandle(file_handle); - } - return 0; -} - #else + // On Posix we want to call strerror_r(), but alarmingly, there are two // different variants. The one that returns int always populates the passed // buffer (except in case of error), whereas the other one always returns a @@ -245,9 +183,50 @@ std::string strerr(int errn) return message_from(errn, buffer, sizeof(buffer), strerror_r(errn, buffer, sizeof(buffer))); } + #endif // ! LL_WINDOWS -static int warnif(const std::string& desc, const std::string& filename, int rc, int accept = 0) +#if LL_WINDOWS && 0 // turn on to debug file-locking problems +#define PROCESS_LOCKING_CHECK 1 +static void find_locking_process(const std::string& filename) +{ + // Only do any of this stuff (before LL_ENDL) if it will be logged. + LL_DEBUGS("LLFile") << ""; + // wrong way + std::string TEMP = LLFile::tmpdir(); + if (TEMP.empty()) + { + LL_CONT << "No $TEMP, not running 'handle'"; + } + else + { + std::string tf(TEMP); + tf += "\\handle.tmp"; + // http://technet.microsoft.com/en-us/sysinternals/bb896655 + std::string cmd(STRINGIZE("handle \"" << filename + // "openfiles /query /v | fgrep -i \"" << filename + << "\" > \"" << tf << '"')); + LL_CONT << cmd; + if (system(cmd.c_str()) != 0) + { + LL_CONT << "\nDownload 'handle.exe' from http://technet.microsoft.com/en-us/sysinternals/bb896655"; + } + else + { + std::ifstream inf(tf); + std::string line; + while (std::getline(inf, line)) + { + LL_CONT << '\n' << line; + } + } + LLFile::remove(tf); + } + LL_CONT << LL_ENDL; +} +#endif // LL_WINDOWS hack to identify processes holding file open + +static int warnif(const std::string& desc, const std::string& filename, int rc, int suppress_warning = 0) { if (rc < 0) { @@ -256,319 +235,951 @@ static int warnif(const std::string& desc, const std::string& filename, int rc, // For certain operations, a particular errno value might be // acceptable -- e.g. stat() could permit ENOENT, mkdir() could permit - // EEXIST. Don't warn if caller explicitly says this errno is okay. - if (errn != accept) + // EEXIST. Don't log a warning if caller explicitly says this errno is okay. + if (errn != suppress_warning) { - LL_WARNS("LLFile") << "Couldn't " << desc << " '" << filename - << "' (errno " << errn << "): " << strerr(errn) << LL_ENDL; + LL_WARNS("LLFile") << "Couldn't " << desc << " '" << filename << "' (errno " << errn << "): " << strerr(errn) << LL_ENDL; } -#if 0 && LL_WINDOWS // turn on to debug file-locking problems +#if PROCESS_LOCKING_CHECK // If the problem is "Permission denied," maybe it's because another // process has the file open. Try to find out. - if (errn == EACCES) // *not* EPERM + if (errn == EACCES) // *not* EPERM { - // Only do any of this stuff (before LL_ENDL) if it will be logged. - LL_DEBUGS("LLFile") << empty; - // would be nice to use LLDir for this, but dependency goes the - // wrong way - const char* TEMP = LLFile::tmpdir(); - if (! (TEMP && *TEMP)) - { - LL_CONT << "No $TEMP, not running 'handle'"; - } - else - { - std::string tf(TEMP); - tf += "\\handle.tmp"; - // http://technet.microsoft.com/en-us/sysinternals/bb896655 - std::string cmd(STRINGIZE("handle \"" << filename - // "openfiles /query /v | fgrep -i \"" << filename - << "\" > \"" << tf << '"')); - LL_CONT << cmd; - if (system(cmd.c_str()) != 0) - { - LL_CONT << "\nDownload 'handle.exe' from http://technet.microsoft.com/en-us/sysinternals/bb896655"; - } - else - { - std::ifstream inf(tf); - std::string line; - while (std::getline(inf, line)) - { - LL_CONT << '\n' << line; - } - } - LLFile::remove(tf); - } - LL_CONT << LL_ENDL; + find_locking_process(filename); } -#endif // LL_WINDOWS hack to identify processes holding file open +#endif } return rc; } -// static -int LLFile::mkdir(const std::string& dirname, int perms) +static int warnif(const std::string& desc, const std::string& filename, const std::error_code& ec, int suppress_warning = 0) { - // We often use mkdir() to ensure the existence of a directory that might - // already exist. There is no known case in which we want to call out as - // an error the requested directory already existing. + if (ec) + { + // get Posix errno from the std::error_code so we can compare it to the suppress_warning parameter + // to see when a caller wants us to not generate a warning for a particular error code #if LL_WINDOWS - // permissions are ignored on Windows - int rc = 0; - std::wstring utf16dirname = utf8path_to_wstring(dirname); - if (!CreateDirectoryW(utf16dirname.c_str(), nullptr)) - { - // Only treat other errors than an already existing file as a real error - unsigned long oserr = GetLastError(); - if (oserr != ERROR_ALREADY_EXISTS) + int errn = get_errno_from_oserror(ec.value()); +#else + int errn = ec.value(); +#endif + // For certain operations, a particular errno value might be acceptable + // Don't warn if caller explicitly says this errno is okay. + if (errn != suppress_warning) + { + LL_WARNS("LLFile") << "Couldn't " << desc << " '" << filename << "' (errno " << errn << "): " << ec.message() << LL_ENDL; + } +#if PROCESS_LOCKING_CHECK + // Try to detect locked files by other processes + if (ec.value() == ERROR_SHARING_VIOLATION || ec.value() == ERROR_LOCK_VIOLATION) + { + find_locking_process(filename); + } +#endif + return -1; + } + return 0; +} + +#if LL_WINDOWS + +inline int set_ec_from_system_error(std::error_code& ec, DWORD error) +{ + ec.assign(error, std::system_category()); + return -1; +} + +static int set_ec_from_system_error(std::error_code& ec) +{ + return set_ec_from_system_error(ec, GetLastError()); +} + +inline int set_ec_to_parameter_error(std::error_code& ec) +{ + return set_ec_from_system_error(ec, ERROR_INVALID_PARAMETER); +} + +inline int set_ec_to_outofmemory_error(std::error_code& ec) +{ + return set_ec_from_system_error(ec, ERROR_NOT_ENOUGH_MEMORY); +} + +inline DWORD decode_access_mode(std::ios_base::openmode omode) +{ + switch (omode & (LLFile::in | LLFile::out)) + { + case LLFile::in: + return GENERIC_READ; + case LLFile::out: + return GENERIC_WRITE; + case static_cast(LLFile::in | LLFile::out): + return GENERIC_READ | GENERIC_WRITE; + } + if (omode & LLFile::app) + { + return GENERIC_WRITE; + } + return 0; +} + +inline DWORD decode_open_create_flags(std::ios_base::openmode omode) +{ + if (omode & LLFile::noreplace) + { + return CREATE_NEW; // create if it does not exist, otherwise fail + } + if (omode & LLFile::trunc) + { + if (!(omode & LLFile::out)) { - rc = set_errno_from_oserror(oserr); + return TRUNCATE_EXISTING; // open and truncate if it exists, otherwise fail } + return CREATE_ALWAYS; // open and truncate if it exists, otherwise create it + } + if (!(omode & LLFile::out)) + { + return OPEN_EXISTING; // open if it exists, otherwise fail + } + // LLFile::app or (LLFile::out and (!LLFile::trunc or !LLFile::noreplace)) + return OPEN_ALWAYS; // open if it exists, otherwise create it +} + +inline DWORD decode_share_mode(int omode) +{ + if (omode & LLFile::exclusive) + { + return 0; // allow no other access + } + if (omode & LLFile::shared) + { + return FILE_SHARE_READ; // allow read access + } + return FILE_SHARE_READ | FILE_SHARE_WRITE; // allow read and write access to others +} + +inline DWORD decode_attributes(std::ios_base::openmode omode, int perm) +{ + return (perm & S_IWRITE) ? FILE_ATTRIBUTE_NORMAL : FILE_ATTRIBUTE_READONLY; +} + +// Under Windows the values for the std::ios_base::seekdir constants match the according FILE_BEGIN +// and other constants but we do a programmatic translation for now to be sure +static DWORD seek_mode_from_dir(std::ios_base::seekdir seekdir) +{ + switch (seekdir) + { + case LLFile::beg: + return FILE_BEGIN; + case LLFile::cur: + return FILE_CURRENT; + case LLFile::end: + return FILE_END; } + return FILE_BEGIN; +} + #else - int rc = ::mkdir(dirname.c_str(), (mode_t)perms); - if (rc < 0 && errno == EEXIST) + +inline int set_ec_from_system_error(std::error_code& ec, int error) +{ + ec.assign(error, std::system_category()); + return -1; +} + +static int set_ec_from_system_error(std::error_code& ec) +{ + return set_ec_from_system_error(ec, errno); +} + +inline int set_ec_to_parameter_error(std::error_code& ec) +{ + return set_ec_from_system_error(ec, EINVAL); +} + +inline int set_ec_to_outofmemory_error(std::error_code& ec) +{ + return set_ec_from_system_error(ec, ENOMEM); +} + +inline int decode_access_mode(std::ios_base::openmode omode) +{ + if (omode & LLFile::out) { - // this is not the error you want, move along - return 0; + if (omode & LLFile::in) + { + return O_RDWR; + } + return O_WRONLY; + } + return O_RDONLY; + + /*switch (omode & (LLFile::in | LLFile::out)) + { + case LLFile::out: + return O_WRONLY; + case static_cast(LLFile::in | LLFile::out): + return O_RDWR; + } + return O_RDONLY;*/ +} + +inline int decode_open_mode(std::ios_base::openmode omode) +{ + int flags = O_CREAT | decode_access_mode(omode); + if (omode & LLFile::app) + { + flags |= O_APPEND; } + if (omode & LLFile::trunc) + { + flags |= O_TRUNC; + } + if (omode & LLFile::binary) + { + // Not a thing under *nix + } + if (omode & LLFile::noreplace) + { + flags |= O_EXCL; + } + return flags; +} + +inline int decode_lock_mode(std::ios_base::openmode omode) +{ + int lmode = omode & LLFile::noblock ? LOCK_NB : 0; + if (omode & LLFile::lock_mask) + { + if (omode & LLFile::exclusive) + { + return lmode | LOCK_EX; + } + return lmode | LOCK_SH; + } + return lmode | LOCK_UN; +} + +// Under Linux and Mac the values for the std::ios_base::seekdir constants match the according SEEK_SET +// and other constants but we do a programmatic translation for now to be sure +inline int seek_mode_from_dir(std::ios_base::seekdir seekdir) +{ + switch (seekdir) + { + case LLFile::beg: + return SEEK_SET; + case LLFile::cur: + return SEEK_CUR; + case LLFile::end: + return SEEK_END; + } + return SEEK_SET; +} + #endif - // anything else might be a problem - return warnif("mkdir", dirname, rc); + +inline int clear_error(std::error_code& ec) +{ + ec.clear(); + return 0; } -// static -int LLFile::rmdir(const std::string& dirname, int suppress_error) +inline bool are_open_mode_flags_invalid(std::ios_base::openmode omode) +{ + // at least one of input or output needs to be specified + if (!(omode & (LLFile::in | LLFile::out))) + { + return true; + } + // output must be possible for any of the extra options + if (!(omode & LLFile::out) && (omode & (LLFile::trunc | LLFile::app | LLFile::noreplace))) + { + return true; + } + // invalid combination, mutually exclusive + if ((omode & LLFile::app) && (omode & (LLFile::trunc | LLFile::noreplace))) + { + return true; + } + return false; +} + +//---------------------------------------------------------------------------------------- +// class member functions +//---------------------------------------------------------------------------------------- +int LLFile::open(const std::string& filename, std::ios_base::openmode omode, std::error_code& ec, int perm) { + close(ec); + if (are_open_mode_flags_invalid(omode)) + { + return set_ec_to_parameter_error(ec); + } #if LL_WINDOWS - std::wstring utf16dirname = utf8path_to_wstring(dirname); - int rc = _wrmdir(utf16dirname.c_str()); + DWORD access = decode_access_mode(omode), + share = decode_share_mode(omode), + create = decode_open_create_flags(omode), + attributes = decode_attributes(omode, perm); + + std::wstring file_path = utf8StringToWstring(filename); + mHandle = CreateFileW(file_path.c_str(), access, share, nullptr, create, attributes, nullptr); + // The dwShareMode = share parameter takes care of locking the file for other processes if indicated, + // no need to do anything else for file locking here #else - int rc = ::rmdir(dirname.c_str()); + int oflags = decode_open_mode(omode); + int lmode = omode & LLFile::lock_mask; + mHandle = ::open(filename.c_str(), oflags, perm); + if (mHandle != InvalidHandle && lmode && lock(lmode | LLFile::noblock, ec) != 0) + { + close(); + return -1; + } #endif - return warnif("rmdir", dirname, rc, suppress_error); + if (mHandle == InvalidHandle) + { + return set_ec_from_system_error(ec); + } + + if (omode & LLFile::ate && seek(0, LLFile::end, ec) != 0) + { + close(); + return -1; + } + mOpen = omode; + return clear_error(ec); } -// static -LLFILE* LLFile::fopen(const std::string& filename, const char* mode) +S64 LLFile::size(std::error_code& ec) { #if LL_WINDOWS - std::wstring utf16filename = utf8path_to_wstring(filename); - std::wstring utf16mode = ll_convert(std::string(mode)); - return _wfopen(utf16filename.c_str(), utf16mode.c_str()); + LARGE_INTEGER value = { 0 }; + if (GetFileSizeEx(mHandle, &value)) + { + clear_error(ec); + return value.QuadPart; + } #else - return ::fopen(filename.c_str(),mode); + struct stat statval; + if (fstat(mHandle, &statval) == 0) + { + clear_error(ec); + return statval.st_size; + } #endif + return set_ec_from_system_error(ec); } -// static -int LLFile::close(LLFILE * file) +S64 LLFile::tell(std::error_code& ec) { - int ret_value = 0; - if (file) +#if LL_WINDOWS + LARGE_INTEGER value = { 0 }; + if (SetFilePointerEx(mHandle, value, &value, FILE_CURRENT)) { - ret_value = fclose(file); + clear_error(ec); + return value.QuadPart; } - return ret_value; +#else + off_t offset = lseek(mHandle, 0, SEEK_CUR); + if (offset != -1) + { + clear_error(ec); + return offset; + } +#endif + return set_ec_from_system_error(ec); } -// static -std::string LLFile::getContents(const std::string& filename) +int LLFile::seek(S64 pos, std::error_code& ec) { - LLFILE* fp = LLFile::fopen(filename, "rb"); - if (fp) + return seek(pos, LLFile::beg, ec); +} + +int LLFile::seek(S64 offset, std::ios_base::seekdir dir, std::error_code& ec) +{ + S64 newOffset = 0; +#if LL_WINDOWS + DWORD seekdir = seek_mode_from_dir(dir); + LARGE_INTEGER value; + value.QuadPart = offset; + if (SetFilePointerEx(mHandle, value, (PLARGE_INTEGER)&newOffset, seekdir)) +#else + newOffset = lseek(mHandle, offset, seek_mode_from_dir(dir)); + if (newOffset != -1) +#endif { - fseek(fp, 0, SEEK_END); - U32 length = ftell(fp); - fseek(fp, 0, SEEK_SET); + return clear_error(ec); + } + return set_ec_from_system_error(ec); +} - std::vector buffer(length); - size_t nread = fread(buffer.data(), 1, length, fp); - fclose(fp); +#if LL_WINDOWS +inline DWORD next_buffer_size(S64 nbytes) +{ + return nbytes > 0x80000000 ? 0x80000000 : (DWORD)nbytes; +} +#endif - return std::string(buffer.data(), nread); +S64 LLFile::read(void* buffer, S64 nbytes, std::error_code& ec) +{ + if (nbytes == 0) + { + // Nothing to do + return clear_error(ec); } + else if (!buffer || nbytes < 0) + { + return set_ec_to_parameter_error(ec); + } +#if LL_WINDOWS + S64 totalBytes = 0; + char *ptr = (char*)buffer; + DWORD bytesRead, bytesToRead = next_buffer_size(nbytes); - return LLStringUtil::null; + // Read in chunks to support >4GB which the S64 nbytes value makes possible + while (ReadFile(mHandle, ptr, bytesToRead, &bytesRead, nullptr)) + { + totalBytes += bytesRead; + if (nbytes <= totalBytes || // requested amount read + bytesRead < bytesToRead) // ReadFile encountered eof + { + clear_error(ec); + return totalBytes; + } + ptr += bytesRead; + bytesToRead = next_buffer_size(nbytes - totalBytes); + } +#else + ssize_t bytesRead = ::read(mHandle, buffer, nbytes); + if (bytesRead != -1) + { + clear_error(ec); + return bytesRead; + } +#endif + return set_ec_from_system_error(ec); } -// static -int LLFile::remove(const std::string& filename, int suppress_error) +S64 LLFile::write(const void* buffer, S64 nbytes, std::error_code& ec) { + if (nbytes == 0) + { + // Nothing to do here + return clear_error(ec); + } + else if (!buffer || nbytes < 0) + { + return set_ec_to_parameter_error(ec); + } #if LL_WINDOWS - // Posix remove() works on both files and directories although on Windows - // remove() and its wide char variant _wremove() only removes files just - // as its siblings unlink() and _wunlink(). - // If we really only want to support files we should instead use - // unlink() in the non-Windows part below too - int rc = -1; - std::wstring utf16filename = utf8path_to_wstring(filename); - unsigned short st_mode = get_fileattr(utf16filename); - if (S_ISDIR(st_mode)) + // If this was opened in append mode, we emulate it on Windows + if (mOpen & LLFile::app && seek(0, LLFile::end, ec) != 0) + { + return -1; + } + + S64 totalBytes = 0; + char* ptr = (char*)buffer; + DWORD bytesWritten, bytesToWrite = next_buffer_size(nbytes); + + // Write in chunks to support >4GB which the S64 nbytes value makes possible + while (WriteFile(mHandle, ptr, bytesToWrite, &bytesWritten, nullptr)) + { + totalBytes += bytesWritten; + if (nbytes <= totalBytes) + { + clear_error(ec); + return totalBytes; + } + ptr += bytesWritten; + bytesToWrite = next_buffer_size(nbytes - totalBytes); + } +#else + ssize_t bytesWritten = ::write(mHandle, buffer, nbytes); + if (bytesWritten != -1) + { + clear_error(ec); + return bytesWritten; + } +#endif + return set_ec_from_system_error(ec); +} + +S64 LLFile::printf(const char* fmt, ...) +{ + va_list args1; + va_start(args1, fmt); + va_list args2; + va_copy(args2, args1); + int length = vsnprintf(nullptr, 0, fmt, args1); + va_end(args1); + if (length < 0) { - rc = _wrmdir(utf16filename.c_str()); + va_end(args2); + return -1; } - else if (S_ISREG(st_mode)) + void* buffer = malloc(length + 1); + if (!buffer) { - rc = _wunlink(utf16filename.c_str()); + va_end(args2); + return -1; } - else if (st_mode) + length = vsnprintf((char*)buffer, length + 1, fmt, args2); + va_end(args2); + std::error_code ec; + S64 written = write(buffer, length, ec); + free(buffer); + return written; +} + +int LLFile::lock(int mode, std::error_code& ec) +{ +#if LL_WINDOWS + if (!(mode & LLFile::lock_mask)) { - // it is something else than a file or directory - // this should not really happen as long as we do not allow for symlink - // detection in the optional parameter to get_fileattr() - rc = set_errno_from_oserror(ERROR_INVALID_PARAMETER); + if (UnlockFile(mHandle, 0, 0, MAXDWORD, MAXDWORD)) + { + return clear_error(ec); + } } else { - // get_fileattr() failed and already set errno, preserve it for correct error reporting + OVERLAPPED overlapped = { 0 }; + DWORD flags = (mode & LLFile::noblock) ? LOCKFILE_FAIL_IMMEDIATELY : 0; + if (mode & LLFile::exclusive) + { + flags |= LOCKFILE_EXCLUSIVE_LOCK; + } + // We lock the maximum range, since flock only supports locking the entire file too + if (LockFileEx(mHandle, flags, 0, MAXDWORD, MAXDWORD, &overlapped)) + { + return clear_error(ec); + } } #else - int rc = ::remove(filename.c_str()); + if (flock(mHandle, decode_lock_mode(static_cast(mode))) == 0) + { + return clear_error(ec); + } #endif - return warnif("remove", filename, rc, suppress_error); + return set_ec_from_system_error(ec); +} + +int LLFile::close(std::error_code& ec) +{ + if (mHandle != InvalidHandle) + { + llfile_handle_t handle = InvalidHandle; + std::swap(handle, mHandle); +#if LL_WINDOWS + if (!CloseHandle(handle)) +#else + if (::close(handle)) +#endif + { + return set_ec_from_system_error(ec); + } + } + return clear_error(ec); +} + +int LLFile::close() +{ + std::error_code ec; + return close(ec); } +//---------------------------------------------------------------------------------------- +// static member functions +//---------------------------------------------------------------------------------------- + // static -int LLFile::rename(const std::string& filename, const std::string& newname, int suppress_error) +LLFILE* LLFile::fopen(const std::string& filename, const char* mode, int lmode) { + LLFILE* file; #if LL_WINDOWS - // Posix rename() will gladly overwrite a file at newname if it exists, the Windows - // rename(), respectively _wrename(), will bark on that. Instead call directly the Windows - // API MoveFileEx() and use its flags to specify that overwrite is allowed. - std::wstring utf16filename = utf8path_to_wstring(filename); - std::wstring utf16newname = utf8path_to_wstring(newname); - int rc = 0; - if (!MoveFileExW(utf16filename.c_str(), utf16newname.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED)) + int shflag = _SH_DENYNO; + switch (lmode) { - rc = set_errno_from_oserror(GetLastError()); + case LLFile::exclusive: + shflag = _SH_DENYRW; + break; + case LLFile::shared: + shflag = _SH_DENYWR; + break; } + std::wstring file_path = utf8StringToWstring(filename); + std::wstring utf16mode = ll_convert(std::string(mode)); + file = _wfsopen(file_path.c_str(), utf16mode.c_str(), shflag); #else - int rc = ::rename(filename.c_str(),newname.c_str()); + file = ::fopen(filename.c_str(), mode); + if (file && (lmode & (LLFile::lock_mask))) + { + // Rather fail on a sharing conflict than block + if (flock(fileno(file), decode_lock_mode(static_cast(lmode | LLFile::noblock)))) + { + ::fclose(file); + file = nullptr; + } + } #endif - return warnif(STRINGIZE("rename to '" << newname << "' from"), filename, rc, suppress_error); + return file; +} + +// static +int LLFile::close(LLFILE* file) +{ + int ret_value = 0; + if (file) + { + ret_value = ::fclose(file); + } + return ret_value; +} + +// static +std::string LLFile::getContents(const std::string& filename) +{ + std::error_code ec; + return getContents(filename, ec); +} + +// static +std::string LLFile::getContents(const std::string& filename, std::error_code& ec) +{ + std::string buffer; + LLFile file(filename, LLFile::in | LLFile::binary, ec); + if (file) + { + S64 length = file.size(ec); + if (!ec && length > 0) + { + buffer = std::string(length, 0); + file.read(&buffer[0], length, ec); + if (ec) + { + buffer.clear(); + } + } + } + return buffer; } -// Make this a define rather than using magic numbers multiple times in the code -#define LLFILE_COPY_BUFFER_SIZE 16384 +// static +int LLFile::mkdir(const std::string& dirname) +{ + std::error_code ec; + std::filesystem::path file_path = utf8StringToPath(dirname); + // We often use mkdir() to ensure the existence of a directory that might + // already exist. There is no known case in which we want to call out as + // an error the requested directory already existing. + std::filesystem::create_directory(file_path, ec); + // The return value is only true if the directory was actually created. + // But if it already existed, ec still indicates success. + return warnif("mkdir", dirname, ec); +} // static -bool LLFile::copy(const std::string& from, const std::string& to) +int LLFile::remove(const std::string& filename, int suppress_warning) { - bool copied = false; - LLFILE* in = LLFile::fopen(from, "rb"); - if (in) + std::error_code ec; + std::filesystem::path file_path = utf8StringToPath(filename); + std::filesystem::remove(file_path, ec); + return warnif("remove", filename, ec, suppress_warning); +} + +// static +int LLFile::rename(const std::string& filename, const std::string& newname, int suppress_warning) +{ + std::error_code ec; + std::filesystem::path file_path = utf8StringToPath(filename); + std::filesystem::path new_path = utf8StringToPath(newname); + std::filesystem::rename(file_path, new_path, ec); + return warnif(STRINGIZE("rename to '" << newname << "' from"), filename, ec, suppress_warning); +} + +// static +S64 LLFile::read(const std::string& filename, void* buf, S64 offset, S64 nbytes) +{ + std::error_code ec; + return read(filename, buf, offset, nbytes, ec); +} + +// static +S64 LLFile::read(const std::string& filename, void* buf, S64 offset, S64 nbytes, std::error_code& ec) +{ + // if number of bytes is 0 or less there is nothing to do here + if (nbytes <= 0) + { + clear_error(ec); + return 0; + } + + if (!buf || offset < 0) { - LLFILE* out = LLFile::fopen(to, "wb"); - if (out) + set_ec_to_parameter_error(ec); + } + else + { + std::ios_base::openmode omode = LLFile::in | LLFile::binary; + + LLFile file(filename, omode, ec); + if (!ec && (bool)file) { - char buf[LLFILE_COPY_BUFFER_SIZE]; - size_t readbytes; - bool write_ok = true; - while (write_ok && (readbytes = fread(buf, 1, LLFILE_COPY_BUFFER_SIZE, in))) + if (offset > 0) + { + file.seek(offset, ec); + } + // else (offset == 0) file was just opened and should already be at 0. + if (!ec) { - if (fwrite(buf, 1, readbytes, out) != readbytes) + S64 bytes_read = file.read(buf, nbytes, ec); + if (!ec) { - LL_WARNS("LLFile") << "Short write" << LL_ENDL; - write_ok = false; + return bytes_read; } } - if ( write_ok ) + } + } + return warnif("read from file failed", filename, ec); +} + +// static +S64 LLFile::write(const std::string& filename, const void* buf, S64 offset, S64 nbytes) +{ + std::error_code ec; + return write(filename, buf, offset, nbytes, ec); +} + +// static +S64 LLFile::write(const std::string& filename, const void* buf, S64 offset, S64 nbytes, std::error_code& ec) +{ + // if number of bytes is 0 or less there is nothing to do here + if (nbytes <= 0) + { + clear_error(ec); + return 0; + } + + if (!buf) + { + set_ec_to_parameter_error(ec); + } + else + { + std::ios_base::openmode omode = LLFile::out | LLFile::binary; + if (offset < 0) + { + omode |= LLFile::app; + } + + LLFile file(filename, omode, ec); + if (!ec && (bool)file) + { + if (offset > 0) + { + file.seek(offset, ec); + } + // else (offset == 0) we are not appending, file was just opened and should already be at 0. + if (!ec) { - copied = true; + S64 bytes_written = file.write(buf, nbytes, ec); + if (!ec) + { + return bytes_written; + } } - fclose(out); } - fclose(in); + } + return warnif("write to file failed", filename, ec); +} + +// static +bool LLFile::copy(const std::string& source, const std::string& target) +{ + std::error_code ec; + return copy(source, target, std::filesystem::copy_options::overwrite_existing, ec); +} + +// static +bool LLFile::copy(const std::string& source, const std::string& target, std::filesystem::copy_options options, std::error_code& ec) +{ + std::filesystem::path source_path = utf8StringToPath(source); + std::filesystem::path target_path = utf8StringToPath(target); + bool copied = std::filesystem::copy_file(source_path, target_path, options, ec); + if (!copied) + { + warnif(STRINGIZE("copy failed, to '" << target << "' from"), source, ec); } return copied; } // static -int LLFile::stat(const std::string& filename, llstat* filestatus, int suppress_error) +int LLFile::stat(const std::string& filename, llstat* filestatus, const char *fname, int suppress_warning) { #if LL_WINDOWS - std::wstring utf16filename = utf8path_to_wstring(filename); - int rc = _wstat64(utf16filename.c_str(), filestatus); + std::wstring file_path = utf8StringToWstring(filename); + int rc = _wstat64(file_path.c_str(), filestatus); #else int rc = ::stat(filename.c_str(), filestatus); #endif - return warnif("stat", filename, rc, suppress_error); + return warnif(fname ? fname : "stat", filename, rc, suppress_warning); } // static -unsigned short LLFile::getattr(const std::string& filename, bool dontFollowSymLink, int suppress_error) +std::time_t LLFile::getCreationTime(const std::string& filename, int suppress_warning) { -#if LL_WINDOWS - // _wstat64() is a bit heavyweight on Windows, use a more lightweight API - // to just get the attributes - int rc = -1; - std::wstring utf16filename = utf8path_to_wstring(filename); - unsigned short st_mode = get_fileattr(utf16filename, dontFollowSymLink); - if (st_mode) + // As of C++20 there is no functionality in std::filesystem to retrieve this information + llstat filestat; + int rc = stat(filename, &filestat, "getCreationTime", suppress_warning); + if (rc == 0) { - return st_mode; - } +#if LL_DARWIN + return filestat.st_birthtime; #else - llstat filestatus; - int rc = dontFollowSymLink ? ::lstat(filename.c_str(), &filestatus) : ::stat(filename.c_str(), &filestatus); + // Linux stat() doesn't have a creation/birth time (st_ctime really is the last status + // change or inode attributes change) unless we would use statx() instead. But that is + // a major effort, which would require Linux specific changes to LLFile::stat() above + // and possibly adaptions for other platforms that we leave for a later exercise if it + // is ever desired. + return filestat.st_ctime; +#endif + } + return 0; +} + +// static +std::time_t LLFile::getModificationTime(const std::string& filename, int suppress_warning) +{ + // tried to use std::filesystem::last_write_time() but the whole std::chrono infrastructure is as of + // C++20 still not fully implemented on all platforms. Specifically MacOS C++20 seems lacking here, + // and Windows requires a roundabout through std::chrono::utc_clock to then get a + // std::chrono::system_clock that can return a more useful time_t. + // So we take the easy way out in a similar way as with getCreationTime(). + llstat filestat; + int rc = stat(filename, &filestat, "getModificationTime", suppress_warning); if (rc == 0) { - return filestatus.st_mode; + return filestat.st_mtime; } -#endif - warnif("getattr", filename, rc, suppress_error); return 0; } +// static +S64 LLFile::size(const std::string& filename, int suppress_warning) +{ + std::error_code ec; + std::filesystem::path file_path = utf8StringToPath(filename); + std::intmax_t size = static_cast(std::filesystem::file_size(file_path, ec)); + if (ec) + { + return warnif("size", filename, ec, suppress_warning); + } + return size; +} + +// static +std::filesystem::file_status LLFile::getStatus(const std::string& filename, bool dontFollowSymLink, int suppress_warning) +{ + std::error_code ec; + std::filesystem::path file_path = utf8StringToPath(filename); + std::filesystem::file_status status; + if (dontFollowSymLink) + { + status = std::filesystem::symlink_status(file_path, ec); + } + else + { + status = std::filesystem::status(file_path, ec); + } + warnif("getStatus()", filename, ec, suppress_warning); + return status; +} + +// static +bool LLFile::exists(const std::string& filename) +{ + std::filesystem::file_status status = getStatus(filename); + return std::filesystem::exists(status); +} + // static bool LLFile::isdir(const std::string& filename) { - return S_ISDIR(getattr(filename)); + std::filesystem::file_status status = getStatus(filename); + return std::filesystem::is_directory(status); } // static bool LLFile::isfile(const std::string& filename) { - return S_ISREG(getattr(filename)); + std::filesystem::file_status status = getStatus(filename); + return std::filesystem::is_regular_file(status); } // static bool LLFile::islink(const std::string& filename) { - return S_ISLNK(getattr(filename, true)); + std::filesystem::file_status status = getStatus(filename, true); + return std::filesystem::is_symlink(status); } // static -const char *LLFile::tmpdir() +const std::string& LLFile::tmpdir() { - static std::string utf8path; - - if (utf8path.empty()) + static std::string temppath; + if (temppath.empty()) { - char sep; -#if LL_WINDOWS - sep = '\\'; + temppath = std::filesystem::temp_directory_path().string(); + } - std::vector utf16path(MAX_PATH + 1); - GetTempPathW(static_cast(utf16path.size()), &utf16path[0]); - utf8path = ll_convert_wide_to_string(&utf16path[0]); + char sep; +#if LL_WINDOWS + sep = '\\'; #else - sep = '/'; + sep = '/'; +#endif + if (temppath[temppath.size() - 1] != sep) + { + temppath += sep; + } + return temppath; +} - utf8path = LLStringUtil::getenv("TMPDIR", "/tmp/"); +// static +std::filesystem::path LLFile::utf8StringToPath(const std::string& pathname) +{ +#if LL_WINDOWS + return ll_convert(pathname); +#else + return pathname; #endif - if (utf8path[utf8path.size() - 1] != sep) +} + +#if LL_WINDOWS + +// static +std::wstring LLFile::utf8StringToWstring(const std::string& pathname) +{ + std::wstring utf16string(ll_convert(pathname)); + if (utf16string.size() >= MAX_PATH) + { + // By going through std::filesystem::path we get a lot of path sanitation done for us that + // is needed when passing a path with a kernel object space prefix to Windows API functions + // since this prefix disables the kernel32 path normalization + std::filesystem::path utf16path(utf16string); + + // By prepending "\\?\" to a path, Windows widechar file APIs will not fail on long path names + utf16string.assign(L"\\\\?\\").append(utf16path); + + /* remove trailing spaces and dots (yes, Windows really does that) */ + size_t last_valid = utf16string.find_last_not_of(L" \t."); + if (last_valid == std::wstring::npos) { - utf8path += sep; + return std::wstring(); } + return utf16string.substr(0, last_valid + 1); } - return utf8path.c_str(); + return utf16string; } -#if LL_WINDOWS - /************** input file stream ********************************/ llifstream::llifstream() {} @@ -586,10 +1197,8 @@ void llifstream::open(const std::string& _Filename, ios_base::openmode _Mode) _Mode | ios_base::in); } - /************** output file stream ********************************/ - llofstream::llofstream() {} // explicit @@ -605,30 +1214,4 @@ void llofstream::open(const std::string& _Filename, ios_base::openmode _Mode) _Mode | ios_base::out); } -/************** helper functions ********************************/ - -std::streamsize llifstream_size(llifstream& ifstr) -{ - if(!ifstr.is_open()) return 0; - std::streampos pos_old = ifstr.tellg(); - ifstr.seekg(0, ios_base::beg); - std::streampos pos_beg = ifstr.tellg(); - ifstr.seekg(0, ios_base::end); - std::streampos pos_end = ifstr.tellg(); - ifstr.seekg(pos_old, ios_base::beg); - return pos_end - pos_beg; -} - -std::streamsize llofstream_size(llofstream& ofstr) -{ - if(!ofstr.is_open()) return 0; - std::streampos pos_old = ofstr.tellp(); - ofstr.seekp(0, ios_base::beg); - std::streampos pos_beg = ofstr.tellp(); - ofstr.seekp(0, ios_base::end); - std::streampos pos_end = ofstr.tellp(); - ofstr.seekp(pos_old, ios_base::beg); - return pos_end - pos_beg; -} - #endif // LL_WINDOWS diff --git a/indra/llcommon/llfile.h b/indra/llcommon/llfile.h old mode 100644 new mode 100755 index 04a2946ac4..0036e896c3 --- a/indra/llcommon/llfile.h +++ b/indra/llcommon/llfile.h @@ -35,118 +35,359 @@ * Attempts to mostly mirror the POSIX style IO functions. */ -typedef FILE LLFILE; - #include +#include #include #if LL_WINDOWS +#include // The Windows version of stat function and stat data structure are called _stat64 // We use _stat64 here to support 64-bit st_size and time_t values -typedef struct _stat64 llstat; +typedef struct _stat64 llstat; #else -typedef struct stat llstat; #include +typedef struct stat llstat; #endif -#ifndef S_ISREG -# define S_ISREG(x) (((x) & S_IFMT) == S_IFREG) -#endif - -#ifndef S_ISDIR -# define S_ISDIR(x) (((x) & S_IFMT) == S_IFDIR) -#endif - -// Windows C runtime library does not define this and does not support symlink detection in the -// stat functions but we do in our getattr() function -#ifndef S_IFLNK -#define S_IFLNK 0xA000 /* symlink */ -#endif - -#ifndef S_ISLNK -#define S_ISLNK(x) (((x) & S_IFMT) == S_IFLNK) -#endif +typedef FILE LLFILE; #include "llstring.h" // safe char* -> std::string conversion -/// LLFile is a class of static functions operating on paths +/// This class provides a selection of functions to operate on files through names and +/// a class implementation to represent a file for reading and writing to it /// All the functions with a path string input take UTF8 path/filenames +/// +/// @nosubgrouping +/// class LL_COMMON_API LLFile { public: + // ================================================================================ + /// @name Constants + /// + ///@{ + /** These can be passed to the omode parameter of LLFile::open() and its constructor + + This is similar to the openmode flags for std:fstream but not exactly the same + std::fstream open() does not allow to open a file for writing without either + forcing the file to be truncated on open or all write operations being always + appended to the end of the file or failing to open when the file does not exist. + But to allow implementing the LLAPRFile::writeEx() functionality we need to be + able to write at a random position to the file without truncating it on open. + + any other combinations than listed here are not allowed and will cause an error + + bin in out trunc app noreplace File exists File doesn't exist + ---------------------------------------------------------------------------------- + - + - - - - Open at begin Failure to open + + + - - - - " " + - - + - - - " Create new + + - + - - - " " + - + + - - - " " + + + + - - - " " + ---------------------------------------------------------------------------------- + - - + + - - Destroy contents Create new + + - + + - - " " + - + + + - - " " + + + + + - - " " + ---------------------------------------------------------------------------------- + - - + x - + Failure to open Create new + + - + x - + " " + - + + x - + " " + + + + x - + " " + ---------------------------------------------------------------------------------- + - - + - + - Write to end Create new + + - + - + - " " + - + + - + - " " + + + + - + - " " + ---------------------------------------------------------------------------------- + */ + static const std::ios_base::openmode app = static_cast(1 << 1); // append to end + static const std::ios_base::openmode ate = static_cast(1 << 2); // initialize to end + static const std::ios_base::openmode binary = static_cast(1 << 3); // binary mode + static const std::ios_base::openmode in = static_cast(1 << 4); // for reading + static const std::ios_base::openmode out = static_cast(1 << 5); // for writing // for writing and reading + static const std::ios_base::openmode trunc = static_cast(1 << 6); // truncate on open + static const std::ios_base::openmode noreplace = static_cast(1 << 7); // no replace if it exists + + /// Additional optional flags to omode in open() and lmode in fopen() or lock() + /// to indicate which sort of lock if any to attempt to get + /// + /// NOTE: there is a fundamental difference between platforms. + /// On Windows this lock is mandatory as it is part of the API to open a file handle and other + /// processes can not avoid it. If a file was opened denying other processes read and/or write + /// access, trying to open the same file in another process with that access will fail. + /// On Mac and Linux it is only an advisory lock implemented through the flock() system call. + /// This means that any other application needs to also attempt to at least acquire a shared + /// lock on the file in order to notice that the file is actually already locked. It can + /// therefore not be used to prevent random other applications from accessing the file, but it + /// works for other viewer processes when they use either the LLFile::open() or LLFile::fopen() + /// functions with the appropriate lock flags to open a file. + static const std::ios_base::openmode exclusive = static_cast(1 << 16); + static const std::ios_base::openmode shared = static_cast(1 << 17); + + /// Additional lmode flag to indicate to rather fail instead of blocking when trying + /// to acquire a lock with LLFile::lock() + static const std::ios_base::openmode noblock = static_cast(1 << 18); + + /// The mask value for the lock mask bits + static const std::ios_base::openmode lock_mask = static_cast(exclusive | shared); + + /// One of these can be passed to the dir parameter of LLFile::seek() + static const std::ios_base::seekdir beg = std::ios_base::beg; + static const std::ios_base::seekdir cur = std::ios_base::cur; + static const std::ios_base::seekdir end = std::ios_base::end; + ///@} + + // ================================================================================ + /// @name constructor/deconstructor + /// + ///@{ + /// default constructor + LLFile() : mHandle(InvalidHandle) {} + + /// no copy constructor + LLFile(const LLFile&) = delete; + + /// move constructor + LLFile(LLFile&& other) noexcept + { + mHandle = other.mHandle; + other.mHandle = InvalidHandle; + } + + /// constructor opening the file + LLFile(const std::string& filename, std::ios_base::openmode omode, std::error_code& ec, int perm = 0666) : + mHandle(InvalidHandle) + { + open(filename, omode, ec, perm); + } + + /// destructor always attempts to close the file + ~LLFile() { close(); } + ///@} + + // ================================================================================ + /// @name operators + /// + ///@{ + /// copy assignment deleted + LLFile& operator=(const LLFile&) = delete; + + /// move assignment + LLFile& operator=(LLFile&& other) noexcept + { + close(); + std::swap(mHandle, other.mHandle); + return *this; + } + + // detect whether the wrapped file descriptor/handle is open or not + explicit operator bool() const { return (mHandle != InvalidHandle); } + bool operator!() { return (mHandle == InvalidHandle); } + ///@} + + /// ================================================================================ + /// @name class member methods + /// + /// These methods provide read and write support as well as additional functionality to query the size of + /// the file, change the position of the current file pointer or query it. + /// + /// Most of these functions take as one of their parameters a std::error_code object which can be used to + /// determine in more detail what error occurred if required + ///@{ + + /// Open a file with the specific open mode flags + int open(const std::string& filename, std::ios_base::openmode omode, std::error_code& ec, int perm = 0666); + ///< @returns 0 on success, -1 on failure + + /// Determine the size of the opened file + S64 size(std::error_code& ec); + ///< @returns the number of bytes in the file or -1 on failure + + /// Query the position of the current file pointer in the file + S64 tell(std::error_code& ec); + ///< @returns the absolute offset of the file pointer in bytes relative to the start of the file or -1 on failure + + /// Move the file pointer to the specified absolute position relative to the start of the file + int seek(S64 pos, std::error_code& ec); + ///< @returns 0 on success, -1 on failure + + /// Move the file pointer to the specified position relative to dir + int seek(S64 offset, std::ios_base::seekdir dir, std::error_code& ec); + ///< @returns 0 on success, -1 on failure + + /// Read the specified number of bytes into the buffer starting at the current file pointer + S64 read(void* buffer, S64 nbytes, std::error_code& ec); + ///< If the file ends before the requested amount of bytes could be read, the function succeeds and + /// returns the bytes up to the end of the file. The return value indicates the number of actually + /// read bytes and can be therefore smaller than the requested amount. + /// @returns the number of bytes read from the file or -1 on failure + + /// Write the specified number of bytes to the file starting at the current file pointer + S64 write(const void* buffer, S64 nbytes, std::error_code& ec); + ///< @returns the number of bytes written to the file or -1 on failure + + /// Write into the file starting at the current file pointer using printf style format and + /// additional optional parameters as specified in the fmt string + S64 printf(const char* fmt, ...); + ///< @returns the number of bytes written to the file or -1 on failure + + /// Attempt to acquire or release a lock on the file + int lock(int lmode, std::error_code& ec); + ///< lmode can be one of LLFile::exclusive or LLFile::shared to acquire the according lock + /// or 0 to give up an earlier acquired lock. Adding LLFile::noblock together with one of + /// the lock requests will cause the function to fail if the lock can not be acquired, + /// otherwise the function will block until the lock can be acquired. + /// @returns 0 on success, -1 on failure + + /// close the file explicitly + int close(std::error_code& ec); + ///< @returns 0 on success, -1 on failure + + /// Convenience function to close the file without additional parameters + int close(); + ///< @returns 0 on success, -1 on failure + ///@} + + /// ================================================================================ + /// @name static member functions + /// + /// These functions are static and operate with UTF8 filenames as one of their parameters. + /// + ///@{ /// open a file with the specified access mode - static LLFILE* fopen(const std::string& filename, const char* accessmode); /* Flawfinder: ignore */ + static LLFILE* fopen(const std::string& filename, const char* accessmode, int lmode = 0); ///< 'accessmode' follows the rules of the Posix fopen() mode parameter - /// "r" open the file for reading only and positions the stream at the beginning - /// "r+" open the file for reading and writing and positions the stream at the beginning - /// "w" open the file for reading and writing and truncate it to zero length - /// "w+" open or create the file for reading and writing and truncate to zero length if it existed - /// "a" open the file for reading and writing and position the stream at the end of the file - /// "a+" open or create the file for reading and writing and position the stream at the end of the file + /// "r" open the file for reading only and positions the stream at the beginning + /// "r+" open the file for reading and writing and positions the stream at the beginning + /// "w" open the file for reading and writing and truncate it to zero length + /// "w+" open or create the file for reading and writing and truncate to zero length if it existed + /// "a" open the file for reading and writing and before every write position the stream at the end of the file + /// "a+" open or create the file for reading and writing and before every write position the stream at the end of the file + /// + /// in addition to these values, "b" can be appended to indicate binary stream access, but on Linux and Mac + /// this is strictly for compatibility and has no effect. On Windows this makes the file functions not + /// try to translate line endings. Windows also allows to append "t" to indicate text mode. If neither + /// "b" or "t" is defined, Windows uses the value set by _fmode which by default is _O_TEXT. + /// This means that it is always a good idea to append "b" specifically for binary file access to + /// avoid corruption of the binary consistency of the data stream when reading or writing + /// Other characters in 'accessmode', while possible on some platforms (Windows), will usually + /// cause an error on other platforms as fopen will verify this parameter /// - /// in addition to these values, "b" can be appended to indicate binary stream access, but on Linux and Mac - /// this is strictly for compatibility and has no effect. On Windows this makes the file functions not - /// try to translate line endings. Windows also allows to append "t" to indicate text mode. If neither - /// "b" or "t" is defined, Windows uses the value set by _fmode which by default is _O_TEXT. - /// This means that it is always a good idea to append "b" specifically for binary file access to - /// avoid corruption of the binary consistency of the data stream when reading or writing - /// Other characters in 'accessmode' will usually cause an error as fopen will verify this parameter - /// @returns a valid LLFILE* pointer on success or NULL on failure + /// lmode is optional and allows to lock the file for other processes either as a shared lock or an + /// exclusive lock. If the requested lock conflicts with an already existing lock, the open fails. + /// Pass either LLFIle::exclusive or LLFile::shared to this parameter if you want to prevent other + /// processes from reading (exclusive lock) or writing (shared lock) to the file. It will always use + /// LLFile::noblock, meaning the open will immediately fail if it conflicts with an existing lock on the + /// file. + /// + /// @returns a valid LLFILE* pointer on success that can be passed to the fread() and fwrite() functions + /// and some other f functions in the Standard C library that accept a FILE* as parameter + /// or NULL on failure + /// Close a file handle opened with fopen() above static int close(LLFILE * file); - - /// retrieve the content of a file into a string - static std::string getContents(const std::string& filename); - ///< @returns the content of the file or an empty string on failure + ///< @returns 0 on success and -1 on failure. /// create a directory - static int mkdir(const std::string& filename, int perms = 0700); - ///< perms is a permissions mask like 0777 or 0700. In most cases it will be - /// overridden by the user's umask. It is ignored on Windows. - /// mkdir() considers "directory already exists" to be not an error. - /// @returns 0 on success and -1 on failure. - - //// remove a directory - static int rmdir(const std::string& filename, int suppress_error = 0); - ///< pass ENOENT in the optional 'suppress_error' parameter - /// if you don't want a warning in the log when the directory does not exist + static int mkdir(const std::string& filename); + ///< mkdir() considers "directory already exists" to be not an error. /// @returns 0 on success and -1 on failure. /// remove a file or directory - static int remove(const std::string& filename, int suppress_error = 0); - ///< pass ENOENT in the optional 'suppress_error' parameter - /// if you don't want a warning in the log when the directory does not exist + static int remove(const std::string& filename, int suppress_warning = 0); + ///< pass an errno value (e.g., ENOENT) in the optional 'suppress_warning' parameter if you want to + /// suppress a warning in the log when the failure matches that errno (e.g., suppress warning if + /// the file or directory does not exist) /// @returns 0 on success and -1 on failure. /// rename a file - static int rename(const std::string& filename, const std::string& newname, int suppress_error = 0); + static int rename(const std::string& filename, const std::string& newname, int suppress_warning = 0); ///< it will silently overwrite newname if it exists without returning an error /// Posix guarantees that if newname already exists, then there will be no moment /// in which for other processes newname does not exist. There is no such guarantee - /// under Windows at this time. It may do it in the same way but the used Windows API - /// does not make such guarantees. + /// under Windows at this time. It may do it in the same way but the used Windows + /// APIs do not make such guarantees. /// @returns 0 on success and -1 on failure. + /// copy the contents of the file from 'source' to 'target' + static bool copy(const std::string& source, const std::string& target); + ///< Copies the contents of the file 'source' to the file 'target', overwriting 'target' if it already + /// existed. + /// This is a convenience function that implements the previous behavior of silently overwriting an + /// already existing target file. Consider using the function below if you desire a different + /// behavior when the target file already exists + /// @returns true on success and false on failure. + + /// copy the contents of the file from 'from' to 'to' + static bool copy(const std::string& source, const std::string& target, std::filesystem::copy_options options, std::error_code& ec); + ///< Copies the contents of the file 'source' to the file 'target'. The options parameter allows to + /// specify what should happen if the "target" file already exists: + /// std::filesystem::copy_options::none - return an error in ec and fail + /// std::filesystem::copy_options::skip_existing - skip the operation and do not overwrite file + /// std::filesystem::copy_options::overwrite_existing - overwrite the file + /// std::filesystem::copy_options::update_existing - overwrite the file only if it is older than the file being copied + /// @returns true on success and false on failure. + + /// retrieve the content of a file into a string + static std::string getContents(const std::string& filename); + static std::string getContents(const std::string& filename, std::error_code& ec); + ///< @returns the entire content of the file as std::string or an empty string on failure + + /// read nBytes from the file into the buffer, starting at offset in the file + static S64 read(const std::string& filename, void* buf, S64 offset, S64 nbytes); + static S64 read(const std::string& filename, void* buf, S64 offset, S64 nbytes, std::error_code& ec); + ///< @returns bytes read on success, or -1 on failure - /// copy the contents of file from 'from' to 'to' filename - static bool copy(const std::string& from, const std::string& to); - ///< @returns true on success and false on failure. + /// write nBytes from the buffer into the file, starting at offset in the file + static S64 write(const std::string& filename, const void* buf, S64 offset, S64 nbytes); + static S64 write(const std::string& filename, const void* buf, S64 offset, S64 nbytes, std::error_code& ec); + ///< If a negative offset is provided, the file is opened in append mode and the + /// write will be appended to the end of the file. + /// @returns bytes written on success, or -1 on failure /// return the file stat structure for filename - static int stat(const std::string& filename, llstat* file_status, int suppress_error = ENOENT); + static int stat(const std::string& filename, llstat* file_status, const char *operation = nullptr, int suppress_warning = ENOENT); ///< for compatibility with existing uses of LL_File::stat() we use ENOENT as default in the - /// optional 'suppress_error' parameter to avoid spamming the log with warnings when the API + /// optional 'suppress_warning' parameter to avoid spamming the log with warnings when the API /// is used to detect if a file exists /// @returns 0 on success and -1 on failure. - /// get the file or directory attributes for filename - static unsigned short getattr(const std::string& filename, bool dontFollowSymLink = false, int suppress_error = ENOENT); - ///< a more lightweight function on Windows to stat, that just returns the file attribute flags - /// dontFollowSymLinks set to true returns the attributes of the symlink if it is one, rather than resolving it - /// we pass by default ENOENT in the optional 'suppress_error' parameter to not spam the log with - /// warnings when the file or directory does not exist - /// @returns 0 on failure and a st_mode value with either S_IFDIR or S_IFREG set otherwise - /// together with the three access bits which under Windows only the write bit is relevant. + /// get the creation data and time of a file + static std::time_t getCreationTime(const std::string& filename, int suppress_warning = 0); + ///< Different systems have different support for this. Under Windows this is supposedly + /// the actual time the file was created, on the Mac this is the actual birth date of + /// the file which is in fact the creation time. The according ctime entry in the stat + /// structure under Linux (and any other *nix really) is however contrary to what one + /// might expect based on the c in ctime not the creation time but the time the last + /// change to the inode entry was made. Changing access rights to a file will update + /// this value too. In order to have a true creation time under Linux, we would have + /// to use the statx() call which is available since kernel 4.19, but that will require + /// considerable changes to the implementation of above stat() function. + /// @returns the creation time (last status change under Linux) of the file or 0 on error + + /// get the last modification data and time of a file + static std::time_t getModificationTime(const std::string& filename, int suppress_warning = 0); + ///< @returns the modification time of the file or 0 on error + + /// get the std::filesystem::file_status for filename + static std::filesystem::file_status getStatus(const std::string& filename, bool dontFollowSymLink = false, int suppress_warning = ENOENT); + ///< dontFollowSymLinks set to true returns the std::filesystem::file_status of the symlink if it + /// is one, rather than resolving it. We pass by default ENOENT in the optional 'suppress_warning' + /// parameter to not spam the log with warnings when the file or directory does not exist + /// @returns a std::filesystem::file_status value that can be passed to the appropriate std::filesystem::exists() + /// and other APIs accepting a file_status. + + /// get the size of a file in bytes + static S64 size(const std::string& filename, int suppress_warning = ENOENT); + ///< we pass by default ENOENT in the optional 'suppress_warning' parameter to not spam + /// the log with warnings when the file does not exist + /// @returns the file size on success or -1 on failure. + + /// check if filename is an existing file or directory + static bool exists(const std::string& filename); + ///< @returns true if the path is for an existing file or directory /// check if filename is an existing directory static bool isdir(const std::string& filename); @@ -161,70 +402,44 @@ public: ///< @returns true if the path is pointing at a symlink /// return a path to the temporary directory on the system - static const char * tmpdir(); -}; - -/// RAII class -class LLUniqueFile -{ -public: - // empty - LLUniqueFile(): mFileHandle(nullptr) {} - // wrap (e.g.) result of LLFile::fopen() - LLUniqueFile(LLFILE* f): mFileHandle(f) {} - // no copy - LLUniqueFile(const LLUniqueFile&) = delete; - // move construction - LLUniqueFile(LLUniqueFile&& other) noexcept - { - mFileHandle = other.mFileHandle; - other.mFileHandle = nullptr; - } - // The point of LLUniqueFile is to close on destruction. - ~LLUniqueFile() - { - close(); - } - - // simple assignment - LLUniqueFile& operator=(LLFILE* f) - { - close(); - mFileHandle = f; - return *this; - } - // copy assignment deleted - LLUniqueFile& operator=(const LLUniqueFile&) = delete; - // move assignment - LLUniqueFile& operator=(LLUniqueFile&& other) noexcept - { - close(); - std::swap(mFileHandle, other.mFileHandle); - return *this; - } - - // explicit close operation - void close() - { - if (mFileHandle) - { - // in case close() throws, set mFileHandle null FIRST - LLFILE* h{nullptr}; - std::swap(h, mFileHandle); - LLFile::close(h); - } - } - - // detect whether the wrapped LLFILE is open or not - explicit operator bool() const { return bool(mFileHandle); } - bool operator!() { return ! mFileHandle; } + static const std::string& tmpdir(); - // LLUniqueFile should be usable for any operation that accepts LLFILE* - // (or FILE* for that matter) - operator LLFILE*() const { return mFileHandle; } + /// converts a string containing a path in utf8 encoding into an explicit filesystem path + static std::filesystem::path utf8StringToPath(const std::string& pathname); + ///< @returns the path as a std::filesystem::path + ///@} private: - LLFILE* mFileHandle; +#if LL_WINDOWS + typedef HANDLE llfile_handle_t; + const llfile_handle_t InvalidHandle = INVALID_HANDLE_VALUE; +#else + typedef int llfile_handle_t; + const llfile_handle_t InvalidHandle = -1; +#endif + + /// ================================================================================ + /// @name private static member functions + /// +#if LL_WINDOWS + /// convert a string containing a path in utf8 encoding into a Windows format std::wstring + static std::wstring utf8StringToWstring(const std::string& pathname); + ///< this will prepend the path with the Windows kernel object space prefix when the path is + /// equal or longer than MAX_PATH characters and do some sanitation on the path. + /// This allows the underlaying Windows APIs to process long path names. Do not pass such a path + /// to std::filesystem functions. These functions are not guaranteed to handle such paths properly. + /// It's only useful to pass the resulting string buffer to Microsoft Windows widechar APIs or + /// the Microsoft C runtime widechar file functions. + /// + /// Example: + /// + /// std::wstring file_path = utf8StringToWstring(filename); + /// HANDLE CreateFileW(file_path.c_str(), ......); + /// + /// @returns the path as a std::wstring path +#endif + llfile_handle_t mHandle; // The file handle/descriptor + std::ios_base::openmode mOpen; // Used to emulate std::ios_base::app under Windows }; #if LL_WINDOWS @@ -315,17 +530,6 @@ class LL_COMMON_API llofstream : public std::ofstream ios_base::openmode _Mode = ios_base::out|ios_base::trunc); }; - -/** - * @brief filesize helpers. - * - * The file size helpers are not considered particularly efficient, - * and should only be used for config files and the like -- not in a - * loop. - */ -std::streamsize LL_COMMON_API llifstream_size(llifstream& fstr); -std::streamsize LL_COMMON_API llofstream_size(llofstream& fstr); - #else // ! LL_WINDOWS // on non-windows, llifstream and llofstream are just mapped directly to the std:: equivalents diff --git a/indra/llcommon/tests/llfile_test.cpp b/indra/llcommon/tests/llfile_test.cpp new file mode 100644 index 0000000000..9f2a9b2988 --- /dev/null +++ b/indra/llcommon/tests/llfile_test.cpp @@ -0,0 +1,253 @@ +/** + * @file llfile_tut.cpp + * @author Frederick Martian + * @date 2025-11 + * @brief LLFile test cases. + * + * $LicenseInfo:firstyear=2025&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2025, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +#include +#include "lltut.h" +#include "linden_common.h" +#include "llfile.h" + +namespace tut +{ + static void clear_entire_dir(std::filesystem::path &dir) + { + std::error_code ec; + std::filesystem::remove_all(dir, ec); + } + + static std::filesystem::path append_filename(const std::filesystem::path& dir, const std::string& element) + { + std::filesystem::path path = dir; + return path.append(element); + } + + static std::filesystem::path get_testdir(const std::filesystem::path& tempdir) + { + return append_filename(tempdir, std::string("test_dir")); + } + + struct llfile_test + { + std::filesystem::path tempdir = LLFile::tmpdir(); + std::filesystem::path testdir = get_testdir(tempdir); + }; + typedef test_group llfile_test_t; + typedef llfile_test_t::object llfile_test_object_t; + tut::llfile_test_t tut_llfile_test("llfile_test"); + + template<> template<> + void llfile_test_object_t::test<1>() + { + // Test creating directories and files and deleting them and checking if the + // relevant status functions work as expected + ensure("LLFile::tmpdir() empty", !tempdir.empty()); + ensure("LLFile::tmpdir() doesn't exist", LLFile::exists(tempdir.string())); + ensure("LLFile::tmpdir() is not a directory", LLFile::isdir(tempdir.string())); + ensure("LLFile::tmpdir() should not be a file", !LLFile::isfile(tempdir.string())); + + // Make sure there is nothing left from a previous test run + clear_entire_dir(testdir); + ensure("llfile_test should not exist anymore", !LLFile::exists(testdir.string())); + + int rc = LLFile::mkdir(testdir.string()); + ensure("LLFile::mkdir() failed", rc == 0); + ensure("llfile_test should be a directory", LLFile::isdir(testdir.string())); + rc = LLFile::mkdir(testdir.string()); + ensure("LLFile::mkdir() should not fail when the directory already exists", rc == 0); + + std::filesystem::path testfile1 = testdir; + testfile1.append("llfile_test.dat"); + ensure("llfile_test1.dat should not yet exist", !LLFile::exists(testfile1.string())); + + const char* testdata = "testdata"; + S64 bytes = LLFile::write(testfile1.string(), testdata, 0, sizeof(testdata)); + ensure("LLFile::write() did not write correctly", bytes == sizeof(testdata)); + + rc = LLFile::remove(testfile1.string()); + ensure("LLFile::remove() for file test_file.dat", rc == 0); + ensure("llfile_test.dat should not exist anymore", !LLFile::exists(testfile1.string())); + ensure("llfile_test.dat should not be a file", !LLFile::isfile(testfile1.string())); + ensure("llfile_test.dat should not be a directory", !LLFile::isdir(testfile1.string())); + ensure("llfile_test.dat should not be a symlink", !LLFile::islink(testfile1.string())); + + rc = LLFile::remove(testdir.string()); + ensure("LLFile::remove() for directory llfile_test failed", rc == 0); + ensure("llfile_test should not exist anymore", !LLFile::exists(testdir.string())); + } + + template<> template<> + void llfile_test_object_t::test<2>() + { + // High level static file IO functions to read and write data files + LLFile::mkdir(testdir.string()); + ensure("llfile_test should exist", LLFile::isdir(testdir.string())); + + std::filesystem::path testfile1 = testdir; + testfile1.append("llfile_test.dat"); + + std::string testdata1("testdata"); + std::string testdata2("datateststuff"); + std::time_t current = time(nullptr); + S64 bytes = LLFile::write(testfile1.string(), testdata1.c_str(), 0, testdata1.length()); + ensure("LLFile::write() did not write correctly", bytes == testdata1.length()); + ensure("llfile_test.dat should exist", LLFile::exists(testfile1.string())); + ensure("llfile_test.dat should be a file", LLFile::isfile(testfile1.string())); + ensure("llfile_test.dat should not be a directory", !LLFile::isdir(testfile1.string())); + + bytes = LLFile::size(testfile1.string()); + ensure("LLFile::size() did not return the correct size", bytes == testdata1.length()); + + std::string data = LLFile::getContents(testfile1.string()); + ensure("LLFile::getContents() did not return the correct size data", data.length() == testdata1.length()); + ensure_memory_matches("LLFile::getContents() did not read correct data", testdata1.c_str(), (U32)testdata1.length(), data.c_str(), (U32)data.length()); + + std::time_t ctime = LLFile::getCreationTime(testfile1.string()); + ensure_approximately_equals_range("LLFile::getCreationTime() did not return correct time", (F32)(ctime - current), 0.f, 1); + + std::time_t mtime = LLFile::getModificationTime(testfile1.string()); + ensure_approximately_equals_range("LLFile::getModificationTime() did not return correct time", (F32)(mtime - current), 0.f, 1); + + char buffer[1024]; + bytes = LLFile::read(testfile1.string(), buffer, 0, testdata1.length()); + ensure("LLFile:read() did not return the correct size", bytes == testdata1.length()); + ensure_memory_matches("LLFile::read() did not read correct data", testdata1.c_str(), (U32)bytes, buffer, (U32)bytes); + + // What if we try to read more data than there is in the file? + bytes = LLFile::read(testfile1.string(), buffer, 0, bytes + 10); + ensure("LLFile:read() did not correctly stop on eof", bytes == testdata1.length()); + ensure_memory_matches("LLFile::read() did not read correct data", testdata1.c_str(), (U32)bytes, buffer, (U32)bytes); + + // Let's append more data + bytes = LLFile::write(testfile1.string(), testdata2.c_str(), -1, testdata2.length()); + ensure("LLFile::write() did not write correctly", bytes == testdata2.length()); + + bytes = LLFile::size(testfile1.string()); + ensure("LLFile::size() did not return the correct size", bytes == testdata1.length() + testdata2.length()); + bytes = LLFile::read(testfile1.string(), buffer, 0, bytes); + ensure("LLFile:read() did not read correct number of bytes", bytes == testdata1.length() + testdata2.length()); + ensure_memory_matches("LLFile:read() did not read correct testdata1", testdata1.c_str(), (U32)testdata1.length(), buffer, (U32)testdata1.length()); + ensure_memory_matches("LLFile:read() did not read correct testdata2", testdata2.c_str(), (U32)testdata2.length(), buffer + testdata1.length(), (U32)testdata2.length()); + } + + template<> template<> + void llfile_test_object_t::test<3>() + { + const size_t numints = 1024; + + // Testing the LLFile class implementation + std::filesystem::path testfile = testdir; + testfile.append("llfile_test.bin"); + + int data[numints]; + for (int &t : data) + { + t = rand(); + } + + std::error_code ec; + LLFile fileout(testfile.string(), LLFile::out, ec); + ensure("LLFile constructor did not open correctly", (bool)fileout); + ensure("error_code from LLFile constructor should not indicate an error", !ec); + if (fileout) + { + S64 length = fileout.size(ec); + ensure("freshly created file should be empty", length == 0); + ensure("error_code from LLFile::size() should not indicate an error", !ec); + S64 bytes = fileout.write(data, sizeof(data), ec); + ensure("LLFile::write() did not write correctly", bytes == sizeof(data)); + ensure("error_code from LLFile::write() should not indicate an error", !ec); + bytes = fileout.write(data, sizeof(data), ec); + ensure("LLFile::write() did not write correctly", bytes == sizeof(data)); + ensure("error_code from LLFile::write() should not indicate an error", !ec); + bytes = fileout.size(ec); + ensure("LLFile::size() returned wrong size", bytes == 2 * sizeof(data)); + ensure("error_code from LLFile::size() should not indicate an error", !ec); + fileout.close(); + } + + LLFile filein(testfile.string(), LLFile::in, ec); + ensure("LLFile constructor did not open correctly", (bool)filein); + ensure("error_code from LLFile constructor should not indicate an error", !ec); + if (filein) + { + S64 length = filein.size(ec); + ensure("LLFile::size() returned wrong size", length == 2 * sizeof(data)); + ensure("error_code from LLFile::size() should not indicate an error", !ec); + char* buffer = (char*)malloc(length); + S64 bytes = filein.read(buffer, length, ec); + ensure("LLFile::read() did not read correctly", bytes == length); + ensure("error_code from LLFile::read() should not indicate an error", !ec); + ensure_memory_matches("LLFile:read() did not read correct data1", data, (U32)sizeof(data), buffer, (U32)sizeof(data)); + ensure_memory_matches("LLFile:read() did not read correct data2", data, (U32)sizeof(data), buffer + sizeof(data), (U32)sizeof(data)); + S64 offset = filein.tell(ec); + ensure("LLFile::tell() returned a bad offset", offset == length); + ensure("error_code from LLFile::read() should not indicate an error", !ec); + offset = sizeof(data) / 2; + int rc = filein.seek(offset, ec); + ensure("LLFile::seek() indicated an error", rc == 0); + ensure("error_code from LLFile::seek() should not indicate an error", !ec); + bytes = filein.read(buffer, 2 * sizeof(data), ec); + ensure("LLFile::read() did not read correctly", bytes == sizeof(data) + offset); + ensure("error_code from LLFile::read() should not indicate an error", !ec); + ensure_memory_matches("LLFile:read() did not read correct data3", (char*)data + offset, (U32)offset, buffer, (U32)offset); + ensure_memory_matches("LLFile:read() did not read correct data4", (char*)data, (U32)sizeof(data), buffer + offset, (U32)sizeof(data)); + filein.close(); + + free(buffer); + } + } + + template<> template<> + void llfile_test_object_t::test<4>() + { + // Testing the LLFile class implementation with wrong paths and parameters + std::filesystem::path testfile = testdir; + testfile.append("llfile_test.bin"); + + std::error_code ec; + LLFile file(testfile.string(), LLFile::out | LLFile::noreplace, ec); + ensure("LLFile constructor should not have opened the already existing file", !file); + ensure("error_code from LLFile constructor should indicate an error", (bool)ec); + + LLFile::remove(testfile.string()); + file = LLFile(testfile.string(), LLFile::out | LLFile::app | LLFile::trunc, ec); + ensure("LLFile constructor should not have opened the file with conflicting flags", !file); + ensure("error_code from LLFile constructor should indicate an error", (bool)ec); + + file = LLFile(testfile.string(), LLFile::out | LLFile::app | LLFile::noreplace, ec); + ensure("LLFile constructor should not have opened the file with conflicting flags", !file); + ensure("error_code from LLFile constructor should indicate an error", (bool)ec); + + testfile = testdir; + testfile.append("llfile_test"); + testfile.append("llfile_test.bin"); + + file = LLFile(testfile.string(), LLFile::in, ec); + ensure("LLFile constructor should not have been able to open the file in the non-existing directory", !file); + ensure("error_code from LLFile constructor should indicate an error", (bool)ec); + } +} // namespace tut diff --git a/indra/llfilesystem/lldir.cpp b/indra/llfilesystem/lldir.cpp old mode 100644 new mode 100755 index 190539cea5..eb3c2d9909 --- a/indra/llfilesystem/lldir.cpp +++ b/indra/llfilesystem/lldir.cpp @@ -30,8 +30,6 @@ #include #include #include -#else -#include #endif #include "lldir.h" @@ -43,7 +41,6 @@ #include "lldiriterator.h" #include "stringize.h" #include "llstring.h" -#include #include #include @@ -93,30 +90,20 @@ LLDir::~LLDir() std::vector LLDir::getFilesInDir(const std::string &dirname) { - //Returns a vector of fullpath filenames. - -#ifdef LL_WINDOWS // or BOOST_WINDOWS_API - boost::filesystem::path p(ll_convert(dirname)); -#else - boost::filesystem::path p(dirname); -#endif - + // Returns a vector of filenames in the directory. + std::filesystem::path p = LLFile::utf8StringToPath(dirname); std::vector v; - - boost::system::error_code ec; - if (exists(p, ec) && !ec.failed()) + std::error_code ec; + if (std::filesystem::is_directory(p, ec)) { - if (is_directory(p, ec) && !ec.failed()) + std::filesystem::directory_iterator end_iter; + for (std::filesystem::directory_iterator dir_itr(p); + dir_itr != end_iter; + ++dir_itr) { - boost::filesystem::directory_iterator end_iter; - for (boost::filesystem::directory_iterator dir_itr(p); - dir_itr != end_iter; - ++dir_itr) + if (std::filesystem::is_regular_file(dir_itr->status())) { - if (boost::filesystem::is_regular_file(dir_itr->status())) - { - v.push_back(dir_itr->path().filename().string()); - } + v.push_back(dir_itr->path().filename().string()); } } } @@ -186,28 +173,23 @@ U32 LLDir::deleteDirAndContents(const std::string& dir_name) //Removes the directory and its contents. Returns number of files deleted. U32 num_deleted = 0; + std::filesystem::path dir_path = LLFile::utf8StringToPath(dir_name); try { -#ifdef LL_WINDOWS // or BOOST_WINDOWS_API - boost::filesystem::path dir_path(ll_convert(dir_name)); -#else - boost::filesystem::path dir_path(dir_name); -#endif - - if (boost::filesystem::exists(dir_path)) + if (std::filesystem::is_directory(dir_path)) { - if (!boost::filesystem::is_empty(dir_path)) + if (!std::filesystem::is_empty(dir_path)) { // Directory has content - num_deleted = (U32)boost::filesystem::remove_all(dir_path); + num_deleted = (U32)std::filesystem::remove_all(dir_path); } else { // Directory is empty - boost::filesystem::remove(dir_path); + std::filesystem::remove(dir_path); } } } - catch (boost::filesystem::filesystem_error &er) + catch (std::filesystem::filesystem_error &er) { LL_WARNS() << "Failed to delete " << dir_name << " with error " << er.code().message() << LL_ENDL; } @@ -1105,15 +1087,15 @@ void dir_exists_or_crash(const std::string &dir_name) #if LL_WINDOWS // *FIX: lame - it doesn't do the same thing on windows. not so // important since we don't deploy simulator to windows boxes. - LLFile::mkdir(dir_name, 0700); + LLFile::mkdir(dir_name); #else - struct stat dir_stat; + llstat dir_stat; if(0 != LLFile::stat(dir_name, &dir_stat)) { S32 stat_rv = errno; if(ENOENT == stat_rv) { - if(0 != LLFile::mkdir(dir_name, 0700)) // octal + if(0 != LLFile::mkdir(dir_name)) { LL_ERRS() << "Unable to create directory: " << dir_name << LL_ENDL; } diff --git a/indra/llfilesystem/lldir_win32.cpp b/indra/llfilesystem/lldir_win32.cpp old mode 100644 new mode 100755 index 9624b1197f..1cfa157634 --- a/indra/llfilesystem/lldir_win32.cpp +++ b/indra/llfilesystem/lldir_win32.cpp @@ -376,18 +376,7 @@ std::string LLDir_Win32::getCurPath() bool LLDir_Win32::fileExists(const std::string &filename) const { - llstat stat_data; - // Check the age of the file - // Now, we see if the files we've gathered are recent... - int res = LLFile::stat(filename, &stat_data); - if (!res) - { - return true; - } - else - { - return false; - } + return LLFile::exists(filename); } diff --git a/indra/llfilesystem/llfilesystem.cpp b/indra/llfilesystem/llfilesystem.cpp old mode 100644 new mode 100755 index 541266af4f..0c220fe7cf --- a/indra/llfilesystem/llfilesystem.cpp +++ b/indra/llfilesystem/llfilesystem.cpp @@ -77,21 +77,17 @@ bool LLFileSystem::getExists(const LLUUID& file_id, const LLAssetType::EType fil LL_PROFILE_ZONE_SCOPED; const std::string filename = LLDiskCache::metaDataToFilepath(file_id, file_type); - llifstream file(filename, std::ios::binary); - if (file.is_open()) - { - file.seekg(0, std::ios::end); - return file.tellg() > 0; - } - return false; + // not only test for existence but for the file to be not empty + S64 size = LLFile::size(filename); + return size > 0; } // static -bool LLFileSystem::removeFile(const LLUUID& file_id, const LLAssetType::EType file_type, int suppress_error /*= 0*/) +bool LLFileSystem::removeFile(const LLUUID& file_id, const LLAssetType::EType file_type, int suppress_warning /*= 0*/) { const std::string filename = LLDiskCache::metaDataToFilepath(file_id, file_type); - LLFile::remove(filename.c_str(), suppress_error); + LLFile::remove(filename.c_str(), suppress_warning); return true; } @@ -116,19 +112,10 @@ bool LLFileSystem::renameFile(const LLUUID& old_file_id, const LLAssetType::ETyp } // static -S32 LLFileSystem::getFileSize(const LLUUID& file_id, const LLAssetType::EType file_type) +S64 LLFileSystem::getFileSize(const LLUUID& file_id, const LLAssetType::EType file_type) { const std::string filename = LLDiskCache::metaDataToFilepath(file_id, file_type); - - S32 file_size = 0; - llifstream file(filename, std::ios::binary); - if (file.is_open()) - { - file.seekg(0, std::ios::end); - file_size = (S32)file.tellg(); - } - - return file_size; + return LLFile::size(filename); } bool LLFileSystem::read(U8* buffer, S32 bytes) @@ -269,7 +256,7 @@ S32 LLFileSystem::tell() const S32 LLFileSystem::getSize() const { - return LLFileSystem::getFileSize(mFileID, mFileType); + return (S32)LLFileSystem::getFileSize(mFileID, mFileType); } S32 LLFileSystem::getMaxSize() const diff --git a/indra/llfilesystem/llfilesystem.h b/indra/llfilesystem/llfilesystem.h index 10649b6920..7188683e7f 100644 --- a/indra/llfilesystem/llfilesystem.h +++ b/indra/llfilesystem/llfilesystem.h @@ -61,10 +61,10 @@ class LLFileSystem void updateFileAccessTime(const std::string& file_path); static bool getExists(const LLUUID& file_id, const LLAssetType::EType file_type); - static bool removeFile(const LLUUID& file_id, const LLAssetType::EType file_type, int suppress_error = 0); + static bool removeFile(const LLUUID& file_id, const LLAssetType::EType file_type, int suppress_warning = 0); static bool renameFile(const LLUUID& old_file_id, const LLAssetType::EType old_file_type, const LLUUID& new_file_id, const LLAssetType::EType new_file_type); - static S32 getFileSize(const LLUUID& file_id, const LLAssetType::EType file_type); + static S64 getFileSize(const LLUUID& file_id, const LLAssetType::EType file_type); public: static const S32 READ; diff --git a/indra/llfilesystem/tests/lldir_test.cpp b/indra/llfilesystem/tests/lldir_test.cpp old mode 100644 new mode 100755 index a2104d1ef9..8b86da40b3 --- a/indra/llfilesystem/tests/lldir_test.cpp +++ b/indra/llfilesystem/tests/lldir_test.cpp @@ -557,8 +557,8 @@ namespace tut LLFile::remove(dir1files[i]); LLFile::remove(dir2files[i]); } - LLFile::rmdir(dir1); - LLFile::rmdir(dir2); + LLFile::remove(dir1); + LLFile::remove(dir2); } template<> template<> diff --git a/indra/llmessage/llassetstorage.cpp b/indra/llmessage/llassetstorage.cpp index 10fd56a68e..34eeacb273 100644 --- a/indra/llmessage/llassetstorage.cpp +++ b/indra/llmessage/llassetstorage.cpp @@ -467,7 +467,7 @@ bool LLAssetStorage::findInCacheAndInvokeCallback(const LLUUID& uuid, LLAssetTyp else { LL_WARNS("AssetStorage") << "Asset vfile " << uuid << ":" << type - << " found in static cache with bad size " << file.getSize() << ", ignoring" << LL_ENDL; + << " found in static cache with bad size " << size << ", ignoring" << LL_ENDL; } } return false; diff --git a/indra/llmessage/tests/llmessageconfig_test.cpp b/indra/llmessage/tests/llmessageconfig_test.cpp old mode 100644 new mode 100755 index 93443467a2..b8942e99b3 --- a/indra/llmessage/tests/llmessageconfig_test.cpp +++ b/indra/llmessage/tests/llmessageconfig_test.cpp @@ -62,7 +62,7 @@ namespace tut int rmfile = LLFile::remove((mTestConfigDir + "/message.xml")); ensure_equals("rmfile value", rmfile, 0); // rm temp dir - int rmdir = LLFile::rmdir(mTestConfigDir); + int rmdir = LLFile::remove(mTestConfigDir); ensure_equals("rmdir value", rmdir, 0); } diff --git a/indra/llmessage/tests/message_test.cpp b/indra/llmessage/tests/message_test.cpp old mode 100644 new mode 100755 index 11cd710ef6..6fb2b92803 --- a/indra/llmessage/tests/message_test.cpp +++ b/indra/llmessage/tests/message_test.cpp @@ -113,7 +113,7 @@ namespace tut ensure_equals("rmfile value", rmfile, 0); // rm temp dir - int rmdir = LLFile::rmdir(mTestConfigDir); + int rmdir = LLFile::remove(mTestConfigDir); ensure_equals("rmdir value", rmdir, 0); } diff --git a/indra/llrender/llshadermgr.cpp b/indra/llrender/llshadermgr.cpp index 1da71e6bf4..7e8d31232b 100644 --- a/indra/llrender/llshadermgr.cpp +++ b/indra/llrender/llshadermgr.cpp @@ -1014,7 +1014,6 @@ void LLShaderMgr::initShaderCache(bool enabled, const LLUUID& old_cache_version, mShaderCacheDir = gDirUtilp->getExpandedFilename(LL_PATH_CACHE, "shader_cache"); LLFile::mkdir(mShaderCacheDir); - { std::string meta_out_path = gDirUtilp->add(mShaderCacheDir, "shaderdata.llsd"); if (gDirUtilp->fileExists(meta_out_path)) @@ -1077,7 +1076,7 @@ void LLShaderMgr::persistShaderCacheMetadata() // Settings and shader cache get saved at different time, thus making // RenderShaderCacheVersion unreliable when running multiple viewer // instances, or for cases where viewer crashes before saving settings. - // Dupplicate version to the cache itself. + // Duplicate version to the cache itself. out["version"] = mShaderCacheVersion; out["shaders"] = LLSD::emptyMap(); LLSD &shaders = out["shaders"]; @@ -1130,11 +1129,11 @@ bool LLShaderMgr::loadCachedProgramBinary(LLGLSLShader* shader) { std::vector in_data; in_data.resize(shader_info.mBinaryLength); - - LLUniqueFile filep = LLFile::fopen(in_path, "rb"); - if (filep) + std::error_code ec; + LLFile filep = LLFile(in_path, LLFile::in | LLFile::binary, ec); + if (!ec && (bool)filep) { - size_t result = fread(in_data.data(), sizeof(U8), in_data.size(), filep); + size_t result = filep.read(in_data.data(), in_data.size(), ec); filep.close(); if (result == in_data.size()) @@ -1179,11 +1178,12 @@ bool LLShaderMgr::saveCachedProgramBinary(LLGLSLShader* shader) if (error == GL_NO_ERROR) { std::string out_path = gDirUtilp->add(mShaderCacheDir, shader->mShaderHash.asString() + ".shaderbin"); - LLUniqueFile outfile = LLFile::fopen(out_path, "wb"); - if (outfile) + std::error_code ec; + LLFile filep = LLFile(out_path, LLFile::out | LLFile::binary, ec); + if (filep) { - fwrite(program_binary.data(), sizeof(U8), program_binary.size(), outfile); - outfile.close(); + filep.write(program_binary.data(), program_binary.size(), ec); + filep.close(); binary_info.mLastUsedTime = (F32)LLTimer::getTotalSeconds(); diff --git a/indra/llxml/tests/llcontrol_test.cpp b/indra/llxml/tests/llcontrol_test.cpp old mode 100644 new mode 100755 index 4192e029c5..e15117fc29 --- a/indra/llxml/tests/llcontrol_test.cpp +++ b/indra/llxml/tests/llcontrol_test.cpp @@ -69,7 +69,7 @@ namespace tut LLFile::remove(filename); } LLFile::remove(mTestConfigFile); - LLFile::rmdir(mTestConfigDir); + LLFile::remove(mTestConfigDir); } void writeSettingsFile(const LLSD& config) { diff --git a/indra/newview/llappviewer.cpp b/indra/newview/llappviewer.cpp old mode 100644 new mode 100755 index ea380896ca..6058973176 --- a/indra/newview/llappviewer.cpp +++ b/indra/newview/llappviewer.cpp @@ -2267,7 +2267,7 @@ void errorCallback(LLError::ELevel level, const std::string &error_string) LLAppViewer::instance()->writeDebugInfo(); std::string error_marker_file = gDirUtilp->getExpandedFilename(LL_PATH_LOGS, ERROR_MARKER_FILE_NAME); - if (!LLAPRFile::isExist(error_marker_file, NULL, LL_APR_RB)) + if (!LLFile::isfile(error_marker_file)) { // If marker doesn't exist, create a marker with llerror code for next launch // otherwise don't override existing file @@ -3030,13 +3030,11 @@ void LLAppViewer::initStrings() } else { - llstat st; - int rc = LLFile::stat(strings_path_full, &st); - if (rc != 0) + if (!LLFile::exists(strings_path_full)) { - crash_reason = "The file '" + strings_path_full + "' failed to get status. Error code: " + std::to_string(rc); + crash_reason = "The file '" + strings_path_full + "' doesn't seem to exist"; } - else if (S_ISDIR(st.st_mode)) + else if (LLFile::isdir(strings_path_full)) { crash_reason = "The filename '" + strings_path_full + "' is a directory name"; } @@ -3891,7 +3889,7 @@ void LLAppViewer::processMarkerFiles() bool marker_is_same_version = true; // first, look for the marker created at startup and deleted on a clean exit mMarkerFileName = gDirUtilp->getExpandedFilename(LL_PATH_LOGS,MARKER_FILE_NAME); - if (LLAPRFile::isExist(mMarkerFileName, NULL, LL_APR_RB)) + if (LLFile::isfile(mMarkerFileName)) { // File exists... // first, read it to see if it was created by the same version (we need this later) @@ -3983,7 +3981,7 @@ void LLAppViewer::processMarkerFiles() // check for any last exec event report based on whether or not it happened during logout // (the logout marker is created when logout begins) std::string logout_marker_file = gDirUtilp->getExpandedFilename(LL_PATH_LOGS, LOGOUT_MARKER_FILE_NAME); - if(LLAPRFile::isExist(logout_marker_file, NULL, LL_APR_RB)) + if(LLFile::isfile(logout_marker_file)) { if (markerIsSameVersion(logout_marker_file)) { @@ -3995,11 +3993,11 @@ void LLAppViewer::processMarkerFiles() { LL_INFOS("MarkerFile") << "Logout crash marker '"<< logout_marker_file << "' found, but versions did not match" << LL_ENDL; } - LLAPRFile::remove(logout_marker_file); + LLFile::remove(logout_marker_file); } // and last refine based on whether or not a marker created during a non-llerr crash is found std::string error_marker_file = gDirUtilp->getExpandedFilename(LL_PATH_LOGS, ERROR_MARKER_FILE_NAME); - if(LLAPRFile::isExist(error_marker_file, NULL, LL_APR_RB)) + if(LLFile::isfile(error_marker_file)) { S32 marker_code = getMarkerErrorCode(error_marker_file); if (marker_code >= 0) @@ -4024,7 +4022,7 @@ void LLAppViewer::processMarkerFiles() { LL_INFOS("MarkerFile") << "Error marker '"<< error_marker_file << "' marker found, but versions did not match" << LL_ENDL; } - LLAPRFile::remove(error_marker_file); + LLFile::remove(error_marker_file); } #if LL_DARWIN @@ -4051,7 +4049,7 @@ void LLAppViewer::removeMarkerFiles() if (mMarkerFile.getFileHandle()) { mMarkerFile.close() ; - LLAPRFile::remove( mMarkerFileName ); + LLFile::remove( mMarkerFileName ); LL_DEBUGS("MarkerFile") << "removed exec marker '"<getExpandedFilename(LL_PATH_LOGS, ERROR_MARKER_FILE_NAME); - return LLAPRFile::isExist(error_marker_file, NULL, LL_APR_RB); + return LLFile::isfile(error_marker_file); } void LLAppViewer::outOfMemorySoftQuit() diff --git a/indra/newview/llfloaterpreference.cpp b/indra/newview/llfloaterpreference.cpp old mode 100644 new mode 100755 index 425e9e2269..4fa14a199d --- a/indra/newview/llfloaterpreference.cpp +++ b/indra/newview/llfloaterpreference.cpp @@ -1500,7 +1500,7 @@ bool LLFloaterPreference::moveTranscriptsAndLog() //Couldn't move the log and created a new directory so remove the new directory if(madeDirectory) { - LLFile::rmdir(chatLogPath); + LLFile::remove(chatLogPath); } return false; } @@ -1526,7 +1526,7 @@ bool LLFloaterPreference::moveTranscriptsAndLog() if(madeDirectory) { - LLFile::rmdir(chatLogPath); + LLFile::remove(chatLogPath); } return false; @@ -2031,17 +2031,15 @@ void LLFloaterPreference::changed() { if (LLConversationLog::instance().getIsLoggingEnabled()) { - getChild("clear_log")->setEnabled(LLConversationLog::instance().getConversations().size() > 0); + getChild("clear_log")->setEnabled(LLConversationLog::instance().getConversations().size() > 0); } else { // onClearLog clears list, then notifies changed() and only then clears file, // so check presence of conversations before checking file, file will cleared later. - llstat st; bool has_logs = LLConversationLog::instance().getConversations().size() > 0 - && LLFile::stat(LLConversationLog::instance().getFileName(), &st) == 0 - && S_ISREG(st.st_mode) - && st.st_size > 0; + && LLFile::isfile(LLConversationLog::instance().getFileName()) + && LLFile::size(LLConversationLog::instance().getFileName()) > 0; getChild("clear_log")->setEnabled(has_logs); } diff --git a/indra/newview/llfloateruipreview.cpp b/indra/newview/llfloateruipreview.cpp old mode 100644 new mode 100755 index c3bc24c6b9..0bf0946c42 --- a/indra/newview/llfloateruipreview.cpp +++ b/indra/newview/llfloateruipreview.cpp @@ -484,47 +484,47 @@ bool LLFloaterUIPreview::postBuild() bool found_en_us = false; std::string language_directory; std::string xui_dir = get_xui_dir(); // directory containing localizations -- don't forget trailing delim - mLanguageSelection->removeall(); // clear out anything temporarily in list from XML + mLanguageSelection->removeall(); // clear out anything temporarily in list from XML LLDirIterator iter(xui_dir, "*"); - while(found) // for every directory + while (found) // for every directory { - if((found = iter.next(language_directory))) // get next directory + if ((found = iter.next(language_directory))) // get next directory { std::string full_path = gDirUtilp->add(xui_dir, language_directory); - if(LLFile::isfile(full_path.c_str())) // if it's not a directory, skip it + if (!LLFile::isdir(full_path.c_str())) // if it's not a directory, skip it { continue; } - if(strncmp("template",language_directory.c_str(),8) && -1 == language_directory.find(".")) // if it's not the template directory or a hidden directory + if (strncmp("template",language_directory.c_str(), 8) && -1 == language_directory.find(".")) // if it's not the template directory or a hidden directory { - if(!strncmp("en",language_directory.c_str(),5)) // remember if we've seen en, so we can make it default + if (!strncmp("en",language_directory.c_str(), 5)) // remember if we've seen en, so we can make it default { found_en_us = true; } else { - mLanguageSelection->add(std::string(language_directory)); // add it to the language selection dropdown menu + mLanguageSelection->add(std::string(language_directory)); // add it to the language selection dropdown menu mLanguageSelection_2->add(std::string(language_directory)); } } } } - if(found_en_us) + if (found_en_us) { - mLanguageSelection->add(std::string("en"),ADD_TOP); // make en first item if we found it - mLanguageSelection_2->add(std::string("en"),ADD_TOP); + mLanguageSelection->add(std::string("en"), ADD_TOP); // make en first item if we found it + mLanguageSelection_2->add(std::string("en"), ADD_TOP); } else { std::string warning = std::string("No EN localization found; check your XUI directories!"); popupAndPrintWarning(warning); } - mLanguageSelection->selectFirstItem(); // select the first item + mLanguageSelection->selectFirstItem(); // select the first item mLanguageSelection_2->selectFirstItem(); - refreshList(); // refresh the list of available floaters + refreshList(); // refresh the list of available floaters return true; } @@ -892,8 +892,7 @@ void LLFloaterUIPreview::displayFloater(bool click, S32 ID) // Add localization to title so user knows whether it's localized or defaulted to en std::string full_path = getLocalizedDirectory() + path; std::string floater_lang = "EN"; - llstat dummy; - if(!LLFile::stat(full_path.c_str(), &dummy)) // if the file does not exist + if (LLFile::isfile(full_path.c_str())) // use localized language if the file exists { floater_lang = getLocStr(ID); } @@ -966,9 +965,8 @@ void LLFloaterUIPreview::onClickEditFloater() } file_path = getLocalizedDirectory() + file_name; - // stat file to see if it exists (some localized versions may not have it there are no diffs, and then we try to open an nonexistent file) - llstat dummy; - if(LLFile::stat(file_path.c_str(), &dummy)) // if the file does not exist + // Does it exist? (Some localized versions may not have it when there are no diffs, and then we try to open a nonexistent file) + if (!LLFile::isfile(file_path.c_str())) // if the file does not exist { popupAndPrintWarning("No file for this floater exists in the selected localization. Opening the EN version instead."); file_path = get_xui_dir() + mDelim + "en" + mDelim + file_name; // open the en version instead, by default @@ -1117,15 +1115,14 @@ void LLFloaterUIPreview::onClickToggleDiffHighlighting() std::string path_in_textfield = mDiffPathTextBox->getText(); // get file path bool error = false; - if(std::string("") == path_in_textfield) // check for blank file + if(std::string("") == path_in_textfield) // check for blank file { std::string warning = "Unable to highlight differences because no file was provided; fill in the relevant text field"; popupAndPrintWarning(warning); error = true; } - llstat dummy; - if(LLFile::stat(path_in_textfield.c_str(), &dummy) && !error) // check if the file exists (empty check is reduntant but useful for the informative error message) + if (!LLFile::isfile(path_in_textfield.c_str()) && !error) // check if the file exists (empty check is redundant but useful for the informative error message) { std::string warning = std::string("Unable to highlight differences because an invalid path to a difference file was provided:\"") + path_in_textfield + "\""; popupAndPrintWarning(warning); diff --git a/indra/newview/llpreviewnotecard.cpp b/indra/newview/llpreviewnotecard.cpp old mode 100644 new mode 100755 index 9a991727b2..4fe661b055 --- a/indra/newview/llpreviewnotecard.cpp +++ b/indra/newview/llpreviewnotecard.cpp @@ -575,8 +575,7 @@ void LLPreviewNotecard::syncExternal() { // Sync with external editor. std::string tmp_file = getTmpFileName(); - llstat s; - if (LLFile::stat(tmp_file, &s) == 0) // file exists + if (LLFile::isfile(tmp_file)) // file exists { if (mLiveFile) mLiveFile->ignoreNextUpdate(); writeToFile(tmp_file); diff --git a/indra/newview/llpreviewscript.cpp b/indra/newview/llpreviewscript.cpp old mode 100644 new mode 100755 index c2aa4925bd..2c436198e3 --- a/indra/newview/llpreviewscript.cpp +++ b/indra/newview/llpreviewscript.cpp @@ -694,8 +694,7 @@ void LLScriptEdCore::sync() if (mLiveFile) { std::string tmp_file = mLiveFile->filename(); - llstat s; - if (LLFile::stat(tmp_file, &s) == 0) // file exists + if (LLFile::isfile(tmp_file)) // file exists { mLiveFile->ignoreNextUpdate(); writeToFile(tmp_file); diff --git a/indra/newview/lltexturecache.cpp b/indra/newview/lltexturecache.cpp old mode 100644 new mode 100755 index 612af0d147..be6c71ab86 --- a/indra/newview/lltexturecache.cpp +++ b/indra/newview/lltexturecache.cpp @@ -180,8 +180,7 @@ private: bool LLTextureCacheLocalFileWorker::doRead() { LL_PROFILE_ZONE_SCOPED_CATEGORY_TEXTURE; - S32 local_size = LLAPRFile::size(mFileName, mCache->getLocalAPRFilePool()); - + S32 local_size = (S32)LLFile::size(mFileName); if (local_size > 0 && mFileName.size() > 4) { mDataSize = local_size; // Only a complete file is valid @@ -210,8 +209,7 @@ bool LLTextureCacheLocalFileWorker::doRead() } mReadData = (U8*)ll_aligned_malloc_16(mDataSize); - S32 bytes_read = LLAPRFile::readEx(mFileName, mReadData, mOffset, mDataSize, mCache->getLocalAPRFilePool()); - + S32 bytes_read = (S32)LLFile::read(mFileName, mReadData, mOffset, mDataSize); if (bytes_read != mDataSize) { // LL_WARNS() << "Error reading file from local cache: " << mFileName @@ -296,7 +294,7 @@ bool LLTextureCacheRemoteWorker::doRead() // Is it a JPEG2000 file? { local_filename = filename + ".j2c"; - local_size = LLAPRFile::size(local_filename, mCache->getLocalAPRFilePool()); + local_size = (S32)LLFile::size(local_filename); if (local_size > 0) { mImageFormat = IMG_CODEC_J2C; @@ -306,7 +304,7 @@ bool LLTextureCacheRemoteWorker::doRead() if (local_size == 0) { local_filename = filename + ".jpg"; - local_size = LLAPRFile::size(local_filename, mCache->getLocalAPRFilePool()); + local_size = (S32)LLFile::size(local_filename); if (local_size > 0) { mImageFormat = IMG_CODEC_JPEG; @@ -317,7 +315,7 @@ bool LLTextureCacheRemoteWorker::doRead() if (local_size == 0) { local_filename = filename + ".tga"; - local_size = LLAPRFile::size(local_filename, mCache->getLocalAPRFilePool()); + local_size = (S32)LLFile::size(local_filename); if (local_size > 0) { mImageFormat = IMG_CODEC_TGA; @@ -346,12 +344,10 @@ bool LLTextureCacheRemoteWorker::doRead() if (mReadData) { - S32 bytes_read = LLAPRFile::readEx( local_filename, - mReadData, - mOffset, - mDataSize, - mCache->getLocalAPRFilePool()); - + S32 bytes_read = (S32)LLFile::read(local_filename, + mReadData, + mOffset, + mDataSize); if (bytes_read != mDataSize) { LL_WARNS() << "Error reading file from local cache: " << local_filename @@ -410,8 +406,7 @@ bool LLTextureCacheRemoteWorker::doRead() mReadData = (U8*)ll_aligned_malloc_16(size); if (mReadData) { - S32 bytes_read = LLAPRFile::readEx(mCache->mHeaderDataFileName, - mReadData, offset, size, mCache->getLocalAPRFilePool()); + S32 bytes_read = (S32)LLFile::read(mCache->mHeaderDataFileName, mReadData, offset, size); if (bytes_read != size) { LL_WARNS() << "LLTextureCacheWorker: " << mID @@ -446,9 +441,9 @@ bool LLTextureCacheRemoteWorker::doRead() if (!done && (mState == BODY)) { std::string filename = mCache->getTextureFileName(mID); - S32 filesize = LLAPRFile::size(filename, mCache->getLocalAPRFilePool()); + S32 filesize = (S32)LLFile::size(filename); - if (filesize && (filesize + TEXTURE_CACHE_ENTRY_SIZE) > mOffset) + if (filesize > 0 && (filesize + TEXTURE_CACHE_ENTRY_SIZE) > mOffset) { S32 max_datasize = TEXTURE_CACHE_ENTRY_SIZE + filesize - mOffset; mDataSize = llmin(max_datasize, mDataSize); @@ -487,10 +482,9 @@ bool LLTextureCacheRemoteWorker::doRead() mReadData = data; // Read the data at last - S32 bytes_read = LLAPRFile::readEx(filename, - mReadData + data_offset, - file_offset, file_size, - mCache->getLocalAPRFilePool()); + S32 bytes_read = (S32)LLFile::read(filename, + mReadData + data_offset, + file_offset, file_size); if (bytes_read != file_size) { LL_WARNS() << "LLTextureCacheWorker: " << mID @@ -636,13 +630,13 @@ bool LLTextureCacheRemoteWorker::doWrite() U8* padBuffer = (U8*)ll_aligned_malloc_16(TEXTURE_CACHE_ENTRY_SIZE); memset(padBuffer, 0, TEXTURE_CACHE_ENTRY_SIZE); // Init with zeros memcpy(padBuffer, mWriteData, mDataSize); // Copy the write buffer - bytes_written = LLAPRFile::writeEx(mCache->mHeaderDataFileName, padBuffer, offset, size, mCache->getLocalAPRFilePool()); + bytes_written = (S32)LLFile::write(mCache->mHeaderDataFileName, padBuffer, offset, size); ll_aligned_free_16(padBuffer); } else { // Write the header record (== first TEXTURE_CACHE_ENTRY_SIZE bytes of the raw file) in the header file - bytes_written = LLAPRFile::writeEx(mCache->mHeaderDataFileName, mWriteData, offset, size, mCache->getLocalAPRFilePool()); + bytes_written = (S32)LLFile::write(mCache->mHeaderDataFileName, mWriteData, offset, size); } if (bytes_written <= 0) @@ -678,15 +672,11 @@ bool LLTextureCacheRemoteWorker::doWrite() else { S32 file_size = mDataSize - TEXTURE_CACHE_ENTRY_SIZE; - { // build the cache file name from the UUID std::string filename = mCache->getTextureFileName(mID); // LL_INFOS() << "Writing Body: " << filename << " Bytes: " << file_offset+file_size << LL_ENDL; - S32 bytes_written = LLAPRFile::writeEx(filename, - mWriteData + TEXTURE_CACHE_ENTRY_SIZE, - 0, file_size, - mCache->getLocalAPRFilePool()); + S32 bytes_written = (S32)LLFile::write(filename, mWriteData + TEXTURE_CACHE_ENTRY_SIZE, 0, file_size); if (bytes_written <= 0) { LL_WARNS() << "LLTextureCacheWorker: " << mID @@ -891,7 +881,7 @@ bool LLTextureCache::isInLocal(const LLUUID& id) // Is it a JPEG2000 file? { local_filename = filename + ".j2c"; - local_size = LLAPRFile::size(local_filename, getLocalAPRFilePool()); + local_size = (S32)LLFile::size(local_filename); if (local_size > 0) { return true ; @@ -901,7 +891,7 @@ bool LLTextureCache::isInLocal(const LLUUID& id) // If not, is it a jpeg file? { local_filename = filename + ".jpg"; - local_size = LLAPRFile::size(local_filename, getLocalAPRFilePool()); + local_size = (S32)LLFile::size(local_filename); if (local_size > 0) { return true ; @@ -911,7 +901,7 @@ bool LLTextureCache::isInLocal(const LLUUID& id) // Hmm... What about a targa file? (used for UI texture mostly) { local_filename = filename + ".tga"; - local_size = LLAPRFile::size(local_filename, getLocalAPRFilePool()); + local_size = (S32)LLFile::size(local_filename); if (local_size > 0) { return true ; @@ -964,11 +954,10 @@ void LLTextureCache::purgeCache(ELLPath location, bool remove_dir) if(LLFile::isdir(mTexturesDirName)) { std::string file_name = gDirUtilp->getExpandedFilename(location, entries_filename); - // mHeaderAPRFilePoolp because we are under header mutex, and can be in main thread - LLAPRFile::remove(file_name, mHeaderAPRFilePoolp); + LLFile::remove(file_name); file_name = gDirUtilp->getExpandedFilename(location, cache_filename); - LLAPRFile::remove(file_name, mHeaderAPRFilePoolp); + LLFile::remove(file_name); purgeAllTextures(true); } @@ -1069,10 +1058,9 @@ void LLTextureCache::readEntriesHeader() { // mHeaderEntriesInfo initializes to default values so safe not to read it llassert_always(mHeaderAPRFile == NULL); - if (LLAPRFile::isExist(mHeaderEntriesFileName, mHeaderAPRFilePoolp)) + if (LLFile::isfile(mHeaderEntriesFileName)) { - LLAPRFile::readEx(mHeaderEntriesFileName, (U8*)&mHeaderEntriesInfo, 0, sizeof(EntriesInfo), - mHeaderAPRFilePoolp); + LLFile::read(mHeaderEntriesFileName, (U8*)&mHeaderEntriesInfo, 0, sizeof(EntriesInfo)); } else //create an empty entries header. { @@ -1088,7 +1076,7 @@ void LLTextureCache::setEntriesHeader() // For simplicity we use predefined size of header, so if version string // doesn't fit, either getEngineInfo() returned malformed string or // sHeaderEncoderStringSize need to be increased. - // Also take into accout that c_str() returns additional null character + // Also take into account that c_str() returns additional null character LL_ERRS() << "Version string doesn't fit in header" << LL_ENDL; } @@ -1103,8 +1091,7 @@ void LLTextureCache::writeEntriesHeader() llassert_always(mHeaderAPRFile == NULL); if (!mReadOnly) { - LLAPRFile::writeEx(mHeaderEntriesFileName, (U8*)&mHeaderEntriesInfo, 0, sizeof(EntriesInfo), - mHeaderAPRFilePoolp); + LLFile::write(mHeaderEntriesFileName, (U8*)&mHeaderEntriesInfo, 0, sizeof(EntriesInfo)); } } @@ -1208,8 +1195,7 @@ void LLTextureCache::writeEntryToHeaderImmediately(S32& idx, Entry& entry, bool idx = -1 ;//mark the idx invalid. return ; } - - mHeaderAPRFile->seek(APR_SET, offset); + aprfile->seek(APR_SET, offset); } else { @@ -1618,7 +1604,7 @@ void LLTextureCache::purgeAllTextures(bool purge_directories) gDirUtilp->deleteFilesInDir(mTexturesDirName, mask); // headers, fast cache if (purge_directories) { - LLFile::rmdir(mTexturesDirName); + LLFile::remove(mTexturesDirName); } } mHeaderIDMap.clear(); @@ -1798,8 +1784,7 @@ void LLTextureCache::purgeTextures(bool validate) { std::string filename = getTextureFileName(entries[idx].mID); LL_DEBUGS("TextureCache") << "Validating: " << filename << "Size: " << entries[idx].mBodySize << LL_ENDL; - // mHeaderAPRFilePoolp because this is under header mutex in main thread - S32 bodysize = LLAPRFile::size(filename, mHeaderAPRFilePoolp); + S32 bodysize = (S32)LLFile::size(filename); if (bodysize != entries[idx].mBodySize) { LL_WARNS("TextureCache") << "TEXTURE CACHE BODY HAS BAD SIZE: " << bodysize << " != " << entries[idx].mBodySize << filename << LL_ENDL; @@ -2150,7 +2135,7 @@ void LLTextureCache::openFastCache(bool first_time) mFastCachePadBuffer = (U8*)ll_aligned_malloc_16(TEXTURE_FAST_CACHE_ENTRY_SIZE); } mFastCachePoolp = new LLVolatileAPRPool(); // is_local= true by default, so not thread safe by default - if (LLAPRFile::isExist(mFastCacheFileName, mFastCachePoolp)) + if (LLFile::isfile(mFastCacheFileName)) { mFastCachep = new LLAPRFile(mFastCacheFileName, APR_READ|APR_WRITE|APR_BINARY, mFastCachePoolp) ; } @@ -2233,9 +2218,7 @@ void LLTextureCache::removeCachedTexture(const LLUUID& id) mTexturesSizeMap.erase(id); } mHeaderIDMap.erase(id); - // We are inside header's mutex so mHeaderAPRFilePoolp is safe to use, - // but getLocalAPRFilePool() is not safe, it might be in use by worker - LLAPRFile::remove(getTextureFileName(id), mHeaderAPRFilePoolp); + LLFile::remove(getTextureFileName(id)); } //called after mHeaderMutex is locked. @@ -2248,9 +2231,7 @@ void LLTextureCache::removeEntry(S32 idx, Entry& entry, std::string& filename) if (entry.mBodySize == 0) // Always attempt to remove when mBodySize > 0. { // Sanity check. Shouldn't exist when body size is 0. - // We are inside header's mutex so mHeaderAPRFilePoolp is safe to use, - // but getLocalAPRFilePool() is not safe, it might be in use by worker - if (LLAPRFile::isExist(filename, mHeaderAPRFilePoolp)) + if (LLFile::isfile(filename)) { LL_WARNS("TextureCache") << "Entry has body size of zero but file " << filename << " exists. Deleting this file, too." << LL_ENDL; } @@ -2270,7 +2251,7 @@ void LLTextureCache::removeEntry(S32 idx, Entry& entry, std::string& filename) if (file_maybe_exists) { - LLAPRFile::remove(filename, mHeaderAPRFilePoolp); + LLFile::remove(filename); } } diff --git a/indra/newview/llviewerassetstorage.cpp b/indra/newview/llviewerassetstorage.cpp index 141f370ecb..e76d340eda 100644 --- a/indra/newview/llviewerassetstorage.cpp +++ b/indra/newview/llviewerassetstorage.cpp @@ -182,7 +182,7 @@ void LLViewerAssetStorage::storeAssetData( else { // LLAssetStorage metric: Successful Request - S32 size = LLFileSystem::getFileSize(asset_id, asset_type); + S32 size = (S32)LLFileSystem::getFileSize(asset_id, asset_type); const char *message = "Added to upload queue"; reportMetric( asset_id, asset_type, LLStringUtil::null, LLUUID::null, size, MR_OKAY, __FILE__, __LINE__, message ); diff --git a/indra/newview/llviewerassetupload.cpp b/indra/newview/llviewerassetupload.cpp index 65a69acc88..5ac7d6b1fe 100644 --- a/indra/newview/llviewerassetupload.cpp +++ b/indra/newview/llviewerassetupload.cpp @@ -45,11 +45,7 @@ #include "llappviewer.h" #include "llviewerstats.h" #include "llfilesystem.h" -#include "llgesturemgr.h" -#include "llpreviewnotecard.h" -#include "llpreviewgesture.h" #include "llcoproceduremanager.h" -#include "llthread.h" #include "llkeyframemotion.h" #include "lldatapacker.h" #include "llvoavatarself.h" @@ -405,6 +401,7 @@ LLSD LLNewFileResourceUploadInfo::exportTempFile() std::string errorMessage; std::string errorLabel; + std::error_code ec; bool error = false; @@ -475,30 +472,38 @@ LLSD LLNewFileResourceUploadInfo::exportTempFile() error = true; // read from getFileName() - LLAPRFile infile; - infile.open(getFileName(),LL_APR_RB); - if (!infile.getFileHandle()) + LLFile infile(getFileName(), LLFile::in | LLFile::binary, ec); + if (ec || !infile) { LL_WARNS() << "Couldn't open file for reading: " << getFileName() << LL_ENDL; errorMessage = llformat("Failed to open animation file %s\n", getFileName().c_str()); } else { - S32 size = LLAPRFile::size(getFileName()); + S64 size = infile.size(ec); + if (ec || size <= 0) + { + LLError::LLUserWarningMsg::showMissingFiles(); + LL_ERRS() << "Invalid file" << LL_ENDL; + } + else if (size > INT_MAX) + { + LL_ERRS() << "File is too big, size: " << size << LL_ENDL; + } U8* buffer = new(std::nothrow) U8[size]; if (!buffer) { LLError::LLUserWarningMsg::showOutOfMemory(); LL_ERRS() << "Bad memory allocation for buffer, size: " << size << LL_ENDL; } - S32 size_read = infile.read(buffer,size); - if (size_read != size) + S64 size_read = infile.read(buffer, size, ec); + if (ec || size_read != size) { errorMessage = llformat("Failed to read animation file %s: wanted %d bytes, got %d\n", getFileName().c_str(), size, size_read); } else { - LLDataPackerBinaryBuffer dp(buffer, size); + LLDataPackerBinaryBuffer dp(buffer, (S32)size); LLKeyframeMotion *motionp = new LLKeyframeMotion(getAssetId()); motionp->setCharacter(gAgentAvatarp); if (motionp->deserialize(dp, getAssetId(), false)) @@ -544,18 +549,17 @@ LLSD LLNewFileResourceUploadInfo::exportTempFile() setAssetType(assetType); // copy this file into the cache for upload - S32 file_size; - LLAPRFile infile; - infile.open(filename, LL_APR_RB, NULL, &file_size); - if (infile.getFileHandle()) + LLFile infile(filename, LLFile::in | LLFile::binary, ec); + if (!ec && infile.size(ec) > 0) { LLFileSystem file(getAssetId(), assetType, LLFileSystem::APPEND); + S64 read_bytes; const S32 buf_size = 65536; U8 copy_buf[buf_size]; - while ((file_size = infile.read(copy_buf, buf_size))) + while (((read_bytes = infile.read(copy_buf, buf_size, ec))) > 0) { - file.write(copy_buf, file_size); + file.write(copy_buf, (S32)read_bytes); } } else @@ -569,7 +573,6 @@ LLSD LLNewFileResourceUploadInfo::exportTempFile() } return LLSD(); - } //========================================================================= diff --git a/indra/newview/llviewerdisplay.cpp b/indra/newview/llviewerdisplay.cpp old mode 100644 new mode 100755 index ce59e844ec..5ad3344a6e --- a/indra/newview/llviewerdisplay.cpp +++ b/indra/newview/llviewerdisplay.cpp @@ -1139,15 +1139,12 @@ std::string getProfileStatsFilename() // same second), may produce (e.g.) sec==61, but avoids collisions and // preserves chronological filename sort order. std::string name; - std::error_code ec; do { // base + missing 2-digit seconds, append ".json" // post-increment sec in case we have to try again name = stringize(base, std::setw(2), std::setfill('0'), sec++, ".json"); - } while (std::filesystem::exists(fsyspath(name), ec)); - // Ignoring ec means we might potentially return a name that does already - // exist -- but if we can't check its existence, what more can we do? + } while (LLFile::exists(fsyspath(name))); return name; } diff --git a/indra/newview/llviewermedia.cpp b/indra/newview/llviewermedia.cpp old mode 100644 new mode 100755 index 071a66209b..a8eaadc426 --- a/indra/newview/llviewermedia.cpp +++ b/indra/newview/llviewermedia.cpp @@ -1833,12 +1833,11 @@ LLPluginClassMedia* LLViewerMediaImpl::newSourceFromMediaType(std::string media_ user_data_path_cache += gDirUtilp->getDirDelimiter(); // See if the plugin executable exists - llstat s; - if(LLFile::stat(launcher_name, &s)) + if (!LLFile::isfile(launcher_name)) { LL_WARNS_ONCE("Media") << "Couldn't find launcher at " << launcher_name << LL_ENDL; } - else if(LLFile::stat(plugin_name, &s)) + else if (!LLFile::isfile(plugin_name)) { LL_WARNS_ONCE("Media") << "Couldn't find plugin at " << plugin_name << LL_ENDL; } diff --git a/indra/newview/llvocache.cpp b/indra/newview/llvocache.cpp old mode 100644 new mode 100755 index 5d456b1a19..cdc41baa88 --- a/indra/newview/llvocache.cpp +++ b/indra/newview/llvocache.cpp @@ -1250,7 +1250,7 @@ void LLVOCache::removeCache(ELLPath location, bool started) std::string cache_dir = gDirUtilp->getExpandedFilename(location, object_cache_dirname); LL_INFOS() << "Removing cache at " << cache_dir << LL_ENDL; gDirUtilp->deleteFilesInDir(cache_dir, mask); //delete all files - LLFile::rmdir(cache_dir); + LLFile::remove(cache_dir); clearCacheInMemory(); mInitialized = false; @@ -1370,7 +1370,7 @@ void LLVOCache::removeFromCache(HeaderEntryInfo* entry) std::string filename; getObjectCacheFilename(entry->mHandle, filename); LL_WARNS("GLTF", "VOCache") << "Removing object cache for handle " << entry->mHandle << "Filename: " << filename << LL_ENDL; - LLAPRFile::remove(filename, mLocalAPRFilePoolp); + LLFile::remove(filename); // Note: `removeFromCache` should take responsibility for cleaning up all cache artefacts specfic to the handle/entry. // as such this now includes the generic extras @@ -1394,7 +1394,7 @@ void LLVOCache::readCacheHeader() clearCacheInMemory(); bool success = true ; - if (LLAPRFile::isExist(mHeaderFileName, mLocalAPRFilePoolp)) + if (LLFile::isfile(mHeaderFileName)) { LLAPRFile apr_file(mHeaderFileName, APR_READ|APR_BINARY, mLocalAPRFilePoolp); diff --git a/indra/newview/llvoicevivox.cpp b/indra/newview/llvoicevivox.cpp old mode 100644 new mode 100755 index d132cbfa36..e58a6577f1 --- a/indra/newview/llvoicevivox.cpp +++ b/indra/newview/llvoicevivox.cpp @@ -943,8 +943,7 @@ bool LLVivoxVoiceClient::startAndLaunchDaemon() gDirUtilp->append(exe_path, "SLVoice"); #endif // See if the vivox executable exists - llstat s; - if (!LLFile::stat(exe_path, &s)) + if (LLFile::isfile(exe_path)) { // vivox executable exists. Build the command line and launch the daemon. LLProcess::Params params; -- cgit v1.3 From b74a3c25d16685b8dfad8880e20ac99c5769d2e4 Mon Sep 17 00:00:00 2001 From: Andrey Kleshchev <117672381+akleshchev@users.noreply.github.com> Date: Mon, 5 Jan 2026 22:33:33 +0200 Subject: #4899 Fix permissions flags on files that shouldn't be executable --- indra/llcommon/llerror.cpp | 0 indra/llfilesystem/lldir_win32.cpp | 0 indra/llfilesystem/tests/lldir_test.cpp | 0 indra/llmessage/tests/llmessageconfig_test.cpp | 0 indra/llmessage/tests/message_test.cpp | 0 indra/llxml/tests/llcontrol_test.cpp | 0 indra/newview/llpreviewnotecard.cpp | 0 indra/newview/llpreviewscript.cpp | 0 indra/newview/llviewerdisplay.cpp | 0 indra/newview/llviewermedia.cpp | 0 indra/newview/llvoicevivox.cpp | 0 11 files changed, 0 insertions(+), 0 deletions(-) mode change 100755 => 100644 indra/llcommon/llerror.cpp mode change 100755 => 100644 indra/llfilesystem/lldir_win32.cpp mode change 100755 => 100644 indra/llfilesystem/tests/lldir_test.cpp mode change 100755 => 100644 indra/llmessage/tests/llmessageconfig_test.cpp mode change 100755 => 100644 indra/llmessage/tests/message_test.cpp mode change 100755 => 100644 indra/llxml/tests/llcontrol_test.cpp mode change 100755 => 100644 indra/newview/llpreviewnotecard.cpp mode change 100755 => 100644 indra/newview/llpreviewscript.cpp mode change 100755 => 100644 indra/newview/llviewerdisplay.cpp mode change 100755 => 100644 indra/newview/llviewermedia.cpp mode change 100755 => 100644 indra/newview/llvoicevivox.cpp (limited to 'indra/llmessage') diff --git a/indra/llcommon/llerror.cpp b/indra/llcommon/llerror.cpp old mode 100755 new mode 100644 diff --git a/indra/llfilesystem/lldir_win32.cpp b/indra/llfilesystem/lldir_win32.cpp old mode 100755 new mode 100644 diff --git a/indra/llfilesystem/tests/lldir_test.cpp b/indra/llfilesystem/tests/lldir_test.cpp old mode 100755 new mode 100644 diff --git a/indra/llmessage/tests/llmessageconfig_test.cpp b/indra/llmessage/tests/llmessageconfig_test.cpp old mode 100755 new mode 100644 diff --git a/indra/llmessage/tests/message_test.cpp b/indra/llmessage/tests/message_test.cpp old mode 100755 new mode 100644 diff --git a/indra/llxml/tests/llcontrol_test.cpp b/indra/llxml/tests/llcontrol_test.cpp old mode 100755 new mode 100644 diff --git a/indra/newview/llpreviewnotecard.cpp b/indra/newview/llpreviewnotecard.cpp old mode 100755 new mode 100644 diff --git a/indra/newview/llpreviewscript.cpp b/indra/newview/llpreviewscript.cpp old mode 100755 new mode 100644 diff --git a/indra/newview/llviewerdisplay.cpp b/indra/newview/llviewerdisplay.cpp old mode 100755 new mode 100644 diff --git a/indra/newview/llviewermedia.cpp b/indra/newview/llviewermedia.cpp old mode 100755 new mode 100644 diff --git a/indra/newview/llvoicevivox.cpp b/indra/newview/llvoicevivox.cpp old mode 100755 new mode 100644 -- cgit v1.3 From 25dc8660efedecfd9f021142ac1e4ff3639e80d4 Mon Sep 17 00:00:00 2001 From: Rye Date: Tue, 30 Dec 2025 11:39:16 -0500 Subject: Clean up LLFile and LLFilesystem operations to reduce temporaries allocations and utf8->utf16 conversions Fix LLFile::tmpdir failing when temp directory is located in a unicode path on windows Add Tracy profiler tagging to LLFile that's disabled by default Replace LLFile::utf8StringToWstring with our fsyspath std::filesystem::path adapter Introduce std::filesystem::path to llifstream/llofstream wrappers Add move operators to fsyspath to match copy operator Restore LLUniqueFile RAII class for direct c file io wrapping and reducing merge conflicts with downstream code that may depend upon it Signed-off-by: Rye --- indra/llappearance/llpolymesh.cpp | 2 +- indra/llcommon/fsyspath.h | 4 +- indra/llcommon/llcrc.cpp | 2 +- indra/llcommon/llcrc.h | 2 +- indra/llcommon/llfile.cpp | 290 +++++++---------- indra/llcommon/llfile.h | 465 +++++++++++++++++++++++----- indra/llcommon/llprocessor.cpp | 4 +- indra/llcommon/llprofilercategories.h | 9 + indra/llcommon/llsys.cpp | 6 +- indra/llcommon/tests/llfile_test.cpp | 115 ++++--- indra/llfilesystem/lldir.cpp | 15 +- indra/llfilesystem/lldir.h | 2 +- indra/llfilesystem/lldir_linux.cpp | 18 -- indra/llfilesystem/lldir_linux.h | 1 - indra/llfilesystem/lldir_mac.cpp | 8 - indra/llfilesystem/lldir_mac.h | 1 - indra/llfilesystem/lldir_win32.cpp | 7 - indra/llfilesystem/lldir_win32.h | 1 - indra/llfilesystem/llfilesystem.cpp | 81 ++--- indra/llfilesystem/llfilesystem.h | 5 +- indra/llfilesystem/tests/lldir_test.cpp | 2 +- indra/llimage/llimagedimensionsinfo.cpp | 2 +- indra/llimage/llimagetga.cpp | 2 +- indra/llmessage/llassetstorage.cpp | 2 +- indra/llmessage/lltransfersourcefile.cpp | 2 +- indra/llmessage/lltransfertargetfile.cpp | 2 +- indra/llmessage/llxfer_file.cpp | 16 +- indra/llmessage/message.cpp | 4 +- indra/llmessage/tests/lldatapacker_test.cpp | 4 +- indra/llrender/llshadermgr.cpp | 4 +- indra/llui/lluicolortable.cpp | 2 +- indra/llui/llxuiparser.cpp | 6 +- indra/llxml/llcontrol.cpp | 2 +- indra/llxml/llxmlparser.cpp | 4 +- indra/newview/llconversationlog.cpp | 4 +- indra/newview/lldrawpoolbump.cpp | 2 +- indra/newview/llfloaterpreference.cpp | 10 +- indra/newview/llfloateruipreview.cpp | 2 +- indra/newview/llinventorymodel.cpp | 4 +- indra/newview/llkeyconflict.cpp | 2 +- indra/newview/lllogchat.cpp | 12 +- indra/newview/llmutelist.cpp | 8 +- indra/newview/llpreviewnotecard.cpp | 4 +- indra/newview/llpreviewscript.cpp | 4 +- indra/newview/llstartup.cpp | 6 +- indra/newview/lltoolbarview.cpp | 2 +- indra/newview/llviewerassetstorage.cpp | 4 +- indra/newview/llviewerinput.cpp | 2 +- indra/newview/llviewermenufile.cpp | 2 +- indra/newview/llviewerstatsrecorder.cpp | 2 +- 50 files changed, 678 insertions(+), 484 deletions(-) (limited to 'indra/llmessage') diff --git a/indra/llappearance/llpolymesh.cpp b/indra/llappearance/llpolymesh.cpp index d5323e0b84..b579dc007b 100644 --- a/indra/llappearance/llpolymesh.cpp +++ b/indra/llappearance/llpolymesh.cpp @@ -280,7 +280,7 @@ bool LLPolyMeshSharedData::loadMesh( const std::string& fileName ) LL_ERRS() << "Filename is Empty!" << LL_ENDL; return false; } - LLFILE* fp = LLFile::fopen(fileName, "rb"); /*Flawfinder: ignore*/ + LLFILE* fp = LLFile::fopen(fileName, TEXT("rb")); /*Flawfinder: ignore*/ if (!fp) { LLError::LLUserWarningMsg::showMissingFiles(); diff --git a/indra/llcommon/fsyspath.h b/indra/llcommon/fsyspath.h index 2c900c02a7..237d99ae86 100644 --- a/indra/llcommon/fsyspath.h +++ b/indra/llcommon/fsyspath.h @@ -57,7 +57,7 @@ class fsyspath: public std::filesystem::path public: // default - fsyspath() {} + fsyspath() = default; // construct from UTF-8 encoded string fsyspath(const std::string& path): fsyspath(std::string_view(path)) {} fsyspath(const char* path): fsyspath(std::string_view(path)) {} @@ -66,8 +66,10 @@ public: {} // construct from existing path fsyspath(const super& path): super(path) {} + fsyspath(super&& path) : super(std::move(path)) {} fsyspath& operator=(const super& p) { super::operator=(p); return *this; } + fsyspath& operator=(super&& p) { super::operator=(std::move(p)); return *this; } fsyspath& operator=(const std::string& p) { return (*this) = std::string_view(p); } fsyspath& operator=(const char* p) { return (*this) = std::string_view(p); } fsyspath& operator=(std::string_view p) diff --git a/indra/llcommon/llcrc.cpp b/indra/llcommon/llcrc.cpp index d79d06e2a2..f836a12c35 100644 --- a/indra/llcommon/llcrc.cpp +++ b/indra/llcommon/llcrc.cpp @@ -166,7 +166,7 @@ void LLCRC::update(const std::string& filename) return; } - FILE* fp = LLFile::fopen(filename, "rb"); /* Flawfinder: ignore */ + FILE* fp = LLFile::fopen(filename, TEXT("rb")); /* Flawfinder: ignore */ if (fp) { diff --git a/indra/llcommon/llcrc.h b/indra/llcommon/llcrc.h index a3bde47780..cbf4cf4e75 100644 --- a/indra/llcommon/llcrc.h +++ b/indra/llcommon/llcrc.h @@ -36,7 +36,7 @@ // example (don't try this at work kids): // // LLCRC crc; -// FILE* fp = LLFile::fopen(filename,"rb"); +// FILE* fp = LLFile::fopen(filename,TEXT("rb")); // while(!feof(fp)) { // crc.update(fgetc(fp)); // } diff --git a/indra/llcommon/llfile.cpp b/indra/llcommon/llfile.cpp index 0ceb2eb03b..114df29f6e 100755 --- a/indra/llcommon/llfile.cpp +++ b/indra/llcommon/llfile.cpp @@ -226,7 +226,7 @@ static void find_locking_process(const std::string& filename) } #endif // LL_WINDOWS hack to identify processes holding file open -static int warnif(std::string_view desc, const std::string& filename, int rc, int suppress_warning = 0) +static int warnif(std::string_view desc, const std::filesystem::path& filename, int rc, int suppress_warning = 0) { if (rc < 0) { @@ -252,7 +252,7 @@ static int warnif(std::string_view desc, const std::string& filename, int rc, in return rc; } -static int warnif(std::string_view desc, const std::string& filename, const std::error_code& ec, int suppress_warning = 0) +static int warnif(std::string_view desc, const std::filesystem::path& filename, const std::error_code& ec, int suppress_warning = 0) { if (ec) { @@ -506,8 +506,9 @@ inline bool are_open_mode_flags_invalid(std::ios_base::openmode omode) //---------------------------------------------------------------------------------------- // class member functions //---------------------------------------------------------------------------------------- -int LLFile::open(const std::string& filename, std::ios_base::openmode omode, std::error_code& ec, int perm) +int LLFile::open(const std::filesystem::path& file_path, std::ios_base::openmode omode, std::error_code& ec, int perm) { + LL_PROFILE_ZONE_SCOPED_CATEGORY_FILE; close(ec); if (are_open_mode_flags_invalid(omode)) { @@ -519,14 +520,13 @@ int LLFile::open(const std::string& filename, std::ios_base::openmode omode, std create = decode_open_create_flags(omode), attributes = decode_attributes(omode, perm); - std::wstring file_path = utf8StringToWstring(filename); - mHandle = CreateFileW(file_path.c_str(), access, share, nullptr, create, attributes, nullptr); + mHandle = CreateFileW(file_path.native().c_str(), access, share, nullptr, create, attributes, nullptr); // The dwShareMode = share parameter takes care of locking the file for other processes if indicated, // no need to do anything else for file locking here #else int oflags = decode_open_mode(omode); int lmode = omode & LLFile::lock_mask; - mHandle = ::open(filename.c_str(), oflags, perm); + mHandle = ::open(file_path.native().c_str(), oflags, perm); if (mHandle != InvalidHandle && lmode && lock(lmode | LLFile::noblock, ec) != 0) { close(); @@ -549,6 +549,7 @@ int LLFile::open(const std::string& filename, std::ios_base::openmode omode, std S64 LLFile::size(std::error_code& ec) { + LL_PROFILE_ZONE_SCOPED_CATEGORY_FILE; #if LL_WINDOWS LARGE_INTEGER value = { 0 }; if (GetFileSizeEx(mHandle, &value)) @@ -570,6 +571,7 @@ S64 LLFile::size(std::error_code& ec) S64 LLFile::tell(std::error_code& ec) { + LL_PROFILE_ZONE_SCOPED_CATEGORY_FILE; #if LL_WINDOWS LARGE_INTEGER value = { 0 }; if (SetFilePointerEx(mHandle, value, &value, FILE_CURRENT)) @@ -595,6 +597,7 @@ int LLFile::seek(S64 pos, std::error_code& ec) int LLFile::seek(S64 offset, std::ios_base::seekdir dir, std::error_code& ec) { + LL_PROFILE_ZONE_SCOPED_CATEGORY_FILE; S64 newOffset = 0; #if LL_WINDOWS DWORD seekdir = seek_mode_from_dir(dir); @@ -620,6 +623,7 @@ inline DWORD next_buffer_size(S64 nbytes) S64 LLFile::read(void* buffer, S64 nbytes, std::error_code& ec) { + LL_PROFILE_ZONE_SCOPED_CATEGORY_FILE; if (nbytes == 0) { // Nothing to do @@ -660,6 +664,7 @@ S64 LLFile::read(void* buffer, S64 nbytes, std::error_code& ec) S64 LLFile::write(const void* buffer, S64 nbytes, std::error_code& ec) { + LL_PROFILE_ZONE_SCOPED_CATEGORY_FILE; if (nbytes == 0) { // Nothing to do here @@ -705,6 +710,7 @@ S64 LLFile::write(const void* buffer, S64 nbytes, std::error_code& ec) S64 LLFile::printf(const char* fmt, ...) { + LL_PROFILE_ZONE_SCOPED_CATEGORY_FILE; va_list args1; va_start(args1, fmt); va_list args2; @@ -732,6 +738,7 @@ S64 LLFile::printf(const char* fmt, ...) int LLFile::lock(int mode, std::error_code& ec) { + LL_PROFILE_ZONE_SCOPED_CATEGORY_FILE; #if LL_WINDOWS if (!(mode & LLFile::lock_mask)) { @@ -765,6 +772,7 @@ int LLFile::lock(int mode, std::error_code& ec) int LLFile::close(std::error_code& ec) { + LL_PROFILE_ZONE_SCOPED_CATEGORY_FILE; if (mHandle != InvalidHandle) { llfile_handle_t handle = InvalidHandle; @@ -792,8 +800,9 @@ int LLFile::close() //---------------------------------------------------------------------------------------- // static -LLFILE* LLFile::fopen(const std::string& filename, const char* mode, int lmode) +LLFILE* LLFile::fopen(const std::filesystem::path& file_path, const fopen_flags_t* mode, int lmode) { + LL_PROFILE_ZONE_SCOPED_CATEGORY_FILE; LLFILE* file; #if LL_WINDOWS int shflag = _SH_DENYNO; @@ -806,11 +815,9 @@ LLFILE* LLFile::fopen(const std::string& filename, const char* mode, int lmode) shflag = _SH_DENYWR; break; } - std::wstring file_path = utf8StringToWstring(filename); - std::wstring utf16mode = ll_convert(std::string(mode)); - file = _wfsopen(file_path.c_str(), utf16mode.c_str(), shflag); + file = _wfsopen(file_path.native().c_str(), mode, shflag); #else - file = ::fopen(filename.c_str(), mode); + file = ::fopen(file_path.native().c_str(), mode); if (file && (lmode & (LLFile::lock_mask))) { // Rather fail on a sharing conflict than block @@ -827,6 +834,7 @@ LLFILE* LLFile::fopen(const std::string& filename, const char* mode, int lmode) // static int LLFile::close(LLFILE* file) { + LL_PROFILE_ZONE_SCOPED_CATEGORY_FILE; int ret_value = 0; if (file) { @@ -836,17 +844,11 @@ int LLFile::close(LLFILE* file) } // static -std::string LLFile::getContents(const std::string& filename) -{ - std::error_code ec; - return getContents(filename, ec); -} - -// static -std::string LLFile::getContents(const std::string& filename, std::error_code& ec) +std::string LLFile::getContents(const std::filesystem::path& file_path, std::error_code& ec) { + LL_PROFILE_ZONE_SCOPED_CATEGORY_FILE; std::string buffer; - LLFile file(filename, LLFile::in | LLFile::binary, ec); + LLFile file(file_path, LLFile::in | LLFile::binary, ec); if (file) { S64 length = file.size(ec); @@ -864,48 +866,41 @@ std::string LLFile::getContents(const std::string& filename, std::error_code& ec } // static -int LLFile::mkdir(const std::string& dirname) +int LLFile::mkdir(const std::filesystem::path& file_path) { + LL_PROFILE_ZONE_SCOPED_CATEGORY_FILE; std::error_code ec; - std::filesystem::path file_path = utf8StringToPath(dirname); // We often use mkdir() to ensure the existence of a directory that might // already exist. There is no known case in which we want to call out as // an error the requested directory already existing. std::filesystem::create_directory(file_path, ec); // The return value is only true if the directory was actually created. // But if it already existed, ec still indicates success. - return warnif("mkdir", dirname, ec); + return warnif("mkdir", file_path, ec); } // static -int LLFile::remove(const std::string& filename, int suppress_warning) +int LLFile::remove(const std::filesystem::path& file_path, int suppress_warning) { + LL_PROFILE_ZONE_SCOPED_CATEGORY_FILE; std::error_code ec; - std::filesystem::path file_path = utf8StringToPath(filename); std::filesystem::remove(file_path, ec); - return warnif("remove", filename, ec, suppress_warning); + return warnif("remove", file_path, ec, suppress_warning); } // static -int LLFile::rename(const std::string& filename, const std::string& newname, int suppress_warning) +int LLFile::rename(const std::filesystem::path& file_path, const std::filesystem::path& new_path, int suppress_warning) { + LL_PROFILE_ZONE_SCOPED_CATEGORY_FILE; std::error_code ec; - std::filesystem::path file_path = utf8StringToPath(filename); - std::filesystem::path new_path = utf8StringToPath(newname); std::filesystem::rename(file_path, new_path, ec); - return warnif(STRINGIZE("rename to '" << newname << "' from"), filename, ec, suppress_warning); -} - -// static -S64 LLFile::read(const std::string& filename, void* buf, S64 offset, S64 nbytes) -{ - std::error_code ec; - return read(filename, buf, offset, nbytes, ec); + return warnif("rename", file_path, ec, suppress_warning); } // static -S64 LLFile::read(const std::string& filename, void* buf, S64 offset, S64 nbytes, std::error_code& ec) +S64 LLFile::read(const std::filesystem::path& file_path, void* buf, S64 offset, S64 nbytes, std::error_code& ec) { + LL_PROFILE_ZONE_SCOPED_CATEGORY_FILE; // if number of bytes is 0 or less there is nothing to do here if (nbytes <= 0) { @@ -921,7 +916,7 @@ S64 LLFile::read(const std::string& filename, void* buf, S64 offset, S64 nbytes, { std::ios_base::openmode omode = LLFile::in | LLFile::binary; - LLFile file(filename, omode, ec); + LLFile file(file_path, omode, ec); if (!ec && (bool)file) { if (offset > 0) @@ -939,19 +934,13 @@ S64 LLFile::read(const std::string& filename, void* buf, S64 offset, S64 nbytes, } } } - return warnif("read from file failed", filename, ec); + return warnif("read from file failed", file_path, ec); } // static -S64 LLFile::write(const std::string& filename, const void* buf, S64 offset, S64 nbytes) -{ - std::error_code ec; - return write(filename, buf, offset, nbytes, ec); -} - -// static -S64 LLFile::write(const std::string& filename, const void* buf, S64 offset, S64 nbytes, std::error_code& ec) +S64 LLFile::write(const std::filesystem::path& file_path, const void* buf, S64 offset, S64 nbytes, std::error_code& ec) { + LL_PROFILE_ZONE_SCOPED_CATEGORY_FILE; // if number of bytes is 0 or less there is nothing to do here if (nbytes <= 0) { @@ -971,7 +960,7 @@ S64 LLFile::write(const std::string& filename, const void* buf, S64 offset, S64 omode |= LLFile::app; } - LLFile file(filename, omode, ec); + LLFile file(file_path, omode, ec); if (!ec && (bool)file) { if (offset > 0) @@ -989,99 +978,52 @@ S64 LLFile::write(const std::string& filename, const void* buf, S64 offset, S64 } } } - return warnif("write to file failed", filename, ec); + return warnif("write to file failed", file_path, ec); } // static -bool LLFile::copy(const std::string& source, const std::string& target) +bool LLFile::copy(const std::filesystem::path& source_path, const std::filesystem::path& target_path, std::filesystem::copy_options options, std::error_code& ec) { - std::error_code ec; - return copy(source, target, std::filesystem::copy_options::overwrite_existing, ec); -} - -// static -bool LLFile::copy(const std::string& source, const std::string& target, std::filesystem::copy_options options, std::error_code& ec) -{ - std::filesystem::path source_path = utf8StringToPath(source); - std::filesystem::path target_path = utf8StringToPath(target); + LL_PROFILE_ZONE_SCOPED_CATEGORY_FILE; bool copied = std::filesystem::copy_file(source_path, target_path, options, ec); if (!copied) { - warnif(STRINGIZE("copy failed, to '" << target << "' from"), source, ec); + warnif(STRINGIZE("copy failed, to '" << target_path << "' from"), source_path, ec); } return copied; } // static -int LLFile::stat(const std::string& filename, llstat* filestatus, const char *fname, int suppress_warning) +int LLFile::stat(const std::filesystem::path& file_path, llstat* filestatus, const char *fname, int suppress_warning) { + LL_PROFILE_ZONE_SCOPED_CATEGORY_FILE; #if LL_WINDOWS - std::wstring file_path = utf8StringToWstring(filename); - int rc = _wstat64(file_path.c_str(), filestatus); + int rc = _wstat64(file_path.native().c_str(), filestatus); #else - int rc = ::stat(filename.c_str(), filestatus); + int rc = ::stat(file_path.native().c_str(), filestatus); #endif - return warnif(fname ? fname : "stat", filename, rc, suppress_warning); + return warnif(fname ? fname : "stat", file_path, rc, suppress_warning); } // static -std::time_t LLFile::getCreationTime(const std::string& filename, int suppress_warning) -{ - // As of C++20 there is no functionality in std::filesystem to retrieve this information - llstat filestat; - int rc = stat(filename, &filestat, "getCreationTime", suppress_warning); - if (rc == 0) - { -#if LL_DARWIN - return filestat.st_birthtime; -#else - // Linux stat() doesn't have a creation/birth time (st_ctime really is the last status - // change or inode attributes change) unless we would use statx() instead. But that is - // a major effort, which would require Linux specific changes to LLFile::stat() above - // and possibly adaptions for other platforms that we leave for a later exercise if it - // is ever desired. - return filestat.st_ctime; -#endif - } - return 0; -} - -// static -std::time_t LLFile::getModificationTime(const std::string& filename, int suppress_warning) -{ - // tried to use std::filesystem::last_write_time() but the whole std::chrono infrastructure is as of - // C++20 still not fully implemented on all platforms. Specifically MacOS C++20 seems lacking here, - // and Windows requires a roundabout through std::chrono::utc_clock to then get a - // std::chrono::system_clock that can return a more useful time_t. - // So we take the easy way out in a similar way as with getCreationTime(). - llstat filestat; - int rc = stat(filename, &filestat, "getModificationTime", suppress_warning); - if (rc == 0) - { - return filestat.st_mtime; - } - return 0; -} - -// static -S64 LLFile::size(const std::string& filename, int suppress_warning) +S64 LLFile::size(const std::filesystem::path& file_path, int suppress_warning) { + LL_PROFILE_ZONE_SCOPED_CATEGORY_FILE; std::error_code ec; - std::filesystem::path file_path = utf8StringToPath(filename); std::intmax_t size = static_cast(std::filesystem::file_size(file_path, ec)); if (ec) { - warnif("size", filename, ec, suppress_warning); + warnif("size", file_path, ec, suppress_warning); return 0; } return size; } // static -std::filesystem::file_status LLFile::getStatus(const std::string& filename, bool dontFollowSymLink, int suppress_warning) +std::filesystem::file_status LLFile::getStatus(const std::filesystem::path& file_path, bool dontFollowSymLink, int suppress_warning) { + LL_PROFILE_ZONE_SCOPED_CATEGORY_FILE; std::error_code ec; - std::filesystem::path file_path = utf8StringToPath(filename); std::filesystem::file_status status; if (dontFollowSymLink) { @@ -1091,100 +1033,43 @@ std::filesystem::file_status LLFile::getStatus(const std::string& filename, bool { status = std::filesystem::status(file_path, ec); } - warnif("getStatus()", filename, ec, suppress_warning); + warnif("getStatus()", file_path, ec, suppress_warning); return status; } -// static -bool LLFile::exists(const std::string& filename) -{ - std::filesystem::file_status status = getStatus(filename); - return std::filesystem::exists(status); -} - -// static -bool LLFile::isdir(const std::string& filename) -{ - std::filesystem::file_status status = getStatus(filename); - return std::filesystem::is_directory(status); -} - -// static -bool LLFile::isfile(const std::string& filename) -{ - std::filesystem::file_status status = getStatus(filename); - return std::filesystem::is_regular_file(status); -} - -// static -bool LLFile::islink(const std::string& filename) -{ - std::filesystem::file_status status = getStatus(filename, true); - return std::filesystem::is_symlink(status); -} - // static const std::string& LLFile::tmpdir() { + LL_PROFILE_ZONE_SCOPED_CATEGORY_FILE; static std::string temppath; if (temppath.empty()) { - temppath = std::filesystem::temp_directory_path().string(); - } - #if LL_WINDOWS - char sep = '\\'; + temppath = ll_convert(std::filesystem::temp_directory_path().native()); + char sep = '\\'; #else - char sep = '/'; + temppath = std::filesystem::temp_directory_path().string(); + char sep = '/'; #endif - if (temppath[temppath.size() - 1] != sep) - { - temppath += sep; + if (temppath[temppath.size() - 1] != sep) + { + temppath += sep; + } } + return temppath; } -// static -std::filesystem::path LLFile::utf8StringToPath(const std::string& pathname) -{ #if LL_WINDOWS - return ll_convert(pathname); -#else - return pathname; -#endif -} -#if LL_WINDOWS +/************** input file stream ********************************/ -// static -std::wstring LLFile::utf8StringToWstring(const std::string& pathname) +// explicit +llifstream::llifstream(const char* _Filename, ios_base::openmode _Mode) : + std::ifstream(ll_convert(_Filename).c_str(), _Mode | ios_base::in) { - std::wstring utf16string(ll_convert(pathname)); - if (utf16string.size() >= MAX_PATH) - { - // By going through std::filesystem::path we get a lot of path sanitation done for us that - // is needed when passing a path with a kernel object space prefix to Windows API functions - // since this prefix disables the kernel32 path normalization - std::filesystem::path utf16path(utf16string); - - // By prepending "\\?\" to a path, Windows widechar file APIs will not fail on long path names - utf16string.assign(L"\\\\?\\").append(utf16path); - - /* remove trailing spaces and dots (yes, Windows really does that) */ - size_t last_valid = utf16string.find_last_not_of(L" \t."); - if (last_valid == std::wstring::npos) - { - return std::wstring(); - } - return utf16string.substr(0, last_valid + 1); - } - return utf16string; } -/************** input file stream ********************************/ - -llifstream::llifstream() {} - // explicit llifstream::llifstream(const std::string& _Filename, ios_base::openmode _Mode): std::ifstream(ll_convert( _Filename ).c_str(), @@ -1192,15 +1077,37 @@ llifstream::llifstream(const std::string& _Filename, ios_base::openmode _Mode): { } +// explicit +llifstream::llifstream(const std::filesystem::path& _Filepath, ios_base::openmode _Mode) : + std::ifstream(_Filepath, _Mode | ios_base::in) +{ +} + +void llifstream::open(const char* _Filename, ios_base::openmode _Mode) +{ + std::ifstream::open(ll_convert(_Filename).c_str(), + _Mode | ios_base::in); +} + void llifstream::open(const std::string& _Filename, ios_base::openmode _Mode) { std::ifstream::open(ll_convert(_Filename).c_str(), _Mode | ios_base::in); } +void llifstream::open(const std::filesystem::path& _Filepath, ios_base::openmode _Mode) +{ + std::ifstream::open(_Filepath, + _Mode | ios_base::in); +} + /************** output file stream ********************************/ -llofstream::llofstream() {} +// explicit +llofstream::llofstream(const char* _Filename, ios_base::openmode _Mode) : + std::ofstream(ll_convert(_Filename).c_str(), _Mode | ios_base::out) +{ +} // explicit llofstream::llofstream(const std::string& _Filename, ios_base::openmode _Mode): @@ -1209,10 +1116,27 @@ llofstream::llofstream(const std::string& _Filename, ios_base::openmode _Mode): { } +// explicit +llofstream::llofstream(const std::filesystem::path& _Filepath, ios_base::openmode _Mode) : + std::ofstream(_Filepath, _Mode | ios_base::out) +{ +} + +void llofstream::open(const char* _Filename, ios_base::openmode _Mode) +{ + std::ofstream::open(ll_convert(_Filename).c_str(), _Mode | ios_base::out); +} + void llofstream::open(const std::string& _Filename, ios_base::openmode _Mode) { std::ofstream::open(ll_convert( _Filename ).c_str(), _Mode | ios_base::out); } +void llofstream::open(const std::filesystem::path& _Filepath, ios_base::openmode _Mode) +{ + std::ofstream::open(_Filepath, + _Mode | ios_base::out); +} + #endif // LL_WINDOWS diff --git a/indra/llcommon/llfile.h b/indra/llcommon/llfile.h index dcd561ce7f..7e8e114098 100755 --- a/indra/llcommon/llfile.h +++ b/indra/llcommon/llfile.h @@ -35,6 +35,8 @@ * Attempts to mostly mirror the POSIX style IO functions. */ +#include "stdtypes.h" + #include #include #include @@ -51,15 +53,24 @@ typedef struct stat llstat; typedef FILE LLFILE; +#include "fsyspath.h" #include "llstring.h" // safe char* -> std::string conversion +#ifndef TEXT +#if LL_WINDOWS +#define TEXT(flags) L##flags +#else +#define TEXT(flags) flags +#endif +#endif + /// This class provides a selection of functions to operate on files through names and /// a class implementation to represent a file for reading and writing to it /// All the functions with a path string input take UTF8 path/filenames /// /// @nosubgrouping /// -class LL_COMMON_API LLFile +class LLFile { public: // ================================================================================ @@ -157,12 +168,24 @@ public: } /// constructor opening the file - LLFile(const std::string& filename, std::ios_base::openmode omode, std::error_code& ec, int perm = 0666) : + explicit LLFile(const char* filename, std::ios_base::openmode omode, std::error_code& ec, int perm = 0666) : + mHandle(InvalidHandle) + { + open(filename, omode, ec, perm); + } + + explicit LLFile(const std::string& filename, std::ios_base::openmode omode, std::error_code& ec, int perm = 0666) : mHandle(InvalidHandle) { open(filename, omode, ec, perm); } + explicit LLFile(const std::filesystem::path& file_path, std::ios_base::openmode omode, std::error_code& ec, int perm = 0666) : + mHandle(InvalidHandle) + { + open(file_path, omode, ec, perm); + } + /// destructor always attempts to close the file ~LLFile() { close(); } ///@} @@ -198,7 +221,17 @@ public: ///@{ /// Open a file with the specific open mode flags - int open(const std::string& filename, std::ios_base::openmode omode, std::error_code& ec, int perm = 0666); + inline int open(const char* filename, std::ios_base::openmode omode, std::error_code& ec, int perm = 0666) + { + std::filesystem::path file_path = fsyspath(filename); + return open(file_path, omode, ec, perm); + } + inline int open(const std::string& filename, std::ios_base::openmode omode, std::error_code& ec, int perm = 0666) + { + std::filesystem::path file_path = fsyspath(filename); + return open(file_path, omode, ec, perm); + } + int open(const std::filesystem::path& filename, std::ios_base::openmode omode, std::error_code& ec, int perm = 0666); ///< @returns 0 on success, -1 on failure /// Determine the size of the opened file @@ -257,7 +290,23 @@ public: /// ///@{ /// open a file with the specified access mode - static LLFILE* fopen(const std::string& filename, const char* accessmode, int lmode = 0); + /// +#if LL_WINDOWS + using fopen_flags_t = wchar_t; +#else + using fopen_flags_t = char; +#endif + inline static LLFILE* fopen(const char* filename, const fopen_flags_t* accessmode, int lmode = 0) + { + std::filesystem::path file_path = fsyspath(filename); + return LLFile::fopen(file_path, accessmode, lmode); + } + inline static LLFILE* fopen(const std::string& filename, const fopen_flags_t* accessmode, int lmode = 0) + { + std::filesystem::path file_path = fsyspath(filename); + return LLFile::fopen(file_path, accessmode, lmode); + } + static LLFILE* fopen(const std::filesystem::path& file_path, const fopen_flags_t* accessmode, int lmode = 0); ///< 'accessmode' follows the rules of the Posix fopen() mode parameter /// "r" open the file for reading only and positions the stream at the beginning /// "r+" open the file for reading and writing and positions the stream at the beginning @@ -291,19 +340,63 @@ public: ///< @returns 0 on success and -1 on failure. /// create a directory - static int mkdir(const std::string& filename); + inline static int mkdir(const char* dirname) + { + std::filesystem::path dir_path = fsyspath(dirname); + return mkdir(dir_path); + } + inline static int mkdir(const std::string& dirname) + { + std::filesystem::path dir_path = fsyspath(dirname); + return mkdir(dir_path); + } + static int mkdir(const std::filesystem::path& dirname); ///< mkdir() considers "directory already exists" to be not an error. /// @returns 0 on success and -1 on failure. /// remove a file or directory - static int remove(const std::string& filename, int suppress_warning = 0); + inline static int remove(const char* filename, int suppress_warning = 0) + { + std::filesystem::path file_path = fsyspath(filename); + return remove(file_path, suppress_warning); + } + inline static int remove(const std::string& filename, int suppress_warning = 0) + { + std::filesystem::path file_path = fsyspath(filename); + return remove(file_path, suppress_warning); + } + static int remove(const std::filesystem::path& file_path, int suppress_warning = 0); ///< pass an errno value (e.g., ENOENT) in the optional 'suppress_warning' parameter if you want to /// suppress a warning in the log when the failure matches that errno (e.g., suppress warning if /// the file or directory does not exist) /// @returns 0 on success and -1 on failure. /// rename a file - static int rename(const std::string& filename, const std::string& newname, int suppress_warning = 0); + inline static int rename(const char* filename, const char* newname, int suppress_warning = 0) + { + std::filesystem::path file_path = fsyspath(filename); + std::filesystem::path new_path = fsyspath(newname); + return rename(file_path, new_path, suppress_warning); + } + inline static int rename(const std::string& filename, const char* newname, int suppress_warning = 0) + { + std::filesystem::path file_path = fsyspath(filename); + std::filesystem::path new_path = fsyspath(newname); + return rename(file_path, new_path, suppress_warning); + } + inline static int rename(const char* filename, const std::string& newname, int suppress_warning = 0) + { + std::filesystem::path file_path = fsyspath(filename); + std::filesystem::path new_path = fsyspath(newname); + return rename(file_path, new_path, suppress_warning); + } + inline static int rename(const std::string& filename, const std::string& newname, int suppress_warning = 0) + { + std::filesystem::path file_path = fsyspath(filename); + std::filesystem::path new_path = fsyspath(newname); + return rename(file_path, new_path, suppress_warning); + } + static int rename(const std::filesystem::path& file_path, const std::filesystem::path& new_path, int suppress_warning = 0); ///< it will silently overwrite newname if it exists without returning an error /// Posix guarantees that if newname already exists, then there will be no moment /// in which for other processes newname does not exist. There is no such guarantee @@ -312,7 +405,31 @@ public: /// @returns 0 on success and -1 on failure. /// copy the contents of the file from 'source' to 'target' - static bool copy(const std::string& source, const std::string& target); + inline static bool copy(const char* source, const char* target) + { + std::error_code ec; + return copy(source, target, std::filesystem::copy_options::overwrite_existing, ec); + } + inline static bool copy(const char* source, const std::string& target) + { + std::error_code ec; + return copy(source, target, std::filesystem::copy_options::overwrite_existing, ec); + } + inline static bool copy(const std::string& source, char* target) + { + std::error_code ec; + return copy(source, target, std::filesystem::copy_options::overwrite_existing, ec); + } + inline static bool copy(const std::string& source, const std::string& target) + { + std::error_code ec; + return copy(source, target, std::filesystem::copy_options::overwrite_existing, ec); + } + inline static bool copy(const std::filesystem::path& source_path, const std::filesystem::path& target_path) + { + std::error_code ec; + return copy(source_path, target_path, std::filesystem::copy_options::overwrite_existing, ec); + } ///< Copies the contents of the file 'source' to the file 'target', overwriting 'target' if it already /// existed. /// This is a convenience function that implements the previous behavior of silently overwriting an @@ -321,7 +438,31 @@ public: /// @returns true on success and false on failure. /// copy the contents of the file from 'from' to 'to' - static bool copy(const std::string& source, const std::string& target, std::filesystem::copy_options options, std::error_code& ec); + inline static bool copy(const char* source, const char* target, std::filesystem::copy_options options, std::error_code& ec) + { + std::filesystem::path source_path = fsyspath(source); + std::filesystem::path target_path = fsyspath(target); + return copy(source_path, target_path, options, ec); + } + inline static bool copy(const char* source, const std::string& target, std::filesystem::copy_options options, std::error_code& ec) + { + std::filesystem::path source_path = fsyspath(source); + std::filesystem::path target_path = fsyspath(target); + return copy(source_path, target_path, options, ec); + } + inline static bool copy(const std::string& source, const char* target, std::filesystem::copy_options options, std::error_code& ec) + { + std::filesystem::path source_path = fsyspath(source); + std::filesystem::path target_path = fsyspath(target); + return copy(source_path, target_path, options, ec); + } + inline static bool copy(const std::string& source, const std::string& target, std::filesystem::copy_options options, std::error_code& ec) + { + std::filesystem::path source_path = fsyspath(source); + std::filesystem::path target_path = fsyspath(target); + return copy(source_path, target_path, options, ec); + } + static bool copy(const std::filesystem::path& source_path, const std::filesystem::path& target_path, std::filesystem::copy_options options, std::error_code& ec); ///< Copies the contents of the file 'source' to the file 'target'. The options parameter allows to /// specify what should happen if the "target" file already exists: /// std::filesystem::copy_options::none - return an error in ec and fail @@ -331,48 +472,115 @@ public: /// @returns true on success and false on failure. /// retrieve the content of a file into a string - static std::string getContents(const std::string& filename); - static std::string getContents(const std::string& filename, std::error_code& ec); + inline static std::string getContents(const char* filename) + { + std::error_code ec; + return getContents(filename, ec); + } + inline static std::string getContents(const std::string& filename) + { + std::error_code ec; + return getContents(filename, ec); + } + inline static std::string getContents(const std::filesystem::path& file_path) + { + std::error_code ec; + return getContents(file_path, ec); + } + inline static std::string getContents(const char* filename, std::error_code& ec) + { + std::filesystem::path file_path = fsyspath(filename); + return getContents(file_path, ec); + } + inline static std::string getContents(const std::string& filename, std::error_code& ec) + { + std::filesystem::path file_path = fsyspath(filename); + return getContents(file_path, ec); + } + static std::string getContents(const std::filesystem::path& file_path, std::error_code& ec); ///< @returns the entire content of the file as std::string or an empty string on failure /// read nBytes from the file into the buffer, starting at offset in the file - static S64 read(const std::string& filename, void* buf, S64 offset, S64 nbytes); - static S64 read(const std::string& filename, void* buf, S64 offset, S64 nbytes, std::error_code& ec); + inline static S64 read(const char* filename, void* buf, S64 offset, S64 nbytes) + { + std::error_code ec; + return read(filename, buf, offset, nbytes, ec); + } + inline static S64 read(const std::string& filename, void* buf, S64 offset, S64 nbytes) + { + std::error_code ec; + return read(filename, buf, offset, nbytes, ec); + } + inline static S64 read(const std::filesystem::path& file_path, void* buf, S64 offset, S64 nbytes) + { + std::error_code ec; + return read(file_path, buf, offset, nbytes, ec); + } + inline static S64 read(const char* filename, void* buf, S64 offset, S64 nbytes, std::error_code& ec) + { + std::filesystem::path file_path = fsyspath(filename); + return read(file_path, buf, offset, nbytes, ec); + } + inline static S64 read(const std::string& filename, void* buf, S64 offset, S64 nbytes, std::error_code& ec) + { + std::filesystem::path file_path = fsyspath(filename); + return read(file_path, buf, offset, nbytes, ec); + } + static S64 read(const std::filesystem::path& filename, void* buf, S64 offset, S64 nbytes, std::error_code& ec); ///< @returns bytes read on success, or -1 on failure /// write nBytes from the buffer into the file, starting at offset in the file - static S64 write(const std::string& filename, const void* buf, S64 offset, S64 nbytes); - static S64 write(const std::string& filename, const void* buf, S64 offset, S64 nbytes, std::error_code& ec); + inline static S64 write(const std::string& filename, const void* buf, S64 offset, S64 nbytes) + { + std::error_code ec; + std::filesystem::path file_path = fsyspath(filename); + return write(file_path, buf, offset, nbytes, ec); + } + inline static S64 write(const std::filesystem::path& filename, const void* buf, S64 offset, S64 nbytes) + { + std::error_code ec; + std::filesystem::path file_path = fsyspath(filename); + return write(file_path, buf, offset, nbytes, ec); + } + inline static S64 write(const std::string& filename, const void* buf, S64 offset, S64 nbytes, std::error_code& ec) + { + std::filesystem::path file_path = fsyspath(filename); + return write(file_path, buf, offset, nbytes, ec); + } + static S64 write(const std::filesystem::path& filename, const void* buf, S64 offset, S64 nbytes, std::error_code& ec); ///< If a negative offset is provided, the file is opened in append mode and the /// write will be appended to the end of the file. /// @returns bytes written on success, or -1 on failure /// return the file stat structure for filename - static int stat(const std::string& filename, llstat* file_status, const char *operation = nullptr, int suppress_warning = ENOENT); + inline static int stat(const char* filename, llstat* file_status, const char* operation = nullptr, int suppress_warning = ENOENT) + { + std::filesystem::path file_path = fsyspath(filename); + return stat(file_path, file_status, operation, suppress_warning); + } + inline static int stat(const std::string& filename, llstat* file_status, const char* operation = nullptr, int suppress_warning = ENOENT) + { + std::filesystem::path file_path = fsyspath(filename); + return stat(file_path, file_status, operation, suppress_warning); + } + static int stat(const std::filesystem::path& file_path, llstat* file_status, const char *operation = nullptr, int suppress_warning = ENOENT); ///< for compatibility with existing uses of LL_File::stat() we use ENOENT as default in the /// optional 'suppress_warning' parameter to avoid spamming the log with warnings when the API /// is used to detect if a file exists /// @returns 0 on success and -1 on failure. - /// get the creation data and time of a file - static std::time_t getCreationTime(const std::string& filename, int suppress_warning = 0); - ///< Different systems have different support for this. Under Windows this is supposedly - /// the actual time the file was created, on the Mac this is the actual birth date of - /// the file which is in fact the creation time. The according ctime entry in the stat - /// structure under Linux (and any other *nix really) is however contrary to what one - /// might expect based on the c in ctime not the creation time but the time the last - /// change to the inode entry was made. Changing access rights to a file will update - /// this value too. In order to have a true creation time under Linux, we would have - /// to use the statx() call which is available since kernel 4.19, but that will require - /// considerable changes to the implementation of above stat() function. - /// @returns the creation time (last status change under Linux) of the file or 0 on error - - /// get the last modification data and time of a file - static std::time_t getModificationTime(const std::string& filename, int suppress_warning = 0); - ///< @returns the modification time of the file or 0 on error - /// get the std::filesystem::file_status for filename - static std::filesystem::file_status getStatus(const std::string& filename, bool dontFollowSymLink = false, int suppress_warning = ENOENT); + inline static std::filesystem::file_status getStatus(const char* filename, bool dontFollowSymLink = false, int suppress_warning = ENOENT) + { + std::filesystem::path file_path = fsyspath(filename); + return getStatus(file_path, dontFollowSymLink, suppress_warning); + } + inline static std::filesystem::file_status getStatus(const std::string& filename, bool dontFollowSymLink = false, int suppress_warning = ENOENT) + { + std::filesystem::path file_path = fsyspath(filename); + return getStatus(file_path, dontFollowSymLink, suppress_warning); + } + static std::filesystem::file_status getStatus(const std::filesystem::path& file_path, bool dontFollowSymLink = false, int suppress_warning = ENOENT); ///< dontFollowSymLinks set to true returns the std::filesystem::file_status of the symlink if it /// is one, rather than resolving it. We pass by default ENOENT in the optional 'suppress_warning' /// parameter to not spam the log with warnings when the file or directory does not exist @@ -380,66 +588,108 @@ public: /// and other APIs accepting a file_status. /// get the size of a file in bytes - static S64 size(const std::string& filename, int suppress_warning = ENOENT); + inline static S64 size(const char* filename, int suppress_warning = ENOENT) + { + std::filesystem::path file_path = fsyspath(filename); + return size(file_path, suppress_warning); + } + inline static S64 size(const std::string& filename, int suppress_warning = ENOENT) + { + std::filesystem::path file_path = fsyspath(filename); + return size(file_path, suppress_warning); + } + static S64 size(const std::filesystem::path& file_path, int suppress_warning = ENOENT); ///< we pass by default ENOENT in the optional 'suppress_warning' parameter to not spam /// the log with warnings when the file does not exist /// @returns the file size on success or 0 on failure. /// check if filename is an existing file or directory - static bool exists(const std::string& filename); + inline static bool exists(const char* filename) + { + std::filesystem::file_status status = getStatus(filename); + return std::filesystem::exists(status); + } + inline static bool exists(const std::string& filename) + { + std::filesystem::file_status status = getStatus(filename); + return std::filesystem::exists(status); + } + inline static bool exists(const std::filesystem::path& file_path) + { + std::filesystem::file_status status = getStatus(file_path); + return std::filesystem::exists(status); + } ///< @returns true if the path is for an existing file or directory /// check if filename is an existing directory - static bool isdir(const std::string& filename); + inline static bool isdir(const char* filename) + { + std::filesystem::file_status status = getStatus(filename); + return std::filesystem::is_directory(status); + } + inline static bool isdir(const std::string& filename) + { + std::filesystem::file_status status = getStatus(filename); + return std::filesystem::is_directory(status); + } + inline static bool isdir(const std::filesystem::path& file_path) + { + std::filesystem::file_status status = getStatus(file_path); + return std::filesystem::is_directory(status); + } ///< @returns true if the path is for an existing directory /// check if filename is an existing file - static bool isfile(const std::string& filename); + inline static bool isfile(const char* filename) + { + std::filesystem::file_status status = getStatus(filename); + return std::filesystem::is_regular_file(status); + } + inline static bool isfile(const std::string& filename) + { + std::filesystem::file_status status = getStatus(filename); + return std::filesystem::is_regular_file(status); + } + inline static bool isfile(const std::filesystem::path& file_path) + { + std::filesystem::file_status status = getStatus(file_path); + return std::filesystem::is_regular_file(status); + } ///< @returns true if the path is for an existing file /// check if filename is a symlink - static bool islink(const std::string& filename); + inline static bool islink(const char* filename) + { + std::filesystem::file_status status = getStatus(filename, true); + return std::filesystem::is_symlink(status); + } + inline static bool islink(const std::string& filename) + { + std::filesystem::file_status status = getStatus(filename, true); + return std::filesystem::is_symlink(status); + } + inline static bool islink(const std::filesystem::path& file_path) + { + std::filesystem::file_status status = getStatus(file_path, true); + return std::filesystem::is_symlink(status); + } ///< @returns true if the path is pointing at a symlink /// return a path to the temporary directory on the system static const std::string& tmpdir(); - /// converts a string containing a path in utf8 encoding into an explicit filesystem path - static std::filesystem::path utf8StringToPath(const std::string& pathname); - ///< @returns the path as a std::filesystem::path - ///@} - private: #if LL_WINDOWS typedef HANDLE llfile_handle_t; const llfile_handle_t InvalidHandle = INVALID_HANDLE_VALUE; + llfile_handle_t mHandle = INVALID_HANDLE_VALUE; // The file handle/descriptor #else typedef int llfile_handle_t; const llfile_handle_t InvalidHandle = -1; + llfile_handle_t mHandle = -1;; // The file handle/descriptor #endif - /// ================================================================================ - /// @name private static member functions - /// -#if LL_WINDOWS - /// convert a string containing a path in utf8 encoding into a Windows format std::wstring - static std::wstring utf8StringToWstring(const std::string& pathname); - ///< this will prepend the path with the Windows kernel object space prefix when the path is - /// equal or longer than MAX_PATH characters and do some sanitation on the path. - /// This allows the underlaying Windows APIs to process long path names. Do not pass such a path - /// to std::filesystem functions. These functions are not guaranteed to handle such paths properly. - /// It's only useful to pass the resulting string buffer to Microsoft Windows widechar APIs or - /// the Microsoft C runtime widechar file functions. - /// - /// Example: - /// - /// std::wstring file_path = utf8StringToWstring(filename); - /// HANDLE CreateFileW(file_path.c_str(), ......); - /// - /// @returns the path as a std::wstring path -#endif - llfile_handle_t mHandle; // The file handle/descriptor - std::ios_base::openmode mOpen; // Used to emulate std::ios_base::app under Windows + std::ios_base::openmode mOpen{}; // Used to emulate std::ios_base::app under Windows }; #if LL_WINDOWS @@ -451,7 +701,7 @@ private: * Does The Right Thing when passed a non-ASCII pathname. Sadly, that isn't * true of Microsoft's std::ifstream. */ -class LL_COMMON_API llifstream : public std::ifstream +class llifstream : public std::ifstream { // input stream associated with a C stream public: @@ -463,7 +713,7 @@ class LL_COMMON_API llifstream : public std::ifstream * @c &sb to the base class initializer. Does not open any files * (you haven't given it a filename to open). */ - llifstream(); + llifstream() = default; /** * @brief Create an input file stream. @@ -472,8 +722,12 @@ class LL_COMMON_API llifstream : public std::ifstream * * @c ios_base::in is automatically included in @a mode. */ + explicit llifstream(const char* _Filename, + ios_base::openmode _Mode = ios_base::in); explicit llifstream(const std::string& _Filename, ios_base::openmode _Mode = ios_base::in); + explicit llifstream(const std::filesystem::path& _Filepath, + ios_base::openmode _Mode = ios_base::in); /** * @brief Opens an external file. @@ -483,10 +737,73 @@ class LL_COMMON_API llifstream : public std::ifstream * Calls @c llstdio_filebuf::open(s,mode|in). If that function * fails, @c failbit is set in the stream's error state. */ + void open(const char* _Filename, + ios_base::openmode _Mode = ios_base::in); void open(const std::string& _Filename, ios_base::openmode _Mode = ios_base::in); + void open(const std::filesystem::path& _Filepath, + ios_base::openmode _Mode = ios_base::in); }; +/// RAII class +class LLUniqueFile +{ +public: + // empty + LLUniqueFile() = default; + // wrap (e.g.) result of LLFile::fopen() + LLUniqueFile(LLFILE* f) : mFileHandle(f) {} + // no copy + LLUniqueFile(const LLUniqueFile&) = delete; + // move construction + LLUniqueFile(LLUniqueFile&& other) noexcept + { + mFileHandle = other.mFileHandle; + other.mFileHandle = nullptr; + } + // The point of LLUniqueFile is to close on destruction. + ~LLUniqueFile() { close(); } + + // simple assignment + LLUniqueFile& operator=(LLFILE* f) + { + close(); + mFileHandle = f; + return *this; + } + // copy assignment deleted + LLUniqueFile& operator=(const LLUniqueFile&) = delete; + // move assignment + LLUniqueFile& operator=(LLUniqueFile&& other) noexcept + { + close(); + std::swap(mFileHandle, other.mFileHandle); + return *this; + } + + // explicit close operation + void close() + { + if (mFileHandle) + { + // in case close() throws, set mFileHandle null FIRST + LLFILE* h{ nullptr }; + std::swap(h, mFileHandle); + LLFile::close(h); + } + } + + // detect whether the wrapped LLFILE is open or not + explicit operator bool() const { return bool(mFileHandle); } + bool operator!() { return !mFileHandle; } + + // LLUniqueFile should be usable for any operation that accepts LLFILE* + // (or FILE* for that matter) + operator LLFILE*() const { return mFileHandle; } + +private: + LLFILE* mFileHandle = nullptr; +}; /** * @brief Controlling output for files. @@ -496,7 +813,7 @@ class LL_COMMON_API llifstream : public std::ifstream * Right Thing when passed a non-ASCII pathname. Sadly, that isn't true of * Microsoft's std::ofstream. */ -class LL_COMMON_API llofstream : public std::ofstream +class llofstream : public std::ofstream { public: // Constructors: @@ -507,7 +824,7 @@ class LL_COMMON_API llofstream : public std::ofstream * @c &sb to the base class initializer. Does not open any files * (you haven't given it a filename to open). */ - llofstream(); + llofstream() = default; /** * @brief Create an output file stream. @@ -516,8 +833,12 @@ class LL_COMMON_API llofstream : public std::ofstream * * @c ios_base::out is automatically included in @a mode. */ + explicit llofstream(const char* _Filename, + ios_base::openmode _Mode = ios_base::out|ios_base::trunc); explicit llofstream(const std::string& _Filename, ios_base::openmode _Mode = ios_base::out|ios_base::trunc); + explicit llofstream(const std::filesystem::path& _Filepath, + ios_base::openmode _Mode = ios_base::out|ios_base::trunc); /** * @brief Opens an external file. @@ -526,8 +847,12 @@ class LL_COMMON_API llofstream : public std::ofstream * * @c ios_base::out is automatically included in @a mode. */ + void open(const char* _Filename, + ios_base::openmode _Mode = ios_base::out|ios_base::trunc); void open(const std::string& _Filename, ios_base::openmode _Mode = ios_base::out|ios_base::trunc); + void open(const std::filesystem::path& _Filepath, + ios_base::openmode _Mode = ios_base::out|ios_base::trunc); }; #else // ! LL_WINDOWS diff --git a/indra/llcommon/llprocessor.cpp b/indra/llcommon/llprocessor.cpp index 37d1c60f91..7656986fe2 100644 --- a/indra/llcommon/llprocessor.cpp +++ b/indra/llcommon/llprocessor.cpp @@ -837,7 +837,7 @@ private: void get_proc_cpuinfo() { std::map< std::string, std::string > cpuinfo; - LLFILE* cpuinfo_fp = LLFile::fopen(CPUINFO_FILE, "rb"); + LLFILE* cpuinfo_fp = LLFile::fopen(CPUINFO_FILE, TEXT("rb")); if(cpuinfo_fp) { char line[MAX_STRING]; @@ -954,7 +954,7 @@ private: std::ostringstream s; // *NOTE:Mani - This is for linux only. - LLFILE* cpuinfo = LLFile::fopen(CPUINFO_FILE, "rb"); + LLFILE* cpuinfo = LLFile::fopen(CPUINFO_FILE, TEXT("rb")); if(cpuinfo) { char line[MAX_STRING]; diff --git a/indra/llcommon/llprofilercategories.h b/indra/llcommon/llprofilercategories.h index 1c4f0f5624..261fdf14b7 100644 --- a/indra/llcommon/llprofilercategories.h +++ b/indra/llcommon/llprofilercategories.h @@ -48,6 +48,7 @@ #define LL_PROFILER_CATEGORY_ENABLE_DRAWPOOL 1 #define LL_PROFILER_CATEGORY_ENABLE_ENVIRONMENT 1 #define LL_PROFILER_CATEGORY_ENABLE_FACE 1 +//#define LL_PROFILER_CATEGORY_ENABLE_FILE 1 #define LL_PROFILER_CATEGORY_ENABLE_LLSD 1 #define LL_PROFILER_CATEGORY_ENABLE_LOGGING 1 #define LL_PROFILER_CATEGORY_ENABLE_MATERIAL 1 @@ -126,6 +127,14 @@ #define LL_PROFILE_ZONE_SCOPED_CATEGORY_FACE #endif +#if LL_PROFILER_CATEGORY_ENABLE_FILE +#define LL_PROFILE_ZONE_NAMED_CATEGORY_FILE LL_PROFILE_ZONE_NAMED +#define LL_PROFILE_ZONE_SCOPED_CATEGORY_FILE LL_PROFILE_ZONE_SCOPED +#else +#define LL_PROFILE_ZONE_NAMED_CATEGORY_FILE(name) +#define LL_PROFILE_ZONE_SCOPED_CATEGORY_FILE +#endif + #if LL_PROFILER_CATEGORY_ENABLE_LLSD #define LL_PROFILE_ZONE_NAMED_CATEGORY_LLSD LL_PROFILE_ZONE_NAMED #define LL_PROFILE_ZONE_SCOPED_CATEGORY_LLSD LL_PROFILE_ZONE_SCOPED diff --git a/indra/llcommon/llsys.cpp b/indra/llcommon/llsys.cpp index 9b5dd2df39..499de996e2 100644 --- a/indra/llcommon/llsys.cpp +++ b/indra/llcommon/llsys.cpp @@ -514,7 +514,7 @@ namespace { #if LL_LINUX constexpr U32 STATUS_SIZE = 2048; - LLFILE* status_filep = LLFile::fopen("/proc/self/status", "rb"); + LLFILE* status_filep = LLFile::fopen("/proc/self/status", TEXT("rb")); if (status_filep) { char buff[STATUS_SIZE]; /* Flawfinder: ignore */ @@ -1273,7 +1273,7 @@ bool gunzip_file(const std::string& srcfile, const std::string& dstfile) src = gzopen(srcfile.c_str(), "rb"); #endif if (! src) goto err; - dst = LLFile::fopen(tmpfile, "wb"); /* Flawfinder: ignore */ + dst = LLFile::fopen(tmpfile, TEXT("wb")); /* Flawfinder: ignore */ if (! dst) goto err; do { @@ -1314,7 +1314,7 @@ bool gzip_file(const std::string& srcfile, const std::string& dstfile) #endif if (! dst) goto err; - src = LLFile::fopen(srcfile, "rb"); /* Flawfinder: ignore */ + src = LLFile::fopen(srcfile, TEXT("rb")); /* Flawfinder: ignore */ if (! src) goto err; while ((bytes = (S32)fread(buffer, sizeof(U8), COMPRESS_BUFFER_SIZE, src)) > 0) diff --git a/indra/llcommon/tests/llfile_test.cpp b/indra/llcommon/tests/llfile_test.cpp index f1cee06856..ab4616cfb2 100644 --- a/indra/llcommon/tests/llfile_test.cpp +++ b/indra/llcommon/tests/llfile_test.cpp @@ -33,14 +33,13 @@ namespace tut { - static void clear_entire_dir(const std::string &dir) + static void clear_entire_dir(const std::filesystem::path& dir_path) { std::error_code ec; - std::filesystem::path dir_path = LLFile::utf8StringToPath(dir); std::filesystem::remove_all(dir_path, ec); } - static std::filesystem::path append_filename(const std::filesystem::path& dir, const std::string& element) + static std::filesystem::path append_filename(const std::filesystem::path& dir, const std::u8string& element) { std::filesystem::path path = dir; return path.append(element); @@ -48,13 +47,13 @@ namespace tut static std::filesystem::path get_testdir(const std::filesystem::path& tempdir) { - return append_filename(tempdir, std::string("test_dir")); + return append_filename(tempdir, std::u8string(u8"test_dir")); } static std::filesystem::path get_testdir_unicode(const std::filesystem::path& tempdir) { // Example Unicode directory name: "test_ユニコード_dir" - return append_filename(tempdir, std::string("test_\xE3\x83\xA6\xE3\x83\x8B\xE3\x82\xB3\xE3\x83\xBC\xE3\x83\x89_dir")); + return append_filename(tempdir, std::u8string(u8"test_\xE3\x83\xA6\xE3\x83\x8B\xE3\x82\xB3\xE3\x83\xBC\xE3\x83\x89_dir")); } struct llfile_test @@ -72,46 +71,46 @@ namespace tut // Test creating directories and files and deleting them and checking if the // relevant status functions work as expected ensure("LLFile::tmpdir() empty", !tempdir.empty()); - ensure("LLFile::tmpdir() doesn't exist", LLFile::exists(tempdir.string())); - ensure("LLFile::tmpdir() is not a directory", LLFile::isdir(tempdir.string())); - ensure("LLFile::tmpdir() should not be a file", !LLFile::isfile(tempdir.string())); + ensure("LLFile::tmpdir() doesn't exist", LLFile::exists(tempdir)); + ensure("LLFile::tmpdir() is not a directory", LLFile::isdir(tempdir)); + ensure("LLFile::tmpdir() should not be a file", !LLFile::isfile(tempdir)); // Make sure there is nothing left from a previous test run - clear_entire_dir(testdir.string()); - ensure("llfile_test should not exist anymore", !LLFile::exists(testdir.string())); + clear_entire_dir(testdir); + ensure("llfile_test should not exist anymore", !LLFile::exists(testdir)); - int rc = LLFile::mkdir(testdir.string()); + int rc = LLFile::mkdir(testdir); ensure("LLFile::mkdir() failed", rc == 0); - ensure("llfile_test should be a directory", LLFile::isdir(testdir.string())); - rc = LLFile::mkdir(testdir.string()); + ensure("llfile_test should be a directory", LLFile::isdir(testdir)); + rc = LLFile::mkdir(testdir); ensure("LLFile::mkdir() should not fail when the directory already exists", rc == 0); std::filesystem::path testfile1 = testdir; testfile1.append("llfile_test.dat"); - ensure("llfile_test1.dat should not yet exist", !LLFile::exists(testfile1.string())); + ensure("llfile_test1.dat should not yet exist", !LLFile::exists(testfile1)); const char* testdata = "testdata"; - S64 bytes = LLFile::write(testfile1.string(), testdata, 0, sizeof(testdata)); + S64 bytes = LLFile::write(testfile1, testdata, 0, sizeof(testdata)); ensure("LLFile::write() did not write correctly", bytes == sizeof(testdata)); - rc = LLFile::remove(testfile1.string()); + rc = LLFile::remove(testfile1); ensure("LLFile::remove() for file test_file.dat", rc == 0); - ensure("llfile_test.dat should not exist anymore", !LLFile::exists(testfile1.string())); - ensure("llfile_test.dat should not be a file", !LLFile::isfile(testfile1.string())); - ensure("llfile_test.dat should not be a directory", !LLFile::isdir(testfile1.string())); - ensure("llfile_test.dat should not be a symlink", !LLFile::islink(testfile1.string())); + ensure("llfile_test.dat should not exist anymore", !LLFile::exists(testfile1)); + ensure("llfile_test.dat should not be a file", !LLFile::isfile(testfile1)); + ensure("llfile_test.dat should not be a directory", !LLFile::isdir(testfile1)); + ensure("llfile_test.dat should not be a symlink", !LLFile::islink(testfile1)); - rc = LLFile::remove(testdir.string()); + rc = LLFile::remove(testdir); ensure("LLFile::remove() for directory llfile_test failed", rc == 0); - ensure("llfile_test should not exist anymore", !LLFile::exists(testdir.string())); + ensure("llfile_test should not exist anymore", !LLFile::exists(testdir)); } template<> template<> void llfile_test_object_t::test<2>() { // High level static file IO functions to read and write data files - LLFile::mkdir(testdir.string()); - ensure("llfile_test should exist", LLFile::isdir(testdir.string())); + LLFile::mkdir(testdir); + ensure("llfile_test should exist", LLFile::isdir(testdir)); std::filesystem::path testfile1 = testdir; testfile1.append("llfile_test.dat"); @@ -119,42 +118,36 @@ namespace tut std::string testdata1("testdata"); std::string testdata2("datateststuff"); std::time_t current = time(nullptr); - S64 bytes = LLFile::write(testfile1.string(), testdata1.c_str(), 0, testdata1.length()); + S64 bytes = LLFile::write(testfile1, testdata1.c_str(), 0, testdata1.length()); ensure("LLFile::write() did not write correctly", bytes == testdata1.length()); - ensure("llfile_test.dat should exist", LLFile::exists(testfile1.string())); - ensure("llfile_test.dat should be a file", LLFile::isfile(testfile1.string())); - ensure("llfile_test.dat should not be a directory", !LLFile::isdir(testfile1.string())); + ensure("llfile_test.dat should exist", LLFile::exists(testfile1)); + ensure("llfile_test.dat should be a file", LLFile::isfile(testfile1)); + ensure("llfile_test.dat should not be a directory", !LLFile::isdir(testfile1)); - bytes = LLFile::size(testfile1.string()); + bytes = LLFile::size(testfile1); ensure("LLFile::size() did not return the correct size", bytes == testdata1.length()); - std::string data = LLFile::getContents(testfile1.string()); + std::string data = LLFile::getContents(testfile1); ensure("LLFile::getContents() did not return the correct size data", data.length() == testdata1.length()); ensure_memory_matches("LLFile::getContents() did not read correct data", testdata1.c_str(), (U32)testdata1.length(), data.c_str(), (U32)data.length()); - std::time_t ctime = LLFile::getCreationTime(testfile1.string()); - ensure_approximately_equals_range("LLFile::getCreationTime() did not return correct time", (F32)(ctime - current), 0.f, 1); - - std::time_t mtime = LLFile::getModificationTime(testfile1.string()); - ensure_approximately_equals_range("LLFile::getModificationTime() did not return correct time", (F32)(mtime - current), 0.f, 1); - char buffer[1024]; - bytes = LLFile::read(testfile1.string(), buffer, 0, testdata1.length()); + bytes = LLFile::read(testfile1, buffer, 0, testdata1.length()); ensure("LLFile:read() did not return the correct size", bytes == testdata1.length()); ensure_memory_matches("LLFile::read() did not read correct data", testdata1.c_str(), (U32)bytes, buffer, (U32)bytes); // What if we try to read more data than there is in the file? - bytes = LLFile::read(testfile1.string(), buffer, 0, bytes + 10); + bytes = LLFile::read(testfile1, buffer, 0, bytes + 10); ensure("LLFile:read() did not correctly stop on eof", bytes == testdata1.length()); ensure_memory_matches("LLFile::read() did not read correct data", testdata1.c_str(), (U32)bytes, buffer, (U32)bytes); // Let's append more data - bytes = LLFile::write(testfile1.string(), testdata2.c_str(), -1, testdata2.length()); + bytes = LLFile::write(testfile1, testdata2.c_str(), -1, testdata2.length()); ensure("LLFile::write() did not write correctly", bytes == testdata2.length()); - bytes = LLFile::size(testfile1.string()); + bytes = LLFile::size(testfile1); ensure("LLFile::size() did not return the correct size", bytes == testdata1.length() + testdata2.length()); - bytes = LLFile::read(testfile1.string(), buffer, 0, bytes); + bytes = LLFile::read(testfile1, buffer, 0, bytes); ensure("LLFile:read() did not read correct number of bytes", bytes == testdata1.length() + testdata2.length()); ensure_memory_matches("LLFile:read() did not read correct testdata1", testdata1.c_str(), (U32)testdata1.length(), buffer, (U32)testdata1.length()); ensure_memory_matches("LLFile:read() did not read correct testdata2", testdata2.c_str(), (U32)testdata2.length(), buffer + testdata1.length(), (U32)testdata2.length()); @@ -176,7 +169,7 @@ namespace tut } std::error_code ec; - LLFile fileout(testfile.string(), LLFile::out, ec); + LLFile fileout(testfile, LLFile::out, ec); ensure("LLFile constructor did not open correctly", (bool)fileout); ensure("error_code from LLFile constructor should not indicate an error", !ec); if (fileout) @@ -196,7 +189,7 @@ namespace tut fileout.close(); } - LLFile filein(testfile.string(), LLFile::in, ec); + LLFile filein(testfile, LLFile::in, ec); ensure("LLFile constructor did not open correctly", (bool)filein); ensure("error_code from LLFile constructor should not indicate an error", !ec); if (filein) @@ -236,16 +229,16 @@ namespace tut testfile.append("llfile_test.bin"); std::error_code ec; - LLFile file(testfile.string(), LLFile::out | LLFile::noreplace, ec); + LLFile file(testfile, LLFile::out | LLFile::noreplace, ec); ensure("LLFile constructor should not have opened the already existing file", !file); ensure("error_code from LLFile constructor should indicate an error", (bool)ec); - LLFile::remove(testfile.string()); - file = LLFile(testfile.string(), LLFile::out | LLFile::app | LLFile::trunc, ec); + LLFile::remove(testfile); + file = LLFile(testfile, LLFile::out | LLFile::app | LLFile::trunc, ec); ensure("LLFile constructor should not have opened the file with conflicting flags", !file); ensure("error_code from LLFile constructor should indicate an error", (bool)ec); - file = LLFile(testfile.string(), LLFile::out | LLFile::app | LLFile::noreplace, ec); + file = LLFile(testfile, LLFile::out | LLFile::app | LLFile::noreplace, ec); ensure("LLFile constructor should not have opened the file with conflicting flags", !file); ensure("error_code from LLFile constructor should indicate an error", (bool)ec); @@ -253,7 +246,7 @@ namespace tut testfile.append("llfile_test"); testfile.append("llfile_test.bin"); - file = LLFile(testfile.string(), LLFile::in, ec); + file = LLFile(testfile, LLFile::in, ec); ensure("LLFile constructor should not have been able to open the file in the non-existing directory", !file); ensure("error_code from LLFile constructor should indicate an error", (bool)ec); } @@ -270,37 +263,37 @@ namespace tut testfile_unicode.append(unicode_filename); // Clean up any previous test artifacts - clear_entire_dir(testdir_unicode.string()); - ensure("Unicode test directory should not exist", !LLFile::exists(testdir_unicode.string())); + clear_entire_dir(testdir_unicode); + ensure("Unicode test directory should not exist", !LLFile::exists(testdir_unicode)); // Create the Unicode directory - int rc = LLFile::mkdir(testdir_unicode.string()); + int rc = LLFile::mkdir(testdir_unicode); ensure("LLFile::mkdir() failed for Unicode directory", rc == 0); - ensure("Unicode test directory should exist", LLFile::isdir(testdir_unicode.string())); + ensure("Unicode test directory should exist", LLFile::isdir(testdir_unicode)); - ensure("Unicode test file should not exist", !LLFile::exists(testfile_unicode.string())); + ensure("Unicode test file should not exist", !LLFile::exists(testfile_unicode)); // Write to the Unicode file const char* testdata = "unicode_testdata"; - S64 bytes = LLFile::write(testfile_unicode.string(), testdata, 0, strlen(testdata)); - ensure("Unicode test file should exist", LLFile::exists(testfile_unicode.string())); - ensure("Unicode test file should be a file", LLFile::isfile(testfile_unicode.string())); + S64 bytes = LLFile::write(testfile_unicode, testdata, 0, strlen(testdata)); + ensure("Unicode test file should exist", LLFile::exists(testfile_unicode)); + ensure("Unicode test file should be a file", LLFile::isfile(testfile_unicode)); ensure("LLFile::write() did not write correctly to Unicode file", bytes == (S64)strlen(testdata)); // Read back the data char buffer[64] = {}; - bytes = LLFile::read(testfile_unicode.string(), buffer, 0, sizeof(buffer)); + bytes = LLFile::read(testfile_unicode, buffer, 0, sizeof(buffer)); ensure("LLFile::read() did not read correctly from Unicode file", bytes == (S64)strlen(testdata)); ensure_memory_matches("LLFile::read() did not read correct Unicode data", testdata, (U32)bytes, buffer, (U32)bytes); // Remove the file and directory - rc = LLFile::remove(testfile_unicode.string()); + rc = LLFile::remove(testfile_unicode); ensure("LLFile::remove() failed for Unicode file", rc == 0); - ensure("Unicode test file should not exist after removal", !LLFile::exists(testfile_unicode.string())); + ensure("Unicode test file should not exist after removal", !LLFile::exists(testfile_unicode)); - rc = LLFile::remove(testdir_unicode.string()); + rc = LLFile::remove(testdir_unicode); ensure("LLFile::remove() failed for Unicode directory", rc == 0); - ensure("Unicode test directory should not exist after removal", !LLFile::exists(testdir_unicode.string())); + ensure("Unicode test directory should not exist after removal", !LLFile::exists(testdir_unicode)); } } // namespace tut diff --git a/indra/llfilesystem/lldir.cpp b/indra/llfilesystem/lldir.cpp index eb3c2d9909..3ec8983e8a 100755 --- a/indra/llfilesystem/lldir.cpp +++ b/indra/llfilesystem/lldir.cpp @@ -91,13 +91,13 @@ LLDir::~LLDir() std::vector LLDir::getFilesInDir(const std::string &dirname) { // Returns a vector of filenames in the directory. - std::filesystem::path p = LLFile::utf8StringToPath(dirname); + fsyspath dir_path(dirname); std::vector v; std::error_code ec; - if (std::filesystem::is_directory(p, ec)) + if (std::filesystem::is_directory(dir_path, ec)) { std::filesystem::directory_iterator end_iter; - for (std::filesystem::directory_iterator dir_itr(p); + for (std::filesystem::directory_iterator dir_itr(dir_path); dir_itr != end_iter; ++dir_itr) { @@ -173,10 +173,10 @@ U32 LLDir::deleteDirAndContents(const std::string& dir_name) //Removes the directory and its contents. Returns number of files deleted. U32 num_deleted = 0; - std::filesystem::path dir_path = LLFile::utf8StringToPath(dir_name); try { + fsyspath dir_path(dir_name); if (std::filesystem::is_directory(dir_path)) { if (!std::filesystem::is_empty(dir_path)) @@ -196,6 +196,11 @@ U32 LLDir::deleteDirAndContents(const std::string& dir_name) return num_deleted; } +bool LLDir::fileExists(const std::string& filename) const +{ + return LLFile::exists(filename); +} + const std::string LLDir::findFile(const std::string &filename, const std::string& searchPath1, const std::string& searchPath2, @@ -1005,7 +1010,7 @@ bool LLDir::setCacheDir(const std::string &path) { LLFile::mkdir(path); std::string tempname = add(path, "temp"); - LLFILE* file = LLFile::fopen(tempname,"wt"); + LLFILE* file = LLFile::fopen(tempname, TEXT("wt")); if (file) { fclose(file); diff --git a/indra/llfilesystem/lldir.h b/indra/llfilesystem/lldir.h index b0d2b6aada..8388816059 100644 --- a/indra/llfilesystem/lldir.h +++ b/indra/llfilesystem/lldir.h @@ -71,7 +71,7 @@ class LLDir std::vector getFilesInDir(const std::string &dirname); // pure virtual functions virtual std::string getCurPath() = 0; - virtual bool fileExists(const std::string &filename) const = 0; + virtual bool fileExists(const std::string &filename) const; const std::string findFile(const std::string& filename, const std::vector filenames) const; const std::string findFile(const std::string& filename, const std::string& searchPath1 = "", const std::string& searchPath2 = "", const std::string& searchPath3 = "") const; diff --git a/indra/llfilesystem/lldir_linux.cpp b/indra/llfilesystem/lldir_linux.cpp index b13b42c954..0ebaab1114 100644 --- a/indra/llfilesystem/lldir_linux.cpp +++ b/indra/llfilesystem/lldir_linux.cpp @@ -238,24 +238,6 @@ std::string LLDir_Linux::getCurPath() return tmp_str; } - -bool LLDir_Linux::fileExists(const std::string &filename) const -{ - struct stat stat_data; - // Check the age of the file - // Now, we see if the files we've gathered are recent... - int res = stat(filename.c_str(), &stat_data); - if (!res) - { - return true; - } - else - { - return false; - } -} - - /*virtual*/ std::string LLDir_Linux::getLLPluginLauncher() { return gDirUtilp->getExecutableDir() + gDirUtilp->getDirDelimiter() + diff --git a/indra/llfilesystem/lldir_linux.h b/indra/llfilesystem/lldir_linux.h index bd031bd7bb..ad9cd76554 100644 --- a/indra/llfilesystem/lldir_linux.h +++ b/indra/llfilesystem/lldir_linux.h @@ -47,7 +47,6 @@ public: virtual std::string getCurPath(); virtual U32 countFilesInDir(const std::string &dirname, const std::string &mask); - /*virtual*/ bool fileExists(const std::string &filename) const; /*virtual*/ std::string getLLPluginLauncher(); /*virtual*/ std::string getLLPluginFilename(std::string base_name); diff --git a/indra/llfilesystem/lldir_mac.cpp b/indra/llfilesystem/lldir_mac.cpp index 2db1b6ec5d..7bddee0f75 100644 --- a/indra/llfilesystem/lldir_mac.cpp +++ b/indra/llfilesystem/lldir_mac.cpp @@ -177,14 +177,6 @@ std::string LLDir_Mac::getCurPath() return boost::filesystem::path( boost::filesystem::current_path() ).string(); } - - -bool LLDir_Mac::fileExists(const std::string &filename) const -{ - return boost::filesystem::exists(filename); -} - - /*virtual*/ std::string LLDir_Mac::getLLPluginLauncher() { return gDirUtilp->getAppRODataDir() + gDirUtilp->getDirDelimiter() + diff --git a/indra/llfilesystem/lldir_mac.h b/indra/llfilesystem/lldir_mac.h index f812ee810b..54dc2eb237 100644 --- a/indra/llfilesystem/lldir_mac.h +++ b/indra/llfilesystem/lldir_mac.h @@ -45,7 +45,6 @@ public: const std::string& app_read_only_data_dir); virtual std::string getCurPath(); - virtual bool fileExists(const std::string &filename) const; /*virtual*/ std::string getLLPluginLauncher(); /*virtual*/ std::string getLLPluginFilename(std::string base_name); diff --git a/indra/llfilesystem/lldir_win32.cpp b/indra/llfilesystem/lldir_win32.cpp index 1cfa157634..912a2963c6 100644 --- a/indra/llfilesystem/lldir_win32.cpp +++ b/indra/llfilesystem/lldir_win32.cpp @@ -373,13 +373,6 @@ std::string LLDir_Win32::getCurPath() return ll_convert(std::wstring(w_str)); } - -bool LLDir_Win32::fileExists(const std::string &filename) const -{ - return LLFile::exists(filename); -} - - /*virtual*/ std::string LLDir_Win32::getLLPluginLauncher() { return gDirUtilp->getExecutableDir() + gDirUtilp->getDirDelimiter() + diff --git a/indra/llfilesystem/lldir_win32.h b/indra/llfilesystem/lldir_win32.h index 21a3f1213b..c3a41d3e33 100644 --- a/indra/llfilesystem/lldir_win32.h +++ b/indra/llfilesystem/lldir_win32.h @@ -44,7 +44,6 @@ public: /*virtual*/ std::string getCurPath(); /*virtual*/ U32 countFilesInDir(const std::string &dirname, const std::string &mask); - /*virtual*/ bool fileExists(const std::string &filename) const; /*virtual*/ std::string getLLPluginLauncher(); /*virtual*/ std::string getLLPluginFilename(std::string base_name); diff --git a/indra/llfilesystem/llfilesystem.cpp b/indra/llfilesystem/llfilesystem.cpp index 0c220fe7cf..388cbc280f 100755 --- a/indra/llfilesystem/llfilesystem.cpp +++ b/indra/llfilesystem/llfilesystem.cpp @@ -34,8 +34,6 @@ #include "llfasttimer.h" #include "lldiskcache.h" -#include "boost/filesystem.hpp" - constexpr S32 LLFileSystem::READ = 0x00000001; constexpr S32 LLFileSystem::WRITE = 0x00000002; constexpr S32 LLFileSystem::READ_WRITE = 0x00000003; // LLFileSystem::READ & LLFileSystem::WRITE @@ -51,22 +49,21 @@ LLFileSystem::LLFileSystem(const LLUUID& file_id, const LLAssetType::EType file_ mBytesRead = 0; mMode = mode; + // build the filepath + mPath = fsyspath(LLDiskCache::metaDataToFilepath(mFileID, mFileType)); + // This block of code was originally called in the read() method but after comments here: // https://bitbucket.org/lindenlab/viewer/commits/e28c1b46e9944f0215a13cab8ee7dded88d7fc90#comment-10537114 // we decided to follow Henri's suggestion and move the code to update the last access time here. if (mode == LLFileSystem::READ) { - // build the filename (TODO: we do this in a few places - perhaps we should factor into a single function) - const std::string filename = LLDiskCache::metaDataToFilepath(mFileID, mFileType); - // update the last access time for the file if it exists - this is required // even though we are reading and not writing because this is the // way the cache works - it relies on a valid "last accessed time" for // each file so it knows how to remove the oldest, unused files - bool exists = gDirUtilp->fileExists(filename); - if (exists) + if (LLFile::exists(mPath)) { - updateFileAccessTime(filename); + updateFileAccessTime(); } } } @@ -111,20 +108,11 @@ bool LLFileSystem::renameFile(const LLUUID& old_file_id, const LLAssetType::ETyp return true; } -// static -S64 LLFileSystem::getFileSize(const LLUUID& file_id, const LLAssetType::EType file_type) -{ - const std::string filename = LLDiskCache::metaDataToFilepath(file_id, file_type); - return LLFile::size(filename); -} - bool LLFileSystem::read(U8* buffer, S32 bytes) { bool success = false; - const std::string filename = LLDiskCache::metaDataToFilepath(mFileID, mFileType); - - llifstream file(filename, std::ios::binary); + llifstream file(mPath, std::ios::binary); if (file.is_open()) { file.seekg(mPosition, std::ios::beg); @@ -164,13 +152,11 @@ bool LLFileSystem::eof() const bool LLFileSystem::write(const U8* buffer, S32 bytes) { - const std::string filename = LLDiskCache::metaDataToFilepath(mFileID, mFileType); - bool success = false; if (mMode == APPEND) { - llofstream ofs(filename, std::ios::app | std::ios::binary); + llofstream ofs(mPath, std::ios::app | std::ios::binary); if (ofs) { ofs.write((const char*)buffer, bytes); @@ -183,7 +169,7 @@ bool LLFileSystem::write(const U8* buffer, S32 bytes) else if (mMode == READ_WRITE) { // Don't truncate if file already exists - llofstream ofs(filename, std::ios::in | std::ios::binary); + llofstream ofs(mPath, std::ios::in | std::ios::binary); if (ofs) { ofs.seekp(mPosition, std::ios::beg); @@ -194,7 +180,7 @@ bool LLFileSystem::write(const U8* buffer, S32 bytes) else { // File doesn't exist - open in write mode - ofs.open(filename, std::ios::binary); + ofs.open(mPath, std::ios::binary); if (ofs.is_open()) { ofs.write((const char*)buffer, bytes); @@ -205,7 +191,7 @@ bool LLFileSystem::write(const U8* buffer, S32 bytes) } else { - llofstream ofs(filename, std::ios::binary); + llofstream ofs(mPath, std::ios::binary); if (ofs) { ofs.write((const char*)buffer, bytes); @@ -256,7 +242,7 @@ S32 LLFileSystem::tell() const S32 LLFileSystem::getSize() const { - return (S32)LLFileSystem::getFileSize(mFileID, mFileType); + return narrow(LLFile::size(mPath)); } S32 LLFileSystem::getMaxSize() const @@ -271,17 +257,18 @@ bool LLFileSystem::rename(const LLUUID& new_id, const LLAssetType::EType new_typ mFileID = new_id; mFileType = new_type; + mPath = fsyspath(LLDiskCache::metaDataToFilepath(mFileID, mFileType)); return true; } bool LLFileSystem::remove() const { - LLFileSystem::removeFile(mFileID, mFileType); + LLFile::remove(mPath); return true; } -void LLFileSystem::updateFileAccessTime(const std::string& file_path) +void LLFileSystem::updateFileAccessTime() { /** * Threshold in time_t units that is used to decide if the last access time @@ -292,52 +279,32 @@ void LLFileSystem::updateFileAccessTime(const std::string& file_path) * * Let's start with 1 hour in time_t units and see how that unfolds */ - constexpr std::time_t time_threshold = 1 * 60 * 60; + constexpr std::chrono::hours time_threshold(1); // current time - const std::time_t cur_time = std::time(nullptr); - - boost::system::error_code ec; -#if LL_WINDOWS - // file last write time - const std::time_t last_write_time = boost::filesystem::last_write_time(ll_convert(file_path), ec); - if (ec.failed()) - { - LL_WARNS() << "Failed to read last write time for cache file " << file_path << ": " << ec.message() << LL_ENDL; - return; - } - - // delta between cur time and last time the file was written - const std::time_t delta_time = cur_time - last_write_time; + const std::filesystem::file_time_type cur_time = std::chrono::file_clock::now(); - // we only write the new value if the time in time_threshold has elapsed - // before the last one - if (delta_time > time_threshold) - { - boost::filesystem::last_write_time(ll_convert(file_path), cur_time, ec); - } -#else + std::error_code ec; // file last write time - const std::time_t last_write_time = boost::filesystem::last_write_time(file_path, ec); - if (ec.failed()) + const std::filesystem::file_time_type last_write_time = std::filesystem::last_write_time(mPath, ec); + if (ec) { - LL_WARNS() << "Failed to read last write time for cache file " << file_path << ": " << ec.message() << LL_ENDL; + LL_WARNS() << "Failed to read last write time for cache file " << mPath << ": " << ec.message() << LL_ENDL; return; } // delta between cur time and last time the file was written - const std::time_t delta_time = cur_time - last_write_time; + const auto delta_time = cur_time - last_write_time; // we only write the new value if the time in time_threshold has elapsed // before the last one if (delta_time > time_threshold) { - boost::filesystem::last_write_time(file_path, cur_time, ec); + std::filesystem::last_write_time(mPath, cur_time, ec); } -#endif - if (ec.failed()) + if (ec) { - LL_WARNS() << "Failed to update last write time for cache file " << file_path << ": " << ec.message() << LL_ENDL; + LL_WARNS() << "Failed to update last write time for cache file " << mPath << ": " << ec.message() << LL_ENDL; } } diff --git a/indra/llfilesystem/llfilesystem.h b/indra/llfilesystem/llfilesystem.h index 7188683e7f..bc8b9216bd 100644 --- a/indra/llfilesystem/llfilesystem.h +++ b/indra/llfilesystem/llfilesystem.h @@ -33,6 +33,7 @@ #include "lluuid.h" #include "llassettype.h" #include "lldiskcache.h" +#include class LLFileSystem { @@ -58,13 +59,12 @@ class LLFileSystem * file in the cache is read (not written) so that the last time the file was * accessed is up to date (This is used in the mechanism for purging the cache) */ - void updateFileAccessTime(const std::string& file_path); + void updateFileAccessTime(); static bool getExists(const LLUUID& file_id, const LLAssetType::EType file_type); static bool removeFile(const LLUUID& file_id, const LLAssetType::EType file_type, int suppress_warning = 0); static bool renameFile(const LLUUID& old_file_id, const LLAssetType::EType old_file_type, const LLUUID& new_file_id, const LLAssetType::EType new_file_type); - static S64 getFileSize(const LLUUID& file_id, const LLAssetType::EType file_type); public: static const S32 READ; @@ -73,6 +73,7 @@ class LLFileSystem static const S32 APPEND; protected: + std::filesystem::path mPath; LLAssetType::EType mFileType; LLUUID mFileID; S32 mPosition; diff --git a/indra/llfilesystem/tests/lldir_test.cpp b/indra/llfilesystem/tests/lldir_test.cpp index 8b86da40b3..b879fef48a 100644 --- a/indra/llfilesystem/tests/lldir_test.cpp +++ b/indra/llfilesystem/tests/lldir_test.cpp @@ -405,7 +405,7 @@ namespace tut std::string makeTestFile( const std::string& dir, const std::string& file ) { std::string path = dir + file; - LLFILE* handle = LLFile::fopen( path, "w" ); + LLFILE* handle = LLFile::fopen(path, TEXT("w")); ensure("failed to open test file '"+path+"'", handle != NULL ); // Harbison & Steele, 4th ed., p. 366: "If an error occurs, fputs // returns EOF; otherwise, it returns some other, nonnegative value." diff --git a/indra/llimage/llimagedimensionsinfo.cpp b/indra/llimage/llimagedimensionsinfo.cpp index c896d60c85..1d93014e1b 100644 --- a/indra/llimage/llimagedimensionsinfo.cpp +++ b/indra/llimage/llimagedimensionsinfo.cpp @@ -166,7 +166,7 @@ bool LLImageDimensionsInfo::getImageDimensionsJpeg() { sJpegErrorEncountered = false; clean(); - FILE* fp = LLFile::fopen(mSrcFilename, "rb"); + FILE* fp = LLFile::fopen(mSrcFilename, TEXT("rb")); if (!fp) { setLastError("Unable to open file for reading", mSrcFilename); diff --git a/indra/llimage/llimagetga.cpp b/indra/llimage/llimagetga.cpp index 25232b77aa..7c6686db95 100644 --- a/indra/llimage/llimagetga.cpp +++ b/indra/llimage/llimagetga.cpp @@ -1191,7 +1191,7 @@ bool LLImageTGA::loadFile( const std::string& path ) return false; } - LLFILE* file = LLFile::fopen(path, "rb"); /* Flawfinder: ignore */ + LLFILE* file = LLFile::fopen(path, TEXT("rb")); /* Flawfinder: ignore */ if( !file ) { LL_WARNS() << "Couldn't open file " << path << LL_ENDL; diff --git a/indra/llmessage/llassetstorage.cpp b/indra/llmessage/llassetstorage.cpp index 34eeacb273..13be0161b4 100644 --- a/indra/llmessage/llassetstorage.cpp +++ b/indra/llmessage/llassetstorage.cpp @@ -1402,7 +1402,7 @@ void LLAssetStorage::legacyGetDataCallback(const LLUUID &uuid, uuid.toString(uuid_str); filename = llformat("%s.%s",gDirUtilp->getExpandedFilename(LL_PATH_CACHE,uuid_str).c_str(),LLAssetType::lookup(type)); - LLFILE* fp = LLFile::fopen(filename, "wb"); /* Flawfinder: ignore */ + LLFILE* fp = LLFile::fopen(filename, TEXT("wb")); /* Flawfinder: ignore */ if (fp) { const S32 buf_size = 65536; diff --git a/indra/llmessage/lltransfersourcefile.cpp b/indra/llmessage/lltransfersourcefile.cpp index 77a6c466c7..c2bf5c2afa 100644 --- a/indra/llmessage/lltransfersourcefile.cpp +++ b/indra/llmessage/lltransfersourcefile.cpp @@ -62,7 +62,7 @@ void LLTransferSourceFile::initTransfer() return; } // Look for the file. - mFP = LLFile::fopen(mParams.getFilename(), "rb"); /* Flawfinder: ignore */ + mFP = LLFile::fopen(mParams.getFilename(), TEXT("rb")); /* Flawfinder: ignore */ if (!mFP) { sendTransferStatus(LLTS_ERROR); diff --git a/indra/llmessage/lltransfertargetfile.cpp b/indra/llmessage/lltransfertargetfile.cpp index 6d8b69fa6f..cc66befcae 100644 --- a/indra/llmessage/lltransfertargetfile.cpp +++ b/indra/llmessage/lltransfertargetfile.cpp @@ -75,7 +75,7 @@ LLTSCode LLTransferTargetFile::dataCallback(const S32 packet_id, U8 *in_datap, c if (!mFP) { - mFP = LLFile::fopen(mParams.mFilename, "wb"); /* Flawfinder: ignore */ + mFP = LLFile::fopen(mParams.mFilename, TEXT("wb")); /* Flawfinder: ignore */ if (!mFP) { diff --git a/indra/llmessage/llxfer_file.cpp b/indra/llmessage/llxfer_file.cpp index 71b910297b..f0310c6297 100644 --- a/indra/llmessage/llxfer_file.cpp +++ b/indra/llmessage/llxfer_file.cpp @@ -161,7 +161,7 @@ S32 LLXfer_File::initializeRequest(U64 xfer_id, S32 LLXfer_File::startDownload() { S32 retval = 0; // presume success - mFp = LLFile::fopen(mTempFilename,"w+b"); /* Flawfinder : ignore */ + mFp = LLFile::fopen(mTempFilename,TEXT("w+b")); /* Flawfinder : ignore */ if (mFp) { fclose(mFp); @@ -209,7 +209,7 @@ S32 LLXfer_File::startSend (U64 xfer_id, const LLHost &remote_host) mBufferStartOffset = 0; // We leave the file open, assuming we'll start reading and sending soon - mFp = LLFile::fopen(mLocalFilename,"rb"); /* Flawfinder : ignore */ + mFp = LLFile::fopen(mLocalFilename,TEXT("rb")); /* Flawfinder : ignore */ if (mFp) { fseek(mFp,0,SEEK_END); @@ -252,7 +252,7 @@ S32 LLXfer_File::reopenFileHandle() if (mFp == NULL) { - mFp = LLFile::fopen(mLocalFilename,"rb"); /* Flawfinder : ignore */ + mFp = LLFile::fopen(mLocalFilename,TEXT("rb")); /* Flawfinder : ignore */ if (mFp == NULL) { LL_INFOS("Xfer") << "Warning: " << mLocalFilename << " not found when re-opening file" << LL_ENDL; @@ -313,7 +313,7 @@ S32 LLXfer_File::flush() { LL_ERRS("Xfer") << "Overwriting open file pointer!" << LL_ENDL; } - mFp = LLFile::fopen(mTempFilename,"a+b"); /* Flawfinder : ignore */ + mFp = LLFile::fopen(mTempFilename,TEXT("a+b")); /* Flawfinder : ignore */ if (mFp) { @@ -381,11 +381,11 @@ S32 LLXfer_File::processEOF() } else { - //LLFILE* fp = LLFile::fopen(mTempFilename, "r"); + //LLFILE* fp = LLFile::fopen(mTempFilename, TEXT("r")); //LL_WARNS() << "File " << mTempFilename << " does " // << (!fp ? "not" : "" ) << " exit." << LL_ENDL; //if(fp) fclose(fp); - //fp = LLFile::fopen(mLocalFilename, "r"); + //fp = LLFile::fopen(mLocalFilename, TEXT("r")); //LL_WARNS() << "File " << mLocalFilename << " does " // << (!fp ? "not" : "" ) << " exit." << LL_ENDL; //if(fp) fclose(fp); @@ -452,8 +452,8 @@ U32 LLXfer_File::getXferTypeTag() S32 copy_file(const std::string& from, const std::string& to) { S32 rv = 0; - LLFILE* in = LLFile::fopen(from, "rb"); /*Flawfinder: ignore*/ - LLFILE* out = LLFile::fopen(to, "wb"); /*Flawfinder: ignore*/ + LLFILE* in = LLFile::fopen(from, TEXT("rb")); /*Flawfinder: ignore*/ + LLFILE* out = LLFile::fopen(to, TEXT("wb")); /*Flawfinder: ignore*/ if(in && out) { S32 read = 0; diff --git a/indra/llmessage/message.cpp b/indra/llmessage/message.cpp index e2937490ba..5b3b57f11e 100644 --- a/indra/llmessage/message.cpp +++ b/indra/llmessage/message.cpp @@ -2376,7 +2376,7 @@ void dump_prehash_files() { U32 i; std::string filename("../../indra/llmessage/message_prehash.h"); - LLFILE* fp = LLFile::fopen(filename, "w"); /* Flawfinder: ignore */ + LLFILE* fp = LLFile::fopen(filename, TEXT("w")); /* Flawfinder: ignore */ if (fp) { fprintf( @@ -2407,7 +2407,7 @@ void dump_prehash_files() fclose(fp); } filename = std::string("../../indra/llmessage/message_prehash.cpp"); - fp = LLFile::fopen(filename, "w"); /* Flawfinder: ignore */ + fp = LLFile::fopen(filename, TEXT("w")); /* Flawfinder: ignore */ if (fp) { fprintf( diff --git a/indra/llmessage/tests/lldatapacker_test.cpp b/indra/llmessage/tests/lldatapacker_test.cpp index 746817936d..92a2c31ca8 100644 --- a/indra/llmessage/tests/lldatapacker_test.cpp +++ b/indra/llmessage/tests/lldatapacker_test.cpp @@ -348,7 +348,7 @@ namespace tut { F32 f_val = 44.44f, f_unpkval; - LLFILE* fp = LLFile::fopen(TEST_FILE_NAME, "w+"); + LLFILE* fp = LLFile::fopen(TEST_FILE_NAME, TEXT("w+")); if(!fp) { LL_ERRS() << "File couldnt be open" << LL_ENDL; @@ -403,7 +403,7 @@ namespace tut LLVector4 unpkllvec4; LLUUID unpkuuid; - LLFILE* fp = LLFile::fopen(TEST_FILE_NAME,"w+"); + LLFILE* fp = LLFile::fopen(TEST_FILE_NAME,TEXT("w+")); if(!fp) { LL_ERRS() << "File couldnt be open" << LL_ENDL; diff --git a/indra/llrender/llshadermgr.cpp b/indra/llrender/llshadermgr.cpp index 7e8d31232b..0ed98f2e7e 100644 --- a/indra/llrender/llshadermgr.cpp +++ b/indra/llrender/llshadermgr.cpp @@ -501,7 +501,7 @@ GLuint LLShaderMgr::loadShaderFile(const std::string& filename, S32 & shader_lev open_file_name = gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS, "shaders/errorF.glsl"); } - file = LLFile::fopen(open_file_name, "r"); + file = LLFile::fopen(open_file_name, TEXT("r")); } else #endif @@ -529,7 +529,7 @@ GLuint LLShaderMgr::loadShaderFile(const std::string& filename, S32 & shader_lev */ LL_DEBUGS("ShaderLoading") << "Looking in " << open_file_name << LL_ENDL; - file = LLFile::fopen(open_file_name, "r"); /* Flawfinder: ignore */ + file = LLFile::fopen(open_file_name, TEXT("r")); /* Flawfinder: ignore */ if (file) { LL_DEBUGS("ShaderLoading") << "Loading file: " << open_file_name << " (Want class " << gpu_class << ")" << LL_ENDL; diff --git a/indra/llui/lluicolortable.cpp b/indra/llui/lluicolortable.cpp index a792cb8103..206d02b366 100644 --- a/indra/llui/lluicolortable.cpp +++ b/indra/llui/lluicolortable.cpp @@ -298,7 +298,7 @@ void LLUIColorTable::saveUserSettings() const if(!output_node->isNull()) { const std::string& filename = gDirUtilp->getExpandedFilename(LL_PATH_USER_SETTINGS, "colors.xml"); - LLFILE *fp = LLFile::fopen(filename, "w"); + LLFILE *fp = LLFile::fopen(filename, TEXT("w")); if(fp != NULL) { diff --git a/indra/llui/llxuiparser.cpp b/indra/llui/llxuiparser.cpp index 8fd85a89a1..e3d806bdd0 100644 --- a/indra/llui/llxuiparser.cpp +++ b/indra/llui/llxuiparser.cpp @@ -637,7 +637,7 @@ void LLXUIXSDWriter::writeXSD(const std::string& type_name, const std::string& p } } - LLFILE* xsd_file = LLFile::fopen(file_name.c_str(), "w"); + LLFILE* xsd_file = LLFile::fopen(file_name.c_str(), TEXT("w")); LLXMLNode::writeHeaderToFile(xsd_file); root_nodep->writeToFile(xsd_file); fclose(xsd_file); @@ -1326,7 +1326,7 @@ void LLXUIParser::parserError(const std::string& message) struct ScopedFile { - ScopedFile( const std::string& filename, const char* accessmode ) + ScopedFile( const std::string& filename, const LLFile::fopen_flags_t* accessmode ) { mFile = LLFile::fopen(filename, accessmode); } @@ -1397,7 +1397,7 @@ bool LLSimpleXUIParser::readXUI(const std::string& filename, LLInitParam::BaseBl mCurReadDepth = 0; setParseSilently(silent); - ScopedFile file(filename, "rb"); + ScopedFile file(filename, TEXT("rb")); if( !file.isOpen() ) { LL_WARNS("ReadXUI") << "Unable to open file " << filename << LL_ENDL; diff --git a/indra/llxml/llcontrol.cpp b/indra/llxml/llcontrol.cpp index 562a30e8d1..a8e44f7bdd 100644 --- a/indra/llxml/llcontrol.cpp +++ b/indra/llxml/llcontrol.cpp @@ -399,7 +399,7 @@ void LLControlGroup::cleanup() if(mSettingsProfile && getCount.size() != 0) { std::string file = gDirUtilp->getExpandedFilename(LL_PATH_LOGS, SETTINGS_PROFILE); - LLFILE* out = LLFile::fopen(file, "w"); /* Flawfinder: ignore */ + LLFILE* out = LLFile::fopen(file, TEXT("w")); /* Flawfinder: ignore */ if(!out) { LL_WARNS("SettingsProfile") << "Error opening " << SETTINGS_PROFILE << LL_ENDL; diff --git a/indra/llxml/llxmlparser.cpp b/indra/llxml/llxmlparser.cpp index e2c7d17e2a..5aac9100dd 100644 --- a/indra/llxml/llxmlparser.cpp +++ b/indra/llxml/llxmlparser.cpp @@ -72,7 +72,7 @@ bool LLXmlParser::parseFile(const std::string &path) bool success = true; - LLFILE* file = LLFile::fopen(path, "rb"); /* Flawfinder: ignore */ + LLFILE* file = LLFile::fopen(path, TEXT("rb")); /* Flawfinder: ignore */ if( !file ) { mAuxErrorString = llformat( "Couldn't open file %s", path.c_str()); @@ -388,7 +388,7 @@ int main() { char buf[1024]; - LLFILE* file = LLFile::fopen("test.xml", "rb"); + LLFILE* file = LLFile::fopen("test.xml", TEXT("rb")); if( !file ) { return 1; diff --git a/indra/newview/llconversationlog.cpp b/indra/newview/llconversationlog.cpp index 4a4985d8ac..63a3743ef7 100644 --- a/indra/newview/llconversationlog.cpp +++ b/indra/newview/llconversationlog.cpp @@ -512,7 +512,7 @@ bool LLConversationLog::saveToFile(const std::string& filename) return false; } - LLFILE* fp = LLFile::fopen(filename, "wb"); + LLFILE* fp = LLFile::fopen(filename, TEXT("wb")); if (!fp) { LL_WARNS() << "Couldn't open call log list" << filename << LL_ENDL; @@ -556,7 +556,7 @@ bool LLConversationLog::loadFromFile(const std::string& filename) return false; } - LLFILE* fp = LLFile::fopen(filename, "rb"); + LLFILE* fp = LLFile::fopen(filename, TEXT("rb")); if (!fp) { LL_WARNS() << "Couldn't open call log list" << filename << LL_ENDL; diff --git a/indra/newview/lldrawpoolbump.cpp b/indra/newview/lldrawpoolbump.cpp index 6c151351ff..200fce7b5b 100644 --- a/indra/newview/lldrawpoolbump.cpp +++ b/indra/newview/lldrawpoolbump.cpp @@ -114,7 +114,7 @@ void LLStandardBumpmap::addstandard() gStandardBumpmapList[LLStandardBumpmap::sStandardBumpmapCount++] = LLStandardBumpmap("Darkness"); // BE_DARKNESS std::string file_name = gDirUtilp->getExpandedFilename( LL_PATH_APP_SETTINGS, "std_bump.ini" ); - LLFILE* file = LLFile::fopen( file_name, "rt" ); /*Flawfinder: ignore*/ + LLFILE* file = LLFile::fopen( file_name, TEXT("rt") ); /*Flawfinder: ignore*/ if( !file ) { LL_WARNS() << "Could not open std_bump <" << file_name << ">" << LL_ENDL; diff --git a/indra/newview/llfloaterpreference.cpp b/indra/newview/llfloaterpreference.cpp index 4fa14a199d..989dbc0c29 100755 --- a/indra/newview/llfloaterpreference.cpp +++ b/indra/newview/llfloaterpreference.cpp @@ -2037,9 +2037,13 @@ void LLFloaterPreference::changed() { // onClearLog clears list, then notifies changed() and only then clears file, // so check presence of conversations before checking file, file will cleared later. - bool has_logs = LLConversationLog::instance().getConversations().size() > 0 - && LLFile::isfile(LLConversationLog::instance().getFileName()) - && LLFile::size(LLConversationLog::instance().getFileName()) > 0; + bool has_logs = false; + if (LLConversationLog::instance().getConversations().size() > 0) + { + std::filesystem::path file_path = fsyspath(LLConversationLog::instance().getFileName()); + has_logs = LLFile::isfile(file_path) + && LLFile::size(file_path) > 0; + } getChild("clear_log")->setEnabled(has_logs); } diff --git a/indra/newview/llfloateruipreview.cpp b/indra/newview/llfloateruipreview.cpp index 0bf0946c42..cf710d45dd 100755 --- a/indra/newview/llfloateruipreview.cpp +++ b/indra/newview/llfloateruipreview.cpp @@ -574,7 +574,7 @@ void LLFloaterUIPreview::onClickExportSchema() // std::string file_name(template_path + gDirUtilp->getDirDelimiter() + widget_name + ".rng"); - // LLFILE* rng_file = LLFile::fopen(file_name.c_str(), "w"); + // LLFILE* rng_file = LLFile::fopen(file_name.c_str(), TEXT("w")); // { // LLXMLNode::writeHeaderToFile(rng_file); // const bool use_type_decorations = false; diff --git a/indra/newview/llinventorymodel.cpp b/indra/newview/llinventorymodel.cpp index 043fd7003d..9491c9d610 100644 --- a/indra/newview/llinventorymodel.cpp +++ b/indra/newview/llinventorymodel.cpp @@ -2745,7 +2745,7 @@ bool LLInventoryModel::loadSkeleton( const S32 NO_VERSION = LLViewerInventoryCategory::VERSION_UNKNOWN; std::string gzip_filename(inventory_filename); gzip_filename.append(".gz"); - LLFILE* fp = LLFile::fopen(gzip_filename, "rb"); + LLFILE* fp = LLFile::fopen(gzip_filename, TEXT("rb")); bool remove_inventory_file = false; if (LLAppViewer::instance()->isSecondInstance()) { @@ -4908,7 +4908,7 @@ bool decompress_file(const char* src_filename, const char* dst_filename) // open the files src = gzopen(src_filename, "rb"); if(!src) goto err_decompress; - dst = LLFile::fopen(dst_filename, "wb"); + dst = LLFile::fopen(dst_filename, TEXT("wb")); if(!dst) goto err_decompress; // decompress. diff --git a/indra/newview/llkeyconflict.cpp b/indra/newview/llkeyconflict.cpp index 666ab4f5d0..458d5225e1 100644 --- a/indra/newview/llkeyconflict.cpp +++ b/indra/newview/llkeyconflict.cpp @@ -575,7 +575,7 @@ void LLKeyConflictHandler::saveToSettings(bool temporary) // Write the resulting XML to file if (!output_node->isNull()) { - LLFILE *fp = LLFile::fopen(filename, "w"); + LLFILE *fp = LLFile::fopen(filename, TEXT("w")); if (fp != NULL) { LLXMLNode::writeHeaderToFile(fp); diff --git a/indra/newview/lllogchat.cpp b/indra/newview/lllogchat.cpp index 30ea255e24..405530f5bd 100644 --- a/indra/newview/lllogchat.cpp +++ b/indra/newview/lllogchat.cpp @@ -453,7 +453,7 @@ void LLLogChat::loadChatHistory(const std::string& file_name, std::list& m // If we got here, we managed to stat the file. // Open the file to read in binary mode to prevent interpreting other characters as EOF - LLFILE* fptr = LLFile::fopen(log_file_name, "rb"); /*Flawfinder: ignore*/ + LLFILE* fptr = LLFile::fopen(log_file_name, TEXT("rb")); /*Flawfinder: ignore*/ if (!fptr) { // Ok, this is strange but not really tragic in the big picture of things LL_WARNS("ChatHistory") << "Unable to read file " << log_file_name << " after stat was successful" << LL_ENDL; @@ -890,7 +890,7 @@ bool LLLogChat::isAdHocTranscriptExist(std::string file_name) bool LLLogChat::isTranscriptFileFound(std::string fullname) { bool result = false; - LLFILE * filep = LLFile::fopen(fullname, "rb"); + LLFILE * filep = LLFile::fopen(fullname, TEXT("rb")); if (NULL != filep) { if (makeLogFileName("chat") == fullname) @@ -1183,7 +1183,7 @@ void LLLoadHistoryThread::loadHistory(const std::string& file_name, std::listgetExpandedFilename(LL_PATH_PER_SL_ACCOUNT, "render_mute_settings.txt"); - LLFILE* fp = LLFile::fopen(filename, "wb"); + LLFILE* fp = LLFile::fopen(filename, TEXT("wb")); if (!fp) { LL_WARNS() << "Couldn't open render mute list file: " << filename << LL_ENDL; @@ -963,7 +963,7 @@ bool LLRenderMuteList::saveToFile() bool LLRenderMuteList::loadFromFile() { std::string filename = gDirUtilp->getExpandedFilename(LL_PATH_PER_SL_ACCOUNT, "render_mute_settings.txt"); - LLFILE* fp = LLFile::fopen(filename, "rb"); + LLFILE* fp = LLFile::fopen(filename, TEXT("rb")); if (!fp) { LL_WARNS() << "Couldn't open render mute list file: " << filename << LL_ENDL; diff --git a/indra/newview/llpreviewnotecard.cpp b/indra/newview/llpreviewnotecard.cpp index 4fe661b055..6928d7e6c3 100644 --- a/indra/newview/llpreviewnotecard.cpp +++ b/indra/newview/llpreviewnotecard.cpp @@ -801,7 +801,7 @@ bool LLPreviewNotecard::loadNotecardText(const std::string& filename) return false; } - LLFILE* file = LLFile::fopen(filename, "rb"); /*Flawfinder: ignore*/ + LLFILE* file = LLFile::fopen(filename, TEXT("rb")); /*Flawfinder: ignore*/ if (!file) { LL_WARNS() << "Error opening " << filename << LL_ENDL; @@ -832,7 +832,7 @@ bool LLPreviewNotecard::loadNotecardText(const std::string& filename) bool LLPreviewNotecard::writeToFile(const std::string& filename) { - LLFILE* fp = LLFile::fopen(filename, "wb"); + LLFILE* fp = LLFile::fopen(filename, TEXT("wb")); if (!fp) { LL_WARNS() << "Unable to write to " << filename << LL_ENDL; diff --git a/indra/newview/llpreviewscript.cpp b/indra/newview/llpreviewscript.cpp index 2c436198e3..c73976e540 100644 --- a/indra/newview/llpreviewscript.cpp +++ b/indra/newview/llpreviewscript.cpp @@ -632,7 +632,7 @@ bool LLScriptEdCore::loadScriptText(const std::string& filename) return false; } - LLFILE* file = LLFile::fopen(filename, "rb"); /*Flawfinder: ignore*/ + LLFILE* file = LLFile::fopen(filename, TEXT("rb")); /*Flawfinder: ignore*/ if (!file) { LL_WARNS() << "Error opening " << filename << LL_ENDL; @@ -663,7 +663,7 @@ bool LLScriptEdCore::loadScriptText(const std::string& filename) bool LLScriptEdCore::writeToFile(const std::string& filename) { - LLFILE* fp = LLFile::fopen(filename, "wb"); + LLFILE* fp = LLFile::fopen(filename, TEXT("wb")); if (!fp) { LL_WARNS() << "Unable to write to " << filename << LL_ENDL; diff --git a/indra/newview/llstartup.cpp b/indra/newview/llstartup.cpp index 3ce9526488..37609f74ed 100644 --- a/indra/newview/llstartup.cpp +++ b/indra/newview/llstartup.cpp @@ -587,7 +587,7 @@ bool idle_startup() std::string message_template_path = gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS,"message_template.msg"); LLFILE* found_template = NULL; - found_template = LLFile::fopen(message_template_path, "r"); /* Flawfinder: ignore */ + found_template = LLFile::fopen(message_template_path, TEXT("r")); /* Flawfinder: ignore */ #if LL_WINDOWS // On the windows dev builds, unpackaged, the message_template.msg @@ -596,7 +596,7 @@ bool idle_startup() if (!found_template) { message_template_path = gDirUtilp->getExpandedFilename(LL_PATH_EXECUTABLE, "app_settings", "message_template.msg"); - found_template = LLFile::fopen(message_template_path.c_str(), "r"); /* Flawfinder: ignore */ + found_template = LLFile::fopen(message_template_path.c_str(), TEXT("r")); /* Flawfinder: ignore */ } #elif LL_DARWIN // On Mac dev builds, message_template.msg lives in: @@ -606,7 +606,7 @@ bool idle_startup() message_template_path = gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS, "message_template.msg"); - found_template = LLFile::fopen(message_template_path.c_str(), "r"); /* Flawfinder: ignore */ + found_template = LLFile::fopen(message_template_path.c_str(), TEXT("r")); /* Flawfinder: ignore */ } #endif diff --git a/indra/newview/lltoolbarview.cpp b/indra/newview/lltoolbarview.cpp index c1ec5fa183..d1e36676af 100644 --- a/indra/newview/lltoolbarview.cpp +++ b/indra/newview/lltoolbarview.cpp @@ -420,7 +420,7 @@ void LLToolBarView::saveToolbars() const if(!output_node->isNull()) { const std::string& filename = gDirUtilp->getExpandedFilename(LL_PATH_PER_SL_ACCOUNT, "toolbars.xml"); - LLFILE *fp = LLFile::fopen(filename, "w"); + LLFILE *fp = LLFile::fopen(filename, TEXT("w")); if (fp != NULL) { LLXMLNode::writeHeaderToFile(fp); diff --git a/indra/newview/llviewerassetstorage.cpp b/indra/newview/llviewerassetstorage.cpp index e76d340eda..c28f3dc73a 100644 --- a/indra/newview/llviewerassetstorage.cpp +++ b/indra/newview/llviewerassetstorage.cpp @@ -182,7 +182,7 @@ void LLViewerAssetStorage::storeAssetData( else { // LLAssetStorage metric: Successful Request - S32 size = (S32)LLFileSystem::getFileSize(asset_id, asset_type); + S32 size = vfile.getSize(); const char *message = "Added to upload queue"; reportMetric( asset_id, asset_type, LLStringUtil::null, LLUUID::null, size, MR_OKAY, __FILE__, __LINE__, message ); @@ -279,7 +279,7 @@ void LLViewerAssetStorage::storeAssetData( LL_DEBUGS("AssetStorage") << "ASSET_ID: " << asset_id << LL_ENDL; S32 size = 0; - LLFILE* fp = LLFile::fopen(filename, "rb"); + LLFILE* fp = LLFile::fopen(filename, TEXT("rb")); if (fp) { fseek(fp, 0, SEEK_END); diff --git a/indra/newview/llviewerinput.cpp b/indra/newview/llviewerinput.cpp index 3c79f0b21c..9b39f7b0e9 100644 --- a/indra/newview/llviewerinput.cpp +++ b/indra/newview/llviewerinput.cpp @@ -1430,7 +1430,7 @@ S32 LLViewerInput::loadBindingsXML(const std::string& filename) // file in app_settings is supposed to be up to date // this is only for the file from user_settings LL_INFOS("ViewerInput") << "Updating file " << filename << " to a newer version" << LL_ENDL; - LLFILE *fp = LLFile::fopen(filename, "w"); + LLFILE *fp = LLFile::fopen(filename, TEXT("w")); if (fp != NULL) { LLXMLNode::writeHeaderToFile(fp); diff --git a/indra/newview/llviewermenufile.cpp b/indra/newview/llviewermenufile.cpp index 0e9bfb102f..a8ed2da9e0 100644 --- a/indra/newview/llviewermenufile.cpp +++ b/indra/newview/llviewermenufile.cpp @@ -1161,7 +1161,7 @@ void handle_compress_image() // so doing dirty, but OS independent fopen and fseek size_t get_file_size(std::string &filename) { - LLFILE* file = LLFile::fopen(filename, "rb"); /*Flawfinder: ignore*/ + LLFILE* file = LLFile::fopen(filename, TEXT("rb")); /*Flawfinder: ignore*/ if (!file) { LL_WARNS() << "Error opening " << filename << LL_ENDL; diff --git a/indra/newview/llviewerstatsrecorder.cpp b/indra/newview/llviewerstatsrecorder.cpp index 58065ecce5..a2141f4eed 100644 --- a/indra/newview/llviewerstatsrecorder.cpp +++ b/indra/newview/llviewerstatsrecorder.cpp @@ -194,7 +194,7 @@ void LLViewerStatsRecorder::writeToLog( F32 interval ) // Open the data file makeStatsFileName(); - mStatsFile = LLFile::fopen(mStatsFileName, "wb"); + mStatsFile = LLFile::fopen(mStatsFileName, TEXT("wb")); if (mStatsFile) { -- cgit v1.3 From 9873abfb94f0d9cbc6df60fef9df622ef51355ec Mon Sep 17 00:00:00 2001 From: Rye Date: Mon, 5 Jan 2026 15:01:23 -0500 Subject: Address feedback from copilot Signed-off-by: Rye --- indra/llappearance/llpolymesh.cpp | 2 +- indra/llcommon/llcrc.cpp | 2 +- indra/llcommon/llcrc.h | 2 +- indra/llcommon/llfile.h | 10 ++++------ indra/llcommon/llprocessor.cpp | 4 ++-- indra/llcommon/llsys.cpp | 6 +++--- indra/llfilesystem/lldir.cpp | 2 +- indra/llfilesystem/tests/lldir_test.cpp | 2 +- indra/llimage/llimagedimensionsinfo.cpp | 2 +- indra/llimage/llimagetga.cpp | 2 +- indra/llmessage/llassetstorage.cpp | 2 +- indra/llmessage/lltransfersourcefile.cpp | 2 +- indra/llmessage/lltransfertargetfile.cpp | 2 +- indra/llmessage/llxfer_file.cpp | 16 ++++++++-------- indra/llmessage/message.cpp | 4 ++-- indra/llmessage/tests/lldatapacker_test.cpp | 4 ++-- indra/llrender/llshadermgr.cpp | 4 ++-- indra/llui/lluicolortable.cpp | 2 +- indra/llui/llxuiparser.cpp | 4 ++-- indra/llxml/llcontrol.cpp | 2 +- indra/llxml/llxmlparser.cpp | 4 ++-- indra/newview/llconversationlog.cpp | 4 ++-- indra/newview/lldrawpoolbump.cpp | 2 +- indra/newview/llfloateruipreview.cpp | 2 +- indra/newview/llinventorymodel.cpp | 4 ++-- indra/newview/llkeyconflict.cpp | 2 +- indra/newview/lllogchat.cpp | 12 ++++++------ indra/newview/llmutelist.cpp | 8 ++++---- indra/newview/llpreviewnotecard.cpp | 4 ++-- indra/newview/llpreviewscript.cpp | 4 ++-- indra/newview/llstartup.cpp | 6 +++--- indra/newview/lltoolbarview.cpp | 2 +- indra/newview/llviewerassetstorage.cpp | 2 +- indra/newview/llviewerinput.cpp | 2 +- indra/newview/llviewermenufile.cpp | 2 +- indra/newview/llviewerstatsrecorder.cpp | 2 +- 36 files changed, 68 insertions(+), 70 deletions(-) (limited to 'indra/llmessage') diff --git a/indra/llappearance/llpolymesh.cpp b/indra/llappearance/llpolymesh.cpp index b579dc007b..45f51950ec 100644 --- a/indra/llappearance/llpolymesh.cpp +++ b/indra/llappearance/llpolymesh.cpp @@ -280,7 +280,7 @@ bool LLPolyMeshSharedData::loadMesh( const std::string& fileName ) LL_ERRS() << "Filename is Empty!" << LL_ENDL; return false; } - LLFILE* fp = LLFile::fopen(fileName, TEXT("rb")); /*Flawfinder: ignore*/ + LLFILE* fp = LLFile::fopen(fileName, LLFILE_MODE("rb")); /*Flawfinder: ignore*/ if (!fp) { LLError::LLUserWarningMsg::showMissingFiles(); diff --git a/indra/llcommon/llcrc.cpp b/indra/llcommon/llcrc.cpp index f836a12c35..33bf01a29b 100644 --- a/indra/llcommon/llcrc.cpp +++ b/indra/llcommon/llcrc.cpp @@ -166,7 +166,7 @@ void LLCRC::update(const std::string& filename) return; } - FILE* fp = LLFile::fopen(filename, TEXT("rb")); /* Flawfinder: ignore */ + FILE* fp = LLFile::fopen(filename, LLFILE_MODE("rb")); /* Flawfinder: ignore */ if (fp) { diff --git a/indra/llcommon/llcrc.h b/indra/llcommon/llcrc.h index cbf4cf4e75..2ea5fbc3b0 100644 --- a/indra/llcommon/llcrc.h +++ b/indra/llcommon/llcrc.h @@ -36,7 +36,7 @@ // example (don't try this at work kids): // // LLCRC crc; -// FILE* fp = LLFile::fopen(filename,TEXT("rb")); +// FILE* fp = LLFile::fopen(filename,LLFILE_MODE("rb")); // while(!feof(fp)) { // crc.update(fgetc(fp)); // } diff --git a/indra/llcommon/llfile.h b/indra/llcommon/llfile.h index 7e8e114098..8de3f5c9b4 100755 --- a/indra/llcommon/llfile.h +++ b/indra/llcommon/llfile.h @@ -56,12 +56,10 @@ typedef FILE LLFILE; #include "fsyspath.h" #include "llstring.h" // safe char* -> std::string conversion -#ifndef TEXT #if LL_WINDOWS -#define TEXT(flags) L##flags +#define LLFILE_MODE(flags) L##flags #else -#define TEXT(flags) flags -#endif +#define LLFILE_MODE(flags) flags #endif /// This class provides a selection of functions to operate on files through names and @@ -415,7 +413,7 @@ public: std::error_code ec; return copy(source, target, std::filesystem::copy_options::overwrite_existing, ec); } - inline static bool copy(const std::string& source, char* target) + inline static bool copy(const std::string& source, const char* target) { std::error_code ec; return copy(source, target, std::filesystem::copy_options::overwrite_existing, ec); @@ -686,7 +684,7 @@ private: #else typedef int llfile_handle_t; const llfile_handle_t InvalidHandle = -1; - llfile_handle_t mHandle = -1;; // The file handle/descriptor + llfile_handle_t mHandle = -1; // The file handle/descriptor #endif std::ios_base::openmode mOpen{}; // Used to emulate std::ios_base::app under Windows diff --git a/indra/llcommon/llprocessor.cpp b/indra/llcommon/llprocessor.cpp index 7656986fe2..9d0ef45bee 100644 --- a/indra/llcommon/llprocessor.cpp +++ b/indra/llcommon/llprocessor.cpp @@ -837,7 +837,7 @@ private: void get_proc_cpuinfo() { std::map< std::string, std::string > cpuinfo; - LLFILE* cpuinfo_fp = LLFile::fopen(CPUINFO_FILE, TEXT("rb")); + LLFILE* cpuinfo_fp = LLFile::fopen(CPUINFO_FILE, LLFILE_MODE("rb")); if(cpuinfo_fp) { char line[MAX_STRING]; @@ -954,7 +954,7 @@ private: std::ostringstream s; // *NOTE:Mani - This is for linux only. - LLFILE* cpuinfo = LLFile::fopen(CPUINFO_FILE, TEXT("rb")); + LLFILE* cpuinfo = LLFile::fopen(CPUINFO_FILE, LLFILE_MODE("rb")); if(cpuinfo) { char line[MAX_STRING]; diff --git a/indra/llcommon/llsys.cpp b/indra/llcommon/llsys.cpp index 499de996e2..5ef042b5a7 100644 --- a/indra/llcommon/llsys.cpp +++ b/indra/llcommon/llsys.cpp @@ -514,7 +514,7 @@ namespace { #if LL_LINUX constexpr U32 STATUS_SIZE = 2048; - LLFILE* status_filep = LLFile::fopen("/proc/self/status", TEXT("rb")); + LLFILE* status_filep = LLFile::fopen("/proc/self/status", LLFILE_MODE("rb")); if (status_filep) { char buff[STATUS_SIZE]; /* Flawfinder: ignore */ @@ -1273,7 +1273,7 @@ bool gunzip_file(const std::string& srcfile, const std::string& dstfile) src = gzopen(srcfile.c_str(), "rb"); #endif if (! src) goto err; - dst = LLFile::fopen(tmpfile, TEXT("wb")); /* Flawfinder: ignore */ + dst = LLFile::fopen(tmpfile, LLFILE_MODE("wb")); /* Flawfinder: ignore */ if (! dst) goto err; do { @@ -1314,7 +1314,7 @@ bool gzip_file(const std::string& srcfile, const std::string& dstfile) #endif if (! dst) goto err; - src = LLFile::fopen(srcfile, TEXT("rb")); /* Flawfinder: ignore */ + src = LLFile::fopen(srcfile, LLFILE_MODE("rb")); /* Flawfinder: ignore */ if (! src) goto err; while ((bytes = (S32)fread(buffer, sizeof(U8), COMPRESS_BUFFER_SIZE, src)) > 0) diff --git a/indra/llfilesystem/lldir.cpp b/indra/llfilesystem/lldir.cpp index 3ec8983e8a..1a647362c5 100755 --- a/indra/llfilesystem/lldir.cpp +++ b/indra/llfilesystem/lldir.cpp @@ -1010,7 +1010,7 @@ bool LLDir::setCacheDir(const std::string &path) { LLFile::mkdir(path); std::string tempname = add(path, "temp"); - LLFILE* file = LLFile::fopen(tempname, TEXT("wt")); + LLFILE* file = LLFile::fopen(tempname, LLFILE_MODE("wt")); if (file) { fclose(file); diff --git a/indra/llfilesystem/tests/lldir_test.cpp b/indra/llfilesystem/tests/lldir_test.cpp index b879fef48a..412feb147b 100644 --- a/indra/llfilesystem/tests/lldir_test.cpp +++ b/indra/llfilesystem/tests/lldir_test.cpp @@ -405,7 +405,7 @@ namespace tut std::string makeTestFile( const std::string& dir, const std::string& file ) { std::string path = dir + file; - LLFILE* handle = LLFile::fopen(path, TEXT("w")); + LLFILE* handle = LLFile::fopen(path, LLFILE_MODE("w")); ensure("failed to open test file '"+path+"'", handle != NULL ); // Harbison & Steele, 4th ed., p. 366: "If an error occurs, fputs // returns EOF; otherwise, it returns some other, nonnegative value." diff --git a/indra/llimage/llimagedimensionsinfo.cpp b/indra/llimage/llimagedimensionsinfo.cpp index 1d93014e1b..2ae7760d4c 100644 --- a/indra/llimage/llimagedimensionsinfo.cpp +++ b/indra/llimage/llimagedimensionsinfo.cpp @@ -166,7 +166,7 @@ bool LLImageDimensionsInfo::getImageDimensionsJpeg() { sJpegErrorEncountered = false; clean(); - FILE* fp = LLFile::fopen(mSrcFilename, TEXT("rb")); + FILE* fp = LLFile::fopen(mSrcFilename, LLFILE_MODE("rb")); if (!fp) { setLastError("Unable to open file for reading", mSrcFilename); diff --git a/indra/llimage/llimagetga.cpp b/indra/llimage/llimagetga.cpp index 7c6686db95..7b09553974 100644 --- a/indra/llimage/llimagetga.cpp +++ b/indra/llimage/llimagetga.cpp @@ -1191,7 +1191,7 @@ bool LLImageTGA::loadFile( const std::string& path ) return false; } - LLFILE* file = LLFile::fopen(path, TEXT("rb")); /* Flawfinder: ignore */ + LLFILE* file = LLFile::fopen(path, LLFILE_MODE("rb")); /* Flawfinder: ignore */ if( !file ) { LL_WARNS() << "Couldn't open file " << path << LL_ENDL; diff --git a/indra/llmessage/llassetstorage.cpp b/indra/llmessage/llassetstorage.cpp index 13be0161b4..a8f0554a71 100644 --- a/indra/llmessage/llassetstorage.cpp +++ b/indra/llmessage/llassetstorage.cpp @@ -1402,7 +1402,7 @@ void LLAssetStorage::legacyGetDataCallback(const LLUUID &uuid, uuid.toString(uuid_str); filename = llformat("%s.%s",gDirUtilp->getExpandedFilename(LL_PATH_CACHE,uuid_str).c_str(),LLAssetType::lookup(type)); - LLFILE* fp = LLFile::fopen(filename, TEXT("wb")); /* Flawfinder: ignore */ + LLFILE* fp = LLFile::fopen(filename, LLFILE_MODE("wb")); /* Flawfinder: ignore */ if (fp) { const S32 buf_size = 65536; diff --git a/indra/llmessage/lltransfersourcefile.cpp b/indra/llmessage/lltransfersourcefile.cpp index c2bf5c2afa..d2d264c520 100644 --- a/indra/llmessage/lltransfersourcefile.cpp +++ b/indra/llmessage/lltransfersourcefile.cpp @@ -62,7 +62,7 @@ void LLTransferSourceFile::initTransfer() return; } // Look for the file. - mFP = LLFile::fopen(mParams.getFilename(), TEXT("rb")); /* Flawfinder: ignore */ + mFP = LLFile::fopen(mParams.getFilename(), LLFILE_MODE("rb")); /* Flawfinder: ignore */ if (!mFP) { sendTransferStatus(LLTS_ERROR); diff --git a/indra/llmessage/lltransfertargetfile.cpp b/indra/llmessage/lltransfertargetfile.cpp index cc66befcae..05dba219ed 100644 --- a/indra/llmessage/lltransfertargetfile.cpp +++ b/indra/llmessage/lltransfertargetfile.cpp @@ -75,7 +75,7 @@ LLTSCode LLTransferTargetFile::dataCallback(const S32 packet_id, U8 *in_datap, c if (!mFP) { - mFP = LLFile::fopen(mParams.mFilename, TEXT("wb")); /* Flawfinder: ignore */ + mFP = LLFile::fopen(mParams.mFilename, LLFILE_MODE("wb")); /* Flawfinder: ignore */ if (!mFP) { diff --git a/indra/llmessage/llxfer_file.cpp b/indra/llmessage/llxfer_file.cpp index f0310c6297..5f27cc4827 100644 --- a/indra/llmessage/llxfer_file.cpp +++ b/indra/llmessage/llxfer_file.cpp @@ -161,7 +161,7 @@ S32 LLXfer_File::initializeRequest(U64 xfer_id, S32 LLXfer_File::startDownload() { S32 retval = 0; // presume success - mFp = LLFile::fopen(mTempFilename,TEXT("w+b")); /* Flawfinder : ignore */ + mFp = LLFile::fopen(mTempFilename,LLFILE_MODE("w+b")); /* Flawfinder : ignore */ if (mFp) { fclose(mFp); @@ -209,7 +209,7 @@ S32 LLXfer_File::startSend (U64 xfer_id, const LLHost &remote_host) mBufferStartOffset = 0; // We leave the file open, assuming we'll start reading and sending soon - mFp = LLFile::fopen(mLocalFilename,TEXT("rb")); /* Flawfinder : ignore */ + mFp = LLFile::fopen(mLocalFilename, LLFILE_MODE("rb")); /* Flawfinder : ignore */ if (mFp) { fseek(mFp,0,SEEK_END); @@ -252,7 +252,7 @@ S32 LLXfer_File::reopenFileHandle() if (mFp == NULL) { - mFp = LLFile::fopen(mLocalFilename,TEXT("rb")); /* Flawfinder : ignore */ + mFp = LLFile::fopen(mLocalFilename, LLFILE_MODE("rb")); /* Flawfinder : ignore */ if (mFp == NULL) { LL_INFOS("Xfer") << "Warning: " << mLocalFilename << " not found when re-opening file" << LL_ENDL; @@ -313,7 +313,7 @@ S32 LLXfer_File::flush() { LL_ERRS("Xfer") << "Overwriting open file pointer!" << LL_ENDL; } - mFp = LLFile::fopen(mTempFilename,TEXT("a+b")); /* Flawfinder : ignore */ + mFp = LLFile::fopen(mTempFilename, LLFILE_MODE("a+b")); /* Flawfinder : ignore */ if (mFp) { @@ -381,11 +381,11 @@ S32 LLXfer_File::processEOF() } else { - //LLFILE* fp = LLFile::fopen(mTempFilename, TEXT("r")); + //LLFILE* fp = LLFile::fopen(mTempFilename, LLFILE_MODE("r")); //LL_WARNS() << "File " << mTempFilename << " does " // << (!fp ? "not" : "" ) << " exit." << LL_ENDL; //if(fp) fclose(fp); - //fp = LLFile::fopen(mLocalFilename, TEXT("r")); + //fp = LLFile::fopen(mLocalFilename, LLFILE_MODE("r")); //LL_WARNS() << "File " << mLocalFilename << " does " // << (!fp ? "not" : "" ) << " exit." << LL_ENDL; //if(fp) fclose(fp); @@ -452,8 +452,8 @@ U32 LLXfer_File::getXferTypeTag() S32 copy_file(const std::string& from, const std::string& to) { S32 rv = 0; - LLFILE* in = LLFile::fopen(from, TEXT("rb")); /*Flawfinder: ignore*/ - LLFILE* out = LLFile::fopen(to, TEXT("wb")); /*Flawfinder: ignore*/ + LLFILE* in = LLFile::fopen(from, LLFILE_MODE("rb")); /*Flawfinder: ignore*/ + LLFILE* out = LLFile::fopen(to, LLFILE_MODE("wb")); /*Flawfinder: ignore*/ if(in && out) { S32 read = 0; diff --git a/indra/llmessage/message.cpp b/indra/llmessage/message.cpp index 5b3b57f11e..df58c8a7f3 100644 --- a/indra/llmessage/message.cpp +++ b/indra/llmessage/message.cpp @@ -2376,7 +2376,7 @@ void dump_prehash_files() { U32 i; std::string filename("../../indra/llmessage/message_prehash.h"); - LLFILE* fp = LLFile::fopen(filename, TEXT("w")); /* Flawfinder: ignore */ + LLFILE* fp = LLFile::fopen(filename, LLFILE_MODE("w")); /* Flawfinder: ignore */ if (fp) { fprintf( @@ -2407,7 +2407,7 @@ void dump_prehash_files() fclose(fp); } filename = std::string("../../indra/llmessage/message_prehash.cpp"); - fp = LLFile::fopen(filename, TEXT("w")); /* Flawfinder: ignore */ + fp = LLFile::fopen(filename, LLFILE_MODE("w")); /* Flawfinder: ignore */ if (fp) { fprintf( diff --git a/indra/llmessage/tests/lldatapacker_test.cpp b/indra/llmessage/tests/lldatapacker_test.cpp index 92a2c31ca8..5823980d43 100644 --- a/indra/llmessage/tests/lldatapacker_test.cpp +++ b/indra/llmessage/tests/lldatapacker_test.cpp @@ -348,7 +348,7 @@ namespace tut { F32 f_val = 44.44f, f_unpkval; - LLFILE* fp = LLFile::fopen(TEST_FILE_NAME, TEXT("w+")); + LLFILE* fp = LLFile::fopen(TEST_FILE_NAME, LLFILE_MODE("w+")); if(!fp) { LL_ERRS() << "File couldnt be open" << LL_ENDL; @@ -403,7 +403,7 @@ namespace tut LLVector4 unpkllvec4; LLUUID unpkuuid; - LLFILE* fp = LLFile::fopen(TEST_FILE_NAME,TEXT("w+")); + LLFILE* fp = LLFile::fopen(TEST_FILE_NAME, LLFILE_MODE("w+")); if(!fp) { LL_ERRS() << "File couldnt be open" << LL_ENDL; diff --git a/indra/llrender/llshadermgr.cpp b/indra/llrender/llshadermgr.cpp index 0ed98f2e7e..f6738364a6 100644 --- a/indra/llrender/llshadermgr.cpp +++ b/indra/llrender/llshadermgr.cpp @@ -501,7 +501,7 @@ GLuint LLShaderMgr::loadShaderFile(const std::string& filename, S32 & shader_lev open_file_name = gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS, "shaders/errorF.glsl"); } - file = LLFile::fopen(open_file_name, TEXT("r")); + file = LLFile::fopen(open_file_name, LLFILE_MODE("r")); } else #endif @@ -529,7 +529,7 @@ GLuint LLShaderMgr::loadShaderFile(const std::string& filename, S32 & shader_lev */ LL_DEBUGS("ShaderLoading") << "Looking in " << open_file_name << LL_ENDL; - file = LLFile::fopen(open_file_name, TEXT("r")); /* Flawfinder: ignore */ + file = LLFile::fopen(open_file_name, LLFILE_MODE("r")); /* Flawfinder: ignore */ if (file) { LL_DEBUGS("ShaderLoading") << "Loading file: " << open_file_name << " (Want class " << gpu_class << ")" << LL_ENDL; diff --git a/indra/llui/lluicolortable.cpp b/indra/llui/lluicolortable.cpp index 206d02b366..cd062b23b8 100644 --- a/indra/llui/lluicolortable.cpp +++ b/indra/llui/lluicolortable.cpp @@ -298,7 +298,7 @@ void LLUIColorTable::saveUserSettings() const if(!output_node->isNull()) { const std::string& filename = gDirUtilp->getExpandedFilename(LL_PATH_USER_SETTINGS, "colors.xml"); - LLFILE *fp = LLFile::fopen(filename, TEXT("w")); + LLFILE *fp = LLFile::fopen(filename, LLFILE_MODE("w")); if(fp != NULL) { diff --git a/indra/llui/llxuiparser.cpp b/indra/llui/llxuiparser.cpp index e3d806bdd0..9bf2f4220c 100644 --- a/indra/llui/llxuiparser.cpp +++ b/indra/llui/llxuiparser.cpp @@ -637,7 +637,7 @@ void LLXUIXSDWriter::writeXSD(const std::string& type_name, const std::string& p } } - LLFILE* xsd_file = LLFile::fopen(file_name.c_str(), TEXT("w")); + LLFILE* xsd_file = LLFile::fopen(file_name.c_str(), LLFILE_MODE("w")); LLXMLNode::writeHeaderToFile(xsd_file); root_nodep->writeToFile(xsd_file); fclose(xsd_file); @@ -1397,7 +1397,7 @@ bool LLSimpleXUIParser::readXUI(const std::string& filename, LLInitParam::BaseBl mCurReadDepth = 0; setParseSilently(silent); - ScopedFile file(filename, TEXT("rb")); + ScopedFile file(filename, LLFILE_MODE("rb")); if( !file.isOpen() ) { LL_WARNS("ReadXUI") << "Unable to open file " << filename << LL_ENDL; diff --git a/indra/llxml/llcontrol.cpp b/indra/llxml/llcontrol.cpp index a8e44f7bdd..24d2facc4c 100644 --- a/indra/llxml/llcontrol.cpp +++ b/indra/llxml/llcontrol.cpp @@ -399,7 +399,7 @@ void LLControlGroup::cleanup() if(mSettingsProfile && getCount.size() != 0) { std::string file = gDirUtilp->getExpandedFilename(LL_PATH_LOGS, SETTINGS_PROFILE); - LLFILE* out = LLFile::fopen(file, TEXT("w")); /* Flawfinder: ignore */ + LLFILE* out = LLFile::fopen(file, LLFILE_MODE("w")); /* Flawfinder: ignore */ if(!out) { LL_WARNS("SettingsProfile") << "Error opening " << SETTINGS_PROFILE << LL_ENDL; diff --git a/indra/llxml/llxmlparser.cpp b/indra/llxml/llxmlparser.cpp index 5aac9100dd..8afd412cda 100644 --- a/indra/llxml/llxmlparser.cpp +++ b/indra/llxml/llxmlparser.cpp @@ -72,7 +72,7 @@ bool LLXmlParser::parseFile(const std::string &path) bool success = true; - LLFILE* file = LLFile::fopen(path, TEXT("rb")); /* Flawfinder: ignore */ + LLFILE* file = LLFile::fopen(path, LLFILE_MODE("rb")); /* Flawfinder: ignore */ if( !file ) { mAuxErrorString = llformat( "Couldn't open file %s", path.c_str()); @@ -388,7 +388,7 @@ int main() { char buf[1024]; - LLFILE* file = LLFile::fopen("test.xml", TEXT("rb")); + LLFILE* file = LLFile::fopen("test.xml", LLFILE_MODE("rb")); if( !file ) { return 1; diff --git a/indra/newview/llconversationlog.cpp b/indra/newview/llconversationlog.cpp index 63a3743ef7..bfcc2e4182 100644 --- a/indra/newview/llconversationlog.cpp +++ b/indra/newview/llconversationlog.cpp @@ -512,7 +512,7 @@ bool LLConversationLog::saveToFile(const std::string& filename) return false; } - LLFILE* fp = LLFile::fopen(filename, TEXT("wb")); + LLFILE* fp = LLFile::fopen(filename, LLFILE_MODE("wb")); if (!fp) { LL_WARNS() << "Couldn't open call log list" << filename << LL_ENDL; @@ -556,7 +556,7 @@ bool LLConversationLog::loadFromFile(const std::string& filename) return false; } - LLFILE* fp = LLFile::fopen(filename, TEXT("rb")); + LLFILE* fp = LLFile::fopen(filename, LLFILE_MODE("rb")); if (!fp) { LL_WARNS() << "Couldn't open call log list" << filename << LL_ENDL; diff --git a/indra/newview/lldrawpoolbump.cpp b/indra/newview/lldrawpoolbump.cpp index 200fce7b5b..a42972205a 100644 --- a/indra/newview/lldrawpoolbump.cpp +++ b/indra/newview/lldrawpoolbump.cpp @@ -114,7 +114,7 @@ void LLStandardBumpmap::addstandard() gStandardBumpmapList[LLStandardBumpmap::sStandardBumpmapCount++] = LLStandardBumpmap("Darkness"); // BE_DARKNESS std::string file_name = gDirUtilp->getExpandedFilename( LL_PATH_APP_SETTINGS, "std_bump.ini" ); - LLFILE* file = LLFile::fopen( file_name, TEXT("rt") ); /*Flawfinder: ignore*/ + LLFILE* file = LLFile::fopen( file_name, LLFILE_MODE("rt") ); /*Flawfinder: ignore*/ if( !file ) { LL_WARNS() << "Could not open std_bump <" << file_name << ">" << LL_ENDL; diff --git a/indra/newview/llfloateruipreview.cpp b/indra/newview/llfloateruipreview.cpp index cf710d45dd..637871da0d 100755 --- a/indra/newview/llfloateruipreview.cpp +++ b/indra/newview/llfloateruipreview.cpp @@ -574,7 +574,7 @@ void LLFloaterUIPreview::onClickExportSchema() // std::string file_name(template_path + gDirUtilp->getDirDelimiter() + widget_name + ".rng"); - // LLFILE* rng_file = LLFile::fopen(file_name.c_str(), TEXT("w")); + // LLFILE* rng_file = LLFile::fopen(file_name.c_str(), LLFILE_MODE("w")); // { // LLXMLNode::writeHeaderToFile(rng_file); // const bool use_type_decorations = false; diff --git a/indra/newview/llinventorymodel.cpp b/indra/newview/llinventorymodel.cpp index 9491c9d610..c34df48f7d 100644 --- a/indra/newview/llinventorymodel.cpp +++ b/indra/newview/llinventorymodel.cpp @@ -2745,7 +2745,7 @@ bool LLInventoryModel::loadSkeleton( const S32 NO_VERSION = LLViewerInventoryCategory::VERSION_UNKNOWN; std::string gzip_filename(inventory_filename); gzip_filename.append(".gz"); - LLFILE* fp = LLFile::fopen(gzip_filename, TEXT("rb")); + LLFILE* fp = LLFile::fopen(gzip_filename, LLFILE_MODE("rb")); bool remove_inventory_file = false; if (LLAppViewer::instance()->isSecondInstance()) { @@ -4908,7 +4908,7 @@ bool decompress_file(const char* src_filename, const char* dst_filename) // open the files src = gzopen(src_filename, "rb"); if(!src) goto err_decompress; - dst = LLFile::fopen(dst_filename, TEXT("wb")); + dst = LLFile::fopen(dst_filename, LLFILE_MODE("wb")); if(!dst) goto err_decompress; // decompress. diff --git a/indra/newview/llkeyconflict.cpp b/indra/newview/llkeyconflict.cpp index 458d5225e1..c082c632f1 100644 --- a/indra/newview/llkeyconflict.cpp +++ b/indra/newview/llkeyconflict.cpp @@ -575,7 +575,7 @@ void LLKeyConflictHandler::saveToSettings(bool temporary) // Write the resulting XML to file if (!output_node->isNull()) { - LLFILE *fp = LLFile::fopen(filename, TEXT("w")); + LLFILE* fp = LLFile::fopen(filename, LLFILE_MODE("w")); if (fp != NULL) { LLXMLNode::writeHeaderToFile(fp); diff --git a/indra/newview/lllogchat.cpp b/indra/newview/lllogchat.cpp index 405530f5bd..59f6993a0b 100644 --- a/indra/newview/lllogchat.cpp +++ b/indra/newview/lllogchat.cpp @@ -453,7 +453,7 @@ void LLLogChat::loadChatHistory(const std::string& file_name, std::list& m // If we got here, we managed to stat the file. // Open the file to read in binary mode to prevent interpreting other characters as EOF - LLFILE* fptr = LLFile::fopen(log_file_name, TEXT("rb")); /*Flawfinder: ignore*/ + LLFILE* fptr = LLFile::fopen(log_file_name, LLFILE_MODE("rb")); /*Flawfinder: ignore*/ if (!fptr) { // Ok, this is strange but not really tragic in the big picture of things LL_WARNS("ChatHistory") << "Unable to read file " << log_file_name << " after stat was successful" << LL_ENDL; @@ -890,7 +890,7 @@ bool LLLogChat::isAdHocTranscriptExist(std::string file_name) bool LLLogChat::isTranscriptFileFound(std::string fullname) { bool result = false; - LLFILE * filep = LLFile::fopen(fullname, TEXT("rb")); + LLFILE * filep = LLFile::fopen(fullname, LLFILE_MODE("rb")); if (NULL != filep) { if (makeLogFileName("chat") == fullname) @@ -1183,7 +1183,7 @@ void LLLoadHistoryThread::loadHistory(const std::string& file_name, std::listgetExpandedFilename(LL_PATH_PER_SL_ACCOUNT, "render_mute_settings.txt"); - LLFILE* fp = LLFile::fopen(filename, TEXT("wb")); + LLFILE* fp = LLFile::fopen(filename, LLFILE_MODE("wb")); if (!fp) { LL_WARNS() << "Couldn't open render mute list file: " << filename << LL_ENDL; @@ -963,7 +963,7 @@ bool LLRenderMuteList::saveToFile() bool LLRenderMuteList::loadFromFile() { std::string filename = gDirUtilp->getExpandedFilename(LL_PATH_PER_SL_ACCOUNT, "render_mute_settings.txt"); - LLFILE* fp = LLFile::fopen(filename, TEXT("rb")); + LLFILE* fp = LLFile::fopen(filename, LLFILE_MODE("rb")); if (!fp) { LL_WARNS() << "Couldn't open render mute list file: " << filename << LL_ENDL; diff --git a/indra/newview/llpreviewnotecard.cpp b/indra/newview/llpreviewnotecard.cpp index 6928d7e6c3..cecda23e7b 100644 --- a/indra/newview/llpreviewnotecard.cpp +++ b/indra/newview/llpreviewnotecard.cpp @@ -801,7 +801,7 @@ bool LLPreviewNotecard::loadNotecardText(const std::string& filename) return false; } - LLFILE* file = LLFile::fopen(filename, TEXT("rb")); /*Flawfinder: ignore*/ + LLFILE* file = LLFile::fopen(filename, LLFILE_MODE("rb")); /*Flawfinder: ignore*/ if (!file) { LL_WARNS() << "Error opening " << filename << LL_ENDL; @@ -832,7 +832,7 @@ bool LLPreviewNotecard::loadNotecardText(const std::string& filename) bool LLPreviewNotecard::writeToFile(const std::string& filename) { - LLFILE* fp = LLFile::fopen(filename, TEXT("wb")); + LLFILE* fp = LLFile::fopen(filename, LLFILE_MODE("wb")); if (!fp) { LL_WARNS() << "Unable to write to " << filename << LL_ENDL; diff --git a/indra/newview/llpreviewscript.cpp b/indra/newview/llpreviewscript.cpp index c73976e540..53d0a712a8 100644 --- a/indra/newview/llpreviewscript.cpp +++ b/indra/newview/llpreviewscript.cpp @@ -632,7 +632,7 @@ bool LLScriptEdCore::loadScriptText(const std::string& filename) return false; } - LLFILE* file = LLFile::fopen(filename, TEXT("rb")); /*Flawfinder: ignore*/ + LLFILE* file = LLFile::fopen(filename, LLFILE_MODE("rb")); /*Flawfinder: ignore*/ if (!file) { LL_WARNS() << "Error opening " << filename << LL_ENDL; @@ -663,7 +663,7 @@ bool LLScriptEdCore::loadScriptText(const std::string& filename) bool LLScriptEdCore::writeToFile(const std::string& filename) { - LLFILE* fp = LLFile::fopen(filename, TEXT("wb")); + LLFILE* fp = LLFile::fopen(filename, LLFILE_MODE("wb")); if (!fp) { LL_WARNS() << "Unable to write to " << filename << LL_ENDL; diff --git a/indra/newview/llstartup.cpp b/indra/newview/llstartup.cpp index 37609f74ed..2cb2a7f8d5 100644 --- a/indra/newview/llstartup.cpp +++ b/indra/newview/llstartup.cpp @@ -587,7 +587,7 @@ bool idle_startup() std::string message_template_path = gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS,"message_template.msg"); LLFILE* found_template = NULL; - found_template = LLFile::fopen(message_template_path, TEXT("r")); /* Flawfinder: ignore */ + found_template = LLFile::fopen(message_template_path, LLFILE_MODE("r")); /* Flawfinder: ignore */ #if LL_WINDOWS // On the windows dev builds, unpackaged, the message_template.msg @@ -596,7 +596,7 @@ bool idle_startup() if (!found_template) { message_template_path = gDirUtilp->getExpandedFilename(LL_PATH_EXECUTABLE, "app_settings", "message_template.msg"); - found_template = LLFile::fopen(message_template_path.c_str(), TEXT("r")); /* Flawfinder: ignore */ + found_template = LLFile::fopen(message_template_path.c_str(), LLFILE_MODE("r")); /* Flawfinder: ignore */ } #elif LL_DARWIN // On Mac dev builds, message_template.msg lives in: @@ -606,7 +606,7 @@ bool idle_startup() message_template_path = gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS, "message_template.msg"); - found_template = LLFile::fopen(message_template_path.c_str(), TEXT("r")); /* Flawfinder: ignore */ + found_template = LLFile::fopen(message_template_path.c_str(), LLFILE_MODE("r")); /* Flawfinder: ignore */ } #endif diff --git a/indra/newview/lltoolbarview.cpp b/indra/newview/lltoolbarview.cpp index d1e36676af..c401a00fd7 100644 --- a/indra/newview/lltoolbarview.cpp +++ b/indra/newview/lltoolbarview.cpp @@ -420,7 +420,7 @@ void LLToolBarView::saveToolbars() const if(!output_node->isNull()) { const std::string& filename = gDirUtilp->getExpandedFilename(LL_PATH_PER_SL_ACCOUNT, "toolbars.xml"); - LLFILE *fp = LLFile::fopen(filename, TEXT("w")); + LLFILE *fp = LLFile::fopen(filename, LLFILE_MODE("w")); if (fp != NULL) { LLXMLNode::writeHeaderToFile(fp); diff --git a/indra/newview/llviewerassetstorage.cpp b/indra/newview/llviewerassetstorage.cpp index c28f3dc73a..867d47c893 100644 --- a/indra/newview/llviewerassetstorage.cpp +++ b/indra/newview/llviewerassetstorage.cpp @@ -279,7 +279,7 @@ void LLViewerAssetStorage::storeAssetData( LL_DEBUGS("AssetStorage") << "ASSET_ID: " << asset_id << LL_ENDL; S32 size = 0; - LLFILE* fp = LLFile::fopen(filename, TEXT("rb")); + LLFILE* fp = LLFile::fopen(filename, LLFILE_MODE("rb")); if (fp) { fseek(fp, 0, SEEK_END); diff --git a/indra/newview/llviewerinput.cpp b/indra/newview/llviewerinput.cpp index 9b39f7b0e9..5741d7f5fb 100644 --- a/indra/newview/llviewerinput.cpp +++ b/indra/newview/llviewerinput.cpp @@ -1430,7 +1430,7 @@ S32 LLViewerInput::loadBindingsXML(const std::string& filename) // file in app_settings is supposed to be up to date // this is only for the file from user_settings LL_INFOS("ViewerInput") << "Updating file " << filename << " to a newer version" << LL_ENDL; - LLFILE *fp = LLFile::fopen(filename, TEXT("w")); + LLFILE *fp = LLFile::fopen(filename, LLFILE_MODE("w")); if (fp != NULL) { LLXMLNode::writeHeaderToFile(fp); diff --git a/indra/newview/llviewermenufile.cpp b/indra/newview/llviewermenufile.cpp index a8ed2da9e0..423bb5f31d 100644 --- a/indra/newview/llviewermenufile.cpp +++ b/indra/newview/llviewermenufile.cpp @@ -1161,7 +1161,7 @@ void handle_compress_image() // so doing dirty, but OS independent fopen and fseek size_t get_file_size(std::string &filename) { - LLFILE* file = LLFile::fopen(filename, TEXT("rb")); /*Flawfinder: ignore*/ + LLFILE* file = LLFile::fopen(filename, LLFILE_MODE("rb")); /*Flawfinder: ignore*/ if (!file) { LL_WARNS() << "Error opening " << filename << LL_ENDL; diff --git a/indra/newview/llviewerstatsrecorder.cpp b/indra/newview/llviewerstatsrecorder.cpp index a2141f4eed..a183d7c8de 100644 --- a/indra/newview/llviewerstatsrecorder.cpp +++ b/indra/newview/llviewerstatsrecorder.cpp @@ -194,7 +194,7 @@ void LLViewerStatsRecorder::writeToLog( F32 interval ) // Open the data file makeStatsFileName(); - mStatsFile = LLFile::fopen(mStatsFileName, TEXT("wb")); + mStatsFile = LLFile::fopen(mStatsFileName, LLFILE_MODE("wb")); if (mStatsFile) { -- cgit v1.3 From 364ff6e6d45087653a302b96ccd8c9e02db2b9d1 Mon Sep 17 00:00:00 2001 From: Rider Linden Date: Tue, 28 Apr 2026 10:23:44 -0700 Subject: Refactor the LLSyntaxIDLSL/Lua into single LLSyntaxDefCache, use new cap when available to retrieve all language definition files and cache them locally. Retrieve the default definition files from the LSL definitions precompiled library. --- indra/llmessage/llcorehttputil.cpp | 33 +- indra/llmessage/llcorehttputil.h | 1 - indra/newview/app_settings/types_lua_default.xml | 5262 ---------------------- indra/newview/llpreviewscript.cpp | 5 +- indra/newview/llscripteditor.cpp | 4 +- indra/newview/llscripteditorws.cpp | 10 +- indra/newview/llsyntaxid.cpp | 517 ++- indra/newview/llsyntaxid.h | 127 +- indra/newview/llviewerregion.cpp | 1 + indra/newview/viewer_manifest.py | 12 +- 10 files changed, 438 insertions(+), 5534 deletions(-) delete mode 100644 indra/newview/app_settings/types_lua_default.xml (limited to 'indra/llmessage') diff --git a/indra/llmessage/llcorehttputil.cpp b/indra/llmessage/llcorehttputil.cpp index b24e5e4fcc..f18af1f18e 100644 --- a/indra/llmessage/llcorehttputil.cpp +++ b/indra/llmessage/llcorehttputil.cpp @@ -39,7 +39,7 @@ #include "llfilesystem.h" #include "message.h" // for getting the port - +#include "llstl.h" using namespace LLCore; @@ -112,15 +112,17 @@ bool responseToLLSD(HttpResponse * response, bool log, LLSD & out_llsd) { // Convert response to LLSD BufferArray * body(response->getBody()); - if (!body || !body->size()) + size_t body_size(body ? body->size() : 0); + if (!body || !body_size) { return false; } LLCore::BufferArrayStream bas(body); LLSD body_llsd; - S32 parse_status(LLSDSerialize::fromXML(body_llsd, bas, log)); - if (LLSDParser::PARSE_FAILURE == parse_status){ + + if (!LLSDSerialize::deserialize(body_llsd, bas, body_size)) + { return false; } out_llsd = body_llsd; @@ -409,28 +411,6 @@ LLSD HttpCoroLLSDHandler::handleSuccess(LLCore::HttpResponse * response, LLCore: result = parseBody(response, success); -#if 0 - bool parsed = !((response->getBodySize() == 0) || - !LLCoreHttpUtil::responseToLLSD(response, emit_parse_errors, result)); - - if (!parsed) - { - // Only emit a warning if we failed to parse when 'content-type' == 'application/llsd+xml' - LLCore::HttpHeaders::ptr_t headers(response->getHeaders()); - const std::string *contentType = (headers) ? headers->find(HTTP_IN_HEADER_CONTENT_TYPE) : NULL; - - if (contentType && (HTTP_CONTENT_LLSD_XML == *contentType)) - { - std::string thebody = LLCoreHttpUtil::responseToString(response); - LL_WARNS("CoreHTTP") << "Failed to deserialize . " << response->getRequestURL() << " [status:" << response->getStatus().toString() << "] " - << " body: " << thebody << LL_ENDL; - - // Replace the status with a new one indicating the failure. - status = LLCore::HttpStatus(499, "Failed to deserialize LLSD."); - } - } -#endif - if (!success) { #if 1 @@ -955,7 +935,6 @@ LLSD HttpCoroutineAdapter::getJsonAndSuspend(LLCore::HttpRequest::ptr_t request, return getAndSuspend_(request, url, options, headers, httpHandler); } - LLSD HttpCoroutineAdapter::getAndSuspend_(LLCore::HttpRequest::ptr_t &request, const std::string & url, LLCore::HttpOptions::ptr_t &options, LLCore::HttpHeaders::ptr_t &headers, diff --git a/indra/llmessage/llcorehttputil.h b/indra/llmessage/llcorehttputil.h index 3dbfd6f00d..8fa638fd6e 100644 --- a/indra/llmessage/llcorehttputil.h +++ b/indra/llmessage/llcorehttputil.h @@ -483,7 +483,6 @@ public: headers); } - /// Execute a DELETE transaction on the supplied URL and yield execution of /// the coroutine until a result is available. /// diff --git a/indra/newview/app_settings/types_lua_default.xml b/indra/newview/app_settings/types_lua_default.xml deleted file mode 100644 index cb40ec3d06..0000000000 --- a/indra/newview/app_settings/types_lua_default.xml +++ /dev/null @@ -1,5262 +0,0 @@ - - - - version - 1.0.0 - typeAliases - - - name - rotation - definition - - kind - reference - name - quaternion - - comment - 'rotation' is an alias for 'quaternion' - - - name - numeric - definition - - kind - union - types - - boolean - number - - - - - name - list - definition - - kind - array - elementType - - kind - union - types - - string - number - vector - uuid - quaternion - boolean - - - - - - name - LLDetectedEventName - definition - - kind - literal-union - values - - - - - name - LLNonDetectedEventName - definition - - kind - literal-union - values - - - - - name - LLEventName - definition - - kind - union - types - - LLDetectedEventName - LLNonDetectedEventName - - - - - name - LLEventHandler - definition - - kind - function - parameters - - - type - any - variadic - true - - - returnType - () - - - - name - LLDetectedEventHandler - definition - - kind - function - parameters - - - name - detected - type - - kind - array - elementType - LLDetectedEvent - - - - returnType - () - - - - name - LLTimerEveryCallback - definition - - kind - function - parameters - - - name - scheduled - type - number - - - name - interval - type - number - - - returnType - () - - comment - Callback type for LLTimers.every() - receives scheduled time and interval - - - name - LLTimerOnceCallback - definition - - kind - function - parameters - - - name - scheduled - type - number - - - returnType - () - - comment - Callback type for LLTimers.once() - receives scheduled time - - - name - LLTimerCallback - definition - - kind - union - types - - LLTimerEveryCallback - LLTimerOnceCallback - (...any) -> ...any - - - comment - Union of timer callback types - - - name - OsDateTime - definition - - kind - table - properties - - - name - year - type - number - - - name - month - type - number - - - name - day - type - number - - - name - hour - type - number - optional - true - - - name - min - type - number - optional - true - - - name - sec - type - number - optional - true - - - name - wday - type - number - optional - true - - - name - yday - type - number - optional - true - - - name - isdst - type - boolean - optional - true - - - - comment - Date/time table structure used by os.date and os.time - - - classes - - - name - quaternion - comment - Luau Type Definition for LSL UserData Type: quaternion - properties - - - name - x - type - number - - - name - y - type - number - - - name - z - type - number - - - name - s - type - number - - - methods - - - name - __add - parameters - - - name - self - - - name - other - type - quaternion - - - returnType - quaternion - - - name - __sub - parameters - - - name - self - - - name - other - type - quaternion - - - returnType - quaternion - - - name - __mul - parameters - - - name - self - - - name - other - type - quaternion - - - returnType - quaternion - - - name - __div - parameters - - - name - self - - - name - other - type - quaternion - - - returnType - quaternion - - - name - __unm - parameters - - - name - self - - - returnType - quaternion - - - name - __eq - parameters - - - name - self - - - name - other - type - quaternion - - - returnType - boolean - - - name - __tostring - parameters - - - name - self - - - returnType - string - - - - - name - uuid - comment - Luau Type Definition for LSL UserData Type: uuid - properties - - - name - istruthy - type - boolean - comment - Returns true if the UUID is not the null UUID (all zeros) - - - name - bytes - type - string? - comment - Returns the raw 16-byte binary string of the UUID, or nil if the UUID is not in a compressed state - - - methods - - - name - __tostring - parameters - - - name - self - - - returnType - string - - - - - name - vector - comment - Luau Type Definition for LSL UserData Type: vector - properties - - - name - x - type - number - - - name - y - type - number - - - name - z - type - number - - - methods - - - name - __add - parameters - - - name - self - - - name - other - type - vector - - - returnType - vector - comment - Native component-wise addition - - - name - __sub - parameters - - - name - self - - - name - other - type - vector - - - returnType - vector - comment - Native component-wise subtraction - - - name - __unm - parameters - - - name - self - - - returnType - vector - comment - Unary negation - - - name - __mul - parameters - - - name - self - - - name - other - type - number | vector | quaternion - - - returnType - vector - comment - Multiplication: vector * number or vector * vector -> vector, vector * quaternion -> vector (Rotation) - - - name - __div - parameters - - - name - self - - - name - other - type - number | vector | quaternion - - - returnType - vector - comment - Division: vector / number or vector / vector -> vector (Scale), vector / quaternion -> vector (Rotation by inverse) - - - name - __mod - parameters - - - name - self - - - name - other - type - vector - - - returnType - vector - comment - LSL-style modulo: vector % vector -> vector (Cross Product) - - - name - __tostring - parameters - - - name - self - - - returnType - string - - - - - name - LLDetectedEvent - comment - Event detection class providing access to detected object/avatar information - properties - - - name - index - type - number - - - name - valid - type - boolean - - - name - canAdjustDamage - type - boolean - - - methods - - - - name - LLEvents - comment - Event registration and management class for Second Life events - methods - - - name - on - parameters - - - name - self - - - name - event - type - LLEventName - - - name - callback - type - LLEventHandler - - - returnType - LLEventHandler - comment - Registers a callback for an event. Returns the callback. - - - name - off - parameters - - - name - self - - - name - event - type - LLEventName - - - name - callback - type - LLEventHandler - - - returnType - boolean - comment - Unregisters a callback. Returns true if found and removed. - - - name - once - parameters - - - name - self - - - name - event - type - LLEventName - - - name - callback - type - LLEventHandler - - - returnType - LLEventHandler - comment - Registers a one-time callback. Returns the wrapper function. - - - name - listeners - parameters - - - name - self - - - name - event - type - LLEventName - - - returnType - {LLEventHandler} - comment - Returns a list of all listeners for a specific event. - - - name - eventNames - parameters - - - name - self - - - returnType - {string} - comment - Returns a list of all event names that have listeners. - - - - - name - LLTimers - comment - Timer management class for scheduling periodic and one-time callbacks - methods - - - name - every - parameters - - - name - self - - - name - seconds - type - number - - - name - callback - type - LLTimerEveryCallback - - - returnType - LLTimerCallback - comment - Registers a callback to be called every N seconds. Returns the callback. - - - name - once - parameters - - - name - self - - - name - seconds - type - number - - - name - callback - type - LLTimerOnceCallback - - - returnType - LLTimerCallback - comment - Registers a callback to be called once after N seconds. Returns the callback. - - - name - off - parameters - - - name - self - - - name - callback - type - LLTimerCallback - - - returnType - boolean - comment - Unregisters a timer callback. Returns true if found and removed. - - - - - globalVariables - - - name - quaternion - type - - kind - callable-table - tableType - - properties - - - name - create - type - - kind - function - parameters - - - name - x - type - number - - - name - y - type - number - - - name - z - type - number - - - name - s - type - number - - - returnType - quaternion - - comment - Constructor - - - name - identity - type - quaternion - comment - Identity quaternion constant - - - name - normalize - type - - kind - function - parameters - - - name - q - type - quaternion - - - returnType - quaternion - - comment - Returns normalized quaternion - - - name - magnitude - type - - kind - function - parameters - - - name - q - type - quaternion - - - returnType - number - - comment - Returns magnitude of quaternion - - - name - dot - type - - kind - function - parameters - - - name - a - type - quaternion - - - name - b - type - quaternion - - - returnType - number - - comment - Dot product of two quaternions - - - name - slerp - type - - kind - function - parameters - - - name - a - type - quaternion - - - name - b - type - quaternion - - - name - t - type - number - - - returnType - quaternion - - comment - Spherical linear interpolation - - - name - conjugate - type - - kind - function - parameters - - - name - q - type - quaternion - - - returnType - quaternion - - comment - Returns conjugate of quaternion - - - name - tofwd - type - - kind - function - parameters - - - name - q - type - quaternion - - - returnType - vector - - comment - Returns forward vector from quaternion rotation - - - name - toleft - type - - kind - function - parameters - - - name - q - type - quaternion - - - returnType - vector - - comment - Returns left vector from quaternion rotation - - - name - toup - type - - kind - function - parameters - - - name - q - type - quaternion - - - returnType - vector - - comment - Returns up vector from quaternion rotation - - - - callSignature - - parameters - - - name - x - type - number - - - name - y - type - number - - - name - z - type - number - - - name - s - type - number - - - returnType - quaternion - - - comment - Global 'quaternion' library table with callable metatable - - - name - rotation - type - - kind - typeof - target - quaternion - - comment - 'rotation' global is an alias to the 'quaternion' library - - - name - uuid - type - - kind - callable-table - tableType - - properties - - - name - create - type - - kind - function - parameters - - - name - value - type - - kind - union - types - - string - buffer - uuid - - - - - returnType - uuid? - - comment - Creates a new uuid from a string, buffer, or existing uuid - - - - callSignature - - parameters - - - name - value - type - - kind - union - types - - string - buffer - uuid - - - - - returnType - uuid? - - - comment - Global 'uuid' library table - - - name - vector - type - - kind - callable-table - tableType - - properties - - - name - create - type - - kind - function - parameters - - - name - x - type - number - - - name - y - type - number - - - name - z - type - number - optional - true - - - returnType - vector - - comment - Creates a new vector with the given component values - - - name - magnitude - type - - kind - function - parameters - - - name - v - type - vector - - - returnType - number - - comment - Calculates the magnitude of a given vector - - - name - normalize - type - - kind - function - parameters - - - name - v - type - vector - - - returnType - vector - - comment - Computes the normalized version (unit vector) of a given vector - - - name - cross - type - - kind - function - parameters - - - name - a - type - vector - - - name - b - type - vector - - - returnType - vector - - comment - Computes the cross product of two vectors - - - name - dot - type - - kind - function - parameters - - - name - a - type - vector - - - name - b - type - vector - - - returnType - number - - comment - Computes the dot product of two vectors - - - name - angle - type - - kind - function - parameters - - - name - a - type - vector - - - name - b - type - vector - - - name - axis - type - vector - optional - true - - - returnType - number - - comment - Computes the angle between two vectors in radians - - - name - floor - type - - kind - function - parameters - - - name - v - type - vector - - - returnType - vector - - comment - Applies math.floor to every component of the input vector - - - name - ceil - type - - kind - function - parameters - - - name - v - type - vector - - - returnType - vector - - comment - Applies math.ceil to every component of the input vector - - - name - abs - type - - kind - function - parameters - - - name - v - type - vector - - - returnType - vector - - comment - Applies math.abs to every component of the input vector - - - name - sign - type - - kind - function - parameters - - - name - v - type - vector - - - returnType - vector - - comment - Applies math.sign to every component of the input vector - - - name - clamp - type - - kind - function - parameters - - - name - v - type - vector - - - name - min - type - vector - - - name - max - type - vector - - - returnType - vector - - comment - Applies math.clamp to every component of the input vector - - - name - max - type - - kind - function - parameters - - - name - v - type - vector - - - type - vector - variadic - true - - - returnType - vector - - comment - Applies math.max to the corresponding components of the input vectors - - - name - min - type - - kind - function - parameters - - - name - v - type - vector - - - type - vector - variadic - true - - - returnType - vector - - comment - Applies math.min to the corresponding components of the input vectors - - - name - lerp - type - - kind - function - parameters - - - name - a - type - vector - - - name - b - type - vector - - - name - t - type - number - - - returnType - vector - - comment - Linear interpolation between two vectors - - - name - zero - type - vector - comment - A zero vector <0,0,0> - - - name - one - type - vector - comment - A one vector <1,1,1> - - - - callSignature - - parameters - - - name - x - type - number - - - name - y - type - number - - - name - z - type - number - optional - true - - - returnType - vector - - - comment - Global 'vector' library table - - - name - LLEvents - type - LLEvents - comment - Second Life event management and registration - - - name - LLTimers - type - LLTimers - comment - Second Life timer management and scheduling - - - name - loadstring - type - nil - comment - loadstring is removed in SLua - - - name - getfenv - type - nil - comment - getfenv is removed in SLua - - - name - setfenv - type - nil - comment - setfenv is removed in SLua - - - modules - - - name - bit32 - comment - Bitwise operations library - functions - - - name - arshift - parameters - - - name - x - type - number - - - name - disp - type - number - - - returnType - number - comment - Arithmetic right shift - - - name - band - parameters - - - type - number - variadic - true - - - returnType - number - comment - Bitwise AND of all arguments - - - name - bnot - parameters - - - name - x - type - number - - - returnType - number - comment - Bitwise NOT - - - name - bor - parameters - - - type - number - variadic - true - - - returnType - number - comment - Bitwise OR of all arguments - - - name - bxor - parameters - - - type - number - variadic - true - - - returnType - number - comment - Bitwise XOR of all arguments - - - name - btest - parameters - - - type - number - variadic - true - - - returnType - boolean - comment - Returns true if bitwise AND of all arguments is not zero - - - name - extract - parameters - - - name - n - type - number - - - name - field - type - number - - - name - width - type - number - optional - true - - - returnType - number - comment - Extracts bits from n at position field with width - - - name - lrotate - parameters - - - name - x - type - number - - - name - disp - type - number - - - returnType - number - comment - Left rotate - - - name - lshift - parameters - - - name - x - type - number - - - name - disp - type - number - - - returnType - number - comment - Left shift - - - name - replace - parameters - - - name - n - type - number - - - name - v - type - number - - - name - field - type - number - - - name - width - type - number - optional - true - - - returnType - number - comment - Replaces bits in n at position field with width using value v - - - name - rrotate - parameters - - - name - x - type - number - - - name - disp - type - number - - - returnType - number - comment - Right rotate - - - name - rshift - parameters - - - name - x - type - number - - - name - disp - type - number - - - returnType - number - comment - Right shift - - - name - countlz - parameters - - - name - n - type - number - - - returnType - number - comment - Count leading zeros - - - name - countrz - parameters - - - name - n - type - number - - - returnType - number - comment - Count trailing zeros - - - name - byteswap - parameters - - - name - n - type - number - - - returnType - number - comment - Swap byte order - - - - - name - buffer - comment - Buffer manipulation library for binary data - functions - - - name - create - parameters - - - name - size - type - number - - - returnType - buffer - comment - Creates a new buffer of the specified size - - - name - fromstring - parameters - - - name - str - type - string - - - returnType - buffer - comment - Creates a buffer from a string - - - name - tostring - parameters - - - name - b - type - buffer - - - returnType - string - comment - Converts buffer to string - - - name - readi8 - parameters - - - name - b - type - buffer - - - name - offset - type - number - - - returnType - number - comment - Read signed 8-bit integer - - - name - readu8 - parameters - - - name - b - type - buffer - - - name - offset - type - number - - - returnType - number - comment - Read unsigned 8-bit integer - - - name - readi16 - parameters - - - name - b - type - buffer - - - name - offset - type - number - - - returnType - number - comment - Read signed 16-bit integer - - - name - readu16 - parameters - - - name - b - type - buffer - - - name - offset - type - number - - - returnType - number - comment - Read unsigned 16-bit integer - - - name - readi32 - parameters - - - name - b - type - buffer - - - name - offset - type - number - - - returnType - number - comment - Read signed 32-bit integer - - - name - readu32 - parameters - - - name - b - type - buffer - - - name - offset - type - number - - - returnType - number - comment - Read unsigned 32-bit integer - - - name - readf32 - parameters - - - name - b - type - buffer - - - name - offset - type - number - - - returnType - number - comment - Read 32-bit float - - - name - readf64 - parameters - - - name - b - type - buffer - - - name - offset - type - number - - - returnType - number - comment - Read 64-bit float - - - name - writei8 - parameters - - - name - b - type - buffer - - - name - offset - type - number - - - name - value - type - number - - - returnType - () - comment - Write signed 8-bit integer - - - name - writeu8 - parameters - - - name - b - type - buffer - - - name - offset - type - number - - - name - value - type - number - - - returnType - () - comment - Write unsigned 8-bit integer - - - name - writei16 - parameters - - - name - b - type - buffer - - - name - offset - type - number - - - name - value - type - number - - - returnType - () - comment - Write signed 16-bit integer - - - name - writeu16 - parameters - - - name - b - type - buffer - - - name - offset - type - number - - - name - value - type - number - - - returnType - () - comment - Write unsigned 16-bit integer - - - name - writei32 - parameters - - - name - b - type - buffer - - - name - offset - type - number - - - name - value - type - number - - - returnType - () - comment - Write signed 32-bit integer - - - name - writeu32 - parameters - - - name - b - type - buffer - - - name - offset - type - number - - - name - value - type - number - - - returnType - () - comment - Write unsigned 32-bit integer - - - name - writef32 - parameters - - - name - b - type - buffer - - - name - offset - type - number - - - name - value - type - number - - - returnType - () - comment - Write 32-bit float - - - name - writef64 - parameters - - - name - b - type - buffer - - - name - offset - type - number - - - name - value - type - number - - - returnType - () - comment - Write 64-bit float - - - name - readstring - parameters - - - name - b - type - buffer - - - name - offset - type - number - - - name - count - type - number - - - returnType - string - comment - Read string from buffer - - - name - writestring - parameters - - - name - b - type - buffer - - - name - offset - type - number - - - name - value - type - string - - - name - count - type - number - optional - true - - - returnType - () - comment - Write string to buffer - - - name - len - parameters - - - name - b - type - buffer - - - returnType - number - comment - Returns the length of the buffer - - - name - copy - parameters - - - name - target - type - buffer - - - name - targetOffset - type - number - - - name - source - type - buffer - - - name - sourceOffset - type - number - optional - true - - - name - count - type - number - optional - true - - - returnType - () - comment - Copy data from source buffer to target buffer - - - name - fill - parameters - - - name - b - type - buffer - - - name - offset - type - number - - - name - value - type - number - - - name - count - type - number - optional - true - - - returnType - () - comment - Fill buffer with a value - - - name - readbits - parameters - - - name - b - type - buffer - - - name - bitOffset - type - number - - - name - bitCount - type - number - - - returnType - number - comment - Read bits from buffer - - - name - writebits - parameters - - - name - b - type - buffer - - - name - bitOffset - type - number - - - name - bitCount - type - number - - - name - value - type - number - - - returnType - () - comment - Write bits to buffer - - - - - name - coroutine - comment - Coroutine manipulation library - functions - - - name - create - parameters - - - name - f - type - (...any) -> ...any - - - returnType - thread - comment - Creates a new coroutine from a function - - - name - resume - parameters - - - name - co - type - thread - - - type - any - variadic - true - - - returnType - (boolean, ...any) - comment - Resumes a coroutine, returns success and results - - - name - running - parameters - - returnType - thread? - comment - Returns the running coroutine, or nil if called from main thread - - - name - status - parameters - - - name - co - type - thread - - - returnType - "running" | "suspended" | "normal" | "dead" - comment - Returns the status of a coroutine - - - name - wrap - parameters - - - name - f - type - (...any) -> ...any - - - returnType - (...any) -> ...any - comment - Creates a coroutine and returns a function that resumes it - - - name - yield - parameters - - - type - any - variadic - true - - - returnType - ...any - comment - Suspends the coroutine and returns values to resume - - - name - isyieldable - parameters - - returnType - boolean - comment - Returns true if the coroutine can yield - - - name - close - parameters - - - name - co - type - thread - - - returnType - (boolean, string?) - comment - Closes a coroutine, returns success and optional error message - - - - - name - debug - comment - Debug library for introspection - functions - - - name - info - parameters - - - name - thread - type - thread - - - name - level - type - number - - - name - options - type - string - - - returnType - ...any - comment - Returns information about a function or stack level - overloads - - - parameters - - - name - level - type - number - - - name - options - type - string - - - returnType - ...any - comment - Returns information about a stack level - - - parameters - - - name - func - type - (...any) -> ...any - - - name - options - type - string - - - returnType - ...any - comment - Returns information about a function - - - - - name - traceback - parameters - - - name - thread - type - thread - - - name - message - type - string - optional - true - - - name - level - type - number - optional - true - - - returnType - string - comment - Returns a string with a traceback of the call stack - overloads - - - parameters - - - name - message - type - string - optional - true - - - name - level - type - number - optional - true - - - returnType - string - comment - Returns a string with a traceback of the current call stack - - - - - - - name - llbase64 - comment - Base64 encoding/decoding library - functions - - - name - encode - parameters - - - name - data - type - string | buffer - - - returnType - string - comment - Encodes a string or buffer to base64 - - - name - decode - parameters - - - name - data - type - string - - - returnType - string - comment - Decodes a base64 string to a string - overloads - - - parameters - - - name - data - type - string - - - name - asBuffer - type - boolean - optional - true - - - returnType - string | buffer - comment - Decodes a base64 string to a string or buffer - - - - - - - name - lljson - comment - JSON encoding/decoding library for Second Life - properties - - - name - null - type - any - comment - A constant to pass for null to json encode - - - name - empty_array_mt - type - { [any]: any } - comment - Metatable for declaring table as an empty array for json encode - - - name - array_mt - type - { [any]: any } - comment - Metatable for declaring table as an array for json encode - - - name - empty_array - type - any - comment - A constant to pass for an empty array to json encode - - - name - _NAME - type - string - comment - Name of the lljson library - - - name - _VERSION - type - string - comment - Version of the lljson library - - - functions - - - name - encode - parameters - - - name - value - type - any - - - returnType - string - comment - Encodes a Lua value as JSON - - - name - decode - parameters - - - name - json - type - string - - - returnType - any - comment - Decodes a JSON string to a Lua value - - - name - slencode - parameters - - - name - value - type - any - - - name - tight - type - boolean - optional - true - - - returnType - string - comment - Encodes a Lua value as JSON preserving SL types. Use tight to encode more compactly. - - - name - sldecode - parameters - - - name - json - type - string - - - returnType - any - comment - Decodes a JSON string to a Lua value preserving SL types - - - - - name - math - comment - Mathematical functions library - properties - - - name - pi - type - number - comment - The value of pi - - - name - huge - type - number - comment - A value larger than any other numeric value (infinity) - - - functions - - - name - abs - parameters - - - name - x - type - number - - - returnType - number - comment - Returns the absolute value of x - - - name - acos - parameters - - - name - x - type - number - - - returnType - number - comment - Returns the arc cosine of x (in radians) - - - name - asin - parameters - - - name - x - type - number - - - returnType - number - comment - Returns the arc sine of x (in radians) - - - name - atan - parameters - - - name - x - type - number - - - returnType - number - comment - Returns the arc tangent of x (in radians) - - - name - atan2 - parameters - - - name - y - type - number - - - name - x - type - number - - - returnType - number - comment - Returns the arc tangent of y/x (in radians), using the signs to determine the quadrant - - - name - ceil - parameters - - - name - x - type - number - - - returnType - number - comment - Returns the smallest integer larger than or equal to x - - - name - clamp - parameters - - - name - n - type - number - - - name - min - type - number - - - name - max - type - number - - - returnType - number - comment - Returns n clamped between min and max - - - name - cos - parameters - - - name - x - type - number - - - returnType - number - comment - Returns the cosine of x (x in radians) - - - name - cosh - parameters - - - name - x - type - number - - - returnType - number - comment - Returns the hyperbolic cosine of x - - - name - deg - parameters - - - name - x - type - number - - - returnType - number - comment - Converts x from radians to degrees - - - name - exp - parameters - - - name - x - type - number - - - returnType - number - comment - Returns e^x - - - name - floor - parameters - - - name - x - type - number - - - returnType - number - comment - Returns the largest integer smaller than or equal to x - - - name - fmod - parameters - - - name - x - type - number - - - name - y - type - number - - - returnType - number - comment - Returns the remainder of x/y that rounds towards zero - - - name - frexp - parameters - - - name - x - type - number - - - returnType - (number, number) - comment - Returns m and e such that x = m * 2^e - - - name - ldexp - parameters - - - name - m - type - number - - - name - e - type - number - - - returnType - number - comment - Returns m * 2^e - - - name - lerp - parameters - - - name - a - type - number - - - name - b - type - number - - - name - t - type - number - - - returnType - number - comment - Linear interpolation between a and b by t - - - name - log - parameters - - - name - x - type - number - - - name - base - type - number - optional - true - - - returnType - number - comment - Returns the logarithm of x in the given base (default e) - - - name - log10 - parameters - - - name - x - type - number - - - returnType - number - comment - Returns the base-10 logarithm of x - - - name - map - parameters - - - name - x - type - number - - - name - inMin - type - number - - - name - inMax - type - number - - - name - outMin - type - number - - - name - outMax - type - number - - - returnType - number - comment - Maps x from input range to output range - - - name - max - parameters - - - name - x - type - number - - - type - number - variadic - true - - - returnType - number - comment - Returns the maximum value among the arguments - - - name - min - parameters - - - name - x - type - number - - - type - number - variadic - true - - - returnType - number - comment - Returns the minimum value among the arguments - - - name - modf - parameters - - - name - x - type - number - - - returnType - (number, number) - comment - Returns the integer and fractional parts of x - - - name - noise - parameters - - - name - x - type - number - - - name - y - type - number - optional - true - - - name - z - type - number - optional - true - - - returnType - number - comment - Returns Perlin noise value for the given coordinates - - - name - pow - parameters - - - name - base - type - number - - - name - exponent - type - number - - - returnType - number - comment - Returns base^exponent - - - name - rad - parameters - - - name - x - type - number - - - returnType - number - comment - Converts x from degrees to radians - - - name - random - parameters - - - name - m - type - number - optional - true - - - name - n - type - number - optional - true - - - returnType - number - comment - Returns a pseudo-random number - - - name - randomseed - parameters - - - name - seed - type - number - - - returnType - () - comment - Sets the seed for the pseudo-random generator - - - name - round - parameters - - - name - x - type - number - - - returnType - number - comment - Returns x rounded to the nearest integer - - - name - sign - parameters - - - name - x - type - number - - - returnType - number - comment - Returns -1, 0, or 1 depending on the sign of x - - - name - sin - parameters - - - name - x - type - number - - - returnType - number - comment - Returns the sine of x (x in radians) - - - name - sinh - parameters - - - name - x - type - number - - - returnType - number - comment - Returns the hyperbolic sine of x - - - name - sqrt - parameters - - - name - x - type - number - - - returnType - number - comment - Returns the square root of x - - - name - tan - parameters - - - name - x - type - number - - - returnType - number - comment - Returns the tangent of x (x in radians) - - - name - tanh - parameters - - - name - x - type - number - - - returnType - number - comment - Returns the hyperbolic tangent of x - - - name - isnan - parameters - - - name - x - type - number - - - returnType - boolean - comment - Returns true if x is NaN - - - name - isinf - parameters - - - name - x - type - number - - - returnType - boolean - comment - Returns true if x is infinite - - - name - isfinite - parameters - - - name - x - type - number - - - returnType - boolean - comment - Returns true if x is finite - - - - - name - os - comment - Operating system facilities library - functions - - - name - clock - parameters - - returnType - number - comment - Returns CPU time used by the program in seconds - - - name - date - parameters - - - name - format - type - string - optional - true - - - name - time - type - number - optional - true - - - returnType - string | OsDateTime | nil - comment - Returns a string or table containing date and time - - - name - difftime - parameters - - - name - t2 - type - number - - - name - t1 - type - number - optional - true - - - returnType - number - comment - Returns the difference in seconds between two times - - - name - time - parameters - - - name - time - type - OsDateTime - optional - true - - - returnType - number? - comment - Returns the current time or converts a table to time - - - - - name - string - comment - String manipulation library - functions - - - name - byte - parameters - - - name - s - type - string - - - name - i - type - number - optional - true - - - name - j - type - number - optional - true - - - returnType - ...number - comment - Returns the internal numeric codes of the characters - - - name - char - parameters - - - type - number - variadic - true - - - returnType - string - comment - Returns a string from character codes - - - name - find - parameters - - - name - s - type - string - - - name - pattern - type - string - - - name - init - type - number - optional - true - - - name - plain - type - boolean - optional - true - - - returnType - (number?, number?, ...string) - comment - Finds first match of pattern in string - - - name - format - parameters - - - name - formatstring - type - string - - - type - any - variadic - true - - - returnType - string - comment - Returns a formatted string - - - name - gmatch - parameters - - - name - s - type - string - - - name - pattern - type - string - - - returnType - () -> ...string - comment - Returns an iterator function for pattern matches - - - name - gsub - parameters - - - name - s - type - string - - - name - pattern - type - string - - - name - repl - type - string | { [string]: string } | (...string) -> string - - - name - n - type - number - optional - true - - - returnType - (string, number) - comment - Global substitution of pattern matches - - - name - len - parameters - - - name - s - type - string - - - returnType - number - comment - Returns the length of the string - - - name - lower - parameters - - - name - s - type - string - - - returnType - string - comment - Converts string to lowercase - - - name - match - parameters - - - name - s - type - string - - - name - pattern - type - string - - - name - init - type - number - optional - true - - - returnType - ...string - comment - Returns captures from pattern match - - - name - pack - parameters - - - name - fmt - type - string - - - type - any - variadic - true - - - returnType - string - comment - Packs values into a binary string - - - name - packsize - parameters - - - name - fmt - type - string - - - returnType - number - comment - Returns the size of a packed string for the given format - - - name - rep - parameters - - - name - s - type - string - - - name - n - type - number - - - returnType - string - comment - Returns a string repeated n times - - - name - reverse - parameters - - - name - s - type - string - - - returnType - string - comment - Reverses a string - - - name - split - parameters - - - name - s - type - string - - - name - separator - type - string - optional - true - - - returnType - {string} - comment - Splits a string by separator - - - name - sub - parameters - - - name - s - type - string - - - name - i - type - number - - - name - j - type - number - optional - true - - - returnType - string - comment - Returns a substring - - - name - unpack - parameters - - - name - fmt - type - string - - - name - s - type - string - - - name - pos - type - number - optional - true - - - returnType - ...any - comment - Unpacks values from a binary string - - - name - upper - parameters - - - name - s - type - string - - - returnType - string - comment - Converts string to uppercase - - - - - name - table - comment - Table manipulation library - functions - - - name - concat - parameters - - - name - list - type - {string} - - - name - sep - type - string - optional - true - - - name - i - type - number - optional - true - - - name - j - type - number - optional - true - - - returnType - string - comment - Concatenates table elements into a string - - - name - foreach - parameters - - - name - t - type - {[any]: any} - - - name - f - type - (key: any, value: any) -> any - - - returnType - any? - comment - Iterates over table key-value pairs (deprecated) - - - name - foreachi - parameters - - - name - t - type - {any} - - - name - f - type - (index: number, value: any) -> any - - - returnType - any? - comment - Iterates over array indices (deprecated) - - - name - getn - parameters - - - name - t - type - {any} - - - returnType - number - comment - Returns the length of a table (deprecated, use # operator) - - - name - maxn - parameters - - - name - t - type - {any} - - - returnType - number - comment - Returns the largest positive numeric index - - - name - insert - parameters - - - name - list - type - {any} - - - name - value - type - any - - - returnType - () - comment - Inserts an element at the end of a list - overloads - - - parameters - - - name - list - type - {any} - - - name - pos - type - number - - - name - value - type - any - - - returnType - () - comment - Inserts an element at a specific position - - - - - name - remove - parameters - - - name - list - type - {any} - - - name - pos - type - number - optional - true - - - returnType - any? - comment - Removes and returns an element from a list - - - name - sort - parameters - - - name - list - type - {any} - - - name - comp - type - (a: any, b: any) -> boolean - optional - true - - - returnType - () - comment - Sorts list elements in place - - - name - pack - parameters - - - type - any - variadic - true - - - returnType - { n: number, [number]: any } - comment - Packs arguments into a table with length field n - - - name - unpack - parameters - - - name - list - type - {any} - - - name - i - type - number - optional - true - - - name - j - type - number - optional - true - - - returnType - ...any - comment - Unpacks table elements as multiple return values - - - name - move - parameters - - - name - a1 - type - {any} - - - name - f - type - number - - - name - e - type - number - - - name - t - type - number - - - name - a2 - type - {any} - optional - true - - - returnType - {any} - comment - Moves elements from one table to another - - - name - create - parameters - - - name - count - type - number - - - name - value - type - any - optional - true - - - returnType - {any} - comment - Creates a new table with pre-allocated array slots - - - name - find - parameters - - - name - t - type - {any} - - - name - value - type - any - - - name - init - type - number - optional - true - - - returnType - number? - comment - Finds the index of a value in an array - - - name - clear - parameters - - - name - t - type - {[any]: any} - - - returnType - () - comment - Removes all elements from a table - - - name - freeze - parameters - - - name - t - type - {[any]: any} - - - returnType - {[any]: any} - comment - Makes a table read-only - - - name - isfrozen - parameters - - - name - t - type - {[any]: any} - - - returnType - boolean - comment - Returns true if a table is frozen - - - name - clone - parameters - - - name - t - type - {[any]: any} - - - returnType - {[any]: any} - comment - Creates a shallow copy of a table - - - - - name - utf8 - comment - UTF-8 support library - properties - - - name - charpattern - type - string - comment - Pattern that matches exactly one UTF-8 byte sequence - - - functions - - - name - char - parameters - - - type - number - variadic - true - - - returnType - string - comment - Returns a string from UTF-8 codepoints - - - name - codes - parameters - - - name - s - type - string - - - returnType - ((string, number) -> (number, number), string, number) - comment - Returns an iterator for UTF-8 codepoints in a string - - - name - codepoint - parameters - - - name - s - type - string - - - name - i - type - number - optional - true - - - name - j - type - number - optional - true - - - returnType - ...number - comment - Returns the codepoints of characters in a string - - - name - len - parameters - - - name - s - type - string - - - name - i - type - number - optional - true - - - name - j - type - number - optional - true - - - returnType - (number?, number?) - comment - Returns the number of UTF-8 characters in a string, or nil and error position - - - name - offset - parameters - - - name - s - type - string - - - name - n - type - number - - - name - i - type - number - optional - true - - - returnType - number? - comment - Returns the byte position of the n-th character - - - - - globalFunctions - - - name - dangerouslyexecuterequiredmodule - parameters - - - name - f - type - (...any) -> ...any - - - returnType - ...any - comment - Dangerously executes a required module function - - - name - touuid - parameters - - - name - val - type - string | buffer | uuid - - - returnType - uuid? - comment - Converts a string, buffer, or uuid to a uuid, returns nil if invalid - - - name - tovector - parameters - - - name - val - type - any - - - returnType - vector? - comment - Converts a value to a vector, returns nil if invalid - - - name - toquaternion - parameters - - - name - val - type - any - - - returnType - quaternion? - comment - Converts a value to a quaternion, returns nil if invalid - - - name - torotation - parameters - - - name - val - type - any - - - returnType - quaternion? - comment - Converts a value to a rotation (quaternion), returns nil if invalid - - - constants - - - diff --git a/indra/newview/llpreviewscript.cpp b/indra/newview/llpreviewscript.cpp index a9e3afbc58..544473ba77 100644 --- a/indra/newview/llpreviewscript.cpp +++ b/indra/newview/llpreviewscript.cpp @@ -507,11 +507,10 @@ bool LLScriptEdCore::postBuild() initMenu(); - mSyntaxIDConnection = LLSyntaxIdLSL::getInstance()->addSyntaxIDCallback(boost::bind(&LLScriptEdCore::processKeywords, this)); + mSyntaxIDConnection = LLSyntaxDefCache::getInstance()->addSyntaxIDCallback(boost::bind(&LLScriptEdCore::processKeywords, this)); // Intialise keyword highlighting for the current simulator's version of LSL - LLSyntaxIdLSL::getInstance()->initialize(); - LLSyntaxLua::getInstance()->initialize(); + LLSyntaxDefCache::getInstance(); processKeywords(); mCommitCallbackRegistrar.add("FontSize.Set", boost::bind(&LLScriptEdCore::onChangeFontSize, this, _2)); diff --git a/indra/newview/llscripteditor.cpp b/indra/newview/llscripteditor.cpp index 2a4c2b9d0b..ac6b81f677 100644 --- a/indra/newview/llscripteditor.cpp +++ b/indra/newview/llscripteditor.cpp @@ -342,8 +342,8 @@ void LLScriptEditor::drawLineNumbers() void LLScriptEditor::initKeywords(bool luau_language) { - mKeywordsLua.initialize(LLSyntaxLua::getInstance()->getKeywordsXML(), true); - mKeywordsLSL.initialize(LLSyntaxIdLSL::getInstance()->getKeywordsXML(), false); + mKeywordsLua.initialize(LLSyntaxDefCache::getInstance()->getLuaKeywords(), true); + mKeywordsLSL.initialize(LLSyntaxDefCache::getInstance()->getLSLKeywords(), false); mLuauLanguage = luau_language; diff --git a/indra/newview/llscripteditorws.cpp b/indra/newview/llscripteditorws.cpp index 30a1ca53f6..11aacd791e 100644 --- a/indra/newview/llscripteditorws.cpp +++ b/indra/newview/llscripteditorws.cpp @@ -73,7 +73,7 @@ LLWebsocketMgr::WSConnection::ptr_t LLScriptEditorWSServer::connectionFactory(LL void LLScriptEditorWSServer::onStarted() { - LLSyntaxIdLSL& syntax_id_mgr = LLSyntaxIdLSL::instance(); + LLSyntaxDefCache& syntax_id_mgr = LLSyntaxDefCache::instance(); wptr_t that(std::static_pointer_cast(shared_from_this())); mLastSyntaxId = syntax_id_mgr.getSyntaxID(); @@ -302,7 +302,7 @@ void LLScriptEditorWSServer::setupConnectionMethods(LLJSONRPCConnection::ptr_t c void LLScriptEditorWSServer::broadcastLanguageChange() { - LLUUID syntax_id = LLSyntaxIdLSL::instance().getSyntaxID(); + LLUUID syntax_id = LLSyntaxDefCache::instance().getSyntaxID(); if (syntax_id != mLastSyntaxId) { @@ -340,12 +340,12 @@ LLSD LLScriptEditorWSServer::handleSyntaxRequest(const LLSD& params) const response["id"] = mLastSyntaxId; if (category == "defs.lua") { - response["defs"] = LLSyntaxLua::instance().getTypesXML(); + response["defs"] = LLSyntaxDefCache::instance().getLuaKeywords(); response["success"] = response["defs"].isDefined(); } else if (category == "defs.lsl") { - response["defs"] = LLSyntaxIdLSL::instance().getKeywordsXML(); + response["defs"] = LLSyntaxDefCache::instance().getLSLKeywords(); response["success"] = response["defs"].isDefined(); } else @@ -710,7 +710,7 @@ void LLScriptEditorWSConnection::onOpen() languages.append("lsl"); languages.append("luau"); handshake["languages"] = languages; - handshake["syntax_id"] = LLSyntaxIdLSL::instance().getSyntaxID(); + handshake["syntax_id"] = LLSyntaxDefCache::instance().getSyntaxID(); // Features object LLSD features; diff --git a/indra/newview/llsyntaxid.cpp b/indra/newview/llsyntaxid.cpp index 16274f59bc..3d0a9d80b4 100644 --- a/indra/newview/llsyntaxid.cpp +++ b/indra/newview/llsyntaxid.cpp @@ -38,37 +38,53 @@ //----------------------------------------------------------------------------- // LLSyntaxIdLSL //----------------------------------------------------------------------------- -const std::string SYNTAX_ID_CAPABILITY_NAME = "LSLSyntax"; -const std::string SYNTAX_ID_SIMULATOR_FEATURE = "LSLSyntaxId"; -const std::string FILENAME_DEFAULT_LSL = "keywords_lsl_default.xml"; -const std::string FILENAME_DEFAULT_LUA = "keywords_lua_default.xml"; - -/** - * @brief LLSyntaxIdLSL constructor - */ -LLSyntaxIdLSL::LLSyntaxIdLSL() -: mKeywordsXml(LLSD()) -, mCapabilityURL(std::string()) -, mFilePath(LL_PATH_APP_SETTINGS) -, mSyntaxId(LLUUID()) -, mInitialized(false) +namespace +{ + const std::string SYNTAX_ID_CAPABILITY_NAME = "LSLSyntax"; + const std::string SYNTAX_DEF_CAPABILITY_NAME = "ScriptDefinitions"; + const std::string SYNTAX_ID_SIMULATOR_FEATURE = "LSLSyntaxId"; + const std::string FILENAME_INTERNAL_LSL = "lsl_keywords.xml"; + const std::string FILENAME_INTERNAL_LUA = "slua_keywords.xml"; + + constexpr U32 LLSD_SYNTAX_LSL_VERSION_EXPECTED = 2; + const std::string LLSD_SYNTAX_LSL_VERSION_KEY("llsd-lsl-syntax-version"); + + const std::unordered_set MEMCACHED_LLSD = { + FILENAME_INTERNAL_LSL, + FILENAME_INTERNAL_LUA + }; +} // namespace + +//======================================================================== +void LLSyntaxDefCache::initSingleton() { - loadDefaultKeywordsIntoLLSD(); - mRegionChangedCallback = gAgent.addRegionChangedCallback(boost::bind(&LLSyntaxIdLSL::handleRegionChanged, this)); + buildDefaultCache(); + loadKeywordsIntoLLSD(); + mRegionChangedCallback = gAgent.addRegionChangedCallback(boost::bind(&LLSyntaxDefCache::handleRegionChanged, this)); handleRegionChanged(); // Kick off an initial caps query and fetch } -void LLSyntaxIdLSL::buildFullFileSpec() +void LLSyntaxDefCache::cleanupSingleton() { - ELLPath path = mSyntaxId.isNull() ? LL_PATH_APP_SETTINGS : LL_PATH_CACHE; - const std::string filename = mSyntaxId.isNull() ? FILENAME_DEFAULT_LSL : "keywords_lsl_" + mSyntaxId.asString() + ".llsd.xml"; - mFullFileSpec = gDirUtilp->getExpandedFilename(path, filename); + gAgent.removeRegionChangedCallback(mRegionChangedCallback); + mLSLKeywords = LLSD(); + mLuaKeywords = LLSD(); + mCapabilityURL = std::string(); + mSyntaxId = LLUUID(); + mFileCachePaths.clear(); } -//----------------------------------------------------------------------------- -// syntaxIdChange() -//----------------------------------------------------------------------------- -bool LLSyntaxIdLSL::syntaxIdChanged() +boost::signals2::connection LLSyntaxDefCache::addSyntaxIDCallback(const syntax_id_changed_signal_t::slot_type& cb) +{ + return mSyntaxIDChangedSignal.connect(cb); +} + +//======================================================================== +// checkSyntaxId() +// Checks the current region for the LSLSyntaxId feature and capability, and +// if found checks the syntax ID against the one we have. If they differ, +// updates the syntax ID and returns true. Otherwise returns false. +bool LLSyntaxDefCache::updateSyntaxId() { LLViewerRegion* region = gAgent.getRegion(); @@ -83,51 +99,97 @@ bool LLSyntaxIdLSL::syntaxIdChanged() { // get and check the hash LLUUID new_syntax_id = sim_features[SYNTAX_ID_SIMULATOR_FEATURE].asUUID(); - mCapabilityURL = region->getCapability(SYNTAX_ID_CAPABILITY_NAME); + + // *Note* the syntax ID may not have changed, but the region almost certainly has. + // update the cap URL + mCapabilityURL = region->getCapability(SYNTAX_DEF_CAPABILITY_NAME); + mUseDefsCap = !mCapabilityURL.empty(); + if (!mUseDefsCap) + { + mCapabilityURL = region->getCapability(SYNTAX_ID_CAPABILITY_NAME); + } LL_DEBUGS("SyntaxLSL") << SYNTAX_ID_SIMULATOR_FEATURE << " capability URL: " << mCapabilityURL << LL_ENDL; + if (new_syntax_id != mSyntaxId) { LL_DEBUGS("SyntaxLSL") << "New SyntaxID '" << new_syntax_id << "' found." << LL_ENDL; mSyntaxId = new_syntax_id; return true; } - else - LL_DEBUGS("SyntaxLSL") << "SyntaxID matches what we have." << LL_ENDL; + + LL_DEBUGS("SyntaxLSL") << "SyntaxID has not changed. Still " << mSyntaxId << LL_ENDL; } } else { - region->setCapabilitiesReceivedCallback(boost::bind(&LLSyntaxIdLSL::handleCapsReceived, this, _1)); + region->setCapabilitiesReceivedCallback(boost::bind(&LLSyntaxDefCache::handleCapsReceived, this, _1)); LL_DEBUGS("SyntaxLSL") << "Region has not received capabilities. Waiting for caps..." << LL_ENDL; } } return false; } +void LLSyntaxDefCache::handleRegionChanged() +{ + if (updateSyntaxId()) + { + if (!checkCacheAndLoad(mSyntaxId)) + { + fetchKeywords(); + } + } +} + +void LLSyntaxDefCache::handleCapsReceived(const LLUUID& region_uuid) +{ + LLViewerRegion* current_region = gAgent.getRegion(); + + if (region_uuid.notNull() && current_region->getRegionID() == region_uuid) + { + updateSyntaxId(); + if (!checkCacheAndLoad(mSyntaxId)) + { + fetchKeywords(); + } + } +} + //----------------------------------------------------------------------------- -// fetchKeywordsFile -//----------------------------------------------------------------------------- -void LLSyntaxIdLSL::fetchKeywordsFile(const std::string& filespec) +// fetchKeywords +// Initiates a fetch of the current language definitions from the region caps. +void LLSyntaxDefCache::fetchKeywords() { - LLCoros::instance().launch("LLSyntaxIdLSL::fetchKeywordsFileCoro", - boost::bind(&LLSyntaxIdLSL::fetchKeywordsFileCoro, this, mCapabilityURL, filespec)); - LL_DEBUGS("SyntaxLSL") << "LSLSyntaxId capability URL is: " << mCapabilityURL << ". Filename to use is: '" << filespec << "'." << LL_ENDL; + if (mCapabilityURL.empty()) + { + LL_WARNS("SyntaxLSL") << "No capability URL for fetching syntax definitions." << LL_ENDL; + return; + } + if (mUseDefsCap) + { + LLCoros::instance().launch("LLSyntaxIdLSL::fetchKeywordsDefsCoro", + boost::bind(&LLSyntaxDefCache::fetchKeywordsDefsCoro, this, mCapabilityURL, mSyntaxId)); + } + else + { + LLCoros::instance().launch("LLSyntaxIdLSL::fetchKeywordsFileCoro", + boost::bind(&LLSyntaxDefCache::fetchKeywordsFileCoro, this, mCapabilityURL, mSyntaxId)); + } } //----------------------------------------------------------------------------- // fetchKeywordsFileCoro -//----------------------------------------------------------------------------- -void LLSyntaxIdLSL::fetchKeywordsFileCoro(std::string url, std::string fileSpec) +// This uses the legacy languge cap which only sends the LSL keywords file. +void LLSyntaxDefCache::fetchKeywordsFileCoro(std::string url, LLUUID syntax_id) { LLCore::HttpRequest::policy_t httpPolicy(LLCore::HttpRequest::DEFAULT_POLICY_ID); LLCoreHttpUtil::HttpCoroutineAdapter::ptr_t httpAdapter = std::make_shared("fetchKeywordsFileCoro", httpPolicy); LLCore::HttpRequest::ptr_t httpRequest = std::make_shared(); - std::pair::iterator, bool> insrt = mInflightFetches.insert(fileSpec); + auto insrt = mInflightFetches.insert(syntax_id); if (!insrt.second) { - LL_WARNS("SyntaxLSL") << "Already downloading keyword file called \"" << fileSpec << "\"." << LL_ENDL; + LL_WARNS("SyntaxLSL") << "Already downloading keyword file for syntax ID \"" << syntax_id << "\"." << LL_ENDL; return; } @@ -136,11 +198,11 @@ void LLSyntaxIdLSL::fetchKeywordsFileCoro(std::string url, std::string fileSpec) LLSD httpResults = result[LLCoreHttpUtil::HttpCoroutineAdapter::HTTP_RESULTS]; LLCore::HttpStatus status = LLCoreHttpUtil::HttpCoroutineAdapter::getStatusFromLLSD(httpResults); - mInflightFetches.erase(fileSpec); + mInflightFetches.erase(syntax_id); if (!status) { - LL_WARNS("SyntaxLSL") << "Failed to fetch syntax file \"" << fileSpec << "\"" << LL_ENDL; + LL_WARNS("SyntaxLSL") << "Failed to fetch syntax file for syntax ID \"" << syntax_id << "\"" << LL_ENDL; return; } @@ -148,13 +210,38 @@ void LLSyntaxIdLSL::fetchKeywordsFileCoro(std::string url, std::string fileSpec) if (isSupportedVersion(result)) { - // Shuttle this task to the main coro/worker. - // loadKeywordsIntoLLSD will attempt to get a mutex which is not coro aware. - LLAppViewer::instance()->postToMainCoro([this, result, fileSpec]() + std::string path = buildCacheDirectoryName(syntax_id); + + if (!LLFile::exists(path)) + { + LL_DEBUGS("SyntaxLSL") << "Cache directory '" << path << "' does not exist. Attempting to create." << LL_ENDL; + if (LLFile::mkdir(path)) { - setKeywordsXml(result); - cacheFile(fileSpec, result); - loadKeywordsIntoLLSD(); + LL_WARNS("SyntaxLSL") << "Failed to create cache directory '" << path << "'. Cannot cache syntax defs file." << LL_ENDL; + return; + } + } + + // Note that after this call the file cache will have all well known files pointing + // to the default versions, so below, where we get the path to the lua keywords + // well be loading the default version. + buildDefaultCache(); + + // The LSL keywords we just received + std::string full_path = gDirUtilp->add(path, FILENAME_INTERNAL_LSL); + if (writeCacheFile(full_path, result)) + { + mFileCachePaths.addNamePath(FILENAME_INTERNAL_LSL, full_path); + } + // We need to manually load the Lua keywords + full_path = mFileCachePaths.getPath(FILENAME_INTERNAL_LUA); + LLSD lua_defs = loadDeserializedCacheFile(full_path); + + setKeywords(result, lua_defs); + + // Shuttle this task to the main coro/worker. + LLAppViewer::instance()->postToMainCoro([this]() { + mSyntaxIDChangedSignal(); }); } else @@ -164,73 +251,196 @@ void LLSyntaxIdLSL::fetchKeywordsFileCoro(std::string url, std::string fileSpec) } -//----------------------------------------------------------------------------- -// cacheFile -//----------------------------------------------------------------------------- -void LLSyntaxIdLSL::cacheFile(const std::string &fileSpec, const LLSD& content_ref) +void LLSyntaxDefCache::fetchKeywordsDefsCoro(std::string url, LLUUID syntax_id) { - std::stringstream str; - LLSDSerialize::toXML(content_ref, str); - const std::string xml = str.str(); + LLCore::HttpRequest::policy_t httpPolicy(LLCore::HttpRequest::DEFAULT_POLICY_ID); + LLCoreHttpUtil::HttpCoroutineAdapter::ptr_t httpAdapter = + std::make_shared("fetchKeywordsDefsCoro", httpPolicy); + LLCore::HttpRequest::ptr_t httpRequest = std::make_shared(); - // save the str to disk, usually to the cache. - llofstream file(fileSpec.c_str(), std::ios_base::out); - file.write(xml.c_str(), str.str().size()); - file.close(); + static std::set inflightDefsFetches; + auto insrt = inflightDefsFetches.insert(syntax_id); + //auto insrt = mInflightFetches.insert(syntax_id); + if (!insrt.second) + { + LL_WARNS("SyntaxLSL") << "Already downloading keyword defs for \"" << syntax_id << "\"." << LL_ENDL; + return; + } - LL_DEBUGS("SyntaxLSL") << "Syntax file received, saving as: '" << fileSpec << "'" << LL_ENDL; -} + LLSD result = httpAdapter->getAndSuspend(httpRequest, url); -//----------------------------------------------------------------------------- -// initialize -//----------------------------------------------------------------------------- -void LLSyntaxIdLSL::initialize() -{ - if(mInitialized) return; - if (mSyntaxId.isNull()) + LLSD httpResults = result[LLCoreHttpUtil::HttpCoroutineAdapter::HTTP_RESULTS]; + LLCore::HttpStatus status = LLCoreHttpUtil::HttpCoroutineAdapter::getStatusFromLLSD(httpResults); + + inflightDefsFetches.erase(syntax_id); + + if (!status) { - loadDefaultKeywordsIntoLLSD(); + LL_WARNS("SyntaxLSL") << "Failed to fetch syntax file \"" << syntax_id << "\"" << LL_ENDL; + result.erase(LLCoreHttpUtil::HttpCoroutineAdapter::HTTP_RESULTS); + return; } - else if (!mCapabilityURL.empty()) + + // Now we need to walk through the returned LLSD. It consists of a map keyed on the file name containing a binary + // blob of the actual file contents. + LLSD files = result["files"]; + LLSD memcached_keywords; + if (files.isMap()) { - LL_DEBUGS("SyntaxLSL") << "LSL version has changed, getting appropriate file." << LL_ENDL; + std::string path = buildCacheDirectoryName(syntax_id); - // Need a full spec regardless of file source, so build it now. - buildFullFileSpec(); - if (mSyntaxId.notNull()) + if (!LLFile::exists(path)) { - if (!gDirUtilp->fileExists(mFullFileSpec)) - { // Does not exist, so fetch it from the capability - LL_DEBUGS("SyntaxLSL") << "LSL syntax not cached, attempting download." << LL_ENDL; - fetchKeywordsFile(mFullFileSpec); - } - else + LL_DEBUGS("SyntaxLSL") << "Cache directory '" << path << "' does not exist. Attempting to create." << LL_ENDL; + if (LLFile::mkdir(path)) { - LL_DEBUGS("SyntaxLSL") << "Found cached Syntax file: " << mFullFileSpec << " Loading keywords." << LL_ENDL; - loadKeywordsIntoLLSD(); + LL_WARNS("SyntaxLSL") << "Failed to create cache directory '" << path << "'. Cannot cache syntax defs file." << LL_ENDL; + return; } } - else + + buildDefaultCache(); + + for (const auto &[filename, contents] : llsd::inMap(files)) { - LL_DEBUGS("SyntaxLSL") << "LSLSyntaxId is null. Loading default values" << LL_ENDL; - loadDefaultKeywordsIntoLLSD(); + std::string full_path = gDirUtilp->add(path, filename); + + if (MEMCACHED_LLSD.find(filename) != MEMCACHED_LLSD.end()) + { // Maintain some keyword LLSDs internally, LSL and Lua + memcached_keywords[filename] = contents; + } + + if (writeCacheFile(full_path, contents)) + { + mFileCachePaths.addNamePath(filename, full_path); + } } } else { - LL_DEBUGS("SyntaxLSL") << "LSLSyntaxId capability URL is empty." << LL_ENDL; - loadDefaultKeywordsIntoLLSD(); + LL_WARNS("SyntaxLSL") << "Malformed syntax defs response, missing 'files' map." << LL_ENDL; } - mInitialized = true; + + result.erase(LLCoreHttpUtil::HttpCoroutineAdapter::HTTP_RESULTS); + + setKeywords(memcached_keywords["lsl_keywords.xml"], memcached_keywords["lua_keywords.xml"]); + LLAppViewer::instance()->postToMainCoro( + [this]() + { + mSyntaxIDChangedSignal(); + }); } +//----------------------------------------------------------------------------- +// buildCache +// Constructs the cache file paths for the given syntax ID. If the syntax ID is null, +// constructs the default cache file paths. +void LLSyntaxDefCache::buildCachePaths(const LLUUID &syntax_id) +{ + if (syntax_id.notNull()) + { // Initialize the cache files to point to the default files + buildCachePaths(LLUUID::null); + } + else + { + mFileCachePaths.clear(); + } + + std::string cache_dir = buildCacheDirectoryName(syntax_id); + if (!LLFile::exists(cache_dir)) + { + LL_DEBUGS("SyntaxLSL") << "Cache directory '" << cache_dir << "' does not exist." << LL_ENDL; + return; + } + + auto files = gDirUtilp->getFilesInDir(cache_dir); + for (const auto &file : files) + { + mFileCachePaths.addNamePath(file, gDirUtilp->add(cache_dir, file)); + } +} + +bool LLSyntaxDefCache::writeCacheFile(const std::string &fileSpec, const LLSD& content_ref) +{ + bool binary(content_ref.isBinary()); + std::ofstream file(fileSpec.c_str(), (binary)? std::ios_base::binary : 0); + + if (!file.is_open()) + { + LL_WARNS("SyntaxLSL") << "Failed to open file for writing: '" << fileSpec << "'" << LL_ENDL; + return false; + } + + if (binary) + { + LL_DEBUGS("SyntaxLSL") << "Caching raw content to '" << fileSpec << "'" << LL_ENDL; + file.write((const char*)content_ref.asBinary().data(), content_ref.asBinary().size()); + } + else + { + LL_DEBUGS("SyntaxLSL") << "Caching XML content to '" << fileSpec << "'" << LL_ENDL; + LLSDSerialize::serialize(content_ref, file, LLSDSerialize::LLSD_XML, LLSDFormatter::OPTIONS_PRETTY); + } + file.close(); + + if (!file.good()) + { + LL_WARNS("SyntaxLSL") << "Failed to write content to file: '" << fileSpec << "'" << LL_ENDL; + return false; + } + return true; +} + +//----------------------------------------------------------------------------- +// checkCacheAndLoad +// Tests the local cache for the given syntax ID. If found it loads the keywords +// from the cache into LLSD and returns true. Otherwise returns false. +bool LLSyntaxDefCache::checkCacheAndLoad(const LLUUID& syntax_id) +{ + if (checkLocalCache(syntax_id)) + { + buildCachePaths(syntax_id); + loadKeywordsIntoLLSD(); + return true; + } + return false; +} + +std::string LLSyntaxDefCache::buildCacheDirectoryName(const LLUUID& syntax_id) +{ + if (syntax_id.isNull()) + { + LL_DEBUGS("SyntaxLSL") << "No SyntaxID, using app settings directory." << LL_ENDL; + return gDirUtilp->getExpandedFilename(LL_PATH_CACHE, "syntax_default"); + } + else + { + LL_DEBUGS("SyntaxLSL") << "Using cache directory for SyntaxID '" << syntax_id << "'." << LL_ENDL; + std::string cache_dir_name = "syntax_" + syntax_id.asString(); + + return gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS, cache_dir_name); + } +} + +bool LLSyntaxDefCache::checkLocalCache(const LLUUID& syntax_id) const +{ + if (syntax_id.isNull()) + { // Cache check will always fail if we don't have a valid SyntaxID, so skip it in that case. + LL_DEBUGS("SyntaxLSL") << "No SyntaxID, skipping local cache check." << LL_ENDL; + return false; + } + + // Check for the existence of the cache directory for this syntax ID. If it doesn't exist, then we don't have a cached file. + std::string cache_dir = buildCacheDirectoryName(syntax_id); + return gDirUtilp->fileExists(cache_dir); +} + + //----------------------------------------------------------------------------- // isSupportedVersion //----------------------------------------------------------------------------- -const U32 LLSD_SYNTAX_LSL_VERSION_EXPECTED = 2; -const std::string LLSD_SYNTAX_LSL_VERSION_KEY("llsd-lsl-syntax-version"); -bool LLSyntaxIdLSL::isSupportedVersion(const LLSD& content) +bool LLSyntaxDefCache::isSupportedVersion(const LLSD& content) { bool is_valid = false; /* @@ -256,128 +466,61 @@ bool LLSyntaxIdLSL::isSupportedVersion(const LLSD& content) } //----------------------------------------------------------------------------- -// loadDefaultKeywordsIntoLLSD() -//----------------------------------------------------------------------------- -void LLSyntaxIdLSL::loadDefaultKeywordsIntoLLSD() -{ - mSyntaxId.setNull(); - buildFullFileSpec(); - loadKeywordsIntoLLSD(); -} - -//----------------------------------------------------------------------------- -// loadKeywordsFileIntoLLSD +// loadKeywordsIntoLLSD //----------------------------------------------------------------------------- /** * @brief Load xml serialized LLSD - * @desc Opens the specified filespec and attempts to deserializes the - * contained data to the specified LLSD object. indicate success/failure with - * sLoaded/sLoadFailed members. + * @desc Open the internal lsl keywords files and deserialize them into the correct + * members. */ -void LLSyntaxIdLSL::loadKeywordsIntoLLSD() +void LLSyntaxDefCache::loadKeywordsIntoLLSD() { - LLSD content; - llifstream file; - file.open(mFullFileSpec.c_str()); - if (file.is_open()) + for (auto& filename : MEMCACHED_LLSD) { - if (LLSDSerialize::fromXML(content, file) != LLSDParser::PARSE_FAILURE) + // Note, in the case of the legacy language cap (it only delivers the LSL keywords file) + // The mFileCachePaths will have been initialized in such a way that the Lua keywords + // point to the default file. + std::string full_path = mFileCachePaths.getPath(filename); + if (!full_path.empty()) { - if (isSupportedVersion(content)) + LLSD content = loadDeserializedCacheFile(full_path); + if (!content.isUndefined() && isSupportedVersion(content)) { - LL_DEBUGS("SyntaxLSL") << "Deserialized: " << mFullFileSpec << LL_ENDL; + LL_DEBUGS("SyntaxLSL") << "Deserialized cached file: " << full_path << LL_ENDL; + if (filename == FILENAME_INTERNAL_LSL) + { + mLSLKeywords = content; + } + else if (filename == FILENAME_INTERNAL_LUA) + { + mLuaKeywords = content; + } } else { - LL_WARNS("SyntaxLSL") << "Unknown or unsupported version of syntax file." << LL_ENDL; + LL_WARNS("SyntaxLSL") << "Unknown or unsupported version of syntax file " << full_path << "." << LL_ENDL; } } } - else - { - LL_WARNS("SyntaxLSL") << "Failed to open: " << mFullFileSpec << LL_ENDL; - } - mKeywordsXml = content; - mSyntaxIDChangedSignal(); -} - -bool LLSyntaxIdLSL::keywordFetchInProgress() -{ - return !mInflightFetches.empty(); -} - -void LLSyntaxIdLSL::handleRegionChanged() -{ - if (syntaxIdChanged()) - { - buildFullFileSpec(); - fetchKeywordsFile(mFullFileSpec); - mInitialized = false; - } -} - -void LLSyntaxIdLSL::handleCapsReceived(const LLUUID& region_uuid) -{ - LLViewerRegion* current_region = gAgent.getRegion(); - - if (region_uuid.notNull() - && current_region->getRegionID() == region_uuid) - { - syntaxIdChanged(); - } -} - -boost::signals2::connection LLSyntaxIdLSL::addSyntaxIDCallback(const syntax_id_changed_signal_t::slot_type& cb) -{ - return mSyntaxIDChangedSignal.connect(cb); -} - - - -//----------------------------------------------------------------------------- -// LLSyntaxLua -//----------------------------------------------------------------------------- -LLSyntaxLua::LLSyntaxLua() - : mKeywordsXml(LLSD()) - , mInitialized(false) -{ -} - -void LLSyntaxLua::initialize() -{ - if (mInitialized) return; - loadDefaultKeywordsIntoLLSD(); - loadLuaTypesIntoLLSD(); - mInitialized = true; + mSyntaxIDChangedSignal(); } -void LLSyntaxLua::loadDefaultKeywordsIntoLLSD() +LLSD LLSyntaxDefCache::loadDeserializedCacheFile(const std::string& file_path) { - std::string fullFileSpec = gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS, FILENAME_DEFAULT_LUA); - llifstream file(fullFileSpec.c_str()); - + std::ifstream file(file_path.c_str()); if (file.good()) { LLSD content; - if (LLSDSerialize::fromXML(content, file) != LLSDParser::PARSE_FAILURE) + if (LLSDSerialize::deserialize(content, file, -1)) { - mKeywordsXml = content; + return content; } } -} - -void LLSyntaxLua::loadLuaTypesIntoLLSD() -{ - std::string fullFileSpec = gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS, "types_lua_default.xml"); - llifstream file(fullFileSpec.c_str()); - - if (file.good()) + else { - LLSD content; - if (LLSDSerialize::fromXML(content, file) != LLSDParser::PARSE_FAILURE) - { - mTypesXml = content; - } + LL_WARNS("SyntaxLSL") << "Failed to open cached file: " << file_path << LL_ENDL; } + return LLSD(); } + diff --git a/indra/newview/llsyntaxid.h b/indra/newview/llsyntaxid.h index 51103e3396..3bd49378b5 100644 --- a/indra/newview/llsyntaxid.h +++ b/indra/newview/llsyntaxid.h @@ -34,66 +34,101 @@ #include "lleventcoro.h" #include "llcoros.h" -class fetchKeywordsFileResponder; - -class LLSyntaxIdLSL : public LLSingleton +class LLSyntaxDefCache : public LLSingleton { - LLSINGLETON(LLSyntaxIdLSL); - friend class fetchKeywordsFileResponder; + LLSINGLETON(LLSyntaxDefCache) = default; public: using syntax_id_changed_signal_t = boost::signals2::signal; using syntax_id_changed_h = boost::signals2::connection; - - void initialize(); - bool keywordFetchInProgress(); - LLSD getKeywordsXML() const { return mKeywordsXml; }; + class cache_names_t + { + public: + using name_path_map_t = std::unordered_map; + using iterator = name_path_map_t::iterator; + using const_iterator = name_path_map_t::const_iterator; + + cache_names_t() = default; + ~cache_names_t() = default; + + std::string getPath(const std::string &name) const + { + auto it = mNamePathMap.find(name); + if (it != mNamePathMap.end()) + { + return it->second; + } + return std::string(); + } + + bool hasName(const std::string &name) const + { + return mNamePathMap.find(name) != mNamePathMap.end(); + } + + void addNamePath(const std::string &name, const std::string &path) + { + mNamePathMap[name] = path; + } + + iterator begin() { return mNamePathMap.begin(); } + const_iterator begin() const { return mNamePathMap.begin(); } + iterator end() { return mNamePathMap.end(); } + const_iterator end() const { return mNamePathMap.end(); } + + size_t size() const { return mNamePathMap.size(); } + void clear() { mNamePathMap.clear(); } + bool empty() const { return mNamePathMap.empty(); } + + private: + name_path_map_t mNamePathMap; + }; + + bool keywordFetchInProgress() const { return !mInflightFetches.empty(); } + LLSD getLSLKeywords() const { return mLSLKeywords; }; + LLSD getLuaKeywords() const { return mLuaKeywords; }; LLUUID getSyntaxID() const { return mSyntaxId; } syntax_id_changed_h addSyntaxIDCallback(const syntax_id_changed_signal_t::slot_type& cb); + bool checkCacheAndLoad(const LLUUID& syntax_id); + + static std::string buildCacheDirectoryName(const LLUUID& syntax_id); + +protected: + void initSingleton() override; + void cleanupSingleton() override; + private: - std::set mInflightFetches; - syntax_id_changed_signal_t mSyntaxIDChangedSignal; - syntax_id_changed_h mRegionChangedCallback; - - bool syntaxIdChanged(); - bool isSupportedVersion(const LLSD& content); - void handleRegionChanged(); - void handleCapsReceived(const LLUUID& region_uuid); - void setKeywordsXml(const LLSD& content) { mKeywordsXml = content; }; - void buildFullFileSpec(); - void fetchKeywordsFile(const std::string& filespec); - void loadDefaultKeywordsIntoLLSD(); - void loadKeywordsIntoLLSD(); - - void fetchKeywordsFileCoro(std::string url, std::string fileSpec); - void cacheFile(const std::string &fileSpec, const LLSD& content_ref); - - std::string mCapabilityURL; - std::string mFullFileSpec; - ELLPath mFilePath; - LLUUID mSyntaxId; - LLSD mKeywordsXml; - bool mInitialized; -}; + bool updateSyntaxId(); + static bool isSupportedVersion(const LLSD& content); + void handleRegionChanged(); + void handleCapsReceived(const LLUUID& region_uuid); + void setKeywords(const LLSD& lsl, const LLSD& lua) { mLSLKeywords = lsl; mLuaKeywords = lua; }; + void loadKeywordsIntoLLSD(); -class LLSyntaxLua : public LLSingleton -{ - LLSINGLETON(LLSyntaxLua); + void fetchKeywords(); + void fetchKeywordsFileCoro(std::string url, LLUUID syntax_id); + void fetchKeywordsDefsCoro(std::string url, LLUUID syntax_id); -public: - void initialize(); - LLSD getKeywordsXML() const { return mKeywordsXml; } - LLSD getTypesXML() const { return mTypesXml; } + bool checkLocalCache(const LLUUID& syntax_id) const; + void buildDefaultCache() { buildCachePaths(LLUUID::null); } + void buildCachePaths(const LLUUID &syntax_id); + bool writeCacheFile(const std::string &fileSpec, const LLSD& content_ref); -private: - void loadDefaultKeywordsIntoLLSD(); - void loadLuaTypesIntoLLSD(); - LLSD mKeywordsXml; - LLSD mTypesXml; - bool mInitialized; + static LLSD loadDeserializedCacheFile(const std::string& file_path); + + std::set mInflightFetches; + syntax_id_changed_signal_t mSyntaxIDChangedSignal; + syntax_id_changed_h mRegionChangedCallback; + + std::string mCapabilityURL; + cache_names_t mFileCachePaths; + LLUUID mSyntaxId; + LLSD mLSLKeywords; + LLSD mLuaKeywords; + bool mUseDefsCap{ false }; }; #endif // LLSYNTAXID_H diff --git a/indra/newview/llviewerregion.cpp b/indra/newview/llviewerregion.cpp index 42a587f376..01ce2a7a21 100644 --- a/indra/newview/llviewerregion.cpp +++ b/indra/newview/llviewerregion.cpp @@ -3325,6 +3325,7 @@ void LLViewerRegionImpl::buildCapabilityNames(LLSD& capabilityNames) capabilityNames.append("ViewerMetrics"); capabilityNames.append("ViewerStartAuction"); capabilityNames.append("ViewerStats"); + capabilityNames.append("ScriptDefinitions"); // Please add new capabilities alphabetically to reduce // merge conflicts. diff --git a/indra/newview/viewer_manifest.py b/indra/newview/viewer_manifest.py index 21e50f4dcb..524077f1b2 100755 --- a/indra/newview/viewer_manifest.py +++ b/indra/newview/viewer_manifest.py @@ -64,6 +64,16 @@ class ViewerManifest(LLManifest): super(ViewerManifest, self).construct() self.path(src="../../scripts/messages/message_template.msg", dst="app_settings/message_template.msg") + # ... and the lsl/lua script definition files (needed at build time and packaging) + pkgdir = os.path.join(self.args['build'], os.pardir, 'packages') + with self.prefix(src=os.path.join(pkgdir, 'lsl_definitions'), dst="app_settings/syntax_default"): + self.path("*.txt") + self.path("*.yaml") + self.path("*.xml") + self.path("*.json") + self.path("*.luau") + self.path("*.yml") + if self.is_packaging_viewer(): with self.prefix(src_dst="app_settings"): self.exclude("logcontrol.xml") @@ -92,7 +102,7 @@ class ViewerManifest(LLManifest): with self.prefix(src=pkgdir): self.path("dictionaries") - # include the extracted packages information (see BuildPackagesInfo.cmake) + # include the extracted packages information self.path(src=os.path.join(self.args['build'],"packages-info.txt"), dst="packages-info.txt") # CHOP-955: If we have "sourceid" or "viewer_channel" in the # build process environment, generate it into -- cgit v1.3 From a1b68fb8ed6c2589dd13bd9ba1fab7050ba38226 Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Wed, 27 May 2026 10:18:29 -0700 Subject: Drop fewer packets on UDP packet flood (#5565) * ACK received-but-unprocessed packets when queued * Prioritize packets between high- and low-priority (high-priority are: reliable packets that need an ACK) * Increase max size of LLPacketRing buffer --- indra/llmessage/llcircuit.cpp | 5 +- indra/llmessage/llpacketbuffer.h | 3 + indra/llmessage/llpacketring.cpp | 315 ++++++------------------------------- indra/llmessage/llpacketring.h | 88 +++-------- indra/llmessage/message.cpp | 315 ++++++++++++++++++++++++++++++++++--- indra/llmessage/message.h | 97 +++++++++++- indra/llmessage/net.cpp | 2 +- indra/newview/llappviewer.cpp | 79 +++++----- indra/newview/llstartup.cpp | 4 +- indra/newview/llviewermenu.cpp | 2 +- indra/newview/llviewerstats.cpp | 2 +- indra/newview/llviewerthrottle.cpp | 23 ++- indra/newview/llviewerthrottle.h | 4 +- indra/newview/llworld.cpp | 10 +- 14 files changed, 529 insertions(+), 420 deletions(-) (limited to 'indra/llmessage') diff --git a/indra/llmessage/llcircuit.cpp b/indra/llmessage/llcircuit.cpp index c2b1a2f069..eaee7b0112 100644 --- a/indra/llmessage/llcircuit.cpp +++ b/indra/llmessage/llcircuit.cpp @@ -346,8 +346,7 @@ S32 LLCircuitData::resendUnackedPackets(const F64Seconds now) packetp->mBuffer[0] |= LL_RESENT_FLAG; // tag packet id as being a resend - gMessageSystem->mPacketRing.sendPacket(packetp->mSocket, - (char *)packetp->mBuffer, packetp->mBufferLength, + gMessageSystem->sendPacketToSocket((char *)packetp->mBuffer, packetp->mBufferLength, packetp->mHost); mThrottles.throttleOverflow(TC_RESEND, packetp->mBufferLength * 8.f); @@ -973,7 +972,7 @@ bool LLCircuitData::updateWatchDogTimers(LLMessageSystem *msgsys) { // let's call this one a loss! mPacketsLost++; - gMessageSystem->mDroppedPackets++; + gMessageSystem->mLostPackets++; if(gMessageSystem->mVerboseLog) { std::ostringstream str; diff --git a/indra/llmessage/llpacketbuffer.h b/indra/llmessage/llpacketbuffer.h index ac4012d330..b0505e7afd 100644 --- a/indra/llmessage/llpacketbuffer.h +++ b/indra/llmessage/llpacketbuffer.h @@ -38,6 +38,9 @@ public: LLPacketBuffer(S32 hSocket); // receive a packet ~LLPacketBuffer(); + LLPacketBuffer(const LLPacketBuffer&) = default; + LLPacketBuffer& operator=(const LLPacketBuffer&) = default; + S32 getSize() const { return mSize; } const char *getData() const { return mData; } LLHost getHost() const { return mHost; } diff --git a/indra/llmessage/llpacketring.cpp b/indra/llmessage/llpacketring.cpp index b8284334ea..bade413e61 100644 --- a/indra/llmessage/llpacketring.cpp +++ b/indra/llmessage/llpacketring.cpp @@ -28,344 +28,121 @@ #include "llpacketring.h" -#if LL_WINDOWS - #include -#else - #include - #include -#endif - -// linden library includes #include "llerror.h" -#include "lltimer.h" -#include "llproxy.h" -#include "llrand.h" -#include "message.h" -#include "u64.h" -constexpr S16 MAX_BUFFER_RING_SIZE = 1024; +constexpr S16 MAX_BUFFER_RING_SIZE = 8192; + +// DANGER: don't adjust DEFAULT_BUFFER_RING_SIZE unless you know what +// you're doing. Its value affects the "buffer load rate" which is used +// to supply backpressure to an overloaded nework queue. constexpr S16 DEFAULT_BUFFER_RING_SIZE = 256; -LLPacketRing::LLPacketRing () - : mPacketRing(DEFAULT_BUFFER_RING_SIZE, nullptr) +LLPacketRing::LLPacketRing() + : mRing(DEFAULT_BUFFER_RING_SIZE, nullptr) { LLHost invalid_host; - for (size_t i = 0; i < mPacketRing.size(); ++i) + for (size_t i = 0; i < mRing.size(); ++i) { - mPacketRing[i] = new LLPacketBuffer(invalid_host, nullptr, 0); + mRing[i] = new LLPacketBuffer(invalid_host, nullptr, 0); } } -LLPacketRing::~LLPacketRing () +LLPacketRing::~LLPacketRing() { - for (auto packet : mPacketRing) + for (auto* packet : mRing) { delete packet; } - mPacketRing.clear(); + mRing.clear(); mNumBufferedPackets = 0; mNumBufferedBytes = 0; mHeadIndex = 0; } -S32 LLPacketRing::receivePacket (S32 socket, char *datap) -{ - bool drop = computeDrop(); - return (mNumBufferedPackets > 0) ? - receiveOrDropBufferedPacket(datap, drop) : - receiveOrDropPacket(socket, datap, drop); -} - -bool send_packet_helper(int socket, const char * datap, S32 data_size, LLHost host) -{ - if (!LLProxy::isSOCKSProxyEnabled()) - { - return send_packet(socket, datap, data_size, host.getAddress(), host.getPort()); - } - - char headered_send_buffer[NET_BUFFER_SIZE + SOCKS_HEADER_SIZE]; - - proxywrap_t *socks_header = static_cast(static_cast(&headered_send_buffer)); - socks_header->rsv = 0; - socks_header->addr = host.getAddress(); - socks_header->port = htons(host.getPort()); - socks_header->atype = ADDRESS_IPV4; - socks_header->frag = 0; - - memcpy(headered_send_buffer + SOCKS_HEADER_SIZE, datap, data_size); - - return send_packet( socket, - headered_send_buffer, - data_size + SOCKS_HEADER_SIZE, - LLProxy::getInstance()->getUDPProxy().getAddress(), - LLProxy::getInstance()->getUDPProxy().getPort()); -} - -bool LLPacketRing::sendPacket(int socket, const char * datap, S32 data_size, LLHost host) +void LLPacketRing::pushPacket(const LLPacketBuffer& packet) { - mActualBytesOut += data_size; - return send_packet_helper(socket, datap, data_size, host); -} - -void LLPacketRing::dropPackets (U32 num_to_drop) -{ - mPacketsToDrop += num_to_drop; -} - -void LLPacketRing::setDropPercentage (F32 percent_to_drop) -{ - mDropPercentage = percent_to_drop; -} - -bool LLPacketRing::computeDrop() -{ - bool drop= (mDropPercentage > 0.0f && (ll_frand(100.f) < mDropPercentage)); - if (drop) - { - ++mPacketsToDrop; - } - if (mPacketsToDrop > 0) - { - --mPacketsToDrop; - drop = true; - } - return drop; -} - -S32 LLPacketRing::receiveOrDropPacket(S32 socket, char *datap, bool drop) -{ - S32 packet_size = 0; - - // pull straight from socket - if (LLProxy::isSOCKSProxyEnabled()) + S16 ring_size = (S16)mRing.size(); + if (mNumBufferedPackets >= ring_size && ring_size < MAX_BUFFER_RING_SIZE) { - char buffer[NET_BUFFER_SIZE + SOCKS_HEADER_SIZE]; /* Flawfinder ignore */ - packet_size = receive_packet(socket, buffer); - if (packet_size > 0) - { - mActualBytesIn += packet_size; - } - - if (packet_size > SOCKS_HEADER_SIZE) - { - if (drop) - { - packet_size = 0; - } - else - { - // *FIX We are assuming ATYP is 0x01 (IPv4), not 0x03 (hostname) or 0x04 (IPv6) - packet_size -= SOCKS_HEADER_SIZE; // The unwrapped packet size - memcpy(datap, buffer + SOCKS_HEADER_SIZE, packet_size); - proxywrap_t * header = static_cast(static_cast(buffer)); - mLastSender.setAddress(header->addr); - mLastSender.setPort(ntohs(header->port)); - mLastReceivingIF = ::get_receiving_interface(); - } - } - else - { - packet_size = 0; - } - } - else - { - packet_size = receive_packet(socket, datap); - if (packet_size > 0) - { - mActualBytesIn += packet_size; - if (drop) - { - packet_size = 0; - } - else - { - mLastSender = ::get_sender(); - mLastReceivingIF = ::get_receiving_interface(); - } - } + expandRing(); + ring_size = (S16)mRing.size(); } - return packet_size; -} -S32 LLPacketRing::receiveOrDropBufferedPacket(char *datap, bool drop) -{ - assert(mNumBufferedPackets > 0); - S32 packet_size = 0; + LLPacketBuffer* slot = mRing[mHeadIndex]; + S32 old_size = slot->getSize(); - S16 ring_size = (S16)(mPacketRing.size()); - S16 packet_index = (mHeadIndex + ring_size - mNumBufferedPackets) % ring_size; - LLPacketBuffer* packet = mPacketRing[packet_index]; - packet_size = packet->getSize(); - mLastSender = packet->getHost(); - mLastReceivingIF = packet->getReceivingInterface(); + *slot = packet; - --mNumBufferedPackets; - mNumBufferedBytes -= packet_size; - if (mNumBufferedPackets == 0) - { - assert(mNumBufferedBytes == 0); - } + mHeadIndex = (mHeadIndex + 1) % ring_size; - if (!drop) + if (mNumBufferedPackets < ring_size) { - if (packet_size > 0) - { - memcpy(datap, packet->getData(), packet_size); - } - else - { - assert(false); - } + ++mNumBufferedPackets; + mNumBufferedBytes += packet.getSize(); } else { - packet_size = 0; + // Ring is at maximum capacity; oldest packet was overwritten. + // This is VERY BAD because we've already ACKed the packet we're loosing + // (if it was "reliable"). + LL_WARNS("PacketRing") << "buffer overflow at " << mNumBufferedPackets << " packets" << LL_ENDL; + mNumBufferedBytes += packet.getSize() - old_size; } - return packet_size; } -S32 LLPacketRing::bufferInboundPacket(S32 socket) +bool LLPacketRing::popPacket(LLPacketBuffer& packet) { - if (mNumBufferedPackets == mPacketRing.size() && mNumBufferedPackets < MAX_BUFFER_RING_SIZE) + if (mNumBufferedPackets <= 0) { - expandRing(); + return false; } - LLPacketBuffer* packet = mPacketRing[mHeadIndex]; - S32 old_packet_size = packet->getSize(); - S32 packet_size = 0; - if (LLProxy::isSOCKSProxyEnabled()) - { - char buffer[NET_BUFFER_SIZE + SOCKS_HEADER_SIZE]; /* Flawfinder ignore */ - packet_size = receive_packet(socket, buffer); - if (packet_size > 0) - { - mActualBytesIn += packet_size; - if (packet_size > SOCKS_HEADER_SIZE) - { - // *FIX We are assuming ATYP is 0x01 (IPv4), not 0x03 (hostname) or 0x04 (IPv6) + S16 ring_size = (S16)mRing.size(); + S16 tail_index = (mHeadIndex + ring_size - mNumBufferedPackets) % ring_size; - proxywrap_t * header = static_cast(static_cast(buffer)); - LLHost sender; - sender.setAddress(header->addr); - sender.setPort(ntohs(header->port)); + LLPacketBuffer* slot = mRing[tail_index]; + S32 packet_size = slot->getSize(); - packet_size -= SOCKS_HEADER_SIZE; // The unwrapped packet size - packet->init(buffer + SOCKS_HEADER_SIZE, packet_size, sender); + packet = *slot; - mHeadIndex = (mHeadIndex + 1) % (S16)(mPacketRing.size()); - if (mNumBufferedPackets < MAX_BUFFER_RING_SIZE) - { - ++mNumBufferedPackets; - mNumBufferedBytes += packet_size; - } - else - { - // we overwrote an older packet - mNumBufferedBytes += packet_size - old_packet_size; - } - } - else - { - packet_size = 0; - } - } - } - else - { - packet->init(socket); - packet_size = packet->getSize(); - if (packet_size > 0) - { - mActualBytesIn += packet_size; + --mNumBufferedPackets; + mNumBufferedBytes -= packet_size; - mHeadIndex = (mHeadIndex + 1) % (S16)(mPacketRing.size()); - if (mNumBufferedPackets < MAX_BUFFER_RING_SIZE) - { - ++mNumBufferedPackets; - mNumBufferedBytes += packet_size; - } - else - { - // we overwrote an older packet - mNumBufferedBytes += packet_size - old_packet_size; - } - } - } - return packet_size; -} + llassert(mNumBufferedPackets > 0 || mNumBufferedBytes == 0); -S32 LLPacketRing::drainSocket(S32 socket) -{ - // drain into buffer - S32 packet_size = 1; - S32 num_loops = 0; - S32 old_num_packets = mNumBufferedPackets; - while (packet_size > 0) - { - packet_size = bufferInboundPacket(socket); - ++num_loops; - } - S32 num_dropped_packets = (num_loops - 1 + old_num_packets) - mNumBufferedPackets; - if (num_dropped_packets > 0) - { - // It will eventually be accounted by mDroppedPackets - // and mPacketsLost, but track it here for logging purposes. - mNumDroppedPackets += num_dropped_packets; - } - return (S32)(mNumBufferedPackets); + return true; } bool LLPacketRing::expandRing() { - // compute larger size - constexpr S16 BUFFER_RING_EXPANSION = 256; - S16 old_size = (S16)(mPacketRing.size()); + constexpr S16 BUFFER_RING_EXPANSION = 512; + S16 old_size = (S16)mRing.size(); S16 new_size = llmin(old_size + BUFFER_RING_EXPANSION, MAX_BUFFER_RING_SIZE); if (new_size == old_size) { - // mPacketRing is already maxed out return false; } - // make a larger ring and copy packet pointers + // Lay existing entries out linearly in FIFO order starting at index 0. std::vector new_ring(new_size, nullptr); for (S16 i = 0; i < old_size; ++i) { S16 j = (mHeadIndex + i) % old_size; - new_ring[i] = mPacketRing[j]; + new_ring[i] = mRing[j]; } - // allocate new packets for the remainder of new_ring LLHost invalid_host; for (S16 i = old_size; i < new_size; ++i) { new_ring[i] = new LLPacketBuffer(invalid_host, nullptr, 0); } - // swap the rings and reset mHeadIndex - mPacketRing.swap(new_ring); + mRing.swap(new_ring); mHeadIndex = mNumBufferedPackets; return true; } F32 LLPacketRing::getBufferLoadRate() const { - // goes up to MAX_BUFFER_RING_SIZE return (F32)mNumBufferedPackets / (F32)DEFAULT_BUFFER_RING_SIZE; } - -void LLPacketRing::dumpPacketRingStats() -{ - mNumDroppedPacketsTotal += mNumDroppedPackets; - LL_INFOS("Messaging") << "Packet ring stats: " << std::endl - << "Buffered packets: " << mNumBufferedPackets << std::endl - << "Buffered bytes: " << mNumBufferedBytes << std::endl - << "Dropped packets current: " << mNumDroppedPackets << std::endl - << "Dropped packets total: " << mNumDroppedPacketsTotal << std::endl - << "Dropped packets percentage: " << mDropPercentage << "%" << std::endl - << "Actual in bytes: " << mActualBytesIn << std::endl - << "Actual out bytes: " << mActualBytesOut << LL_ENDL; - mNumDroppedPackets = 0; -} diff --git a/indra/llmessage/llpacketring.h b/indra/llmessage/llpacketring.h index 572dcbd271..5315e5a5bd 100644 --- a/indra/llmessage/llpacketring.h +++ b/indra/llmessage/llpacketring.h @@ -1,7 +1,16 @@ /** * @file llpacketring.h - * @brief definition of LLPacketRing class for implementing a resend, - * drop, or delay in packet transmissions + * @brief LLPacketRing: a simple ring buffer for LLPacketBuffers. + * + * LLPacketRing stores incoming UDP packets that have already been received + * from the network socket. It has no socket or proxy awareness; callers + * push packets in with pushPacket() and retrieve them in FIFO order with + * popPacket(). + * + * The ring starts at DEFAULT_BUFFER_RING_SIZE slots and grows in increments + * of BUFFER_RING_EXPANSION up to MAX_BUFFER_RING_SIZE. Once at the ceiling, + * pushPacket() silently overwrites the oldest queued packet to make room for + * the incoming one. * * $LicenseInfo:firstyear=2001&license=viewerlgpl$ * Second Life Viewer Source Code @@ -29,9 +38,7 @@ #include -#include "llhost.h" #include "llpacketbuffer.h" -#include "llthrottle.h" class LLPacketRing @@ -40,71 +47,26 @@ public: LLPacketRing(); ~LLPacketRing(); - // receive one packet: either buffered or from the socket - S32 receivePacket (S32 socket, char *datap); - - // send one packet - bool sendPacket(int h_socket, const char * send_buffer, S32 buf_size, LLHost host); - - // drains packets from socket and returns final mNumBufferedPackets - S32 drainSocket(S32 socket); + // Copy 'packet' onto the tail of the ring, growing the ring or + // overwriting the oldest entry when the ring is at capacity. + void pushPacket(const LLPacketBuffer& packet); - void dropPackets(U32); - void setDropPercentage (F32 percent_to_drop); - - inline LLHost getLastSender() const; - inline LLHost getLastReceivingInterface() const; - - S32 getActualInBytes() const { return mActualBytesIn; } - S32 getActualOutBytes() const { return mActualBytesOut; } - S32 getAndResetActualInBits() { S32 bits = mActualBytesIn * 8; mActualBytesIn = 0; return bits;} - S32 getAndResetActualOutBits() { S32 bits = mActualBytesOut * 8; mActualBytesOut = 0; return bits;} + // Copy the head (oldest) packet into 'packet'. + // Returns true if a packet was available, false if the ring was empty. + bool popPacket(LLPacketBuffer& packet); S32 getNumBufferedPackets() const { return (S32)(mNumBufferedPackets); } - S32 getNumBufferedBytes() const { return mNumBufferedBytes; } - S32 getNumDroppedPackets() const { return mNumDroppedPacketsTotal + mNumDroppedPackets; } - - F32 getBufferLoadRate() const; // from 0 to 4 (0 - empty, 1 - default size is full) - void dumpPacketRingStats(); -protected: - // returns 'true' if we should intentionally drop a packet - bool computeDrop(); - - // returns packet_size of received packet, zero or less if no packet found - S32 receiveOrDropPacket(S32 socket, char *datap, bool drop); - S32 receiveOrDropBufferedPacket(char *datap, bool drop); + S32 getNumBufferedBytes() const { return mNumBufferedBytes; } - // returns packet_size of packet buffered - S32 bufferInboundPacket(S32 socket); + // Ratio of buffered packets to DEFAULT_BUFFER_RING_SIZE (0 = empty, 1 = nominal full). + F32 getBufferLoadRate() const; - // returns 'true' if ring was expanded +private: + // Returns true if the ring was expanded, false if already at the ceiling. bool expandRing(); -protected: - std::vector mPacketRing; - S16 mHeadIndex { 0 }; + std::vector mRing; + S16 mHeadIndex { 0 }; S16 mNumBufferedPackets { 0 }; - S32 mNumDroppedPackets { 0 }; - S32 mNumDroppedPacketsTotal { 0 }; - S32 mNumBufferedBytes { 0 }; - - S32 mActualBytesIn { 0 }; - S32 mActualBytesOut { 0 }; - F32 mDropPercentage { 0.0f }; // % of inbound packets to drop - U32 mPacketsToDrop { 0 }; // drop next inbound n packets - - // These are the sender and receiving_interface for the last packet delivered by receivePacket() - LLHost mLastSender; - LLHost mLastReceivingIF; + S32 mNumBufferedBytes { 0 }; }; - - -inline LLHost LLPacketRing::getLastSender() const -{ - return mLastSender; -} - -inline LLHost LLPacketRing::getLastReceivingInterface() const -{ - return mLastReceivingIF; -} diff --git a/indra/llmessage/message.cpp b/indra/llmessage/message.cpp index e2937490ba..b11e4598e7 100644 --- a/indra/llmessage/message.cpp +++ b/indra/llmessage/message.cpp @@ -78,6 +78,8 @@ #include "lltransfertargetvfile.h" #include "llcorehttputil.h" #include "llpounceable.h" +#include "llproxy.h" +#include "llrand.h" // Constants //const char* MESSAGE_LOG_FILENAME = "message.log"; @@ -173,7 +175,7 @@ void LLMessageSystem::init() mTotalBytesIn = 0; mTotalBytesOut = 0; - mDroppedPackets = 0; // total dropped packets in + mLostPackets = 0; // total lost packets out mResentPackets = 0; // total resent packets out mFailedResendPackets = 0; // total resend failure packets out mOffCircuitPackets = 0; // total # of off-circuit packets rejected @@ -184,6 +186,13 @@ void LLMessageSystem::init() mIncomingCompressedSize = 0; mCurrentRecvPacketID = 0; + mActualBytesIn = 0; + mActualBytesOut = 0; + mDropPercentage = 0.0f; + mPacketsToDrop = 0; + mNumDroppedPackets = 0; + mNumDroppedPacketsTotal = 0; + mMessageFileVersionNumber = 0.f; mTimingCallback = NULL; @@ -508,18 +517,16 @@ bool LLMessageSystem::checkMessages(LockMessageChecker&, S64 frame_count ) bool recv_reliable = false; bool recv_resent = false; - S32 acks = 0; + S32 num_acks = 0; S32 true_rcv_size = 0; U8* buffer = mTrueReceiveBuffer; - mTrueReceiveSize = mPacketRing.receivePacket(mSocket, (char *)mTrueReceiveBuffer); + mTrueReceiveSize = receivePacketOrDrop((char *)mTrueReceiveBuffer); // If you want to dump all received packets into SecondLife.log, uncomment this //dumpPacketToLog(); receive_size = mTrueReceiveSize; - mLastSender = mPacketRing.getLastSender(); - mLastReceivingIF = mPacketRing.getLastReceivingInterface(); if (receive_size < (S32) LL_MINIMUM_VALID_PACKET_SIZE) { @@ -535,24 +542,23 @@ bool LLMessageSystem::checkMessages(LockMessageChecker&, S64 frame_count ) } else { - LLHost host; - LLCircuitData* cdp; - - // note if packet acks are appended. + // handle any packet ACKs (for outbound messages) found at tail of inbound message if(buffer[0] & LL_ACK_FLAG) { - acks += buffer[--receive_size]; + // Note: these ACKs may have already been handled if this was a buffered message + // but it doesn't hurt to handle them again. + num_acks += buffer[--receive_size]; true_rcv_size = receive_size; - if(receive_size >= ((S32)(acks * sizeof(TPACKETID) + LL_MINIMUM_VALID_PACKET_SIZE))) + if(receive_size >= ((S32)(num_acks * sizeof(TPACKETID) + LL_MINIMUM_VALID_PACKET_SIZE))) { - receive_size -= acks * sizeof(TPACKETID); + receive_size -= num_acks * sizeof(TPACKETID); } else { // mal-formed packet. ignore it and continue with // the next one LL_WARNS("Messaging") << "Malformed packet received. Packet size " - << receive_size << " with invalid no. of acks " << acks + << receive_size << " with invalid no. of acks " << num_acks << LL_ENDL; valid_packet = false; continue; @@ -562,20 +568,20 @@ bool LLMessageSystem::checkMessages(LockMessageChecker&, S64 frame_count ) // process the message as normal mIncomingCompressedSize = zeroCodeExpand(&buffer, &receive_size); mCurrentRecvPacketID = ntohl(*((U32*)(&buffer[1]))); - host = getSender(); + LLHost host = getSender(); const bool resetPacketId = true; - cdp = findCircuit(host, resetPacketId); + LLCircuitData* cdp = findCircuit(host, resetPacketId); // At this point, cdp is now a pointer to the circuit that // this message came in on if it's valid, and NULL if the // circuit was bogus. - if(cdp && (acks > 0) && ((S32)(acks * sizeof(TPACKETID)) < (true_rcv_size))) + if(cdp && (num_acks > 0) && ((S32)(num_acks * sizeof(TPACKETID)) < (true_rcv_size))) { TPACKETID packet_id; U32 mem_id=0; - for(S32 i = 0; i < acks; ++i) + for(S32 i = 0; i < num_acks; ++i) { true_rcv_size -= sizeof(TPACKETID); memcpy(&mem_id, &mTrueReceiveBuffer[true_rcv_size], /* Flawfinder: ignore*/ @@ -630,7 +636,7 @@ bool LLMessageSystem::checkMessages(LockMessageChecker&, S64 frame_count ) str << tbuf << "(unknown)" << (recv_reliable ? " reliable" : "") << " resent " - << ((acks > 0) ? "acks" : "") + << ((num_acks > 0) ? "acks" : "") << " DISCARD DUPLICATE"; LL_INFOS("Messaging") << str.str() << LL_ENDL; } @@ -680,7 +686,7 @@ bool LLMessageSystem::checkMessages(LockMessageChecker&, S64 frame_count ) if ( valid_packet ) { - logValidMsg(cdp, host, recv_reliable, recv_resent, acks>0 ); + logValidMsg(cdp, host, recv_reliable, recv_resent, num_acks>0 ); valid_packet = mTemplateMessageReader->readMessage(buffer, host); } @@ -724,7 +730,7 @@ bool LLMessageSystem::checkMessages(LockMessageChecker&, S64 frame_count ) // Check to see if we need to print debug info if ((mt_sec - mCircuitPrintTime) > mCircuitPrintFreq) { - mPacketRing.dumpPacketRingStats(); + dumpPacketRingStats(); dumpCircuitInfo(); mCircuitPrintTime = mt_sec; } @@ -749,6 +755,10 @@ S32 LLMessageSystem::getReceiveBytes() const } } +F32 LLMessageSystem::getBufferLoadRate() const +{ + return llmax(mHighPriorityInbound.getBufferLoadRate(), mLowPriorityInbound.getBufferLoadRate()); +} void LLMessageSystem::processAcks(LockMessageChecker&, F32 collect_time) { @@ -822,7 +832,264 @@ void LLMessageSystem::processAcks(LockMessageChecker&, F32 collect_time) S32 LLMessageSystem::drainUdpSocket() { - return mPacketRing.drainSocket(mSocket); + S32 packet_size = 1; + S32 num_loops = 0; + S32 old_num_buffered_packets = getNumBufferedPackets(); + while (packet_size > 0) + { + packet_size = bufferInboundPacket(); + ++num_loops; + } + S32 num_dropped_packets = (num_loops - 1 + old_num_buffered_packets) - getNumBufferedPackets(); + if (num_dropped_packets > 0) + { + mNumDroppedPackets += num_dropped_packets; + } + return getNumBufferedPackets(); +} + +bool LLMessageSystem::computeDrop() +{ + bool drop = (mDropPercentage > 0.0f && (ll_frand(100.f) < mDropPercentage)); + if (drop) + { + ++mPacketsToDrop; + } + if (mPacketsToDrop > 0) + { + --mPacketsToDrop; + drop = true; + } + return drop; +} + +bool LLMessageSystem::isHighPriorityMessage(const LLPacketBuffer& pkt) const +{ + S32 size = pkt.getSize(); + if (size < LL_PACKET_ID_SIZE + 1) + { + return false; + } + + // We want to prioritize crucial messages use to establish viewer <--> simulator connection, + // which are all low-frequency. A simple approximation is to just prioritize all non high- + // frequency messages. + // + // High frequency messages use a single byte for message_id whereas all low- and medium- + // frequency messages have 255 at the first byte of the message_id (which is after the + // LL_PACKET_ID_SIZE bytes of packet_id). + return *((const U8*)pkt.getData() + LL_PACKET_ID_SIZE) == 255; +} + +void LLMessageSystem::dropPackets(U32 num_to_drop) +{ + mPacketsToDrop += num_to_drop; +} + +void LLMessageSystem::setDropPercentage(F32 percent_to_drop) +{ + mDropPercentage = percent_to_drop; +} + +S32 LLMessageSystem::receivePacketOrDrop(char* datap) +{ + if (getNumBufferedPackets() > 0) + { + LLHost invalid_host; + LLPacketBuffer pkt(invalid_host, nullptr, 0); + if (!mHighPriorityInbound.popPacket(pkt)) + { + mLowPriorityInbound.popPacket(pkt); + } + + S32 packet_size = pkt.getSize(); + mLastSender = pkt.getHost(); + mLastReceivingIF = pkt.getReceivingInterface(); + + if (packet_size > 0) + { + memcpy(datap, pkt.getData(), packet_size); + } + return packet_size; + } + + // Read directly from the socket. + bool drop = computeDrop(); + S32 packet_size = 0; + if (LLProxy::isSOCKSProxyEnabled()) + { + char buffer[NET_BUFFER_SIZE + SOCKS_HEADER_SIZE]; /* Flawfinder ignore */ + packet_size = receive_packet(mSocket, buffer); + if (packet_size > 0) + { + mActualBytesIn += packet_size; + } + if (packet_size > SOCKS_HEADER_SIZE) + { + if (drop) + { + packet_size = 0; + } + else + { + // *FIX We are assuming ATYP is 0x01 (IPv4), not 0x03 (hostname) or 0x04 (IPv6) + packet_size -= SOCKS_HEADER_SIZE; + memcpy(datap, buffer + SOCKS_HEADER_SIZE, packet_size); + proxywrap_t* header = static_cast(static_cast(buffer)); + mLastSender.setAddress(header->addr); + mLastSender.setPort(ntohs(header->port)); + mLastReceivingIF = ::get_receiving_interface(); + } + } + else + { + packet_size = 0; + } + } + else + { + packet_size = receive_packet(mSocket, datap); + if (packet_size > 0) + { + mActualBytesIn += packet_size; + if (drop) + { + packet_size = 0; + } + else + { + mLastSender = ::get_sender(); + mLastReceivingIF = ::get_receiving_interface(); + } + } + } + return packet_size; +} + +S32 LLMessageSystem::bufferInboundPacket() +{ + LLHost invalid_host; + LLPacketBuffer pkt(invalid_host, nullptr, 0); + S32 packet_size = 0; + + if (LLProxy::isSOCKSProxyEnabled()) + { + char buffer[NET_BUFFER_SIZE + SOCKS_HEADER_SIZE]; /* Flawfinder ignore */ + packet_size = receive_packet(mSocket, buffer); + if (packet_size > 0) + { + mActualBytesIn += packet_size; + if (packet_size > SOCKS_HEADER_SIZE) + { + // *FIX We are assuming ATYP is 0x01 (IPv4), not 0x03 (hostname) or 0x04 (IPv6) + proxywrap_t* header = static_cast(static_cast(buffer)); + LLHost sender; + sender.setAddress(header->addr); + sender.setPort(ntohs(header->port)); + packet_size -= SOCKS_HEADER_SIZE; + pkt.init(buffer + SOCKS_HEADER_SIZE, packet_size, sender); + } + else + { + packet_size = 0; + } + } + } + else + { + pkt.init(mSocket); + packet_size = pkt.getSize(); + if (packet_size > 0) + { + mActualBytesIn += packet_size; + } + } + + if (packet_size >= (S32)LL_MINIMUM_VALID_PACKET_SIZE && !computeDrop()) + { + const char* data = pkt.getData(); + LLCircuitData* cdp = mCircuitInfo.findCircuit(pkt.getHost()); + TPACKETID recv_packet_id = ntohl(*((U32*)(&data[1]))); + + // Harvest piggybacked ACKs for outbound messages from the packet tail of this inbound message + if (cdp && (data[0] & LL_ACK_FLAG)) + { + U8 num_acks = (U8)data[packet_size - 1]; + S32 true_rcv_size = packet_size - 1; + if (true_rcv_size >= (S32)(num_acks * sizeof(TPACKETID) + LL_MINIMUM_VALID_PACKET_SIZE)) + { + TPACKETID ack_id; + U32 mem_id = 0; + for (S32 i = 0; i < num_acks; ++i) + { + true_rcv_size -= sizeof(TPACKETID); + memcpy(&mem_id, &data[true_rcv_size], sizeof(TPACKETID)); /* Flawfinder: ignore */ + ack_id = ntohl(mem_id); + cdp->ackReliablePacket(ack_id); + } + if (!cdp->getUnackedPacketCount()) + { + mCircuitInfo.mUnackedCircuitMap.erase(cdp->mHost); + } + } + } + + // ACK inbound reliable packet ASAP + if (cdp && (data[0] & LL_RELIABLE_FLAG)) + { + cdp->collectRAck(recv_packet_id); + } + + if (isHighPriorityMessage(pkt)) + { + mHighPriorityInbound.pushPacket(pkt); + } + else + { + mLowPriorityInbound.pushPacket(pkt); + } + } + + return packet_size; +} + +bool LLMessageSystem::sendPacketToSocket(const char* datap, S32 data_size, LLHost host) +{ + mActualBytesOut += data_size; + if (!LLProxy::isSOCKSProxyEnabled()) + { + return send_packet(mSocket, datap, data_size, host.getAddress(), host.getPort()); + } + + char headered_send_buffer[NET_BUFFER_SIZE + SOCKS_HEADER_SIZE]; + + proxywrap_t* socks_header = static_cast(static_cast(&headered_send_buffer)); + socks_header->rsv = 0; + socks_header->addr = host.getAddress(); + socks_header->port = htons(host.getPort()); + socks_header->atype = ADDRESS_IPV4; + socks_header->frag = 0; + + memcpy(headered_send_buffer + SOCKS_HEADER_SIZE, datap, data_size); + + return send_packet(mSocket, + headered_send_buffer, + data_size + SOCKS_HEADER_SIZE, + LLProxy::getInstance()->getUDPProxy().getAddress(), + LLProxy::getInstance()->getUDPProxy().getPort()); +} + +void LLMessageSystem::dumpPacketRingStats() +{ + mNumDroppedPacketsTotal += mNumDroppedPackets; + LL_INFOS("Messaging") << "buffered_packets=" << getNumBufferedPackets() + << "buffered_bytes=" << (mHighPriorityInbound.getNumBufferedBytes() + mLowPriorityInbound.getNumBufferedBytes()) + << "recently_dropped=" << mNumDroppedPackets + << "total_dropped=" << mNumDroppedPacketsTotal + << "dropped_percentage=" << mDropPercentage << "%" + << "bytes_IN=" << mActualBytesIn + << "bytes_OUT=" << mActualBytesOut << LL_ENDL; + mNumDroppedPackets = 0; } void LLMessageSystem::copyMessageReceivedToSend() @@ -1277,7 +1544,7 @@ S32 LLMessageSystem::sendMessage(const LLHost &host) } bool success; - success = mPacketRing.sendPacket(mSocket, (char *)buf_ptr, buffer_length, host); + success = sendPacketToSocket((char *)buf_ptr, buffer_length, host); if (!success) { @@ -2607,7 +2874,7 @@ void LLMessageSystem::summarizeLogs(std::ostream& str) str << buffer << std::endl << std::endl; buffer = llformat( "SendPacket failures: %20d", mSendPacketFailureCount); str << buffer << std::endl; - buffer = llformat( "Dropped packets: %20d", mDroppedPackets); + buffer = llformat( "Dropped packets: %20d", getTotalNumDroppedPackets()); str << buffer << std::endl; buffer = llformat( "Resent packets: %20d", mResentPackets); str << buffer << std::endl; @@ -3333,7 +3600,7 @@ void LLMessageSystem::establishBidirectionalTrust(const LLHost &host, S64 frame_ void LLMessageSystem::dumpPacketToLog() { - LL_WARNS("Messaging") << "Packet Dump from:" << mPacketRing.getLastSender() << LL_ENDL; + LL_WARNS("Messaging") << "Packet Dump from:" << mLastSender << LL_ENDL; LL_WARNS("Messaging") << "Packet Size:" << mTrueReceiveSize << LL_ENDL; char line_buffer[256]; /* Flawfinder: ignore */ S32 i; diff --git a/indra/llmessage/message.h b/indra/llmessage/message.h index 14cdc48a07..e81cfe16a9 100644 --- a/indra/llmessage/message.h +++ b/indra/llmessage/message.h @@ -119,6 +119,49 @@ public: // Repeat for number of messages in file // +// UDP Packet Buffer Layout +// +// Every UDP message sent or received by LLMessageSystem uses the following +// on-wire layout. Offsets are defined in EPacketHeaderLayout below. +// +// Byte(s) Name Description +// ------- ---- ----------- +// 0 Flags Bit-field (see flag constants below): +// 0x80 LL_ZERO_CODE_FLAG – body is zero-run-length encoded +// 0x40 LL_RELIABLE_FLAG – sender expects a packet ACK +// 0x20 LL_RESENT_FLAG – this is a retransmission +// 0x10 LL_ACK_FLAG – piggybacked ACKs are appended +// at the tail of this packet +// 1-4 Packet ID Sequence number, U32 in network (big-endian) byte order. +// 5 Offset Byte offset from PHL_NAME to the start of the message +// body (past the message-ID bytes). Zero for most messages. +// 6+ Message ID Variable-length message type identifier: +// High-frequency (1 byte, values 0x01–0xFE) +// Medium-frequency (2 bytes, 0xFF hh) +// Low-frequency (4 bytes, 0xFF 0xFF hh ll) +// ... Body Message block data, described by the message template. +// Present only when LL_ZERO_CODE_FLAG is clear; otherwise +// the body (everything after byte 5) is zero-coded (see +// below). The 6-byte header is never zero-coded. +// +// Optional ACK tail (present when LL_ACK_FLAG is set in the flags byte): +// +// ... ACK IDs N packet-sequence IDs being acknowledged, each a U32 in +// network byte order, packed contiguously immediately before +// the ACK count byte. Read in reverse: walk backwards from +// just before the count byte, 4 bytes at a time. +// last ACK Count U8 giving N, the number of appended ACK IDs (max 255). +// This is the very last byte of the UDP payload. +// +// Zero-coding (applied when LL_ZERO_CODE_FLAG is set): +// +// Runs of zero bytes in the body are replaced by a two-byte token: +// 0x00 N – represents (N + 1) zero bytes, for N in 1..254 +// 0x00 0x00 N – represents (256 + N) zero bytes (wrap/overflow case) +// A literal 0x00 byte that starts no run is encoded as 0x00 0x00 0x00. +// The six-byte packet header is excluded from zero-coding and is always +// transmitted as-is. + // Constants const S32 MAX_MESSAGE_INTERNAL_NAME_SIZE = 255; const S32 MAX_BUFFER_SIZE = NET_BUFFER_SIZE; @@ -291,8 +334,11 @@ class LLMessageSystem : public LLMessageSenderInterface bool mBlockUntrustedInterface; LLHost mUntrustedInterface; + protected: + LLPacketRing mHighPriorityInbound; + LLPacketRing mLowPriorityInbound; + public: - LLPacketRing mPacketRing; LLReliablePacketParams mReliablePacketParams; // Set this flag to true when you want *very* verbose logs. @@ -334,7 +380,7 @@ public: U32 mReliablePacketsIn; // total reliable packets in U32 mReliablePacketsOut; // total reliable packets out - U32 mDroppedPackets; // total dropped packets in + U32 mLostPackets; // total reliable outbound packets declared lost U32 mResentPackets; // total resent packets out U32 mFailedResendPackets; // total resend failure packets out U32 mOffCircuitPackets; // total # of off-circuit packets rejected @@ -420,6 +466,25 @@ public: // returns total number of buffered packets after the drain S32 drainUdpSocket(); + // Inbound Packet-loss simulation controls + void dropPackets(U32 num_to_drop); + void setDropPercentage(F32 percent_to_drop); + + // UDP byte-accounting + S32 getActualInBytes() const { return mActualBytesIn; } + S32 getActualOutBytes() const { return mActualBytesOut; } + S32 getAndResetActualInBits() { S32 bits = mActualBytesIn * 8; mActualBytesIn = 0; return bits; } + S32 getAndResetActualOutBits() { S32 bits = mActualBytesOut * 8; mActualBytesOut = 0; return bits; } + + // Get number of "dropped" inbound packets + S32 getTotalNumDroppedPackets() const { return mNumDroppedPacketsTotal + mNumDroppedPackets; } + + S32 getNumBufferedPackets() const { return mHighPriorityInbound.getNumBufferedPackets() + mLowPriorityInbound.getNumBufferedPackets(); } + void dumpPacketRingStats(); + + // Send datap to host via mSocket (with SOCKS proxy support if enabled). + bool sendPacketToSocket(const char* datap, S32 data_size, LLHost host); + bool isMessageFast(const char *msg); bool isMessage(const char *msg) { @@ -754,7 +819,7 @@ public: S32 getReceiveBytes() const; S32 getUnackedListSize() const { return mUnackedListSize; } - F32 getBufferLoadRate() const { return mPacketRing.getBufferLoadRate(); } + F32 getBufferLoadRate() const; //const char* getCurrentSMessageName() const { return mCurrentSMessageName; } //const char* getCurrentSBlockName() const { return mCurrentSBlockName; } @@ -898,6 +963,32 @@ private: S32 mIncomingCompressedSize; // original size of compressed msg (0 if uncomp.) TPACKETID mCurrentRecvPacketID; // packet ID of current receive packet (for reporting) + // Socket I/O helpers + + // Receive one packet: pop from ring if buffered, else read from mSocket. + // Sets mLastSender and mLastReceivingIF. + // Returns packet_size, or 0 if no packet or packet was dropped. + S32 receivePacketOrDrop(char* datap); + + // Read one raw packet from mSocket into inbound message queues + // Returns packet_size (0 if no packet was available). + S32 bufferInboundPacket(); + + // Returns true if the next inbound packet should be intentionally dropped. + bool computeDrop(); + + // Returns true if pkt carries a high-priority message and should be queued + // in mHighPriorityInbound. + bool isHighPriorityMessage(const LLPacketBuffer& pkt) const; + + // Packet-loss simulation and byte-accounting state + S32 mActualBytesIn; + S32 mActualBytesOut; + F32 mDropPercentage; // % of inbound packets to drop + U32 mPacketsToDrop; // drop next N inbound packets + S32 mNumDroppedPackets; // inbound + S32 mNumDroppedPacketsTotal;// inbound + LLMessageBuilder* mMessageBuilder; LLTemplateMessageBuilder* mTemplateMessageBuilder; LLSDMessageBuilder* mLLSDMessageBuilder; diff --git a/indra/llmessage/net.cpp b/indra/llmessage/net.cpp index 2be5a9e5b6..0df38d040a 100644 --- a/indra/llmessage/net.cpp +++ b/indra/llmessage/net.cpp @@ -326,7 +326,7 @@ S32 receive_packet(int hSocket, char * receiveBuffer) return 0; if (WSAECONNRESET == WSAGetLastError()) return 0; - LL_INFOS() << "receivePacket() failed, Error: " << WSAGetLastError() << LL_ENDL; + LL_INFOS() << "receive_packet() failed, Error: " << WSAGetLastError() << LL_ENDL; } return nRet; diff --git a/indra/newview/llappviewer.cpp b/indra/newview/llappviewer.cpp index 79752d2315..7f06f991b0 100644 --- a/indra/newview/llappviewer.cpp +++ b/indra/newview/llappviewer.cpp @@ -5894,7 +5894,6 @@ void LLAppViewer::idleNetwork() pingMainloopTimeout("idleNetwork"); gObjectList.mNumNewObjects = 0; - S32 total_decoded = 0; static LLCachedControl speed_test(gSavedSettings, "SpeedTest", false); if (!speed_test()) @@ -5902,64 +5901,56 @@ void LLAppViewer::idleNetwork() LL_PROFILE_ZONE_NAMED_CATEGORY_NETWORK("idle network"); //LL_RECORD_BLOCK_TIME(FTM_IDLE_NETWORK); // decode LLTimer check_message_timer; - // Read all available packets from network const S64 frame_count = gFrameCount; // U32->S64 - F32 total_time = 0.0f; + S32 total_decoded = 0; + // Process packets from network + LockMessageChecker lmc(gMessageSystem); + while (lmc.checkAllMessages(frame_count, gServicePump)) { - bool needs_drain = false; - LockMessageChecker lmc(gMessageSystem); - while (lmc.checkAllMessages(frame_count, gServicePump)) - { - if (gDoDisconnect) - { - // We're disconnecting, don't process any more messages from the server - // We're usually disconnecting due to either network corruption or a - // server going down, so this is OK. - break; - } - - total_decoded++; + ++total_decoded; - if (total_decoded > MESSAGE_MAX_PER_FRAME) + // Time-box processing of network packets to prevent framerate catastrophe + if (check_message_timer.getElapsedTimeF32() >= CheckMessagesMaxTime) + { + // Drain the socket buffer so we know how many messages remain to process + S32 num_buffered_packets = gMessageSystem->drainUdpSocket(); + if (num_buffered_packets > total_decoded) { - needs_drain = true; - break; + // Grow CheckMessagesMaxTime until we process more packets each frame than arrive. + // This might spiral out of control on very slow computers on fast networks when + // the bandwidth settings are too high. There is a mechanism for providing backpressure + // to network bandwidth but it may be inadequate for the task + // (see LLViewerThrottle::updateDynamicThrottle() for more details). + CheckMessagesMaxTime *= 1.035f; // 3.5% ~= 2x in 20 frames, ~8x in 60 frames } - - // Prevent slow packets from completely destroying the frame rate. - // This usually happens due to clumps of avatars taking huge amount - // of network processing time (which needs to be fixed, but this is - // a good limit anyway). - total_time = check_message_timer.getElapsedTimeF32(); - if (total_time >= CheckMessagesMaxTime) + else if (num_buffered_packets == 0) { - needs_drain = true; - break; + // Reset CheckMessagesMaxTime to default value + CheckMessagesMaxTime = CHECK_MESSAGES_DEFAULT_MAX_TIME; } + break; } - if (needs_drain || gMessageSystem->mPacketRing.getNumBufferedPackets() > 0) + + if (total_decoded > MESSAGE_MAX_PER_FRAME) { - // Rather than allow packets to silently backup on the socket - // we drain them into our own buffer so we know how many exist. - S32 num_buffered_packets = gMessageSystem->drainUdpSocket(); - if (num_buffered_packets > 0) - { - // Increase CheckMessagesMaxTime so that we will eventually catch up - CheckMessagesMaxTime *= 1.035f; // 3.5% ~= 2x in 20 frames, ~8x in 60 frames - } + // MESSAGE_MAX_PER_FRAME is very high (400) + // We expect to run out of time before reaching here, but just in case... + gMessageSystem->drainUdpSocket(); + break; } - else + + if (gDoDisconnect) { - // Reset CheckMessagesMaxTime to default value - CheckMessagesMaxTime = CHECK_MESSAGES_DEFAULT_MAX_TIME; + // We're disconnecting so no need to process packets. + break; } + } - // Handle per-frame message system processing. + // Handle per-frame message system processing. - static LLCachedControl ack_collection_time(gSavedSettings, "AckCollectTime", 0.1f); - lmc.processAcks(ack_collection_time()); - } + static LLCachedControl ack_collection_time(gSavedSettings, "AckCollectTime", 0.1f); + lmc.processAcks(ack_collection_time()); } add(LLStatViewer::NUM_NEW_OBJECTS, gObjectList.mNumNewObjects); diff --git a/indra/newview/llstartup.cpp b/indra/newview/llstartup.cpp index 6a85ca069a..cd4c9d40b1 100644 --- a/indra/newview/llstartup.cpp +++ b/indra/newview/llstartup.cpp @@ -401,7 +401,7 @@ void do_startup_frame() break; } } - if (needs_drain || gMessageSystem->mPacketRing.getNumBufferedPackets() > 0) + if (needs_drain || gMessageSystem->getNumBufferedPackets() > 0) { gMessageSystem->drainUdpSocket(); } @@ -785,7 +785,7 @@ bool idle_startup() F32 dropPercent = gSavedSettings.getF32("PacketDropPercentage"); - msg->mPacketRing.setDropPercentage(dropPercent); + msg->setDropPercentage(dropPercent); } LL_INFOS("AppInit") << "Message System Initialized." << LL_ENDL; diff --git a/indra/newview/llviewermenu.cpp b/indra/newview/llviewermenu.cpp index ff111dd1bc..7f36244685 100644 --- a/indra/newview/llviewermenu.cpp +++ b/indra/newview/llviewermenu.cpp @@ -2298,7 +2298,7 @@ class LLAdvancedDropPacket : public view_listener_t { bool handleEvent(const LLSD& userdata) { - gMessageSystem->mPacketRing.dropPackets(1); + gMessageSystem->dropPackets(1); return true; } }; diff --git a/indra/newview/llviewerstats.cpp b/indra/newview/llviewerstats.cpp index 6490fe76a2..3b2796572b 100644 --- a/indra/newview/llviewerstats.cpp +++ b/indra/newview/llviewerstats.cpp @@ -791,7 +791,7 @@ void send_viewer_stats(bool include_preferences) LLSD &fail = body["stats"]["failures"]; fail["send_packet"] = (S32) gMessageSystem->mSendPacketFailureCount; - fail["dropped"] = (S32) gMessageSystem->mDroppedPackets; + fail["dropped"] = (S32) gMessageSystem->getTotalNumDroppedPackets(); fail["resent"] = (S32) gMessageSystem->mResentPackets; fail["failed_resends"] = (S32) gMessageSystem->mFailedResendPackets; fail["off_circuit"] = (S32) gMessageSystem->mOffCircuitPackets; diff --git a/indra/newview/llviewerthrottle.cpp b/indra/newview/llviewerthrottle.cpp index 3ccfbea6e2..90a60c7a94 100644 --- a/indra/newview/llviewerthrottle.cpp +++ b/indra/newview/llviewerthrottle.cpp @@ -45,8 +45,8 @@ using namespace LLOldEvents; const F32 MAX_FRACTIONAL = 1.5f; const F32 MIN_FRACTIONAL = 0.2f; -const F32 MIN_BANDWIDTH = 50.f; -const F32 MAX_BANDWIDTH = 6000.f; +const F32 MIN_BANDWIDTH = 50.f; // Kbps +const F32 MAX_BANDWIDTH = 6000.f; // Kbps const F32 STEP_FRACTIONAL = 0.1f; const F32 HIGH_BUFFER_LOAD_TRESHOLD = 1.f; const F32 LOW_BUFFER_LOAD_TRESHOLD = 0.8f; @@ -244,6 +244,8 @@ void LLViewerThrottle::sendToSim() const F32 LLViewerThrottle::getMaxBandwidthKbps() { + // Why are thse different than the constants with the same names higher up? + // Anybody know? -- Leviathan constexpr F32 MIN_BANDWIDTH = 100.0f; // 100 Kbps constexpr F32 MAX_BANDWIDTH = 10000.0f; // 10 Mbps @@ -309,6 +311,21 @@ void LLViewerThrottle::resetDynamicThrottle() void LLViewerThrottle::updateDynamicThrottle() { + // User configurable bandwidth settings are merely vague aspirations. Translating those + // to what should be sent to the servers is complicated. Servers will tend to spike data + // transmission upon arrival, packets will arrive faster than we can process them, and this + // can overflow the buffer, which causes packet loss. + // + // In an attempt to avoid catastrophe we periodically measure buffer load and packet loss + // and then transmit a modified desired bandwidth to the server. Unfortunately, this system + // does not work well for spikey data bursts because: + // (1) the response takes too long (up to 5 seconds) to kick in + // (2) once it starts it tends to ramp up too slowly + // (3) it doesn't know which region is providing the flood; it just assumes it is + // all from the main region + // + // TODO: fix those ^^^ problems + if (mUpdateTimer.getElapsedTimeF32() < DYNAMIC_UPDATE_DURATION) { return; @@ -347,5 +364,7 @@ void LLViewerThrottle::updateDynamicThrottle() LL_INFOS() << "Easing network throttle to " << mCurrentBandwidth << LL_ENDL; } + // Now that we've used mBufferLoadRate we reset it to zero because otherwise it only + // increases (see clamping behavior in setBufferLoadRate()). mBufferLoadRate = 0; } diff --git a/indra/newview/llviewerthrottle.h b/indra/newview/llviewerthrottle.h index ef898a97d7..7ff0a7d1f0 100644 --- a/indra/newview/llviewerthrottle.h +++ b/indra/newview/llviewerthrottle.h @@ -77,8 +77,8 @@ public: static const std::string sNames[TC_EOF]; protected: - F32 mMaxBandwidth; - F32 mCurrentBandwidth; + F32 mMaxBandwidth; // bps + F32 mCurrentBandwidth; // bps F32 mBufferLoadRate = 0; LLViewerThrottleGroup mCurrent; diff --git a/indra/newview/llworld.cpp b/indra/newview/llworld.cpp index d02694de7d..cad36828d1 100644 --- a/indra/newview/llworld.cpp +++ b/indra/newview/llworld.cpp @@ -794,10 +794,10 @@ void LLWorld::updateNetStats() S32 packets_in = gMessageSystem->mPacketsIn - mLastPacketsIn; S32 packets_out = gMessageSystem->mPacketsOut - mLastPacketsOut; - S32 packets_lost = gMessageSystem->mDroppedPackets - mLastPacketsLost; + S32 packets_lost = gMessageSystem->mLostPackets - mLastPacketsLost; - F64Bits actual_in_bits(gMessageSystem->mPacketRing.getAndResetActualInBits()); - F64Bits actual_out_bits(gMessageSystem->mPacketRing.getAndResetActualOutBits()); + F64Bits actual_in_bits(gMessageSystem->getAndResetActualInBits()); + F64Bits actual_out_bits(gMessageSystem->getAndResetActualOutBits()); add(LLStatViewer::MESSAGE_SYSTEM_DATA_IN, actual_in_bits); add(LLStatViewer::MESSAGE_SYSTEM_DATA_OUT, actual_out_bits); @@ -815,7 +815,7 @@ void LLWorld::updateNetStats() mLastPacketsIn = gMessageSystem->mPacketsIn; mLastPacketsOut = gMessageSystem->mPacketsOut; - mLastPacketsLost = gMessageSystem->mDroppedPackets; + mLastPacketsLost = gMessageSystem->mLostPackets; } @@ -838,7 +838,7 @@ void LLWorld::printPacketsLost() << " packets lost: " << cdp->getPacketsLost() << LL_ENDL; } } - LL_INFOS() << "Packets dropped by Packet Ring: " << gMessageSystem->mPacketRing.getNumDroppedPackets() << LL_ENDL; + LL_INFOS() << "Packets dropped by Packet Ring: " << gMessageSystem->getTotalNumDroppedPackets() << LL_ENDL; } void LLWorld::processCoarseUpdate(LLMessageSystem* msg, void** user_data) -- cgit v1.3 From bcabe07958c3f7dde2aa30962126c9ba9d7b95bd Mon Sep 17 00:00:00 2001 From: Andrey Kleshchev <117672381+akleshchev@users.noreply.github.com> Date: Fri, 19 Jun 2026 22:32:20 +0300 Subject: #5837 Fix mature group search showing zero results --- indra/llmessage/llqueryflags.h | 4 ++-- indra/newview/llpaneldirgroups.cpp | 17 ++++++++++++++--- 2 files changed, 16 insertions(+), 5 deletions(-) (limited to 'indra/llmessage') diff --git a/indra/llmessage/llqueryflags.h b/indra/llmessage/llqueryflags.h index 227d28ba5c..8dfb74aab0 100644 --- a/indra/llmessage/llqueryflags.h +++ b/indra/llmessage/llqueryflags.h @@ -56,8 +56,8 @@ const U32 DFQ_NAME_SORT = 0x1 << 19; const U32 DFQ_LIMIT_BY_PRICE = 0x1 << 20; const U32 DFQ_LIMIT_BY_AREA = 0x1 << 21; -const U32 DFQ_FILTER_MATURE = 0x1 << 22; -const U32 DFQ_PG_PARCELS_ONLY = 0x1 << 23; +const U32 DFQ_FILTER_MATURE = 0x1 << 22; // legacy, will not work with any from DFQ_INC_NEW_VIEWER +const U32 DFQ_PG_PARCELS_ONLY = 0x1 << 23; // legacy, will not work with any from DFQ_INC_NEW_VIEWER const U32 DFQ_INC_PG = 0x1 << 24; // Flags appear in 1.23 viewer or later const U32 DFQ_INC_MATURE = 0x1 << 25; diff --git a/indra/newview/llpaneldirgroups.cpp b/indra/newview/llpaneldirgroups.cpp index 992d92091c..3ab02eb16e 100644 --- a/indra/newview/llpaneldirgroups.cpp +++ b/indra/newview/llpaneldirgroups.cpp @@ -51,6 +51,12 @@ bool LLPanelDirGroups::postBuild() childSetAction("Search", &LLPanelDirBrowser::onClickSearchCore, this); setDefaultBtn( "Search" ); + if (gAgent.isTeen()) + { + childSetEnabled("incmature", false); + gSavedSettings.setBOOL("ShowMatureGroups", false); + } + return true; } @@ -70,13 +76,18 @@ void LLPanelDirGroups::performQuery() // groups U32 scope = DFQ_GROUPS; + // if nothing is set will search for <= mature + // if DFQ_INC_PG is set, will look for <= PG + // if DFQ_INC_MATURE is set, will look for == mature + // if DFQ_INC_ADULT is set, will look for >= adult + scope |= DFQ_INC_PG; // Check group mature filter. - if ( !gSavedSettings.getBOOL("ShowMatureGroups") || gAgent.isTeen() ) + if ( gSavedSettings.getBOOL("ShowMatureGroups") && !gAgent.isTeen() ) { - scope |= DFQ_FILTER_MATURE; + scope |= DFQ_INC_MATURE; + scope |= DFQ_INC_ADULT; } - mCurrentSortColumn = "score"; mCurrentSortAscending = false; -- cgit v1.3 From 5986568a23836f9ce448a1912406eaedd3794175 Mon Sep 17 00:00:00 2001 From: Andrey Kleshchev <117672381+akleshchev@users.noreply.github.com> Date: Mon, 20 Jul 2026 19:21:50 +0300 Subject: #6014 More tracy coverage --- indra/llappearance/llpolymesh.cpp | 1 + indra/llcommon/llcoros.cpp | 1 + indra/llcommon/llwatchdog.cpp | 1 + indra/llfilesystem/lllfsthread.cpp | 1 + indra/llmessage/message.cpp | 1 + indra/llphysicsextensionsos/llphysicsextensions.cpp | 1 + indra/llplugin/llpluginclassmedia.cpp | 1 + indra/llxml/llcontrol.cpp | 2 ++ 8 files changed, 9 insertions(+) (limited to 'indra/llmessage') diff --git a/indra/llappearance/llpolymesh.cpp b/indra/llappearance/llpolymesh.cpp index d5323e0b84..1162efb868 100644 --- a/indra/llappearance/llpolymesh.cpp +++ b/indra/llappearance/llpolymesh.cpp @@ -862,6 +862,7 @@ LLPolyMesh *LLPolyMesh::getMesh(const std::string &name, LLPolyMesh* reference_m //----------------------------------------------------------------------------- void LLPolyMesh::freeAllMeshes() { + LL_PROFILE_ZONE_SCOPED; // delete each item in the global lists for_each(sGlobalSharedMeshList.begin(), sGlobalSharedMeshList.end(), DeletePairedPointer()); sGlobalSharedMeshList.clear(); diff --git a/indra/llcommon/llcoros.cpp b/indra/llcommon/llcoros.cpp index 9e95d9c85f..ae7c50e9a3 100644 --- a/indra/llcommon/llcoros.cpp +++ b/indra/llcommon/llcoros.cpp @@ -252,6 +252,7 @@ void LLCoros::setStackSize(S32 stacksize) void LLCoros::printActiveCoroutines(const std::string& when) { + LL_PROFILE_ZONE_SCOPED; LL_INFOS("LLCoros") << "Number of active coroutines " << when << ": " << CoroData::instanceCount() << LL_ENDL; if (CoroData::instanceCount() > 0) diff --git a/indra/llcommon/llwatchdog.cpp b/indra/llcommon/llwatchdog.cpp index 056a0cc940..b17b68dbe7 100644 --- a/indra/llcommon/llwatchdog.cpp +++ b/indra/llcommon/llwatchdog.cpp @@ -236,6 +236,7 @@ void LLWatchdog::shutdown() void LLWatchdog::cleanup() { + LL_PROFILE_ZONE_SCOPED; if (mTimer) { mTimer->stop(); diff --git a/indra/llfilesystem/lllfsthread.cpp b/indra/llfilesystem/lllfsthread.cpp index 6a882f64a8..69f7085290 100644 --- a/indra/llfilesystem/lllfsthread.cpp +++ b/indra/llfilesystem/lllfsthread.cpp @@ -51,6 +51,7 @@ S32 LLLFSThread::updateClass(U32 ms_elapsed) //static void LLLFSThread::cleanupClass() { + LL_PROFILE_ZONE_SCOPED; llassert(sLocal != NULL); sLocal->setQuitting(); while (sLocal->getPending()) diff --git a/indra/llmessage/message.cpp b/indra/llmessage/message.cpp index b11e4598e7..52180b20f1 100644 --- a/indra/llmessage/message.cpp +++ b/indra/llmessage/message.cpp @@ -2906,6 +2906,7 @@ void LLMessageSystem::summarizeLogs(std::ostream& str) void end_messaging_system(bool print_summary) { + LL_PROFILE_ZONE_SCOPED; gTransferManager.cleanup(); LLTransferTargetVFile::updateQueue(true); // shutdown LLTransferTargetVFile if (gMessageSystem) diff --git a/indra/llphysicsextensionsos/llphysicsextensions.cpp b/indra/llphysicsextensionsos/llphysicsextensions.cpp index 3bb8ffbf1a..295ab41a17 100644 --- a/indra/llphysicsextensionsos/llphysicsextensions.cpp +++ b/indra/llphysicsextensionsos/llphysicsextensions.cpp @@ -72,6 +72,7 @@ //============================================================================= /*static */bool LLPhysicsExtensions::quitSystem() { + LL_PROFILE_ZONE_SCOPED; return LLPhysicsExtensionsImpl::quitSystem(); } //============================================================================= diff --git a/indra/llplugin/llpluginclassmedia.cpp b/indra/llplugin/llpluginclassmedia.cpp index 94c29d9457..9a1f408b34 100644 --- a/indra/llplugin/llpluginclassmedia.cpp +++ b/indra/llplugin/llpluginclassmedia.cpp @@ -92,6 +92,7 @@ bool LLPluginClassMedia::init(const std::string &launcher_filename, const std::s void LLPluginClassMedia::reset() { + LL_PROFILE_ZONE_SCOPED; if(mPlugin) { mPlugin->requestShutdown(); diff --git a/indra/llxml/llcontrol.cpp b/indra/llxml/llcontrol.cpp index 5a37167f18..be53a93a2d 100644 --- a/indra/llxml/llcontrol.cpp +++ b/indra/llxml/llcontrol.cpp @@ -407,6 +407,7 @@ static bool compareRoutine(settings_pair_t lhs, settings_pair_t rhs) void LLControlGroup::cleanup() { + LL_PROFILE_ZONE_SCOPED; if(mSettingsProfile && getCount.size() != 0) { std::string file = gDirUtilp->getExpandedFilename(LL_PATH_LOGS, SETTINGS_PROFILE); @@ -982,6 +983,7 @@ U32 LLControlGroup::loadFromFileLegacy(const std::string& filename, bool require U32 LLControlGroup::saveToFile(const std::string& filename, bool nondefault_only) { + LL_PROFILE_ZONE_SCOPED; LLSD settings; int num_saved = 0; for (ctrl_name_table_t::iterator iter = mNameTable.begin(); -- cgit v1.3 From b906284977b120c4c554fd08b78fac62759b160a Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Wed, 22 Jul 2026 09:01:47 -0700 Subject: Defer processing AvatarAppearance until after first ObjectUpdate (#6017) * make AvatarAppearance a low-priority message * remember agent_id of unexpected AvatarAppearance message for later --- indra/llmessage/llpacketbuffer.h | 7 ++++ indra/llmessage/message.cpp | 80 +++++++++++++++++++++++++++++++-------- indra/llmessage/message.h | 6 ++- indra/llprimitive/llprimitive.cpp | 8 +++- indra/llprimitive/llprimitive.h | 3 ++ indra/newview/llagent.cpp | 1 + indra/newview/llviewermessage.cpp | 9 +++-- indra/newview/llvoavatar.cpp | 18 ++++++++- indra/newview/llvoavatar.h | 21 +++++++++- 9 files changed, 128 insertions(+), 25 deletions(-) (limited to 'indra/llmessage') diff --git a/indra/llmessage/llpacketbuffer.h b/indra/llmessage/llpacketbuffer.h index b0505e7afd..a08e6c22e5 100644 --- a/indra/llmessage/llpacketbuffer.h +++ b/indra/llmessage/llpacketbuffer.h @@ -49,11 +49,18 @@ public: void init(S32 hSocket); void init(const char* buffer, S32 data_size, const LLHost& host); + // Whether LLCircuitData::checkPacketInID() has already been run for this + // packet (done at socket-read time, before this packet was sorted into + // the high/low priority inbound queue). + bool getPacketIDChecked() const { return mPacketIDChecked; } + void setPacketIDChecked(bool checked) { mPacketIDChecked = checked; } + protected: char mData[NET_BUFFER_SIZE]; // packet data /* Flawfinder : ignore */ S32 mSize; // size of buffer in bytes LLHost mHost; // source/dest IP and port LLHost mReceivingIF; // source/dest IP and port + bool mPacketIDChecked = false; }; #endif diff --git a/indra/llmessage/message.cpp b/indra/llmessage/message.cpp index 52180b20f1..8d86856706 100644 --- a/indra/llmessage/message.cpp +++ b/indra/llmessage/message.cpp @@ -519,10 +519,11 @@ bool LLMessageSystem::checkMessages(LockMessageChecker&, S64 frame_count ) bool recv_resent = false; S32 num_acks = 0; S32 true_rcv_size = 0; + bool recv_packet_id_checked = false; U8* buffer = mTrueReceiveBuffer; - mTrueReceiveSize = receivePacketOrDrop((char *)mTrueReceiveBuffer); + mTrueReceiveSize = receivePacketOrDrop((char *)mTrueReceiveBuffer, recv_packet_id_checked); // If you want to dump all received packets into SecondLife.log, uncomment this //dumpPacketToLog(); @@ -686,7 +687,7 @@ bool LLMessageSystem::checkMessages(LockMessageChecker&, S64 frame_count ) if ( valid_packet ) { - logValidMsg(cdp, host, recv_reliable, recv_resent, num_acks>0 ); + logValidMsg(cdp, host, recv_reliable, recv_resent, num_acks>0, recv_packet_id_checked ); valid_packet = mTemplateMessageReader->readMessage(buffer, host); } @@ -866,19 +867,37 @@ bool LLMessageSystem::computeDrop() bool LLMessageSystem::isHighPriorityMessage(const LLPacketBuffer& pkt) const { S32 size = pkt.getSize(); - if (size < LL_PACKET_ID_SIZE + 1) + + // avoid stepping out of bounds + const S32 MIN_VALID_PACKET_SIZE = LL_PACKET_ID_SIZE + 4; + if (size < MIN_VALID_PACKET_SIZE) { return false; } - // We want to prioritize crucial messages use to establish viewer <--> simulator connection, + // We want to prioritize crucial messages used to establish viewer <--> simulator connection, // which are all low-frequency. A simple approximation is to just prioritize all non high- // frequency messages. // - // High frequency messages use a single byte for message_id whereas all low- and medium- - // frequency messages have 255 at the first byte of the message_id (which is after the - // LL_PACKET_ID_SIZE bytes of packet_id). - return *((const U8*)pkt.getData() + LL_PACKET_ID_SIZE) == 255; + // High frequency messages use a single byte for message_id whereas medium- and low- + // frequency messages have 255 at the first byte (which is after the LL_PACKET_ID_SIZE + // bytes of packet_id). + const U8* header = (const U8*)pkt.getData() + LL_PACKET_ID_SIZE; + if (header[0] != 255) + { + // high-frequency message + return false; + } + + // BUG: The low-frequency AvatarAppearance message will be ignored if its agent is unknown + // and the agent is created upon receipt of its first high-frequency ObjectUpdate message. + // This race condition will be exacerbated by our default prioritization strategy. + // + // WORKAROUND: All middle- and low-frequency messages are high-priority except AvatarAppearance + // + // AvatarAppearance is "Low 158" which means it is stored in four bytes: 0xff 0xff 0x00 0x9E + // the last two bytes represent 158 in a BigEndian U16 + return header[1] != 255 && header[2] != 0 && header[3] != 158; } void LLMessageSystem::dropPackets(U32 num_to_drop) @@ -891,8 +910,10 @@ void LLMessageSystem::setDropPercentage(F32 percent_to_drop) mDropPercentage = percent_to_drop; } -S32 LLMessageSystem::receivePacketOrDrop(char* datap) +S32 LLMessageSystem::receivePacketOrDrop(char* datap, bool& packet_id_already_checked) { + packet_id_already_checked = false; + if (getNumBufferedPackets() > 0) { LLHost invalid_host; @@ -905,6 +926,7 @@ S32 LLMessageSystem::receivePacketOrDrop(char* datap) S32 packet_size = pkt.getSize(); mLastSender = pkt.getHost(); mLastReceivingIF = pkt.getReceivingInterface(); + packet_id_already_checked = pkt.getPacketIDChecked(); if (packet_size > 0) { @@ -913,7 +935,8 @@ S32 LLMessageSystem::receivePacketOrDrop(char* datap) return packet_size; } - // Read directly from the socket. + // Read directly from the socket. checkPacketInID() has not run yet for + // this packet. bool drop = computeDrop(); S32 packet_size = 0; if (LLProxy::isSOCKSProxyEnabled()) @@ -1034,10 +1057,24 @@ S32 LLMessageSystem::bufferInboundPacket() } } - // ACK inbound reliable packet ASAP - if (cdp && (data[0] & LL_RELIABLE_FLAG)) + if (cdp) { - cdp->collectRAck(recv_packet_id); + // ACK inbound reliable packet ASAP + if ((data[0] & LL_RELIABLE_FLAG)) + { + cdp->collectRAck(recv_packet_id); + } + + // Check packet sequencing here, in true socket-arrival order, before + // this packet is sorted into the high/low priority inbound queue. + // Skip genuine duplicate resends, same as checkMessages()/logValidMsg() + // would do further downstream. + bool recv_resent = (data[0] & LL_RESENT_FLAG) != 0; + if (!recv_resent || !cdp->isDuplicateResend(recv_packet_id)) + { + cdp->checkPacketInID(recv_packet_id, recv_resent); + pkt.setPacketIDChecked(true); + } } if (isHighPriorityMessage(pkt)) @@ -1668,7 +1705,13 @@ void LLMessageSystem::logTrustedMsgFromUntrustedCircuit( const LLHost& host ) } } -void LLMessageSystem::logValidMsg(LLCircuitData *cdp, const LLHost& host, bool recv_reliable, bool recv_resent, bool recv_acks ) +void LLMessageSystem::logValidMsg( + LLCircuitData *cdp, + const LLHost& host, + bool recv_reliable, + bool recv_resent, + bool recv_acks, + bool skip_packet_id_check ) { if (mNumMessageCounts >= MAX_MESSAGE_COUNT_NUM) { @@ -1685,8 +1728,13 @@ void LLMessageSystem::logValidMsg(LLCircuitData *cdp, const LLHost& host, bool r if (cdp) { - // update circuit packet ID tracking (missing/out of order packets) - cdp->checkPacketInID( mCurrentRecvPacketID, recv_resent ); + if (!skip_packet_id_check) + { + // update circuit packet ID tracking (missing/out of order packets) + // Already done in bufferInboundPacket(), in true socket-arrival + // order, if this packet came off the high/low priority queues. + cdp->checkPacketInID( mCurrentRecvPacketID, recv_resent ); + } cdp->addBytesIn( (S32Bytes)mTrueReceiveSize ); } diff --git a/indra/llmessage/message.h b/indra/llmessage/message.h index e81cfe16a9..e23a67c04a 100644 --- a/indra/llmessage/message.h +++ b/indra/llmessage/message.h @@ -910,7 +910,7 @@ private: void logMsgFromInvalidCircuit( const LLHost& sender, bool recv_reliable ); void logTrustedMsgFromUntrustedCircuit( const LLHost& sender ); - void logValidMsg(LLCircuitData *cdp, const LLHost& sender, bool recv_reliable, bool recv_resent, bool recv_acks ); + void logValidMsg(LLCircuitData *cdp, const LLHost& sender, bool recv_reliable, bool recv_resent, bool recv_acks, bool skip_packet_id_check ); class LLMessageCountInfo { @@ -967,8 +967,10 @@ private: // Receive one packet: pop from ring if buffered, else read from mSocket. // Sets mLastSender and mLastReceivingIF. + // Sets packet_id_already_checked to whether checkPacketInID() was already + // run for this packet back when it was buffered (see bufferInboundPacket()). // Returns packet_size, or 0 if no packet or packet was dropped. - S32 receivePacketOrDrop(char* datap); + S32 receivePacketOrDrop(char* datap, bool& packet_id_already_checked); // Read one raw packet from mSocket into inbound message queues // Returns packet_size (0 if no packet was available). diff --git a/indra/llprimitive/llprimitive.cpp b/indra/llprimitive/llprimitive.cpp index 7a638dd625..fd755e35dd 100644 --- a/indra/llprimitive/llprimitive.cpp +++ b/indra/llprimitive/llprimitive.cpp @@ -1369,6 +1369,12 @@ bool LLPrimitive::packTEMessage(LLDataPacker &dp) const } S32 LLPrimitive::parseTEMessage(LLMessageSystem* mesgsys, char const* block_name, const S32 block_num, LLTEContents& tec) +{ + return parseTEMessage(mesgsys, block_name, block_num, tec, getNumTEs()); +} + +// static +S32 LLPrimitive::parseTEMessage(LLMessageSystem* mesgsys, char const* block_name, const S32 block_num, LLTEContents& tec, U8 face_count) { S32 retval = 0; // temp buffer for material ID processing @@ -1403,7 +1409,7 @@ S32 LLPrimitive::parseTEMessage(LLMessageSystem* mesgsys, char const* block_name tec.packed_buffer[tec.size] = 0x00; ++tec.size; - tec.face_count = llmin((U32)getNumTEs(),(U32)LLTEContents::MAX_TES); + tec.face_count = llmin((U32)face_count,(U32)LLTEContents::MAX_TES); U8 *cur_ptr = tec.packed_buffer; LL_DEBUGS("TEXTUREENTRY") << "Texture Entry with buffere sized: " << tec.size << LL_ENDL; diff --git a/indra/llprimitive/llprimitive.h b/indra/llprimitive/llprimitive.h index c3e3e19ee9..21bf52610e 100644 --- a/indra/llprimitive/llprimitive.h +++ b/indra/llprimitive/llprimitive.h @@ -502,6 +502,9 @@ public: S32 unpackTEMessage(LLMessageSystem* mesgsys, char const* block_name, const S32 block_num); // Variable num of blocks S32 unpackTEMessage(LLDataPacker &dp); S32 parseTEMessage(LLMessageSystem* mesgsys, char const* block_name, const S32 block_num, LLTEContents& tec); + // Same as above, but usable before an instance exists to derive the face count from + // (e.g. decoding a message for an object that hasn't been created yet). + static S32 parseTEMessage(LLMessageSystem* mesgsys, char const* block_name, const S32 block_num, LLTEContents& tec, U8 face_count); S32 applyParsedTEMessage(LLTEContents& tec); #ifdef CHECK_FOR_FINITE diff --git a/indra/newview/llagent.cpp b/indra/newview/llagent.cpp index 35d60e6595..2f0ad15d18 100644 --- a/indra/newview/llagent.cpp +++ b/indra/newview/llagent.cpp @@ -4151,6 +4151,7 @@ void LLAgent::handleTeleportFinished() } clearTeleportRequest(); mTeleportCanceled.reset(); + LLVOAvatar::resetEarlyAppearanceList(); if (mIsMaturityRatingChangingDuringTeleport) { // notify user that the maturity preference has been changed diff --git a/indra/newview/llviewermessage.cpp b/indra/newview/llviewermessage.cpp index 1f1ff30b8f..e435ce08e3 100644 --- a/indra/newview/llviewermessage.cpp +++ b/indra/newview/llviewermessage.cpp @@ -4181,11 +4181,12 @@ void process_avatar_appearance(LLMessageSystem *mesgsys, void **user_data) if (avatarp) { avatarp->processAvatarAppearance( mesgsys ); + return; } - else - { - LL_WARNS("Messaging") << "avatar_appearance sent for unknown avatar " << uuid << LL_ENDL; - } + // The avatar object doesn't exist yet. + // We will re-request its appearance data after it is created. + LLVOAvatar::registerEarlyAppearance(uuid); + LL_WARNS("Messaging") << "AvatarAppearance received for avatar " << uuid << " before object created" << LL_ENDL; } void process_camera_constraint(LLMessageSystem *mesgsys, void **user_data) diff --git a/indra/newview/llvoavatar.cpp b/indra/newview/llvoavatar.cpp index cd71a2c660..89ee5ede2a 100644 --- a/indra/newview/llvoavatar.cpp +++ b/indra/newview/llvoavatar.cpp @@ -615,6 +615,8 @@ const LLUUID LLVOAvatar::sStepSounds[LL_MCODE_END] = SND_RUBBER_RUBBER }; +uuid_list_t LLVOAvatar::sEarlyAppearanceList; + S32 LLVOAvatar::sRenderName = RENDER_NAME_ALWAYS; S32 LLVOAvatar::sRenderGroupTitles = RENDER_GROUP_TITLE_ALWAYS; S32 LLVOAvatar::sNumVisibleChatBubbles = 0; @@ -779,6 +781,20 @@ LLVOAvatar::LLVOAvatar(const LLUUID& id, mVisuallyMuteSetting = LLVOAvatar::VisualMuteSettings(LLRenderMuteList::getInstance()->getSavedVisualMuteSetting(getID())); sInstances.push_back(this); + + uuid_list_t::iterator it = sEarlyAppearanceList.find(id); + if (it != sEarlyAppearanceList.end()) + { + // Note: aside from LLVOAvatar::resetEarlyAppearanceList() (called on + // teleport), this is the only place where we remove from + // sEarlyAppearanceList, which means any agent who receives an + // AvatarAppearance message but is never actually instantiated will + // remain on the list until the next teleport. This is a resource leak + // but we expect it to be small enough per-session to not cause problems. + sEarlyAppearanceList.erase(it); + LL_INFOS("Avatar") << "Re-requesting AvatarAppearance for new avatar " << id << LL_ENDL; + LLAvatarPropertiesProcessor::getInstance()->sendAvatarTexturesRequest(getID()); + } } std::string LLVOAvatar::avString() const @@ -9937,7 +9953,7 @@ void LLVOAvatar::applyParsedAppearanceMessage(LLAppearanceMessageContents& conte if (visualParamWeightsAreDefault() && mRuthTimer.getElapsedTimeF32() > LOADING_TIMEOUT_SECONDS) { // re-request appearance, hoping that it comes back with a shape next time - LL_INFOS() << "Re-requesting AvatarAppearance for object: " << getID() << LL_ENDL; + LL_INFOS() << "Re-requesting AvatarAppearance for agent: " << getID() << LL_ENDL; LLAvatarPropertiesProcessor::getInstance()->sendAvatarTexturesRequest(getID()); mRuthTimer.reset(); } diff --git a/indra/newview/llvoavatar.h b/indra/newview/llvoavatar.h index 3f33dc54b8..3457e7bb6a 100644 --- a/indra/newview/llvoavatar.h +++ b/indra/newview/llvoavatar.h @@ -949,9 +949,26 @@ protected: ** APPEARANCE **/ +public: + // Used when an AvatarAppearance UDP message is received before the + // corresponding avatar could be created. + static void registerEarlyAppearance(const LLUUID& av_id) + { + sEarlyAppearanceList.emplace(av_id); + } + + // Entries left behind by agents who never get instantiated (e.g. an + // AvatarAppearance message arrives for an avatar we never rez) are a + // small resource leak. Teleporting to another region invalidates the + // whole list, since it was only ever relevant to avatars in the region + // we're leaving, so clear it out at that point to bound the leak. + static void resetEarlyAppearanceList() + { + sEarlyAppearanceList.clear(); + } + LLPointer mLastProcessedAppearance; -public: void parseAppearanceMessage(LLMessageSystem* mesgsys, LLAppearanceMessageContents& msg); void processAvatarAppearance(LLMessageSystem* mesgsys); void applyParsedAppearanceMessage(LLAppearanceMessageContents& contents, bool slam_params); @@ -983,6 +1000,8 @@ private: bool mIsEditingAppearance; // flag for if we're actively in appearance editing mode bool mUseLocalAppearance; // flag for if we're using a local composite + static uuid_list_t sEarlyAppearanceList; + //-------------------------------------------------------------------- // Visibility //-------------------------------------------------------------------- -- cgit v1.3 From 63eb2da05a6211ce4e038f1bf1aef5dda3c6ac77 Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Wed, 19 Aug 2026 08:57:03 -0700 Subject: move zerocode logic to util, add unit-tests (#6152) --- indra/llmessage/CMakeLists.txt | 2 + indra/llmessage/lltemplatemessagebuilder.cpp | 93 ++-------- indra/llmessage/llzerocode.h | 211 ++++++++++++++++++++++ indra/llmessage/message.cpp | 152 +--------------- indra/llmessage/message.h | 1 - indra/llmessage/tests/llzerocode_test.cpp | 253 +++++++++++++++++++++++++++ 6 files changed, 490 insertions(+), 222 deletions(-) create mode 100644 indra/llmessage/llzerocode.h create mode 100644 indra/llmessage/tests/llzerocode_test.cpp (limited to 'indra/llmessage') diff --git a/indra/llmessage/CMakeLists.txt b/indra/llmessage/CMakeLists.txt index f143ee18cf..2306c377ba 100644 --- a/indra/llmessage/CMakeLists.txt +++ b/indra/llmessage/CMakeLists.txt @@ -165,6 +165,7 @@ set(llmessage_HEADER_FILES llxfer_mem.h llxfer_vfile.h llxorcipher.h + llzerocode.h machine.h mean_collision_data.h message.h @@ -228,6 +229,7 @@ if (LL_TESTS) LL_ADD_INTEGRATION_TEST(llservicebuilder "" "${test_libs}") LL_ADD_INTEGRATION_TEST(lltemplatemessagebuilder "" "${test_libs}") LL_ADD_INTEGRATION_TEST(llxfer_file "" "${test_libs}") + LL_ADD_INTEGRATION_TEST(llzerocode "" "${test_libs}") LL_ADD_INTEGRATION_TEST(llxorcipher "" "${test_libs}") LL_ADD_INTEGRATION_TEST(message "" "${test_libs}") endif (LL_TESTS) diff --git a/indra/llmessage/lltemplatemessagebuilder.cpp b/indra/llmessage/lltemplatemessagebuilder.cpp index 758d6d343f..c4ff63bea4 100644 --- a/indra/llmessage/lltemplatemessagebuilder.cpp +++ b/indra/llmessage/lltemplatemessagebuilder.cpp @@ -29,6 +29,7 @@ #include "lltemplatemessagebuilder.h" #include "llmessagetemplate.h" +#include "llzerocode.h" #include "llmath.h" #include "llquaternion.h" #include "u64.h" @@ -492,93 +493,29 @@ void LLTemplateMessageBuilder::addUUID(const char *varname, const LLUUID& uuid) addData(varname, uuid.mData, MVT_LLUUID, sizeof(uuid.mData)); } -static S32 zero_code(U8 **data, U32 *data_size) +void LLTemplateMessageBuilder::compressMessage(U8*& buf_ptr, U32& buffer_length) { - // Encoded send buffer needs to be slightly larger since the zero - // coding can potentially increase the size of the send data. - static U8 encodedSendBuffer[2 * MAX_BUFFER_SIZE]; - - S32 count = *data_size; - - S32 net_gain = 0; - U8 num_zeroes = 0; - - U8 *inptr = (U8 *)*data; - U8 *outptr = (U8 *)encodedSendBuffer; - -// skip the packet id field - - for (U32 ii = 0; ii < LL_PACKET_ID_SIZE ; ++ii) - { - count--; - *outptr++ = *inptr++; - } - -// build encoded packet, keeping track of net size gain - -// sequential zero bytes are encoded as 0 [U8 count] -// with 0 0 [count] representing wrap (>256 zeroes) - - while (count--) + if(ME_ZEROCODED != mCurrentSMessageTemplate->getEncoding()) { - if (!(*inptr)) // in a zero count - { - if (num_zeroes) - { - if (++num_zeroes > 254) - { - *outptr++ = num_zeroes; - num_zeroes = 0; - } - net_gain--; // subseqent zeroes save one - } - else - { - *outptr++ = 0; - net_gain++; // starting a zero count adds one - num_zeroes = 1; - } - inptr++; - } - else - { - if (num_zeroes) - { - *outptr++ = num_zeroes; - num_zeroes = 0; - } - *outptr++ = *inptr++; - } + return; } - if (num_zeroes) - { - *outptr++ = num_zeroes; - } + // Encoded send buffer needs to be slightly larger since the zero + // coding can potentially increase the size of the send data. + static U8 encodedSendBuffer[2 * MAX_BUFFER_SIZE]; - if (net_gain < 0) + S32 encoded_size = LLZeroCode::encode(buf_ptr, buffer_length, + encodedSendBuffer, sizeof(encodedSendBuffer), + LL_PACKET_ID_SIZE); + if (encoded_size >= 0) { // TODO: babbage: reinstate stat collecting... //mCompressedPacketsOut++; - //mUncompressedBytesOut += *data_size; - - *data = encodedSendBuffer; - *data_size += net_gain; - encodedSendBuffer[0] |= LL_ZERO_CODE_FLAG; // set the head bit to indicate zero coding - - //mCompressedBytesOut += *data_size; - - } - //mTotalBytesOut += *data_size; + //mUncompressedBytesOut += buffer_length; + //mCompressedBytesOut += encoded_size; - return(net_gain); -} - -void LLTemplateMessageBuilder::compressMessage(U8*& buf_ptr, U32& buffer_length) -{ - if(ME_ZEROCODED == mCurrentSMessageTemplate->getEncoding()) - { - zero_code(&buf_ptr, &buffer_length); + buf_ptr = encodedSendBuffer; + buffer_length = (U32)encoded_size; } } diff --git a/indra/llmessage/llzerocode.h b/indra/llmessage/llzerocode.h new file mode 100644 index 0000000000..7246c9d946 --- /dev/null +++ b/indra/llmessage/llzerocode.h @@ -0,0 +1,211 @@ +/** + * @file llzerocode.h + * @brief Zero-code run-length compression used by the LLMessageSystem UDP protocol. + * + * $LicenseInfo:firstyear=2001&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2010, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +#ifndef LL_LLZEROCODE_H +#define LL_LLZEROCODE_H + +#include + +#include "stdtypes.h" + +// Zero-coding compresses runs of zero bytes in a packet body, leaving the +// first header_size bytes of the buffer (the packet header - flags, +// sequence number, offset, etc.) untouched aside from the flag bit below. +// +// Runs of zero bytes in the body are replaced by a two-byte token: +// 0x00 N - represents N zero bytes, for N in 1..254 +// 0x00 0x00 N - represents (255 + N) zero bytes (wrap/overflow case, +// produced by decode()'s wire format but never emitted +// by encode(), which instead starts a fresh 0x00 token +// every 255 zero bytes) +namespace LLZeroCode +{ + // High bit of the first header byte: set by encode() and cleared by + // decode() to indicate whether the body that follows is zero-coded. + const U8 FLAG = 0x80; + + // Zero-codes src (src_size bytes, the first header_size of which are the + // packet header and are copied verbatim) into dst. + // + // dst_capacity must be at least 2 * src_size: a pathological body of + // isolated zero bytes can nearly double in size when encoded. + // + // Returns the encoded size (with FLAG set in dst[0]) if doing so made the + // packet smaller. Returns -1 if compression would not help (or the + // arguments are invalid), in which case dst is left untouched and the + // caller should keep using the original, uncompressed buffer. + inline S32 encode(const U8* src, U32 src_size, U8* dst, U32 dst_capacity, U32 header_size) + { + if (src_size < header_size || dst_capacity < 2 * src_size) + { + return -1; + } + + S32 count = (S32)(src_size - header_size); + S32 net_gain = 0; + U8 num_zeroes = 0; + + const U8* inptr = src; + U8* outptr = dst; + + // copy the header verbatim + for (U32 ii = 0; ii < header_size; ++ii) + { + *outptr++ = *inptr++; + } + + // sequential zero bytes are encoded as 0 [U8 count]; a run longer + // than 254 bytes is split into consecutive 0 [U8 count] tokens. + while (count--) + { + if (!(*inptr)) // in a zero count + { + if (num_zeroes) + { + if (++num_zeroes > 254) + { + *outptr++ = num_zeroes; + num_zeroes = 0; + } + net_gain--; // subsequent zeroes save one + } + else + { + *outptr++ = 0; + net_gain++; // starting a zero count adds one + num_zeroes = 1; + } + inptr++; + } + else + { + if (num_zeroes) + { + *outptr++ = num_zeroes; + num_zeroes = 0; + } + *outptr++ = *inptr++; + } + } + + if (num_zeroes) + { + *outptr++ = num_zeroes; + } + + if (net_gain >= 0) + { + // compression did not shrink the packet; caller should keep the original + return -1; + } + + dst[0] |= FLAG; + return (S32)src_size + net_gain; + } + + // Expands a zero-coded src (src_size bytes) into dst. + // + // If FLAG is not set in src[0], the body is not zero-coded: no work is + // done and the function returns 0. + // + // On success, returns the number of bytes written to dst (always includes + // the header_size header bytes, copied verbatim except for FLAG being + // cleared from dst[0]). + // + // If expansion would write past dst_capacity - which only a malformed or + // malicious packet should cause - decoding is aborted, *overflow is set + // true, and the returned size reflects however much (if anything) was + // salvaged; the caller should treat the packet as invalid. + inline U32 decode(const U8* src, U32 src_size, U8* dst, U32 dst_capacity, U32 header_size, bool& overflow) + { + overflow = false; + + if (src_size < header_size || !(src[0] & FLAG)) + { + return 0; + } + + S32 count = (S32)(src_size - header_size); + + const U8* inptr = src; + U8* outptr = dst; + + for (U32 ii = 0; ii < header_size; ++ii) + { + *outptr++ = *inptr++; + } + dst[0] &= ~FLAG; + + // reconstruct the body: a 0x00 byte starts a run; the byte(s) that + // follow give its length (see the wire format described above). + while (count--) + { + if (outptr > &dst[dst_capacity - 1]) + { + overflow = true; + outptr = dst; + break; + } + + if (!((*outptr++ = *inptr++))) + { + while ((count--) && (!(*inptr))) + { + if (outptr > &dst[dst_capacity - 256]) + { + overflow = true; + outptr = dst; + count = -1; + break; + } + *outptr++ = *inptr++; + memset(outptr, 0, 255); + outptr += 255; + } + + if (count < 0) + { + break; + } + else + { + if (outptr > &dst[dst_capacity - (*inptr)]) + { + overflow = true; + outptr = dst; + } + memset(outptr, 0, (*inptr) - 1); + outptr += ((*inptr) - 1); + inptr++; + } + } + } + + return (U32)(outptr - dst); + } +} + +#endif // LL_LLZEROCODE_H diff --git a/indra/llmessage/message.cpp b/indra/llmessage/message.cpp index db7405f93f..71210f7535 100644 --- a/indra/llmessage/message.cpp +++ b/indra/llmessage/message.cpp @@ -67,6 +67,7 @@ #include "llsdmessagereader.h" #include "llsdserialize.h" #include "llstring.h" +#include "llzerocode.h" #include "lltransfermanager.h" #include "lluuid.h" #include "llxfermanager.h" @@ -3060,85 +3061,6 @@ U32 LLMessageSystem::getListenPort( void ) const return mPort; } -// TODO: babbage: remove this horror! -S32 LLMessageSystem::zeroCodeAdjustCurrentSendTotal() -{ - if(mMessageBuilder == mLLSDMessageBuilder) - { - // babbage: don't compress LLSD messages, so delta is 0 - return 0; - } - - if (! mMessageBuilder->isBuilt()) - { - mSendSize = mMessageBuilder->buildMessage( - mSendBuffer, - MAX_BUFFER_SIZE, - 0); - } - // TODO: babbage: remove this horror - mMessageBuilder->setBuilt(false); - - S32 count = mSendSize; - - S32 net_gain = 0; - U8 num_zeroes = 0; - - U8 *inptr = (U8 *)mSendBuffer; - -// skip the packet id field - - for (U32 ii = 0; ii < LL_PACKET_ID_SIZE; ++ii) - { - count--; - inptr++; - } - -// don't actually build, just test - -// sequential zero bytes are encoded as 0 [U8 count] -// with 0 0 [count] representing wrap (>256 zeroes) - - while (count--) - { - if (!(*inptr)) // in a zero count - { - if (num_zeroes) - { - if (++num_zeroes > 254) - { - num_zeroes = 0; - } - net_gain--; // subseqent zeroes save one - } - else - { - net_gain++; // starting a zero count adds one - num_zeroes = 1; - } - inptr++; - } - else - { - if (num_zeroes) - { - num_zeroes = 0; - } - inptr++; - } - } - if (net_gain < 0) - { - return net_gain; - } - else - { - return 0; - } -} - - - S32 LLMessageSystem::zeroCodeExpand(U8** data, S32* data_size) { if ((*data_size ) < LL_MINIMUM_VALID_PACKET_SIZE) @@ -3159,74 +3081,18 @@ S32 LLMessageSystem::zeroCodeExpand(U8** data, S32* data_size) mCompressedPacketsIn++; mCompressedBytesIn += *data_size; - *data[0] &= (~LL_ZERO_CODE_FLAG); - - S32 count = (*data_size); - - U8 *inptr = (U8 *)*data; - U8 *outptr = (U8 *)mEncodedRecvBuffer; - -// skip the packet id field - - for (U32 ii = 0; ii < LL_PACKET_ID_SIZE; ++ii) - { - count--; - *outptr++ = *inptr++; - } - -// reconstruct encoded packet, keeping track of net size gain - -// sequential zero bytes are encoded as 0 [U8 count] -// with 0 0 [count] representing wrap (>256 zeroes) - - while (count--) + bool overflow = false; + U32 decoded_size = LLZeroCode::decode(*data, (U32)*data_size, + mEncodedRecvBuffer, sizeof(mEncodedRecvBuffer), + LL_PACKET_ID_SIZE, overflow); + if (overflow) { - if (outptr > (&mEncodedRecvBuffer[MAX_BUFFER_SIZE-1])) - { - LL_WARNS("Messaging") << "attempt to write past reasonable encoded buffer size 1" << LL_ENDL; - callExceptionFunc(MX_WROTE_PAST_BUFFER_SIZE); - outptr = mEncodedRecvBuffer; - break; - } - if (!((*outptr++ = *inptr++))) - { - while (((count--)) && (!(*inptr))) - { - *outptr++ = *inptr++; - if (outptr > (&mEncodedRecvBuffer[MAX_BUFFER_SIZE-256])) - { - LL_WARNS("Messaging") << "attempt to write past reasonable encoded buffer size 2" << LL_ENDL; - callExceptionFunc(MX_WROTE_PAST_BUFFER_SIZE); - outptr = mEncodedRecvBuffer; - count = -1; - break; - } - memset(outptr,0,255); - outptr += 255; - } - - if (count < 0) - { - break; - } - - else - { - if (outptr > (&mEncodedRecvBuffer[MAX_BUFFER_SIZE-(*inptr)])) - { - LL_WARNS("Messaging") << "attempt to write past reasonable encoded buffer size 3" << LL_ENDL; - callExceptionFunc(MX_WROTE_PAST_BUFFER_SIZE); - outptr = mEncodedRecvBuffer; - } - memset(outptr,0,(*inptr) - 1); - outptr += ((*inptr) - 1); - inptr++; - } - } + LL_WARNS("Messaging") << "attempt to write past reasonable encoded buffer size" << LL_ENDL; + callExceptionFunc(MX_WROTE_PAST_BUFFER_SIZE); } *data = mEncodedRecvBuffer; - *data_size = (S32)(outptr - mEncodedRecvBuffer); + *data_size = (S32)decoded_size; mUncompressedBytesIn += *data_size; return(in_size); diff --git a/indra/llmessage/message.h b/indra/llmessage/message.h index e23a67c04a..2e19e567e6 100644 --- a/indra/llmessage/message.h +++ b/indra/llmessage/message.h @@ -604,7 +604,6 @@ public: //void buildMessage(); S32 zeroCodeExpand(U8 **data, S32 *data_size); - S32 zeroCodeAdjustCurrentSendTotal(); // Uses ping-based retry S32 sendReliable(const LLHost &host); diff --git a/indra/llmessage/tests/llzerocode_test.cpp b/indra/llmessage/tests/llzerocode_test.cpp new file mode 100644 index 0000000000..1aba46149d --- /dev/null +++ b/indra/llmessage/tests/llzerocode_test.cpp @@ -0,0 +1,253 @@ +/** + * @file llzerocode_test.cpp + * @brief LLZeroCode test cases. + * + * $LicenseInfo:firstyear=2026&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2010, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +#include "linden_common.h" + +#include "../llzerocode.h" + +#include "../test/lltut.h" + +#include + +namespace tut +{ + struct zerocode_data + { + }; + typedef test_group zerocode_test; + typedef zerocode_test::object zerocode_object; + tut::zerocode_test zerocode_testcase("LLZeroCode"); + + // Builds header_size bytes of header (with header[0] == header0) followed by body. + static std::vector makeBuffer(U32 header_size, U8 header0, const std::vector& body) + { + std::vector buf(header_size, 0); + if (header_size) + { + buf[0] = header0; + } + buf.insert(buf.end(), body.begin(), body.end()); + return buf; + } + + // Runs src through encode() then decode(), and (when compression is expected to help) + // asserts the round trip reproduces src exactly, including untouched header bits other + // than the zero-code flag. When compression is not expected to help, asserts encode() + // refuses it. + static void ensureRoundTrip(const char* msg, U32 header_size, U8 header0, + const std::vector& body, bool expect_compressed) + { + std::vector src = makeBuffer(header_size, header0, body); + std::vector enc(2 * src.size() + 16, 0xAA); + + S32 enc_size = LLZeroCode::encode(src.data(), (U32)src.size(), + enc.data(), (U32)enc.size(), header_size); + + if (!expect_compressed) + { + ensure(std::string(msg) + ": encode should refuse (no benefit)", enc_size < 0); + return; + } + + ensure(std::string(msg) + ": encode should succeed", enc_size >= 0); + ensure(std::string(msg) + ": encoded size should be smaller", (U32)enc_size < src.size()); + ensure(std::string(msg) + ": FLAG should be set on encoded output", (enc[0] & LLZeroCode::FLAG) != 0); + if (header_size > 0) + { + ensure_equals(std::string(msg) + ": non-flag header bits preserved on encode", + (U8)(enc[0] & ~LLZeroCode::FLAG), (U8)(header0 & ~LLZeroCode::FLAG)); + } + + std::vector dec(src.size() + 16, 0xBB); + bool overflow = false; + U32 dec_size = LLZeroCode::decode(enc.data(), (U32)enc_size, + dec.data(), (U32)dec.size(), header_size, overflow); + ensure(std::string(msg) + ": decode should not overflow", !overflow); + ensure_equals(std::string(msg) + ": decoded size should match original", dec_size, (U32)src.size()); + ensure(std::string(msg) + ": decoded bytes should match original", + memcmp(dec.data(), src.data(), src.size()) == 0); + } + + // Basic mixed body; header carries an unrelated flag bit (0x40) that must survive untouched. + template<> template<> + void zerocode_object::test<1>() + { + ensureRoundTrip("mixed body", 6, 0x40, + {0,0,0,5,0,0,0,0,0,0,7,8,9,0,0}, true); + } + + // A body with no zero bytes at all cannot benefit from zero-coding. + template<> template<> + void zerocode_object::test<2>() + { + ensureRoundTrip("no zero bytes", 1, 0x00, {1,2,3,4,5,6,7,8,9}, false); + } + + // Isolated zero-byte runs of length 1 or 2 cost as much or more than they save + // (marker + terminator == 2 bytes), so encode must refuse them. + template<> template<> + void zerocode_object::test<3>() + { + ensureRoundTrip("isolated single zero", 1, 0x00, {5, 0}, false); + ensureRoundTrip("isolated double zero", 1, 0x00, {5, 0, 0, 9}, false); + } + + // A long enough zero run followed by other data pays off. + template<> template<> + void zerocode_object::test<4>() + { + std::vector body(20, 0); + body.push_back(99); + ensureRoundTrip("long zero run", 1, 0x00, body, true); + } + + // Wrap boundary: runs are split into chunks of at most 255 zero bytes each + // (encode never emits the doubled-0x00 wire form; see test<7> for that). + // A run only shrinks the packet once it is longer than 2 bytes. + template<> template<> + void zerocode_object::test<5>() + { + static const U32 lengths[] = {1, 2, 253, 254, 255, 256, 257, 300, 509, 510, 511, 1000}; + for (U32 n : lengths) + { + std::vector body(n, 0); + body.push_back(42); // trailing nonzero byte + ensureRoundTrip("wrap boundary (with trailing byte)", 1, 0x00, body, n > 2); + } + } + + // Same boundary check, but with the zero run flushed at end-of-buffer + // (no trailing nonzero byte to force the terminator write mid-loop). + template<> template<> + void zerocode_object::test<6>() + { + static const U32 lengths[] = {1, 2, 254, 255, 256, 300}; + for (U32 n : lengths) + { + std::vector body(n, 0); + ensureRoundTrip("wrap boundary (end-of-buffer flush)", 1, 0x00, body, n > 2); + } + } + + // decode() must also accept the "0x00 0x00 N" doubled-marker wire format + // (worth +255 zero bytes per extra marker) for compatibility with any + // encoder other than this one's chunking strategy, even though encode() + // itself never emits it. + template<> template<> + void zerocode_object::test<7>() + { + // header (1 byte, FLAG set) + [0x00 marker][0x00 extra-wrap-marker][terminator=5] + // decoded body length = 1 (marker) + 1 (extra marker) + 255 (memset) + (5 - 1) = 261 + std::vector encoded = {(U8)LLZeroCode::FLAG, 0x00, 0x00, 0x05}; + std::vector dec(1024, 0xDD); + bool overflow = false; + U32 dec_size = LLZeroCode::decode(encoded.data(), (U32)encoded.size(), + dec.data(), (U32)dec.size(), 1, overflow); + ensure("wrap format: no overflow", !overflow); + ensure_equals("wrap format: decoded size", dec_size, (U32)262); + ensure_equals("wrap format: FLAG cleared on header", dec[0], (U8)0x00); + for (U32 i = 1; i < dec_size; ++i) + { + ensure_equals("wrap format: decoded byte is zero", dec[i], (U8)0); + } + } + + // decode() is a no-op (returns 0, does not touch dst) when FLAG is not set. + template<> template<> + void zerocode_object::test<8>() + { + std::vector src = makeBuffer(6, 0x00, {1,2,3,0,0,0}); + std::vector dec(64, 0xCC); + bool overflow = false; + U32 dec_size = LLZeroCode::decode(src.data(), (U32)src.size(), + dec.data(), (U32)dec.size(), 6, overflow); + ensure_equals("not zero-coded: decode returns 0", dec_size, (U32)0); + ensure("not zero-coded: no overflow", !overflow); + } + + // encode() refuses to write into an undersized destination buffer. + template<> template<> + void zerocode_object::test<9>() + { + std::vector body(50, 0); + std::vector src = makeBuffer(1, 0, body); + std::vector enc(src.size(), 0); // smaller than the required 2 * src_size + S32 r = LLZeroCode::encode(src.data(), (U32)src.size(), enc.data(), (U32)enc.size(), 1); + ensure("encode: capacity guard rejects undersized dst", r < 0); + } + + // decode() reports overflow (rather than writing out of bounds) when dst is too small, + // whether the destination is smaller than a single byte's worth of headroom... + template<> template<> + void zerocode_object::test<10>() + { + std::vector body(500, 0); + std::vector src = makeBuffer(1, 0, body); + std::vector enc(2 * src.size() + 16, 0); + S32 enc_size = LLZeroCode::encode(src.data(), (U32)src.size(), enc.data(), (U32)enc.size(), 1); + ensure("decode overflow setup: encode succeeded", enc_size >= 0); + + std::vector dec(1, 0); // capacity == header_size exactly + bool overflow = false; + U32 dec_size = LLZeroCode::decode(enc.data(), (U32)enc_size, + dec.data(), (U32)dec.size(), 1, overflow); + ensure("decode overflow (minimal capacity): overflow flagged", overflow); + ensure("decode overflow (minimal capacity): size bounded by capacity", dec_size <= dec.size()); + } + + // ...or comfortably larger than 256 bytes but still short of the true decoded size. + template<> template<> + void zerocode_object::test<11>() + { + std::vector body(500, 0); + std::vector src = makeBuffer(1, 0, body); + std::vector enc(2 * src.size() + 16, 0); + S32 enc_size = LLZeroCode::encode(src.data(), (U32)src.size(), enc.data(), (U32)enc.size(), 1); + ensure("decode overflow setup: encode succeeded", enc_size >= 0); + + std::vector dec(300, 0); // > 256, but less than the true decoded size (~501) + bool overflow = false; + U32 dec_size = LLZeroCode::decode(enc.data(), (U32)enc_size, + dec.data(), (U32)dec.size(), 1, overflow); + ensure("decode overflow (insufficient capacity): overflow flagged", overflow); + ensure("decode overflow (insufficient capacity): size bounded by capacity", dec_size <= dec.size()); + } + + // A pathological alternating zero/non-zero pattern grows under zero-coding + // (every isolated zero costs 2 output bytes for 1 input byte), so encode + // must refuse it and leave the original buffer in use. + template<> template<> + void zerocode_object::test<12>() + { + std::vector body; + for (int i = 0; i < 200; ++i) + { + body.push_back(0); + body.push_back((U8)(i + 1)); + } + ensureRoundTrip("alternating pattern", 1, 0x00, body, false); + } +} -- cgit v1.3