diff options
author | Nat Goodspeed <nat@lindenlab.com> | 2024-09-20 15:13:43 -0400 |
---|---|---|
committer | Nat Goodspeed <nat@lindenlab.com> | 2024-09-20 15:13:43 -0400 |
commit | 6d29beb91b019e1995cdb7c4aaf7a043de4bf053 (patch) | |
tree | c4772496fd833a934d1b7e93028b107b0e36ed8f | |
parent | 50513bab2d6b1823f983c145553b8a6af44c2f28 (diff) |
Add ability to pass command-line arguments to a Lua script.
Introduce `ScriptCommand` class that parses a command line into a script name
and optional args, using bash-like quoting and escaping. `ScriptCommand`
searches for a file with that script name on a passed list of directories; the
directories may be specified relative to a particular base directory.
`ScriptCommand` supports the special case of a script name containing unescaped
spaces. It guarantees that either the returned script file exists, or its
`error()` string is non-empty.
Replace `LLLeap::create()` logic, from which `ScriptCommand` was partly
derived, with a `ScriptCommand` instance.
Make `LLLUAmanager::runScriptFile()` use a `ScriptCommand` instance to parse
the passed command line.
Subsume `LLAppViewer::init()` script-path-searching logic for `--luafile`
into `ScriptCommand`. In fact that lambda now simply calls
`LLLUAmanager::runScriptFile()`.
Make `lluau::dostring()` accept an optional vector of script argument strings.
Following PUC-Rio Lua convention, pass these arguments into a Lua script as
the predefined global `arg`, and also as the script's `...` argument.
`LuaState::expr()` also accepts and passes through script argument strings.
Change the log tag for the Lua script interruption message: if we want it, we
can still enable it, but we don't necessarily want it along with all other
"Lua" DEBUG messages.
Remove `LuaState::script_finished_fn`, which isn't used any more. Also remove
the corresponding `LLLUAmanager::script_finished_fn`. This allows us to
simplify `~LuaState()` slightly, as well as the parameter signatures for
`LLLUAmanager::runScriptFile()` and `runScriptLine()`.
-rw-r--r-- | indra/llcommon/CMakeLists.txt | 2 | ||||
-rw-r--r-- | indra/llcommon/llleap.cpp | 45 | ||||
-rw-r--r-- | indra/llcommon/lua_function.cpp | 199 | ||||
-rw-r--r-- | indra/llcommon/lua_function.h | 6 | ||||
-rw-r--r-- | indra/llcommon/scriptcommand.cpp | 117 | ||||
-rw-r--r-- | indra/llcommon/scriptcommand.h | 64 | ||||
-rw-r--r-- | indra/newview/llappviewer.cpp | 26 | ||||
-rw-r--r-- | indra/newview/llluamanager.cpp | 83 | ||||
-rw-r--r-- | indra/newview/llluamanager.h | 22 |
9 files changed, 368 insertions, 196 deletions
diff --git a/indra/llcommon/CMakeLists.txt b/indra/llcommon/CMakeLists.txt index f47136f781..9b99d86434 100644 --- a/indra/llcommon/CMakeLists.txt +++ b/indra/llcommon/CMakeLists.txt @@ -108,6 +108,7 @@ set(llcommon_SOURCE_FILES lua_function.cpp lualistener.cpp resultset.cpp + scriptcommand.cpp threadpool.cpp throttle.cpp u64.cpp @@ -257,6 +258,7 @@ set(llcommon_HEADER_FILES lua_function.h lualistener.h resultset.h + scriptcommand.h stdtypes.h stringize.h tempset.h diff --git a/indra/llcommon/llleap.cpp b/indra/llcommon/llleap.cpp index 306d4e48d0..ef43af6ceb 100644 --- a/indra/llcommon/llleap.cpp +++ b/indra/llcommon/llleap.cpp @@ -21,17 +21,18 @@ // external library headers // other Linden headers #include "llerror.h" -#include "llstring.h" -#include "llprocess.h" +#include "llerrorcontrol.h" #include "llevents.h" -#include "stringize.h" -#include "llsdutil.h" +#include "llexception.h" +#include "llleaplistener.h" +#include "llprocess.h" #include "llsdserialize.h" -#include "llerrorcontrol.h" +#include "llsdutil.h" +#include "llstring.h" #include "lltimer.h" #include "lluuid.h" -#include "llleaplistener.h" -#include "llexception.h" +#include "scriptcommand.h" +#include "stringize.h" #if LL_MSVC #pragma warning (disable : 4355) // 'this' used in initializer list: yes, intentionally @@ -107,7 +108,7 @@ public: // If that didn't work, no point in keeping this LLLeap object. if (! mChild) { - LLTHROW(Error(STRINGIZE("failed to run " << mDesc))); + LLTHROW(Error(stringize("failed to run ", mDesc))); } // Okay, launch apparently worked. Change our mDonePump listener. @@ -484,12 +485,24 @@ LLLeap* LLLeap::create(const std::string& desc, const std::vector<std::string>& LLLeap* LLLeap::create(const std::string& desc, const std::string& plugin, bool exc) { - // Use LLStringUtil::getTokens() to parse the command line - return create(desc, - LLStringUtil::getTokens(plugin, - " \t\r\n", // drop_delims - "", // no keep_delims - "\"'", // either kind of quotes - "\\"), // backslash escape - exc); + // Use ScriptCommand to parse the command line + ScriptCommand command(plugin); + auto error = command.error(); + if (! error.empty()) + { + if (exc) + { + LLTHROW(Error(error)); + } + return nullptr; + } + + LLProcess::Params params; + params.desc = desc; + params.executable = command.script; + for (const auto& arg : command.args) + { + params.args.add(arg); + } + return create(params, exc); } diff --git a/indra/llcommon/lua_function.cpp b/indra/llcommon/lua_function.cpp index 014ff3c4c4..a9f88f3170 100644 --- a/indra/llcommon/lua_function.cpp +++ b/indra/llcommon/lua_function.cpp @@ -63,6 +63,8 @@ namespace lluau int dostring(lua_State* L, const std::string& desc, const std::string& text, const std::vector<std::string>& args) { + // debug.traceback() + compiled chunk + args table + args... + slop + lluau_checkstack(L, 1 + 1 + 1 + int(args.size()) + 2); auto r = loadstring(L, desc, text); if (r != LUA_OK) return r; @@ -86,12 +88,56 @@ int dostring(lua_State* L, const std::string& desc, const std::string& text, // remove it from stack on exit LuaRemover cleanup(L, traceback); - // push any args passed -- all strings -- script must handle any desired - // conversions + // Originally we just pushed 'args' to the Lua stack before entering the + // chunk. But that's awkward for the chunk: it must reference those + // arguments as '...', using any of a number of tactics to move them to + // named variables. This doesn't work as a Lua chunk expecting arguments: + // function(a, b, c) + // -- ... + // end + // because that code only *defines* a function: the function's body isn't + // entered by executing the chunk. + // + // Per https://www.lua.org/manual/5.1/manual.html#6 Lua Stand-alone, we + // now also create a global table called 'arg' whose [0] is the script + // name, ['n'] is the number of additional arguments and [1] through + // [['n']] are the additional arguments. We diverge from that spec in not + // creating any negative indices. + // + // Since the spec notes that the chunk can also reference args using + // '...', we also leave them on the stack. + + // stack: debug.traceback(), compiled chunk + // create arg table pre-sized to hold the args array, plus [0] and ['n'] + lua_createtable(L, narrow(args.size()), 2); + // stack: debug.traceback(), compiled chunk, arg table + int argi = lua_absindex(L, -1); + lua_Integer i = 0; + // store desc (e.g. script name) as arg[0] + lua_pushinteger(L, i); + lua_pushstdstring(L, desc); + lua_rawset(L, argi); // rawset() pops key and value + // store args.size() as arg.n + lua_pushinteger(L, narrow(args.size())); + lua_setfield(L, argi, "n"); // setfield() pops value for (const auto& arg : args) { + // push each arg in order lua_pushstdstring(L, arg); + // push index + lua_pushinteger(L, ++i); + // duplicate arg[i] to store in arg table + lua_pushvalue(L, -2); + // stack: ..., arg[i], i, arg[i] + lua_rawset(L, argi); + // leave ..., arg[i] on stack } + // stack: debug.traceback(), compiled chunk, arg, arg[1], arg[2], ... + // duplicate the arg table to store it + lua_pushvalue(L, argi); + lua_setglobal(L, "arg"); + lua_remove(L, argi); + // stack: debug.traceback(), compiled chunk, arg[1], arg[2], ... // It's important to pass LUA_MULTRET as the expected number of return // values: if we pass any fixed number, we discard any returned values @@ -101,6 +147,7 @@ int dostring(lua_State* L, const std::string& desc, const std::string& text, int loadstring(lua_State *L, const std::string &desc, const std::string &text) { + lluau_checkstack(L, 1); size_t bytecodeSize = 0; // The char* returned by luau_compile() must be freed by calling free(). // Use unique_ptr so the memory will be freed even if luau_load() throws. @@ -540,8 +587,7 @@ int lua_metaipair(lua_State* L); } // anonymous namespace -LuaState::LuaState(script_finished_fn cb): - mCallback(cb) +LuaState::LuaState() { /*---------------------------- feature flag ----------------------------*/ try @@ -726,80 +772,74 @@ LuaState::~LuaState() return; /*---------------------------- feature flag ----------------------------*/ - if (mFeature) + if (! mFeature) + return; /*---------------------------- feature flag ----------------------------*/ + + // We're just about to destroy this lua_State mState. Did this Lua chunk + // register any atexit() functions? + lluau_checkstack(mState, 3); + // look up Registry.atexit + lua_getfield(mState, LUA_REGISTRYINDEX, "atexit"); + // stack contains Registry.atexit + if (lua_istable(mState, -1)) { - // We're just about to destroy this lua_State mState. Did this Lua chunk - // register any atexit() functions? - lluau_checkstack(mState, 3); - // look up Registry.atexit - lua_getfield(mState, LUA_REGISTRYINDEX, "atexit"); - // stack contains Registry.atexit - if (lua_istable(mState, -1)) + // We happen to know that Registry.atexit is built by appending array + // entries using table.insert(). That's important because it means + // there are no holes, and therefore lua_objlen() should be correct. + // That's important because we walk the atexit table backwards, to + // destroy last the things we created (passed to LL.atexit()) first. + int len(lua_objlen(mState, -1)); + LL_DEBUGS("Lua") << LLCoros::getName() << ": Registry.atexit is a table with " + << len << " entries" << LL_ENDL; + + // Push debug.traceback() onto the stack as lua_pcall()'s error + // handler function. On error, lua_pcall() calls the specified error + // handler function with the original error message; the message + // returned by the error handler is then returned by lua_pcall(). + // Luau's debug.traceback() is called with a message to prepend to the + // returned traceback string. Almost as if they'd been designed to + // work together... + lua_getglobal(mState, "debug"); + lua_getfield(mState, -1, "traceback"); + // ditch "debug" + lua_remove(mState, -2); + // stack now contains atexit, debug.traceback() + + for (int i(len); i >= 1; --i) { - // We happen to know that Registry.atexit is built by appending array - // entries using table.insert(). That's important because it means - // there are no holes, and therefore lua_objlen() should be correct. - // That's important because we walk the atexit table backwards, to - // destroy last the things we created (passed to LL.atexit()) first. - int len(lua_objlen(mState, -1)); - LL_DEBUGS("Lua") << LLCoros::getName() << ": Registry.atexit is a table with " - << len << " entries" << LL_ENDL; - - // Push debug.traceback() onto the stack as lua_pcall()'s error - // handler function. On error, lua_pcall() calls the specified error - // handler function with the original error message; the message - // returned by the error handler is then returned by lua_pcall(). - // Luau's debug.traceback() is called with a message to prepend to the - // returned traceback string. Almost as if they'd been designed to - // work together... - lua_getglobal(mState, "debug"); - lua_getfield(mState, -1, "traceback"); - // ditch "debug" - lua_remove(mState, -2); - // stack now contains atexit, debug.traceback() - - for (int i(len); i >= 1; --i) + lua_pushinteger(mState, i); + // stack contains Registry.atexit, debug.traceback(), i + lua_gettable(mState, -3); + // stack contains Registry.atexit, debug.traceback(), atexit[i] + // Call atexit[i](), no args, no return values. + // Use lua_pcall() because errors in any one atexit() function + // shouldn't cancel the rest of them. Pass debug.traceback() as + // the error handler function. + LL_DEBUGS("Lua") << LLCoros::getName() + << ": calling atexit(" << i << ")" << LL_ENDL; + if (lua_pcall(mState, 0, 0, -2) != LUA_OK) { - lua_pushinteger(mState, i); - // stack contains Registry.atexit, debug.traceback(), i - lua_gettable(mState, -3); - // stack contains Registry.atexit, debug.traceback(), atexit[i] - // Call atexit[i](), no args, no return values. - // Use lua_pcall() because errors in any one atexit() function - // shouldn't cancel the rest of them. Pass debug.traceback() as - // the error handler function. - LL_DEBUGS("Lua") << LLCoros::getName() - << ": calling atexit(" << i << ")" << LL_ENDL; - if (lua_pcall(mState, 0, 0, -2) != LUA_OK) - { - auto error{ lua_tostdstring(mState, -1) }; - LL_WARNS("Lua") << LLCoros::getName() - << ": atexit(" << i << ") error: " << error << LL_ENDL; - // pop error message - lua_pop(mState, 1); - } - LL_DEBUGS("Lua") << LLCoros::getName() << ": atexit(" << i << ") done" << LL_ENDL; - // lua_pcall() has already popped atexit[i]: - // stack contains atexit, debug.traceback() + auto error{ lua_tostdstring(mState, -1) }; + LL_WARNS("Lua") << LLCoros::getName() + << ": atexit(" << i << ") error: " << error << LL_ENDL; + // pop error message + lua_pop(mState, 1); } - // pop debug.traceback() - lua_pop(mState, 1); + LL_DEBUGS("Lua") << LLCoros::getName() << ": atexit(" << i << ") done" << LL_ENDL; + // lua_pcall() has already popped atexit[i]: + // stack contains atexit, debug.traceback() } - // pop Registry.atexit (either table or nil) + // pop debug.traceback() lua_pop(mState, 1); - - // with the demise of this LuaState, remove sLuaStateMap entry - sLuaStateMap.erase(mState); - - lua_close(mState); } + // pop Registry.atexit (either table or nil) + lua_pop(mState, 1); - if (mCallback) - { - // mError potentially set by previous checkLua() call(s) - mCallback(mError); - } + // with the demise of this LuaState, remove sLuaStateMap entry + sLuaStateMap.erase(mState); + + lua_close(mState); } bool LuaState::checkLua(const std::string& desc, int r) @@ -815,11 +855,6 @@ bool LuaState::checkLua(const std::string& desc, int r) return true; } -std::pair<int, LLSD> LuaState::expr(const std::string& desc, const ScriptCommand& command) -{ - return expr(desc, , command.args); -} - std::pair<int, LLSD> LuaState::expr(const std::string& desc, const std::string& text, const std::vector<std::string>& args) { @@ -969,8 +1004,8 @@ void LuaState::check_interrupts_counter() } else if (mInterrupts % INTERRUPTS_SUSPEND_LIMIT == 0) { - LL_DEBUGS("Lua") << LLCoros::getName() << " suspending at " << mInterrupts - << " interrupts" << LL_ENDL; + LL_DEBUGS("Lua.suspend") << LLCoros::getName() << " suspending at " + << mInterrupts << " interrupts" << LL_ENDL; llcoro::suspend(); } } @@ -1067,18 +1102,6 @@ std::pair<LuaFunction::Registry&, LuaFunction::Lookup&> LuaFunction::getState() } /***************************************************************************** -* LuaCommand -*****************************************************************************/ -LuaCommand::LuaCommand(const std::string& command) -{ -} - -bool LuaCommand::found() const -{ - return ; -} - -/***************************************************************************** * source_path() *****************************************************************************/ lua_function(source_path, "source_path(): return the source path of the running Lua script") diff --git a/indra/llcommon/lua_function.h b/indra/llcommon/lua_function.h index a5022db225..ae6e0bf7ba 100644 --- a/indra/llcommon/lua_function.h +++ b/indra/llcommon/lua_function.h @@ -83,9 +83,7 @@ void lua_pushllsd(lua_State* L, const LLSD& data); class LuaState { public: - typedef std::function<void(std::string msg)> script_finished_fn; - - LuaState(script_finished_fn cb={}); + LuaState(); LuaState(const LuaState&) = delete; LuaState& operator=(const LuaState&) = delete; @@ -109,7 +107,6 @@ public: // multiple results, represented as the entries of the array. std::pair<int, LLSD> expr(const std::string& desc, const std::string& text, const std::vector<std::string>& args={}); - std::pair<int, LLSD> expr(const std::string& desc, const ScriptCommand& command); operator lua_State*() const { return mState; } @@ -129,7 +126,6 @@ private: /*---------------------------- feature flag ----------------------------*/ bool mFeature{ false }; /*---------------------------- feature flag ----------------------------*/ - script_finished_fn mCallback; lua_State* mState{ nullptr }; std::string mError; S32 mInterrupts{ 0 }; diff --git a/indra/llcommon/scriptcommand.cpp b/indra/llcommon/scriptcommand.cpp new file mode 100644 index 0000000000..79afbc2063 --- /dev/null +++ b/indra/llcommon/scriptcommand.cpp @@ -0,0 +1,117 @@ +/** + * @file scriptcommand.cpp + * @author Nat Goodspeed + * @date 2024-09-16 + * @brief Implementation for scriptcommand. + * + * $LicenseInfo:firstyear=2024&license=viewerlgpl$ + * Copyright (c) 2024, Linden Research, Inc. + * $/LicenseInfo$ + */ + +// Precompiled header +#include "linden_common.h" +// associated header +#include "scriptcommand.h" +// STL headers +// std headers +#include <sstream> +// external library headers +// other Linden headers +#include "fsyspath.h" +#include "llerror.h" +#include "llsdutil.h" +#include "llstring.h" +#include "stringize.h" + +ScriptCommand::ScriptCommand(const std::string& command, const LLSD& path, + const std::string& base) +{ + fsyspath basepath(base); + // Use LLStringUtil::getTokens() to parse the script command line + args = LLStringUtil::getTokens(command, + " \t\r\n", // drop_delims + "", // no keep_delims + "\"'", // either kind of quotes + "\\"); // backslash escape + // search for args[0] on paths + if (search(args[0], path, basepath)) + { + // The first token is in fact the script filename. Now that we've + // found the script file, we've consumed that token. The rest are + // command-line arguments. + args.erase(args.begin()); + return; + } + + // Parsing the command line produced a script file path we can't find. + // Maybe that's because there are spaces in the original pathname that + // were neither quoted nor escaped? See if we can find the whole original + // command line string. + if (search(command, path, basepath)) + { + // Here we found script, using the whole input command line as its + // pathname. Discard any parts of it we mistook for command-line + // arguments. + args.clear(); + return; + } + + // Couldn't find the script either way. Is it because we can't even check + // existence? + if (! mError.empty()) + { + return; + } + + // No, existence check works, we just can't find the script. + std::ostringstream msgstream; + msgstream << "Can't find script file " << std::quoted(args[0]); + if (command != args[0]) + { + msgstream << " or " << std::quoted(command); + } + if (path.size() > 0) + { + msgstream << " on " << path; + } + if (! base.empty()) + { + msgstream << " relative to " << base; + } + mError = msgstream.str(); + LL_WARNS("Lua") << mError << LL_ENDL; +} + +bool ScriptCommand::search(const fsyspath& script, const LLSD& paths, const fsyspath& base) +{ + for (const auto& path : llsd::inArray(paths)) + { + // If a path is already absolute, (otherpath / path) preserves it. + // Explicitly instantiate fsyspath for every string conversion to + // properly convert UTF-8 filename strings on Windows. + fsyspath absscript{ base / fsyspath(path.asString()) / script }; + bool exists; + try + { + exists = std::filesystem::exists(absscript); + } + catch (const std::filesystem::filesystem_error& exc) + { + mError = stringize("Can't check existence: ", exc.what()); + LL_WARNS("Lua") << mError << LL_ENDL; + return false; + } + if (exists) + { + this->script = absscript.string(); + return true; + } + } + return false; +} + +std::string ScriptCommand::error() const +{ + return mError; +} diff --git a/indra/llcommon/scriptcommand.h b/indra/llcommon/scriptcommand.h new file mode 100644 index 0000000000..dafed552bb --- /dev/null +++ b/indra/llcommon/scriptcommand.h @@ -0,0 +1,64 @@ +/** + * @file scriptcommand.h + * @author Nat Goodspeed + * @date 2024-09-16 + * @brief ScriptCommand parses a string into a script filepath plus arguments. + * + * $LicenseInfo:firstyear=2024&license=viewerlgpl$ + * Copyright (c) 2024, Linden Research, Inc. + * $/LicenseInfo$ + */ + +#if ! defined(LL_SCRIPTCOMMAND_H) +#define LL_SCRIPTCOMMAND_H + +#include "llsd.h" + +#include <string> +#include <vector> + +class fsyspath; + +class ScriptCommand +{ +public: + /** + * ScriptCommand accepts a command-line string to invoke an existing + * script, which may or may not include arguments to pass to that script. + * The constructor parses the command line into tokens using quoting and + * escaping rules similar to bash. The first token is assumed to be the + * script name; ScriptCommand tries to find that script on the filesystem, + * trying each directory listed in the LLSD array of strings 'path'. When + * it finds the script file, it stores its full pathname in 'script' and + * the remaining tokens in 'args'. + * + * But if the constructor can't find the first token on 'path', it + * considers the possibility that the whole command-line string is + * actually a single pathname containing unescaped spaces. If that script + * file is found on 'path', it stores its full pathname in 'script' and + * leaves 'args' empty. + * + * We accept 'path' as an LLSD array rather than (e.g.) + * std::vector<std::string> because the primary use case involves + * retrieving 'path' from settings. + * + * If you also pass 'base', any directory on 'path' may be specified + * relative to 'base'. Otherwise, every directory on 'path' must be + * absolute. + */ + ScriptCommand(const std::string& command, const LLSD& path=LLSD::emptyArray(), + const std::string& base={}); + + std::string script; + std::vector<std::string> args; + + // returns empty string if no error + std::string error() const; + +private: + bool search(const fsyspath& script, const LLSD& path, const fsyspath& base); + + std::string mError; +}; + +#endif /* ! defined(LL_SCRIPTCOMMAND_H) */ diff --git a/indra/newview/llappviewer.cpp b/indra/newview/llappviewer.cpp index 789aaab70d..a9ac48ac88 100644 --- a/indra/newview/llappviewer.cpp +++ b/indra/newview/llappviewer.cpp @@ -1234,23 +1234,8 @@ bool LLAppViewer::init() "--luafile", "LuaScript", [](const LLSD& script) { - LLSD paths(gSavedSettings.getLLSD("LuaCommandPath")); - LL_DEBUGS("Lua") << "LuaCommandPath = " << paths << LL_ENDL; - for (const auto& path : llsd::inArray(paths)) - { - // if script path is already absolute, operator/() preserves it - auto abspath(fsyspath(gDirUtilp->getAppRODataDir()) / path.asString()); - auto absscript{ (abspath / script.asString()) }; - std::error_code ec; - if (std::filesystem::exists(absscript, ec)) - { - // no completion callback: we don't need to know - LLLUAmanager::runScriptFile(absscript.u8string()); - return; // from lambda - } - } - LL_WARNS("Lua") << "--luafile " << std::quoted(script.asString()) - << " not found on " << paths << LL_ENDL; + // no completion callback: we don't need to know + LLLUAmanager::runScriptFile(script); }); processComposeSwitch( "LuaAutorunPath", "LuaAutorunPath", @@ -1259,15 +1244,16 @@ bool LLAppViewer::init() // each directory can be relative to the viewer's install // directory -- if directory is already absolute, operator/() // preserves it - auto abspath(fsyspath(gDirUtilp->getAppRODataDir()) / directory.asString()); - std::string absdir(abspath.string()); + fsyspath abspath(fsyspath(gDirUtilp->getAppRODataDir()) / + fsyspath(directory.asString())); + std::string absdir(fsyspath(abspath).string()); LL_DEBUGS("InitInfo") << "LuaAutorunPath: " << absdir << LL_ENDL; LLDirIterator scripts(absdir, "*.lua"); std::string script; while (scripts.next(script)) { LL_DEBUGS("InitInfo") << "LuaAutorunPath: " << absdir << ": " << script << LL_ENDL; - LLLUAmanager::runScriptFile((abspath / script).string(), true); + LLLUAmanager::runScriptFile(fsyspath(abspath / fsyspath(script)).string(), true); } }); diff --git a/indra/newview/llluamanager.cpp b/indra/newview/llluamanager.cpp index c4ce07e492..046526ac3c 100644 --- a/indra/newview/llluamanager.cpp +++ b/indra/newview/llluamanager.cpp @@ -186,75 +186,41 @@ LLLUAmanager::script_result LLLUAmanager::waitScriptFile(const std::string& file } void LLLUAmanager::runScriptFile(const std::string &filename, bool autorun, - script_result_fn result_cb, script_finished_fn finished_cb) + script_result_fn result_cb) { // A script_result_fn will be called when LuaState::expr() completes. - LLCoros::instance().launch(filename, [filename, autorun, result_cb, finished_cb]() + LLCoros::instance().launch(filename, [filename, autorun, result_cb]() { ScriptObserver observer(LLCoros::getName(), filename); - // Use LLStringUtil::getTokens() to parse the script command line - auto tokens = LLStringUtil::getTokens(filename, - " \t\r\n", // drop_delims - "", // no keep_delims - "\"'", // either kind of quotes - "\\"); // backslash escape - -#error Under construction - // TODO: - // - Move this either/or file existence logic to LuaCommand() - // - Accept LuaCommand in all LLLUAmanager::mumbleScriptFile() methods - // - Update all existing mumbleScriptFile() callers - - llifstream in_file; - in_file.open(tokens[0]); - if (in_file.is_open()) - { - // The first token is in fact the script filename. Now that the - // script file is open, we've consumed that token. The rest are - // command-line arguments. - tokens.erase(tokens.begin()); - } - else + LLSD paths(gSavedSettings.getLLSD("LuaCommandPath")); + LL_DEBUGS("Lua") << "LuaCommandPath = " << paths << LL_ENDL; + // allow LuaCommandPath to be specified relative to install dir + ScriptCommand command(filename, paths, gDirUtilp->getAppRODataDir()); + auto error = command.error(); + if (! error.empty()) { - // Parsing the command line produced a script file path we can't - // open. Maybe that's because there are spaces in the original - // pathname that were neither quoted nor escaped? See if we can - // open the whole original command line string. - in_file.open(filename); - if (! in_file.is_open()) + if (result_cb) { - std::ostringstream msgstream; - msgstream << "Can't open script file " << std::quoted(tokens[0]); - if (filename != tokens[0]) - { - msgstream << " or " << std::quoted(filename); - } - auto msg = msgstream.str(); - LL_WARNS("Lua") << msg << LL_ENDL; - if (result_cb) - { - result_cb(-1, msg); - } - return; + result_cb(-1, error); } - // Here we do have in_file open, using the whole input command - // line as its pathname. Discard any parts of it we mistook for - // command-line arguments. - tokens.clear(); - } + return; + } - // Here in_file is open. + llifstream in_file; + in_file.open(command.script); + // At this point, since ScriptCommand did not report an error, we + // should be able to assume that 'script' exists. If we can't open it, + // something else is wrong?! + llassert(in_file.is_open()); if (autorun) { sAutorunScriptCount++; } sScriptCount++; - // A script_finished_fn is used to initialize the LuaState. - // It will be called when the LuaState is destroyed. - LuaState L(finished_cb); + LuaState L; std::string text{std::istreambuf_iterator<char>(in_file), {}}; - auto [count, result] = L.expr(filename, text, tokens); + auto [count, result] = L.expr(command.script, text, command.args); if (result_cb) { result_cb(count, result); @@ -279,8 +245,7 @@ LLLUAmanager::script_result LLLUAmanager::waitScriptLine(const std::string& chun return startScriptLine(chunk).get(); } -void LLLUAmanager::runScriptLine(const std::string& chunk, script_result_fn result_cb, - script_finished_fn finished_cb) +void LLLUAmanager::runScriptLine(const std::string& chunk, script_result_fn result_cb) { // find a suitable abbreviation for the chunk string std::string shortchunk{ chunk }; @@ -292,11 +257,9 @@ void LLLUAmanager::runScriptLine(const std::string& chunk, script_result_fn resu shortchunk = stringize(shortchunk.substr(0, shortlen), "..."); std::string desc{ "lua: " + shortchunk }; - LLCoros::instance().launch(desc, [desc, chunk, result_cb, finished_cb]() + LLCoros::instance().launch(desc, [desc, chunk, result_cb]() { - // A script_finished_fn is used to initialize the LuaState. - // It will be called when the LuaState is destroyed. - LuaState L(finished_cb); + LuaState L; auto [count, result] = L.expr(desc, chunk); if (result_cb) { diff --git a/indra/newview/llluamanager.h b/indra/newview/llluamanager.h index df76ddd3e2..b98b5d4ef6 100644 --- a/indra/newview/llluamanager.h +++ b/indra/newview/llluamanager.h @@ -44,9 +44,6 @@ class LLLUAmanager friend class ScriptObserver; public: - // Pass a callback with this signature to obtain the error message, if - // any, from running a script or source string. Empty msg means success. - typedef std::function<void(std::string msg)> script_finished_fn; // Pass a callback with this signature to obtain the result, if any, of // running a script or source string. // count < 0 means error, and result.asString() is the error message. @@ -58,20 +55,31 @@ public: // same semantics as script_result_fn parameters typedef std::pair<int, LLSD> script_result; - static void runScriptFile(const std::string &filename, bool autorun = false, script_result_fn result_cb = {}, - script_finished_fn finished_cb = {}); + // Run the script specified by the command line passed as @a filename. + // This can be followed by some number of command-line arguments, which + // a Lua script can view using either '...' or predefined global 'arg'. + // The script pathname or its arguments can be quoted using 'single + // quotes' or "double quotes", or special characters can be \escaped. + // runScriptFile() recognizes the case in which the whole 'filename' + // string is a path containing spaces; if so no arguments are permitted. + // In either form, if the script pathname isn't absolute, it is sought on + // LuaCommandPath. + // If autorun is true, statistics will count this as an autorun script. + static void runScriptFile(const std::string &filename, bool autorun = false, + script_result_fn result_cb = {}); // Start running a Lua script file, returning an LLCoros::Future whose // get() method will pause the calling coroutine until it can deliver the // (count, result) pair described above. Between startScriptFile() and // Future::get(), the caller and the Lua script coroutine will run // concurrently. + // @a filename is as described for runScriptFile(). static LLCoros::Future<script_result> startScriptFile(const std::string& filename); // Run a Lua script file, and pause the calling coroutine until it completes. // The return value is the (count, result) pair described above. + // @a filename is as described for runScriptFile(). static script_result waitScriptFile(const std::string& filename); - static void runScriptLine(const std::string &chunk, script_result_fn result_cb = {}, - script_finished_fn finished_cb = {}); + static void runScriptLine(const std::string &chunk, script_result_fn result_cb = {}); // Start running a Lua chunk, returning an LLCoros::Future whose // get() method will pause the calling coroutine until it can deliver the // (count, result) pair described above. Between startScriptLine() and |